CCCPaste

NRFL01_RC CAR_transmitter_ESP32C3

//PROGRAM BY: RANDY N. CAÑADA (NOV. 2025)

//CONNECTIONS
/*CE_PIN 7
CSN_PIN 10
SCK_PIN 4
MOSI_PIN 6
MISO_PIN 5
GND-GND
VCC-5Vdc/3.3vdc

JOYSTICKS:
VRX = A1
VRY= A0
gnd-grnd
vcc-vcc

note: when you are using breakout board for nrfl01, you can supply 5vdc. If not use 3.3vdc
*/
#include <SPI.h>
#include <RF24.h>

#define CE_PIN 7
#define CSN_PIN 10

#define joyVert A0 // VRy → forward/backward
#define joyHorz A1 // VRx → turning

RF24 radio(CE_PIN, CSN_PIN);
const byte address[6] = "00001";

struct Data_Package {
int8_t motorLeft;
int8_t motorRight;
};

Data_Package data;

int centerVert = 0;
int centerHorz = 0;

void setup() {
Serial.begin(115200);
pinMode(joyVert, INPUT);
pinMode(joyHorz, INPUT);

SPI.begin();
//SPI.begin(4, 5, 6); // SCK, MISO, MOSI


if (!radio.begin()) {
Serial.println("NRF24 not responding!");
while (1);
}

radio.openWritingPipe(address);
radio.setChannel(100);
radio.setPALevel(RF24_PA_LOW);
radio.setDataRate(RF24_250KBPS);
radio.stopListening();

// Calibrate joystick center
Serial.println("Calibrating joystick, keep it untouched...");
delay(2000);
centerVert = analogRead(joyVert);
centerHorz = analogRead(joyHorz);
Serial.print("Center Vert: "); Serial.print(centerVert);
Serial.print(" Center Horz: "); Serial.println(centerHorz);
Serial.println("Calibration done!");
}

void loop() {
int deadZone = 30;

int joyV_raw = analogRead(joyVert) - centerVert;
int joyH_raw = analogRead(joyHorz) - centerHorz;

int joyV = 0;
int joyH = 0;

// Map Vertical (forward/backward)
if (abs(joyV_raw) > deadZone) {
joyV = map(joyV_raw, -512, 512, -127, 127);
}

// Map Horizontal (turning)
if (abs(joyH_raw) > deadZone) {
joyH = map(joyH_raw, -512, 512, -127, 127);
}

// Combine for motor speeds
int MotorLeft = joyV + joyH;
int MotorRight = joyV - joyH;

MotorLeft = constrain(MotorLeft, -127, 127);
MotorRight = constrain(MotorRight, -127, 127);

if (abs(MotorLeft) < 5) MotorLeft = 0;
if (abs(MotorRight) < 5) MotorRight = 0;

data.motorLeft = MotorLeft;
data.motorRight = MotorRight;

radio.write(&data, sizeof(Data_Package));

Serial.print("joyV_raw: "); Serial.print(joyV_raw);
Serial.print(" joyH_raw: "); Serial.print(joyH_raw);
Serial.print(" MotorLeft: "); Serial.print(MotorLeft);
Serial.print(" MotorRight: "); Serial.println(MotorRight);

delay(100);
}