Hello Everybody , I use the NEC announce infrared remote control intelligent vehicles, a serial port is normal, but the motor won't work, the following is my code, bother everybody to help see, where wrong, thank you!
#define LED_RED 7
#define IR_IN 8
int Pulse_Width=0;
int ir_code=0x00;
uint8_t i;
#include <AFMotor.h>
AF_DCMotor motor1(1,MOTOR12_64KHZ);
AF_DCMotor motor2(4,MOTOR12_64KHZ);
AF_DCMotor motor3(3,MOTOR12_64KHZ);
AF_DCMotor motor4(2,MOTOR12_64KHZ);
void timer1_init(void)
{
TCCR1A=0X00;
TCCR1B=0X05;
TCCR1C=0X00;
TCNT1=0X00;
TIMSK1=0X00;
}
void remote_deal(void)
{
switch(ir_code)
{
case 0xff00:
Serial.print("tick");
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
i=255;
motor1.setSpeed(i);
motor2.setSpeed(i);
motor3.setSpeed(i);
motor4.setSpeed(i);
break;
case 0xfe01:
Serial.print("tock");
motor1.run(BACKWARD);
motor2.run(BACKWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
i=255;
motor1.setSpeed(i);
motor2.setSpeed(i);
motor3.setSpeed(i);
motor4.setSpeed(i);
delay(3000);
break;
}
}
char logic_value()
{
while(!(digitalRead(8)));
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=7&&Pulse_Width<=10)
{
while(digitalRead(8));
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=7&&Pulse_Width<=10)
return 0;
else if(Pulse_Width>25&&Pulse_Width<=27)
return 1;
}
return -1;
}
void pulse_deal()
{
int i;
for(i=0;i<8;i++)
{
if(logic_value()!=0)
return;
}
for(i=0;i<6;i++)
{
if(logic_value()!=1)
return;
}
if(logic_value()!=0)
return;
if(logic_value()!=1)
return;
ir_code=0x00;
for(i=0;i<16;i++)
{
if(logic_value()==1)
{
ir_code|=(1<<i);
}
}
}
void remote_decode(void)
{
TCNT1=0X00;
while(digitalRead(8))
{
if(TCNT1>=1563)
{
ir_code=0xff00;
return;
}
}
TCNT1=0X00;
while(!(digitalRead(8)));
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=140&&Pulse_Width<=141)
{
while(digitalRead(8));
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=68&&Pulse_Width<=72)
{
pulse_deal();
return;
}
else if(Pulse_Width>=34&&Pulse_Width<=36)
{
while(!(digitalRead(8)));
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=7&&Pulse_Width<=10)
{
return;
}
}
}
}
void setup()
{
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("Motor test!");
// turn on motor
motor1.setSpeed(255);
motor2.setSpeed(255);
motor3.setSpeed(255);
motor4.setSpeed(255);
motor1.run(RELEASE);
motor2.run(RELEASE);
motor3.run(RELEASE);
motor4.run(RELEASE);
unsigned char i;
pinMode(LED_RED,OUTPUT);
pinMode(IR_IN,INPUT);
}
void loop()
{
timer1_init();
while(1)
{
remote_decode();
remote_deal();
}
}