Created
July 24, 2019 05:29
-
-
Save botamochi6277/ba515c048bb7d2c0491def1459b5f4f6 to your computer and use it in GitHub Desktop.
M5Stack-with-RCServo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef _M5_SERVO_ | |
#define _M5_SERVO_ | |
// http://ogimotokin.hatenablog.com/entry/2018/07/22/182140 | |
class M5Servo{ | |
protected: | |
constexpr static const float MIN_WIDTH_MS = 0.6; | |
constexpr static const float MAX_WIDTH_MS = 2.4; | |
constexpr static const int LEDC_CHANNEL = 3; | |
// サーボ信号の1サイクル 50Hz:20ms | |
constexpr static const int LEDC_SERVO_FREQ = 50; | |
constexpr static const int LEDC_TIMER_BIT = 16; | |
int pin_; | |
int angle_; | |
public: | |
// M5Servo(); | |
void attach(int pin){ | |
pin_ = pin; | |
ledcSetup(LEDC_CHANNEL, LEDC_SERVO_FREQ, LEDC_TIMER_BIT) ; // 16ビット精度で制御 | |
ledcAttachPin(pin_, LEDC_CHANNEL) ; | |
} | |
int count(int v){ | |
float vv = (v + 90) / 180.0 ; | |
return (int)(65536 * (MIN_WIDTH_MS + vv * (MAX_WIDTH_MS - MIN_WIDTH_MS)) / 20.0) ; | |
} | |
/** | |
* send reference angle to servo | |
* @param angle reference angle which is -90--+90 [deg] | |
*/ | |
void write(int angle){ | |
angle_ = angle; | |
ledcWrite(LEDC_CHANNEL, count(angle)); | |
} | |
int read(){ | |
return angle_; | |
} | |
}; | |
#endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <M5Stack.h> | |
#include "utility/M5Servo.h" | |
M5Servo myServo; | |
// the setup routine runs once when M5Stack starts up | |
void setup(){ | |
// Initialize the M5Stack object | |
M5.begin(); | |
// LCD display | |
M5.Lcd.print("Servo test"); | |
myServo.attach(5); | |
} | |
// the loop routine runs over and over again forever | |
void loop() { | |
for (int i = -90; i <= 90; i+=5){ | |
myServo.write(i); | |
uint8_t v = map(i,-90,90,0,100); | |
M5.Lcd.progressBar(0,40,M5.Lcd.width(),20,v,BLUE); | |
delay(15); | |
} | |
for (int i = 90; i >= -90; i-=5){ | |
myServo.write(i); | |
uint8_t v = map(i,-90,90,0,100); | |
M5.Lcd.progressBar(0,40,M5.Lcd.width(),20,v,BLUE); | |
delay(15); | |
} | |
delay(300); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment