2023年9月29日金曜日

ESP32サーボ

ESP32で サーボを3つ動かしたいけどやり方がわからないと相談されたので作ってみました

BTシリアルから A10 B10 C10 のように送信すると、A,B,Cのサーボが動きます

依頼された方のソースを修正したものですが、

オリジナルはおそらくESP32サーボのサンプルソースだと思います

流用は問題ないと思いますので、

ピン配置(18,19,20の部分)等、カスタマイズはご自由にどうぞ



#include "BluetoothSerial.h"
#include <ESP32Servo.h> // Include the ESP32 Arduino Servo Library instead of the original Arduino Servo Library


BluetoothSerial SerialBT;

Servo myservo[3];  // create servo object to control a servo

// Possible PWM GPIO pins on the ESP32: 0(used by on-board button),2,4,5(used by on-board LED),12-19,21-23,25-27,32-33
int servoPin[3] = {18,19,20};      // GPIO pin used to connect the servo control (digital out)
String motorName[3] = {"A","B","C"};
int val[3] = {90,90,90};    // variable to read the value from the analog pin

void setup()
{
  //BTの処理
  Serial.begin(115200);
  SerialBT.begin("ESP32test");

  //Servo用の処理
  // Allow allocation of all timers
  ESP32PWM::allocateTimer(0);
  ESP32PWM::allocateTimer(1);
  ESP32PWM::allocateTimer(2);
  ESP32PWM::allocateTimer(3);
  myservo[0].setPeriodHertz(50);// Standard 50hz servo
  myservo[0].attach(servoPin[0], 500, 2400);  
  myservo[1].setPeriodHertz(50);// Standard 50hz servo
  myservo[1].attach(servoPin[1], 500, 2400);  
  myservo[2].setPeriodHertz(50);// Standard 50hz servo
  myservo[2].attach(servoPin[2], 500, 2400);
}

void loop() {
    int s,e;
    String tmp[3];
  //Bluetooth経由でのデータ取得
  if (SerialBT.available()) {
    String receiveData = SerialBT.readStringUntil(';');
    receiveData.replace(";"," ");
    // Search A,B,C
    for (int i=0;i<3;i++){
      s = receiveData.indexOf(motorName[i]);
      e = receiveData.indexOf(" ", s);
      if (s != -1){
        // set val
        tmp[i] = receiveData.substring(s+1, e);
        if (tmp[i].length() > 0){
          val[i] = tmp[i].toInt();
        }
      }
    }
    if(receiveData.length()>0){
      String tmpStr = "received A=" + tmp[0] + " B=" + tmp[1] + " C=" + tmp[2];
      SerialBT.print(tmpStr);
    }
  }
  for (int i=0;i<3;i++){
    myservo[i].write(val[i]); // set the servo position
  }
  delay(200);                 // wait
}

0 件のコメント: