如何使用ESP32控制多个伺服

时间:2019-09-30 14:32:18

标签: arduino esp32 servo arduino-c++

我是arduino / ESP32的新手。我想借助ESP32来控制多个伺服电机。我想以不同的速度控制所有伺服器,并想使用正弦波逻辑来控制速度。

我有可以分别控制2个伺服器的代码。我已经在这里附加了代码,

#include <ESP32Servo.h>
#include "esp32-hal-ledc.h"
// create two servo objects 
Servo servo1SV;
Servo servo2SV;

// Published values of servos; adjust if needed
int minUs = 550;
int maxUs = 2250;

// These are all GPIO pins on the ESP32
// Recommended pins include 2,4,12-19,21-23,25-27,32-33 
int servo1SVPin = 15;   //outlet valve
int servo2SVPin = 16;   //inlet valve


int pos = 0;      // position in degrees
ESP32PWM pwm;
void setup() {
    Serial.begin(115200);
    servo1SV.setPeriodHertz(50);      // Standard 50hz servo
    servo2SV.setPeriodHertz(50);      // Standard 50hz servo
}

void loop() {
    servo1SV.attach(servo1SVPin, 500, maxUs);
    servo2SV.attach(servo2SVPin, minUs, maxUs);  

//// About outlet valve

    for (pos = 0; pos <= 85; pos += 1) { // sweep from 0 degrees to 85 degrees
        // in steps of 1 degree
        servo1SV.write(pos);
        delay(10);             // Opening of outlet valve
    }
 delay(5000);            // Outlet valve stay openned for 5 sec 

    for (pos = 85; pos >= 0; pos -= 1) { // sweep from 85 degrees to 0 degrees
        servo1SV.write(pos);
        delay(10);            // closing of outlet valve
    }

// About inlet valve

    for (pos = 0; pos <= 70; pos += 1) { // sweep from 0 degrees to 70 degrees
        // in steps of 1 degree
        servo2SV.write(pos);
        delay(10);             // Opening of inlet valve 
    }
  delay(5000);            // Inlet valve stay openned for 5 sec

    for (pos = 70; pos >= 0; pos -= 1) { // sweep from 70 degrees to 0 degrees
        servo2SV.write(pos);
        delay(10);            // Opening of inlet valve
    }

    servo1SV.detach();
    servo2SV.detach();
    delay(5000);
}

我想要的是此代码给出的相同输出,但使用正弦波。但我不知道如何在ESP32中实现正弦波逻辑。我该怎么办?

1 个答案:

答案 0 :(得分:0)

我不确定您对

的含义
  

正弦波逻辑

但是假设您希望随时间推移的伺服位置是一个正弦函数,而您的问题是如何获得该正弦函数:

要么使用Arduino sin()函数,要么使用LUT。

后者更常见,因为您不必每次都计算正弦值,这非常昂贵。只需定义一个预先计算的值数组即可,其中包含每个伺服步骤的正弦值。