材料:Arduino主板一個、18650電池盒1個(兩個電源接頭)、麵包短版1個、ZK-2自走車底盤套件、L298N電機驅動模組1個、遙控器一個、杜邦線約15條、紅外線遙控接收器一個。
L298N電機驅動模組規格請參考:L298N紅外線遙控接收器模組規格請參考:1838b紅外線接收器
實作演練:利用L298N電機驅動模組和 使自動車照著遙控器的指令動作。
應用:電動遙控車。
成品外觀:
程式碼:(程式碼參考:楊明峰,ARDUINO自走車最佳入門與應用打造輪型機器人輕鬆學,碁峰)
#include <IRremote.h>
const int negR=4;
const int posR=5;
const int negL=6;
const int posL=7;
const int pwmR=9;
const int pwmL=10;
const int Rspeed=200;
const int Lspeed=200;
long FOR=0xFF18E7;
long BACK=0xFF4AB5;
long RIGHT=0xFF5AA5;
long LEFT=0xFF10EF;
long PAUSE=0xFF38C7;
int RECV_PIN = 2; // 使用數位腳位2接收紅外線訊號
IRrecv irrecv(RECV_PIN); // 初始化紅外線訊號輸入
decode_results results; // 儲存訊號的結構
void setup()
{
pinMode(posR,OUTPUT);
pinMode(negR,OUTPUT);
pinMode(posL,OUTPUT);
pinMode(negL,OUTPUT);
irrecv.blink13(true); // 設為true的話,當收到訊號時,腳位13的LED便會閃爍
irrecv.enableIRIn(); // 啟動接收
}
void loop() {
if (irrecv.decode(&results)) // 接收紅外線訊號並解碼
{
irrecv.resume(); // 準備接收下一個訊號
if(results.value==FOR)
forward(Rspeed,Lspeed);
else if(results.value==BACK)
back(Rspeed,Lspeed);
else if(results.value==RIGHT)
right(Rspeed,Lspeed);
else if(results.value==LEFT)
left(Rspeed,Lspeed);
else if(results.value==PAUSE)
pause(0,0);
}
}
void forward(byte RmotorSpeed, byte LmotorSpeed)
{
analogWrite(pwmR,RmotorSpeed);
analogWrite(pwmL,LmotorSpeed);
digitalWrite(posR,HIGH);
digitalWrite(negR,LOW);
digitalWrite(posL,LOW);
digitalWrite(negL,HIGH);
}
void back(byte RmotorSpeed, byte LmotorSpeed)
{
analogWrite(pwmR,RmotorSpeed);
analogWrite(pwmL,LmotorSpeed);
digitalWrite(posR,LOW);
digitalWrite(negR,HIGH);
digitalWrite(posL,HIGH);
digitalWrite(negL,LOW);
}
void pause(byte RmotorSpeed, byte LmotorSpeed)
{
analogWrite(pwmR,RmotorSpeed);
analogWrite(pwmL,LmotorSpeed);
digitalWrite(posR,LOW);
digitalWrite(negR,LOW);
digitalWrite(posL,LOW);
digitalWrite(negL,LOW);
}
void right(byte RmotorSpeed, byte LmotorSpeed)
{
analogWrite(pwmR,RmotorSpeed);
analogWrite(pwmL,LmotorSpeed);
digitalWrite(posR,LOW);
digitalWrite(negR,LOW);
digitalWrite(posL,LOW);
digitalWrite(negL,HIGH);
}
void left(byte RmotorSpeed, byte LmotorSpeed)
{
analogWrite(pwmR,RmotorSpeed);
analogWrite(pwmL,LmotorSpeed);
digitalWrite(posR,HIGH);
digitalWrite(negR,LOW);
digitalWrite(posL,LOW);
digitalWrite(negL,LOW);
}
沒有留言:
張貼留言