#define uchar unsigned char
#define uint unsigned int
unsigned char front; //小车前后走的标志位
/***************一毫秒的延时*****************/
void delay(uint i)
{
unsigned int a, b;
for (a = 1; a < i; a++)
{
for (b = 1; b<1141; b++)
{
;
}
}
}
/*******************小车向前向后函数************************/
void go(uchar speed)
{
OCR1A=speed;
OCR1B=speed;
if(front==1)//如果FRONT为一,小车向前
{
PORTD&=~BIT(PD0);PORTD&=~BIT(PD1);PORTD|=BIT(PD6);PORTD|=BIT(PD7);
}
else
{
PORTD&=~BIT(PD6);PORTD&=~BIT(PD7);PORTD|=BIT(PD0);PORTD|=BIT(PD1);
OCR1B=1;OCR1A=150;
}
}
/**********************小车向左向右的函数************************/
void l_r(uchar p)
{
switch(p)
{
case 'r' :
{PORTD&=~BIT(PD0);PORTD&=~BIT(PD1);PORTD|=BIT(PD6);PORTD|=BIT(PD7);
OCR1A=145;OCR1B=1;break;}
case 'l' :
{PORTD&=~BIT(PD0);PORTD&=~BIT(PD1);PORTD|=BIT(PD6);PORTD|=BIT(PD7);
OCR1A=1;OCR1B=145; break;}
}
}
/************************用查询法完成四路的单通道AD采样*******************/
uint mega16_ad1()
{
uint addata1;
DDRA&=~BIT(PA0);
PORTA&=~BIT(PA0);/*端口设置*/
ADMUX=0B11000000;/*选择ADC通道0*/
ACSR=0x80;/*关模拟比较器*/
ADCSRA=0X86;/*ADC使能*/
ADCSRA|=BIT(ADSC);/*开始转换*/
while(!(ADCSRA&(BIT(ADIF)))); /*等转换完成*/
addata1=ADCL;
addata1=addata1+ADCH*256;/*接收数据*/
ADCSRA&=~BIT(ADIF); /*清标志*/
ADCSRA&=~BIT(ADEN); /*关闭转换*/
return addata1;
}
uint mega16_ad2()
{
uint addata2;
DDRA&=~BIT(PA2);
PORTA&=~BIT(PA2);
ADMUX=0B11000010;
ACSR=0x80;
ADCSRA=0X86;
ADCSRA|=BIT(ADSC);
while(!(ADCSRA&(BIT(ADIF))));
addata2=ADCL;
addata2=addata2+ADCH*256;
ADCSRA&=~BIT(ADIF);
ADCSRA&=~BIT(ADEN);
return addata2;
}
uint mega16_ad3()
{
uint addata3;
DDRA&=~BIT(PA4);
PORTA&=~BIT(PA4);
ADMUX=0B11000100;
ACSR=0x80;
ADCSRA=0X86;
ADCSRA|=BIT(ADSC);
while(!(ADCSRA&(BIT(ADIF))));
addata3=ADCL;
addata3=addata3+ADCH*256;
ADCSRA&=~BIT(ADIF);
ADCSRA&=~BIT(ADEN);
return addata3;
}
uint mega16_ad4()
{
uint addata4;
DDRA&=~BIT(PA6);
PORTA&=~BIT(PA6);
ADMUX=0B11000110;
ACSR=0x80;
ADCSRA=0X86;
ADCSRA|=BIT(ADSC);
while(!(ADCSRA&(BIT(ADIF))));
addata4=ADCL;
addata4=addata4+ADCH*256;
ADCSRA&=~BIT(ADIF);
ADCSRA&=~BIT(ADEN);
return addata4;
}
void main()
{
DDRB = 0xFF;
PORTB = 0x00;
DDRC = 0xFF;
PORTC = 0x00;
DDRD = 0xFF;
PORTD = 0xFF;/*端口设置*/
TCCR1A=0xA1;
TCCR1B=0x03;/*8位相位修正PWM,64分频*/
TCNT1H=0xFF;
TCNT1L=0XFF;
while(1)
{
uint ad1,ad2,ad3,ad4,i,max,selectad=0;
for(i=0;i<4;i++)/*四路AD采样过程*/
{
switch(selectad)
{
case 0:
ad1=mega16_ad1();selectad++;break;
case 1:
ad2=mega16_ad2();selectad++;break;
case 2:
ad3=mega16_ad3();selectad++;break;
case 3:
ad4=mega16_ad4();selectad++;break;
}
}
/*四路AD采样结果比较*/
max=ad1;
if(max
if(max==ad1)
{front=1;go(80); delay(100);}
else if(max==ad2)
{ l_r('r');delay(100);}
else if(max==ad3)
{ l_r('l');delay(100);}
else if(max==ad4)
{front=0;go(120);delay(200);}
}
}