|
写了一段程序,希望在串口输入 b150,1号舵机就转到150度, b50,1号舵机就转到50度,依次类推,但是在处理串口数据和截取字符串时老是提示数据类型不符,求大神帮忙补全代码!
**************************************************
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
int DSD = 15;
int base=0; //1号舵机
int fArm=1; //2号舵机
int rArm=2; //3号舵机
int claw=3; //4号舵机
//默认地址 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
//9g舵机 高电平宽度在20ms内通过控制脉冲宽度范围0.5ms~2.5ms
#define SERVOMIN 102 // this is the \'minimum\' pulse length count (out of 4096) 0度
#define SERVOMAX 512 // this is the \'maximum\' pulse length count (out of 4096) 180度
void setup() {
Serial.begin(9600);
Serial.println("16 channel Servo test!");
pwm.begin();
pwm.setPWMFreq(50); //频率 50Hz,最高60Hz
}
void setServoPulse(uint8_t n, double pulse) {
double pulselength;
pulselength = 1000000; // 1,000,000 us per second
pulselength /= 50; // 50 Hz
Serial.print(pulselength); Serial.println(" us per period");
pulselength /= 4096; // 12 bits of resolution
Serial.print(pulselength); Serial.println(" us per bit");
pulse *= 1000;
pulse /= pulselength;
Serial.println(pulse);
pwm.setPWM(n, 0, pulse);
}
//设置9g舵机角度
void servo_9g_write(uint8_t n,int Angle)
{
double pulse = Angle;
pulse = pulse/90 + 0.5;
setServoPulse(n,pulse);//0到180度映射为0.5到2.5ms
}
//********************************************
void loop() {
// 如果缓冲区中有数据,则读取并输出
if(Serial.available()>0)
{
char serialCmd=Serial.read();
//Serial.print(serialCmd);
armDataCmd(serialCmd);
}
}
void armDataCmd(char serialCmd){
//Arduino根据串行指令执行相应操作
//指令示例:b45 1号舵机转到45度角度位置
if (serialCmd == 'b' || serialCmd == 'c' || serialCmd == 'f' || serialCmd == 'r'){
int servoData = Serial.parseInt();
servoCmd(serialCmd, servoData, DSD); // 机械臂舵机运行函数(参数:舵机名,目标角度,延迟/速度)
} else {
switch(serialCmd){
case 'o': // 输出舵机状态信息
break;
default: //未知指令反馈
Serial.println("未知指令");
Serial.print(serialCmd);
}
}
}
void servoCmd(char servoName, int toPos, int servoDelay){
switch(servoName){
case 'b':
if(1){
servo_9g_write(base,toPos);//控制第1路度数
break;
} else {
Serial.println("+Warning: Base Servo Value Out Of Limit!");
return;
}
case 'c':
if(1){
servo_9g_write(fArm,toPos);//控制第2路度数
break;
} else {
Serial.println("+Warning: Claw Servo Value Out Of Limit!");
return;
}
case 'f':
if(1){
servo_9g_write(rArm,toPos);//控制第3路度数
break;
} else {
Serial.println("+Warning: fArm Servo Value Out Of Limit!");
return;
}
case 'r':
if(1){
servo_9g_write(claw,toPos);//控制第4路度数
break;
} else {
Serial.println("+Warning: rArm Servo Value Out Of Limit!");
return;
}
}
}
|
|