1、HC-SR501人體紅外感應模組 測試
//紅外感應
//訊號接 7 連接埠
int ledpin = 7;
void setup()
{
pinMode(ledpin, INPUT);
Serial.begin(9600); // 開啟串口,設定傳輸速率為9600 bps
}
void loop()
{
int in = digitalRead(ledpin);
Serial.println(in); //有人的時候輸出高電平1 無人0
delay(2000);
}
我買個模組是這樣使用的:如果放在小車上那麼可以感應周圍是否有人,如果沒人的時候不運行,有人的時候才會出來得瑟一下,哈。。
2、超聲波測距模組測試
//超聲波測距
//Echo 接 arduino.5;Trig 接 arduino.4
//VCC +,END - GND 無需外接電源即可測試
const int TrigPin = 4;
const int EchoPin = 5;
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop()
{
// establish variables for duration of the ping,
// and the distance result in centimeters:
long duration, cm;
// The HC-SR04 is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(TrigPin, OUTPUT);
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(5);
digitalWrite(TrigPin, LOW);
// The same pin is used to read the signal from the HC-SR04: a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(EchoPin, INPUT);
duration = pulseIn(EchoPin, HIGH);
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(1000);
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
機器人三定律 第一法則機器人不得傷害人類,或袖手旁觀坐視人類受到傷害; 第二法則除非違背第一法則,機器人必須服從人類的命令; 第三法則在不違背第一及第二法則下,機器人必須保護自己。
有了超聲波模組就能檢測小車離障礙物的距離,並根據距離作出反應。那麼就能保護自己,符合第三定律。
3、直流電機控制模組測試
//直流電機控制
//需要外接電源 5V - 12V
//VCC接 arduino +5,GND 接 arduino GND
//1INA 1INB 分別接 arduino PWM 6,7
int leftmotorpin1 = 7; // define your motor pins
int leftmotorpin2 = 6;
void setup()
{
for (int pinindex = 0; pinindex < 14; pinindex++) {
pinMode(pinindex, OUTPUT); // set pins 0 to 13 as outputs
}
Serial.begin(9600); // 開啟串口,設定傳輸速率為9600 bps
}
void loop()
{
Serial.println("run");
digitalWrite(leftmotorpin1, HIGH);
digitalWrite(leftmotorpin2, LOW);
delay(5000);
Serial.println("back");
digitalWrite(leftmotorpin1, LOW);
digitalWrite(leftmotorpin2, HIGH);
delay(5000);
Serial.println("stop");
digitalWrite(leftmotorpin1, LOW);
digitalWrite(leftmotorpin2, LOW);
delay(3000);
}
有了電機驅動就能控制小車前進、後退。也可以利用兩輪轉速差來實現左轉、右轉、迴轉等功能。開始我用的是的驅動模組結果發現這個模組對超聲波模組訊號幹擾嚴重,最終換成了帶光耦的電機驅動解決了這個問題。
帶光耦的電機驅動:
4、舵機控制測試
//舵機控制測試
//需要外接電源 +5V - +12V
//舵機接5+ arduino.GND 型號端接 arduino.PWM 9
#include <Servo.h>
Servo myservo;//定義舵機變數名
void setup()
{
myservo.attach(9);//定義舵機介面,9或10
Serial.begin(9600); // 開啟串口,設定傳輸速率為9600 bps
}
void loop()
{
for(int i=0;i<=18;i++)
{
myservo.write(i * 10);//設定舵機旋轉的角度
Serial.println(i * 10);
delay(1000);
}
}
需要注意的是:舵機電流比較大,需要外接電源供電不能直接用 android 板子上的5v供電。