--- tags: Arduino --- # Arduino 自走車 ## Audino mega 2560 ![](https://i.imgur.com/Hv4dYcZ.png =350x) ## L298P motor shield ![](https://i.imgur.com/PIN9dHq.png) 不錯的介紹: https://protosupplies.com/product/l298p-motor-driver-shield/ ## 線路連接 - 馬達 - Motor b-/Motor b+ 接自走車左側馬達 - Motor a-/Motor a+ 接自走車右側馬達 - Motor control a 接 D10/D12 pin - Motor control b 接 D11/D13 pin - 超音波感測器 - Triggrr 接D7 pin - Echo 接D8 pin - Buzzer - 接D4 ## 完整接線圖 ![](https://i.imgur.com/BrcFzBq.png =500x) ## 程式 ```c= int M1 = 10; //enable right whell int E1 =12; //high;forward int M2 =11; //enable left whell int E2 = 13; //high:forward int BUZZER =4; int TRIGGER_OUT=7; int ECHO_IN=8; long ultrasonic_rangefinder() { digitalWrite(TRIGGER_OUT, HIGH); // 給 Trig 高電位,持續 10微秒 delayMicroseconds(10); digitalWrite(TRIGGER_OUT, LOW); long duration = pulseIn(ECHO_IN, HIGH); long cm = (duration/2) / 29.1; return(cm); } void motor_forward() { digitalWrite(M1,HIGH); digitalWrite(E1,HIGH); digitalWrite(M2,HIGH); digitalWrite(E2,HIGH); } void motor_stop() { digitalWrite(M1,LOW); digitalWrite(M2,LOW); } void motor_backward() { digitalWrite(M1,HIGH); digitalWrite(E1,LOW); digitalWrite(M2,HIGH); digitalWrite(E2,LOW); } void setup() { // put your setup code here, to run once: Serial.begin(9600); //initial motor pinMode(M1, OUTPUT); pinMode(E1, OUTPUT); pinMode(M2, OUTPUT); pinMode(E2, OUTPUT); //initial buzzer pinMode(BUZZER,OUTPUT); //initial ultrasonic rangefinder pinMode(TRIGGER_OUT,OUTPUT); pinMode(ECHO_IN,INPUT); //motor stop digitalWrite(M1,LOW); digitalWrite(M2,LOW); //buzzer off digitalWrite(BUZZER,LOW); //ultrasonic rangefinder off digitalWrite(TRIGGER_OUT,LOW); } void loop() { // put your main code here, to run repeatedly: long dist,dist1,dist2; delay(50); dist1=ultrasonic_rangefinder(); dist2=ultrasonic_rangefinder(); dist=(dist1+dist2)/2; Serial.print(dist); Serial.print(" "); if(dist>50) { motor_forward(); digitalWrite(BUZZER,LOW); } else if(dist<20) { motor_backward(); digitalWrite(BUZZER,HIGH); } } ``` --- {%youtube kPZBUO3W380 %} ## 問題 - 齒輪轉動好像有偏心 -重新調整齒輪嗎? - 輪子走得不快,不知是否正常 -換馬達嗎?驅動晶片模組? ## 不錯的文章 https://jk3527101.pixnet.net/blog/post/14108743 --- ## 連接藍芽模組(HC-05/HC-06) 藍芽模組的LED燈號: 連續的快閃: 藍芽等待配對中。--->bluetooth板子的EN腳接地 --->手機可搜尋到裝置 連續的快閃2下後停1下: 藍芽已配對成功,運作中。 連續慢速閃爍(約兩秒一次): 藍芽已進入AT模式,準備設定。 -->-->bluetooth板子的EN腳3.3V 裡面有講到細節: https://swf.com.tw/?p=712 程式摘要: ```= #include <SoftwareSerial.h> SoftwareSerial BT(2,3); //接收,傳送 模組的RX接於 MMega2560 的第3腳 BT.begin(9600); BT.print("xxx"); ``` ---