i made schematics, i hope that they are good enough because there is quit alot going on.
transmitter:
in this photo you can see the joystick pins:
receiver:
code transmitter:
#include <SPI.h>
#include <RF24.h>
#include <nRF24L01.h>
#define CE_PIN 7
#define CSN_PIN 6
RF24 radio(CE_PIN, CSN_PIN);
const byte pipeName[] = "00001";
const byte joystickPins[] = {A7, A2, A3, A5};
const byte joysticksCount = sizeof joystickPins / sizeof * joystickPins;
struct __attribute__ ((packed)) t_message {
int16_t rawValues[joysticksCount];
} payload, previousPayload;
void setup() {
pinMode(10, OUTPUT);
radio.begin();
Serial.begin(9600);
radio.openWritingPipe(pipeName);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();
}
void loop() {
// read the joysticks
for (byte i = 0; i < joysticksCount; i++) {
payload.rawValues[i] = analogRead(joystickPins[i]);
payload.rawValues[i] = analogRead(joystickPins[i]) & 0xFFFD; // two reads for stability, dropping the 2 LSb to filter out instability
}
// broadcast the data if it has changed
if (memcmp(&payload, &previousPayload, sizeof(t_message)) != 0) { // returns 0 when they match, https://cplusplus.com/reference/cstring/memcmp/
radio.write(&payload, sizeof(payload));
previousPayload = payload;
}
}
receiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Servo.h>
#define CE_PIN 49
#define CSN_PIN 48
RF24 radio(CE_PIN, CSN_PIN);
const byte pipeName[] = "00001";
const byte servoPins[] = {2, 5, 4, 3};
const byte servosCount = sizeof servoPins / sizeof * servoPins;
const int initialPositions[servosCount] = {90, 90, 90, 8};
const int mappedRanges[servosCount][2] = {{80, 100}, {65, 115}, {65, 115}, {80, 88}};
Servo servos[servosCount];
struct __attribute__ ((packed)) t_message {
int16_t rawValues[servosCount];
} payload;
uint8_t messageBuffer[sizeof(t_message)];
void setup() {
pinMode(10, OUTPUT);
for (byte i = 0; i < servosCount; i++) {
servos[i].write(initialPositions[i]); //set starting positions
servos[i].attach(servoPins[i]);
}
// Serial
Serial.begin(9600);
//radio
radio.begin();
radio.openReadingPipe(0, pipeName);
radio.setPALevel(RF24_PA_MIN);
radio.startListening();
}
void loop() {
if (radio.available()) {
radio.read(messageBuffer, sizeof messageBuffer);
memcpy(&payload, messageBuffer, sizeof payload);
Serial.print(F("New positions: "));
for (byte i = 0; i < servosCount; i++) {
int angle = map(payload.rawValues[i], 0, 1023, mappedRanges[i][0], mappedRanges[i][1]);
Serial.print(angle); Serial.write('\t');
servos[i].write(angle); //set starting positions
}
Serial.println();
}
}