简介:
在本篇文章中,我们主要介绍如何使用NRF24L01和Arduino控制舵机。我们在发送端移动操纵杆,使用NRF24L01,将操纵杆移动的值发送到接收侧,然后在接收侧接收该值,使用此值移动舵机。
材料清单:
● Arduino开发板
● NRF24L01模块
● 操纵杆模块
● 舵机一个
● 连接导线

伺服电机控制如何工作
在发送侧,我们有一个操纵杆模块、Arduino和NRF24L01,而在接收侧,我们有一个NRF24L01、Arduino和一个伺服电机。
当我们在水平方向上移动操纵杆时,操纵杆模块将向Arduino发送模拟值。我们已将NRF24L01模块设置为发送模式,并将操纵杆移动值发送到特定地址。
在接收侧,将NRF24L01模块设置为接收模式。我们在接收端给出了相同的地址,其他NRF24L01模块正在传输数据。因此,只要模块接收到数据,Arduino就会读取数据并根据它移动伺服电机。

NRF24L01引脚说明
该模块的功耗非常低。它在传输过程中消耗大约12mA的功率,甚至低于LED。
该模块工作在3.3V,因此不要将其直接连接到5V的Arduino,因为它可能会损坏。 NRF24L01模块的其他引脚具有5V容限,因此您可以将它们直接连接到Arduino。
SCK、MOSI和MISO引脚用于SPI通信,CSN和CE引脚用于设置待机或活动模式以及设置发送或命令模式。

电路原理图
连接有点冗长,因此我将分别介绍发送器和接收器的连接。
在发送器侧,NRF24L01与Arduino的连接如下:
● 3.3V引脚与3.3V连接
● GND引脚与GND连接
● CSN引脚与引脚8连接
● CE引脚与引脚7连接
● SCK引脚与引脚13连接
● MOSI引脚与引脚11连接
● MISO引脚与引脚12连接
然后将操纵杆模块与Arduino连接如下:
● 操纵杆模块的VCC到Arduino的5V
● 操纵杆模块的GND到Arduino的GND
● 操纵杆模块的VER到Arduino的A1
● 操纵杆模块的HOR到Arduino的A0
在接收器侧,NRF24L01与Arduino的连接与发送器侧的连接相同。使用Arduino连接伺服电机如下:
● 红线到Arduino的5V
● 棕色线到Arduino的GND
● 黄色线到Arduino的引脚6

代码介绍
首先,包括NRF24L01和伺服电机的库
#include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #include <Servo.h>
然后,定义我们连接NRF24L01的CSN和CE引脚的引脚。之后,我们初始化将发送和接收数据的地址。该地址在发射机和接收机侧应该相同。该地址可以是任何五个字母的字符串。
RF24 radio(7, 8); // ce, Csn const byte address[6] = "00001";
在发送器的setup()函数中,我们设置了发送数据的地址。然后将功率放大范围设置为最小,因为模块彼此很接近。
radio.openWritingPipe(address); radio.setPALevel(RF24_PA_MIN);
在接收器侧,我们使用以下命令并设置模块以从该地址接收数据。
radio.openReadingPipe(0, address);
在发送器的loop()函数中,我们从操纵杆模块读取并在我们之前设置的地址发送值。
radio.write(&x_pos, sizeof(x_pos));
接收器侧的以下命令将从发送器获取数据,并且在将数据映射到0-180之后,我们将移动伺服电机。
radio.read(&x_pos, sizeof(x_pos));
发射端代码:
#include <SPI.h> #include <nRF24L01.h> #include <RF24.h> RF24 radio(7, 8); // CSN, CE const byte address[6] = "00001"; int x_key = A1; int y_key = A0; int x_pos; int y_pos; void setup() { radio.begin(); radio.openWritingPipe(address); radio.setPALevel(RF24_PA_MIN); radio.stopListening(); pinMode (x_key, INPUT) ; pinMode (y_key, INPUT) ; } void loop() { x_pos = analogRead (x_key) ; y_pos = analogRead (y_key) ; radio.write(&x_pos, sizeof(x_pos)); delay(100); }
接收端代码:
#include <SPI.h> #include <nRF24L01.h> #include <RF24.h> #include <Servo.h> Servo servo; RF24 radio(7, 8); // CSN, CE const byte address[6] = "00001"; int servo_pin = 6; void setup() { Serial.begin(9600); radio.begin(); servo.attach (servo_pin ) ; radio.openReadingPipe(0, address); radio.setPALevel(RF24_PA_MIN); radio.startListening(); } void loop() { if (radio.available()) { int x_pos ; radio.read(&x_pos, sizeof(x_pos)); Serial.println(x_pos); x_pos = map(x_pos, 0, 1023, 0, 180); if (x_pos>400 && x_pos<600) { } else{ servo.write (x_pos) ; } } }