这是之前课程设计做的遥控小车,简单的控制电机转速使小车前进和后退,左转右转也是参考了网上别人的,有需要的可以看看,哪里有不足也请指出
ATMEGA168单片机+L298仿真原理图如下
单片机源码:
int Foreward_key=2;//正转按钮
int Reverse_key=3;//反转按钮
int Stop_key=4;//停止按钮
int Trunleft_key=0;//左转按钮
int Trunright_key=1;//右转按钮
int Foreward_led=5;//正转指示灯
int Reverse_led=6;//反转指示灯
int Stop_led=7;//停止指示灯
int pinI1=8;//定义电机1正转接口
int pinI2=9;//定义电机1反转接口
int pinI3=13;//定义电机2正转接口
int pinI4=12;//定义电机2反转接口
int speedpin=14;//定义EA(PWM调速)接口
int speedpin1=14;//定义EB(PWM调速)接口
void setup()
{
pinMode(Foreward_key,INPUT);
pinMode(Reverse_key,INPUT);
pinMode(Trunleft_key,INPUT);
pinMode(Trunright_key,INPUT);
pinMode(Stop_key,INPUT);
pinMode(Foreward_led,OUTPUT);
pinMode(Reverse_led,OUTPUT);
pinMode(Stop_led,OUTPUT);
pinMode(pinI1,OUTPUT);//定义该接口为输出接口
pinMode(pinI2,OUTPUT);
pinMode(pinI3,OUTPUT);//定义该接口为输出接口
pinMode(pinI4,OUTPUT);
pinMode(speedpin,OUTPUT);
pinMode(speedpin1,OUTPUT);
digitalWrite(Foreward_led,HIGH);
digitalWrite(Reverse_led,HIGH);
digitalWrite(Stop_led,HIGH);
}
void loop()
{
if(digitalRead(Foreward_key)==HIGH)//正转
{
while(digitalRead(Foreward_key)==HIGH);
digitalWrite(Foreward_led,LOW);
digitalWrite(Reverse_led,HIGH);
digitalWrite(Stop_led,HIGH);
digitalWrite(pinI1,LOW);//使直流电机顺时针转
digitalWrite(pinI2,HIGH);
analogWrite(speedpin,100);
digitalWrite(pinI3,LOW);//使直流电机顺时针转
digitalWrite(pinI4,HIGH);
analogWrite(speedpin1,100);
}
if(digitalRead(Reverse_key)==HIGH)//反转
{
while(digitalRead(Reverse_key)==HIGH);
digitalWrite(Foreward_led,HIGH);
digitalWrite(Reverse_led,LOW);
digitalWrite(Stop_led,HIGH);
digitalWrite(pinI1,HIGH);//使直流电机逆时针转
digitalWrite(pinI2,LOW);
analogWrite(speedpin,100);
digitalWrite(pinI3,HIGH);//使直流电机逆时针转
digitalWrite(pinI4,LOW);
analogWrite(speedpin1,100);
}
if(digitalRead(Stop_key)==HIGH)//停止
{
while(digitalRead(Stop_key)==HIGH);
digitalWrite(Foreward_led,HIGH);
digitalWrite(Reverse_led,HIGH);
digitalWrite(Stop_led,LOW);
digitalWrite(pinI1,LOW);//使直流电机逆时针转
digitalWrite(pinI2,LOW);
analogWrite(speedpin,100);
digitalWrite(pinI3,LOW);//使直流电机逆时针转
digitalWrite(pinI4,LOW);
analogWrite(speedpin1,100);
}
if(digitalRead(Trunleft_key)==HIGH)//左转
{
while(digitalRead(Trunleft_key)==HIGH);
digitalWrite(Foreward_led,LOW);
digitalWrite(Reverse_led,HIGH);
digitalWrite(Stop_led,HIGH);
digitalWrite(pinI1,LOW);//使直流电机顺时针转
digitalWrite(pinI2,HIGH);
analogWrite(speedpin,100);
delay(120);
digitalWrite(pinI3,LOW);//使直流电机顺时针转
digitalWrite(pinI4,HIGH);
analogWrite(speedpin1,100);
}
if(digitalRead(Trunright_key)==HIGH)//右转
{
while(digitalRead(Trunright_key)==HIGH);
digitalWrite(Foreward_led,LOW);
digitalWrite(Reverse_led,HIGH);
digitalWrite(Stop_led,HIGH);
digitalWrite(pinI3,LOW);//使直流电机顺时针转
digitalWrite(pinI4,HIGH);
analogWrite(speedpin1,100);
delay(120);
digitalWrite(pinI1,LOW);//使直流电机顺时针转
digitalWrite(pinI2,HIGH);
analogWrite(speedpin,100);
}
}
上一篇:AVR单片机电子抽奖完整项目仿真+源码设计
下一篇:avr单片机读写时钟芯片DS3231程序(通过测试)
推荐阅读最新更新时间:2024-10-25 15:43