【发布时间】:2020-09-07 14:56:03
【问题描述】:
此代码旨在利用电位计来转动伺服电机。当我试图将它插入程序时,伺服器根本没有移动,我不知道这是我的电路板、我的接线还是我的代码的结果。如果有人可以帮助或提供一些帮助,将不胜感激。我使用的开发板是 Nucleo STM L476RG 开发板,电机是微型 SG90。
#include "mbed.h"
#include "Servo.h"
#include "iostream"
Servo myservo(D6);
AnalogOut MyPot(A1);
int main() {
float PotReading;
PotReading = MyPot.read();
while(1) {
for(int i=0; i<100; i++) {
myservo.SetPosition(PotReading);
wait(0.01);
}
}
}
另外,我使用的代码在已发布的库伺服中将此代码列为 Servo.h
#ifndef MBED_SERVO_H
#define MBED_SERVO_H
#include "mbed.h"
/** Class to control a servo on any pin, without using pwm
*
* Example:
* @code
* // Keep sweeping servo from left to right
* #include "mbed.h"
* #include "Servo.h"
*
* Servo Servo1(p20);
*
* Servo1.Enable(1500,20000);
*
* while(1) {
* for (int pos = 1000; pos < 2000; pos += 25) {
* Servo1.SetPosition(pos);
* wait_ms(20);
* }
* for (int pos = 2000; pos > 1000; pos -= 25) {
* Servo1.SetPosition(pos);
* wait_ms(20);
* }
* }
* @endcode
*/
class Servo {
public:
/** Create a new Servo object on any mbed pin
*
* @param Pin Pin on mbed to connect servo to
*/
Servo(PinName Pin);
/** Change the position of the servo. Position in us
*
* @param NewPos The new value of the servos position (us)
*/
void SetPosition(int NewPos);
/** Enable the servo. Without enabling the servo won't be running. Startposition and period both in us.
*
* @param StartPos The position of the servo to start (us)
* @param Period The time between every pulse. 20000 us = 50 Hz(standard) (us)
*/
void Enable(int StartPos, int Period);
/** Disable the servo. After disabling the servo won't get any signal anymore
*
*/
void Disable();
private:
void StartPulse();
void EndPulse();
int Position;
DigitalOut ServoPin;
Ticker Pulse;
Timeout PulseStop;
};
#endif
它还有一个 .cpp 文件与它在同一个地方,所以如果有人需要它作为参考,我会将它作为编辑发布。我也会把接线以防万一
伺服是SG90。
【问题讨论】:
-
你的电位器应该是
AnalogIn吗?您可能还想在每次循环迭代时读取底池输入。现在你只是在程序开始时阅读它一次,再也不会。你在启动程序后立即把它变成一个无用的旋钮。 -
@JohnFilleau 刚刚改了,测试了一下,结果和之前一样
-
第四个问题:
Servo::SetPosition期望在0和(可能)20000之间有一个int(取决于您特定伺服的规格表)。AnalogIn::read在0和1之间返回一个float。您需要将该浮点数转换为 int。 -
@GB "刚刚改了并测试了" 改成 what?测试它如何?这里有几个错误,都需要解决。
-
现在你有几个移动的部分。你有一个产生电压的电位器。这是由您的 ADC 读取的。然后由您的 ADC 驱动程序读取。然后将其写入您的伺服器。你有万用表吗?从头开始。确保扭转电位器实际上会导致电压偏离。如果是,则转到下一个。这些芯片是否有一些调试接口可以让您单步执行代码?