Arduino循迹小车(使用TCRT5000红外反射传感器)
#include<Servo.h> //引用库 //因为很多子函数要用这个变量,所以把servo定义称全局变量,作用域是整个代码文件 Servo myServo; int leftX = 11; int rightX = 12; //全速:digitalWrite(2,3左轮;4,5右轮) //调速:analogwrite(pin,0~255)--3,5左轮6,9 //analogWrite只支持3,5,6,9,10,11引脚 //所以对4,5的物理接线对换一下 //前进 void Forward(){ digitalWrite(2,LOW); //digitalWrite(3,HIGH); analogWrite(3,60); digitalWrite(4,LOW); //digitalWrite(5,LOW); analogWrite(5,60); } //后退 void BackOff(){ digitalWrite(2,LOW); analogWrite(3,80); digitalWrite(4,LOW); analogWrite(5,80); } //左转 void TurnLeft(){ //小车左转(左轮后退) digitalWrite(2,LOW); analogWrite(3,0); //小车左转(右轮前进) digitalWrite(4,LOW); analogWrite(5,100); } //右转 void TurnRight(){ //小车右转(左轮前进) digitalWrite(2,LOW); analogWrite(3,100); //小车右转(右轮后退) digitalWrite(4,LOW); analogWrite(5,0); } //停止 void Stop(){ digitalWrite(2,LOW); analogWrite(3,0); digitalWrite(4,LOW); analogWrite(5,0); } void Init(){ //put your setup code here, to run once: //串口初始化 //配置2,3口为输出引脚(左轮初始化) pinMode(2,OUTPUT); pinMode(3,OUTPUT); //配置4,5口为输出引脚(右轮初始化) pinMode(4,OUTPUT); pinMode(5,OUTPUT); //Trig接9,通过9发送一个触发信号给超声波 pinMode(9,OUTPUT); //Echo接8,通过读取8高电平维持的实践,确认超声波哦在空气中传播的时间 pinMode(8,INPUT); //pinMode(LED_BUILTIN,OUTPUT); //监听串口 Serial.begin(9600); //把舵机黄色信号线插在ardino的引脚10 //myServo.attach(10); //初始化左右循迹模块(左循迹模块11;右循迹模块12) pinMode(leftX,INPUT); pinMode(rightX,INPUT); } void setup() { // put your setup code here, to run once: Init(); } void loop() { // put your main code here, to run repeatedly: //左循迹模块11;右循迹模块12 //要左转(左循迹模块电平为高电平,右循迹模块为低电平) if(digitalRead(leftX) == 1 && digitalRead(rightX) == 0){ TurnLeft(); } //要右转(左循迹模块电平为低电平,右循迹模块为高电平) if(digitalRead(leftX) == 0 && digitalRead(rightX) == 1){ TurnRight(); } //前进(左循迹模块和右循迹模块为低电平) if(digitalRead(leftX) == 0 && digitalRead(rightX) == 0){ Forward(); } //停止 //(左循迹模块和右循迹模块为高电平) if(digitalRead(leftX) == 1 && digitalRead(rightX) == 1){ Stop(); } }