程式碼如下:
const int M1_enable = 5; //定義腳位
const int M2_enable = 6;
const int M1_int1 = 12;
const int M1_int2 = 11;
const int M2_int3 = 10;
const int M2_int4 = 9;
int speed = 0;
void setup() {
Serial.begin(9600); //將狀態顯示在序列窗上
pinMode(M1_int1, OUTPUT); //設定pin腳為輸出
pinMode(M1_int2, OUTPUT);
pinMode(M2_int3, OUTPUT);
pinMode(M2_int4, OUTPUT);
Serial. println(" '+':speed up '-':speed down 'F':forward, 'B':backward, others:Stop"); //指令設定
}
void loop() {
int _speed;
if (Serial. available()) {
char ch = Serial.read();
if (ch=='+') {
speed ++;
if (speed>10) speed=10;
_speed =map(speed, 1, 10, 60, 255);
Serial.print("speed , _speed=> "); Serial.print(speed); Serial.print(" , ");
Serial.println(_speed);
analogWrite(M1_enable, _speed);
analogWrite(M2_enable, _speed);
} else if (ch== '-'){
speed--;
if (speed<=0){
speed=0;
_speed=0;
} else {
_speed = map(speed, 1, 10, 60, 255);
}
Serial.print("speed , _speed=>");
Serial.print(speed);
Serial.print( " , ");
Serial.print(_speed);
analogWrite(M1_enable, _speed);
analogWrite(M2_enable, _speed);
} else if (ch== 'F') {
Serial.println("forward");
digitalWrite(M1_int1, HIGH); //right正轉
digitalWrite(M1_int2, LOW);
digitalWrite(M2_int3, HIGH); //lift正轉
digitalWrite(M2_int4, LOW );
} else if (ch=='B') {
Serial.println("backward");
digitalWrite(M1_int1, LOW); //right反轉
digitalWrite(M1_int2, HIGH);
digitalWrite(M2_int3, LOW); //lift反轉
digitalWrite(M2_int4, HIGH);
}else {
Serial.println("Stop" );
speed=0;
analogWrite(M1_enable, speed);
analogWrite(M2_enable, speed);
}
}
}
序列窗畫面 |
載入後執行序列窗就會這樣,當下達 F 的指令就是前進但此時的轉速是0,因此還要在下 + 轉速從0變為60,在按 + 會依序增加20直到255極限, B 是倒退, 一樣按 + 增加轉速;相反按 - 是降速
O 是停止的意思
沒有留言:
張貼留言