Here is my full reciever code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <ESP32Servo.h>
#define CE_PIN 9
#define CSN_PIN 10
#define ENA_PIN 4
#define IN1_PIN 5
#define IN2_PIN 6
#define SERVO_PIN 7
RF24 radio(CE_PIN, CSN_PIN);
const byte address[6] = "00001";
struct JoystickData {
int throttle;
int steering;
};
JoystickData joyData;
// -------- Servo --------
Servo myServo;
// -------- Motor PWM (ESP32-S3 core v3.x) --------
const int motorChannel = 0; // LEDC kanal
const int motorResolution = 8; // 0-255
const int motorFreq = 20000; // 20 kHz
// -------- Failsafe --------
unsigned long lastPacketTime = 0;
const unsigned long failsafeTimeout = 300; // ms
// -------- Motor control --------
void driveMotor(int throttle) {
const int center = 2048;
const int deadzone = 100;
int diff = throttle - center;
if (abs(diff) <= deadzone) {
digitalWrite(IN1_PIN, LOW);
digitalWrite(IN2_PIN, LOW);
ledcWrite(ENA_PIN, 0);
return;
}
if (diff > 0) {
digitalWrite(IN1_PIN, HIGH);
digitalWrite(IN2_PIN, LOW);
} else {
digitalWrite(IN1_PIN, LOW);
digitalWrite(IN2_PIN, HIGH);
diff = -diff;
}
int speed = map(diff, deadzone, center, 0, 255);
speed = constrain(speed, 0, 255);
ledcWrite(ENA_PIN, speed);
}
// -------- Servo kontrol --------
void updateServo(int steering) {
// Map joystick 0-4095 til servo vinkel 0-180°
int angle = map(steering, 0, 4095, 0, 180);
angle = constrain(angle, 0, 180);
myServo.write(angle);
}
void setup() {
Serial.begin(115200);
// Motor pins
pinMode(IN1_PIN, OUTPUT);
pinMode(IN2_PIN, OUTPUT);
// Motor PWM kanal (ESP32-S3 core v3.x)
ledcAttach(ENA_PIN, motorChannel, motorResolution); // pin, kanal, resolution
ledcWriteTone(motorChannel, motorFreq); // frekvens
// Servo
myServo.attach(SERVO_PIN); // ESP32Servo håndterer PWM
// NRF24
if (!radio.begin()) {
Serial.println("NRF24L01 not detected!");
while (1);
}
radio.openReadingPipe(1, address);
radio.setPALevel(RF24_PA_LOW);
radio.setDataRate(RF24_250KBPS); // mere stabilt
radio.setRetries(5, 15); // 5 gange, 15*250µs delay
radio.startListening();
}
void loop() {
// ---------- Check for new packet ----------
if (radio.available()) {
radio.read(&joyData, sizeof(joyData));
lastPacketTime = millis();
// Motor
driveMotor(joyData.throttle);
// Servo
static unsigned long lastServo = 0;
if (millis() - lastServo > 50) { // opdater servo max hver 50ms
updateServo(joyData.steering);
lastServo = millis();
}
Serial.print("Throttle: ");
Serial.print(joyData.throttle);
Serial.print(" Steering: ");
Serial.println(joyData.steering);
}
// ---------- Failsafe ----------
if (millis() - lastPacketTime > failsafeTimeout) {
// Stop motor
digitalWrite(IN1_PIN, LOW);
digitalWrite(IN2_PIN, LOW);
ledcWrite(ENA_PIN, 0);
// Servo neutral
myServo.write(90); // midtposition
}
}