3
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

サーボをPWMで操作する(M5Stack)

Last updated at Posted at 2020-09-30

サーボのライブラリを使わずPWMで角度を指定して操作します

サーボが安定しないときはM5Stackの5Vじゃなくて外部電源に繋ぐようにするといいかもしれません

M5Stackの左右ボタンを押すと10度ずつ回転、
中ボタンを押すとセンターにリセットされます

こちらを参考にしました

ESP32 でサーボモーターを動かしてみた:息子と一緒に Makers:So-netブログ
https://makers-with-myson.blog.ss-blog.jp/2017-11-26

// (26/1024)*20ms ≒ 0.5 ms  (-90°)
int minimum = 26;
// (123/1024)*20ms ≒ 2.4 ms (+90°)
int maximum = 123;

int deg = 0;

void servo(int degree) {
  ledcWrite(SERVO_CH_0, map(degree, -90, 90, minimum, maximum));
  delay(200);
  ledcWrite(SERVO_CH_0, 0);
}

minimum,maximumはpwmのパルスの長さで-90度と90度に対応します

関数は角度をdegreeで入力、map()でminimam,maximumに変換してPWMを出力します

M5Stackライブラリ依存の部分を外せば普通のESP32でも使えます

#include <M5Stack.h>

#define SERVO_PIN_0        16
#define SERVO_CH_0        0

// (26/1024)*20ms ≒ 0.5 ms  (-90°)
int minimum = 26;
// (123/1024)*20ms ≒ 2.4 ms (+90°)
int maximum = 123;

int deg = 0;

void servo(int degree) {
  ledcWrite(SERVO_CH_0, map(degree, -90, 90, minimum, maximum));
  delay(200);
  ledcWrite(SERVO_CH_0, 0);

  drawScreen();
}

void drawScreen() {
  M5.Lcd.fillScreen(BLACK);
  M5.Lcd.setCursor(0, 0);
  M5.Lcd.printf("%d", deg);
  M5.Lcd.setCursor(0, 240 - 18);
  M5.Lcd.print("    +        0       -");
}

void setup() {

  M5.begin();
  dacWrite(25, 0); // ノイズ対策

  ledcSetup(SERVO_CH_0, 50, 10);
  ledcAttachPin(SERVO_PIN_0, SERVO_CH_0);

  M5.Lcd.setTextSize(2);
  M5.Lcd.setBrightness(40);
  drawScreen();
}

void loop() {

  M5.update();

  if ( M5.BtnA.wasPressed() ) {
    if (deg < 90) {
      deg += 10;
    }
    servo(deg);
  }
  if ( M5.BtnB.wasPressed() ) {
    deg = 0;
    servo(deg);
  }
  if ( M5.BtnC.wasPressed() ) {
    if (-90 < deg) {
      deg -= 10;
    }
    servo(deg);
  }
  delay(1);
}
3
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?