标签:
下面的代码演示的是让小车直线前进的arduino程序:
/*the following codes functions to make the car run forward repeatedly*/ int pin1=8; int pin2=9; int speedpin1=11; int pin3=6; int pin4=7; int speedpin2=10; void setup() { // put your setup code here, to run once: pinMode(pin1,OUTPUT); pinMode(pin2,OUTPUT); pinMode(speedpin1,OUTPUT); pinMode(pin3,OUTPUT); pinMode(pin4,OUTPUT); pinMode(speedpin2,OUTPUT); } void loop() { // put your main code here, to run repeatedly: analogWrite(speedpin1,150);//set the PWM speed as 100,range from 0 to 250 analogWrite(speedpin2,150);//set the PWM speed as 100 digitalWrite(pin1,LOW); digitalWrite(pin2,HIGH); digitalWrite(pin3,HIGH); digitalWrite(pin4,LOW); delay(2000); }
下面的代码演示的通过树莓派传输控制指令控制小车基本运动:按键8:——前进,按键2——后退,按键4——左转弯,按键6——右转弯,按键5——停止。
int pin1=8; int pin2=9; int speedpin1=11; int pin3=6; int pin4=7; int speedpin2=10; char sign; void setup() { // put your setup code here, to run once: pinMode(pin1,OUTPUT); pinMode(pin2,OUTPUT); pinMode(speedpin1,OUTPUT); pinMode(pin3,OUTPUT); pinMode(pin4,OUTPUT); pinMode(speedpin2,OUTPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: if(Serial.available()) { sign=Serial.read(); switch (sign){ case ‘4‘://backword { analogWrite(speedpin1,200);//set the PWM speed as 100 analogWrite(speedpin2,200);//set the PWM speed as 100 digitalWrite(pin1,HIGH);//set the motor run right for 2 seconds digitalWrite(pin2,LOW); digitalWrite(pin3,HIGH); digitalWrite(pin4,LOW); break; } case ‘8‘://forward { analogWrite(speedpin1,200);//set the PWM speed as 100 analogWrite(speedpin2,200);//set the PWM speed as 100 digitalWrite(pin1,LOW);//set the motor run right for 2 seconds digitalWrite(pin2,HIGH); digitalWrite(pin3,HIGH); digitalWrite(pin4,LOW); break; } case ‘6‘://right { analogWrite(speedpin1,200);//set the PWM speed as 100 analogWrite(speedpin2,200);//set the PWM speed as 100 digitalWrite(pin1,LOW);//set the motor run right for 2 seconds digitalWrite(pin2,HIGH); digitalWrite(pin3,LOW); digitalWrite(pin4,HIGH); break; } case ‘2‘://left { analogWrite(speedpin1,200);//set the PWM speed as 100 analogWrite(speedpin2,200);//set the PWM speed as 100 digitalWrite(pin1,HIGH);//set the motor run right for 2 seconds digitalWrite(pin2,LOW); digitalWrite(pin3,LOW); digitalWrite(pin4,HIGH); break; } case ‘5‘://stop { analogWrite(speedpin1,0);//set the PWM speed as 0 analogWrite(speedpin2,0);//set the PWM speed as 0 break; } Serial.flush(); } } }
标签:
原文地址:http://www.cnblogs.com/lou424/p/4340350.html