我用433MHz无线模块做了无线遥控小车,可是遥控的数据传输却出现了问题,遥控器发送数据后,另一块板子总是过一会才会接收导数据,导致了车子不好控制,我把代码列出来,希望大神们帮我。
这是遥控器的代码:
[mw_shl_code=cpp,true]#include <RCSwitch.h>
int X=0;
int Y=1;
RCSwitch mySwitch = RCSwitch();
void setup() {
Serial.begin(9600);
mySwitch.enableTransmit(11);
}
void loop() {
X=analogRead(0);
Y=analogRead(1)/2;
Serial.print( "X:" );
Serial.print( X );
Serial.println();
Serial.print( "Y:" );
Serial.println( Y );
int K=X+Y;
Serial.print("K");
Serial.println(K);
mySwitch.send(K,24);
}
[/mw_shl_code]
这是接收板即车子上的代码:
[mw_shl_code=cpp,true]#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
void stop();
void forward();
void back();
void left();
void right();
void forward()
{
analogWrite(4 , HIGH);
analogWrite(5 , HIGH);
digitalWrite( 6 , HIGH );
digitalWrite( 7 , LOW );
digitalWrite( 8 , HIGH );
digitalWrite( 9 , LOW );
}
void right()
{
digitalWrite( 4 , HIGH );
digitalWrite( 5 ,HIGH );
digitalWrite( 6 , HIGH );
digitalWrite( 7 , LOW );
digitalWrite( 9 , HIGH );
digitalWrite( 8 , LOW );
}
void stop()
{
digitalWrite( 6 , LOW );
digitalWrite( 7 , LOW );
digitalWrite( 8 , LOW );
digitalWrite( 9 , LOW );
}
void back()
{
analogWrite(4 , HIGH);
analogWrite(5 , HIGH);
digitalWrite( 7 , HIGH );
digitalWrite( 6 , LOW );
digitalWrite( 9 , HIGH );
digitalWrite( 8 , LOW );
}
void left()
{
digitalWrite( 5 , HIGH );
digitalWrite( 4 , HIGH );
digitalWrite( 8 , HIGH );
digitalWrite( 9 , LOW );
digitalWrite( 7 , HIGH );
digitalWrite( 6 , LOW );
}
void setup()
{
Serial.begin(9600);
mySwitch.enableReceive(0);
pinMode( 4 , OUTPUT);
pinMode( 5 , OUTPUT);
pinMode( 6 , OUTPUT);
pinMode( 7 , OUTPUT);
pinMode( 8 , OUTPUT);
pinMode( 9 , OUTPUT);
}
void loop()
{
if (mySwitch.available()) {
int J = mySwitch.getReceivedValue();
Serial.println(J);
if (( ( J ) > ( 1250) ))
{
forward();
}
else
{ stop();
if (( ( J ) ==( 526 ) ))
{
left();
}
else
{
stop();
if (( ( J ) == ( 1037) ))
{
right();
}
else
{
stop();
if (( (J ) <( 270 ) ))
{
back();
}
else
{
stop();
}
}
}
}
mySwitch.resetAvailable();
}}
[/mw_shl_code]
请求大神们给建议,看看代码。。
|