电路板装进去,将电机插头插到板子上,到这里所有的结构搭建以及硬件电路都连接好了,下面就是给气垫船注入灵魂——编写代码了!
程序的编写
其实控制程序非常简单,首先说接受端,其实就是将无线模块接收到的数据转换成对应引脚输出的PWM占空比来控制电机的转速。于是一段时间过后,我编好了接受端的代码。[mw_shl_code=arduino,true]//接收端程序
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
unsigned int value;
unsigned int CH1,CH3,left,right,qi;
void setup()
{
Serial.begin(9600);
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setRADDR((byte *)"FGHIJ"); //设置自己的地址(接收端地址),使用5个字符
Mirf.payload = sizeof(value);
Mirf.channel = 90; //设置使用的信道
Mirf.config();
Serial.println("Listening..."); //开始监听接收到的数据
pinMode(10,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(3,OUTPUT);
pinMode(9,OUTPUT);
digitalWrite(5,0);
digitalWrite(6,0);
digitalWrite(9,0);
digitalWrite(3,0);
digitalWrite(10,0);
}
void loop()
{
if(Mirf.dataReady()) { //当接收到程序,便从串口输出接收到的数据
Mirf.getData((byte *) &value);
CH3=(unsigned int)value&255;
CH1=(unsigned int)value>>8;
if(CH1>140)
{
qi=CH1;
if(CH3>135) //左转弯
{
right=CH1;
if(CH1<CH3)
left=0;
else
left=CH1-CH3/3.5;
}
else if(CH3<120) //右转弯
{
if(CH1<(255-CH3))
right=0;
else
right=CH1-((255-CH3)/3.5);
left=CH1;
}
else
{
right=CH1;
left=CH1;
}
}
else
{
left=0;
right=0;
qi=0;
}
analogWrite(3,left);
analogWrite(9,right);
analogWrite(10,qi);
Serial.print("Got data: ");
Serial.print(CH1);
Serial.print(" ");
Serial.print(CH3);
Serial.print(" ");
Serial.print(left);
Serial.print(" ");
Serial.println(right);
}
}
[/mw_shl_code]
发送端也是很简单,我使用摇杆作为控制杆,用arduino的ADC引脚读取摇杆输出的电压来获得当前的摇杆位置,然后将摇杆位置的数据通过无线模块发送出去。
[mw_shl_code=arduino,true]//发射端程序
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
unsigned int value,value1;
unsigned int data;
unsigned int CH1,CH3;
void setup()
{
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setRADDR((byte *)"ABCDE"); //设置自己的地址(发送端地址),使用5个字符
Mirf.payload = sizeof(value);
Mirf.channel = 90; //设置所用信道
Mirf.config();
Serial.begin(9600);
}
void loop()
{
Mirf.setTADDR((byte *)"FGHIJ"); //设置接收端地址
value = analogRead(1); //0-255的随机数
value1 = analogRead(6);
CH1=value/4;
CH3=value1/4;
data=((unsigned int)(CH1<<8)+CH3);
Serial.print(CH1);
Serial.print(" ");
Serial.print(CH3);
Serial.print(" ");
Serial.println(data);
//Serial.println(value1);
Mirf.send((byte *)&data); //发送指令,发送随机数value
while(Mirf.isSending()) delay(1); //直到发送成功,退出循环
delay(10);
}
[/mw_shl_code]
下载程序到气垫船和遥控器中: