#include <Servo.h>
#include <Metro.h>
Metro measureDistance = Metro(50)
Metro sweepServo = Metro(20)
unsigned long actualDistance = 0
Servo myservo //创建舵机
int pos = 60
int sweepFlag = 1
int URPWM = 3//PWM输出0-25000us,每50us代表1cm
int URTRIG= 10// PWM trigger pin PWM串口为10
uint8_t EnPwmCmd[4]={0x44,0x02,0xbb,0x01} // distance measure command 距离测量命令
void setup(){ // Serial initialization 串行初始化
myservo.attach(9) //舵机串口为9
Serial.begin(9600)// Sets the baud rate to 9600
SensorSetup()
}
void loop(){
if(measureDistance.check() == 1){
actualDistance = MeasureDistance()
// Serial.println(actualDistance)
// delay(100)
}
if(sweepServo.check() == 1){
servoSweep()
}
}
void SensorSetup(){
pinMode(URTRIG,OUTPUT)// A low pull on pin COMP/TRIG
digitalWrite(URTRIG,HIGH) // Set to HIGH
pinMode(URPWM, INPUT) // Sending Enable PWM mode command 发送使能控制模式命令
for(int i=0i<4i++){
Serial.write(EnPwmCmd[i])
}
}
int MeasureDistance(){// a low pull on pin COMP/TRIG triggering a sensor reading 触发传感器读数
digitalWrite(URTRIG, LOW)
digitalWrite(URTRIG, HIGH) // reading Pin PWM will output pulses读引脚脉宽调制将输出脉冲
unsigned long distance=pulseIn(URPWM,LOW)
if(distance==50000){ // the reading is invalid.阅读无效
Serial.print("Invalid")
}else{
distance=distance/50 // every 50us low level stands for 1cm
}
return distance
}
void servoSweep(){
if(sweepFlag ){
if(pos>=60 &&pos<=120){
pos=pos+1 // in steps of 1 degree 1度角度的转动
myservo.write(pos)// tell servo to go to position in variable 'pos' 告诉舵机转动的角度
}
if(pos>119) sweepFlag = false // assign the variable again 重新分配变量
}else {
if(pos>=60 &&pos<=120){
pos=pos-1
myservo.write(pos)
}
if(pos<61) sweepFlag = true
}
}
////////////////////////////////////////////////////////////
需要加载一个Metro.h的库,这只是调试机器,余下的完全看你的发挥了,加上电机
最后一句赋值错了!这个方法是好用的,我就是抄写的你的代码。
不过要封装成
rotate_angle(LEFT,360)
rotate_angle(ALL,720) 形式的函数才好用
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)