I am very new to this thing and the resources that i got from the internet i only got how to control a servo or 2 motors. But I would want to know how to integrate these two together.
*need help as soon as possible as it is for my project
Please let me know it he code is correct.
The below code is for the receiving end.
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10); // NRF24L01 pins
// Motor A
int enA = 3;
int in1 = 4;
int in2 = 5;
// Motor B
int enB = 6;
int in3 = 7;
int in4 = 8;
// Servo
int servoPin = 11;
int servoAngle = 90;
void setup() {
// Motor pins setup
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
// Servo setup
pinMode(servoPin, OUTPUT);
// NRF24L01 setup
radio.begin();
radio.openReadingPipe(1, 0xF0F0F0F0E1LL); // Address of the receiver
radio.setPALevel(RF24_PA_HIGH);
radio.startListening();
}
void loop() {
if (radio.available()) {
int joystickValues[4];
radio.read(&joystickValues, sizeof(joystickValues));
// Motor A control
int motorA_speed = map(joystickValues[1], 0, 1023, -255, 255);
if (motorA_speed > 0) {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
} else if (motorA_speed < 0) {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
motorA_speed = -motorA_speed;
} else {
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}
analogWrite(enA, motorA_speed);
// Motor B control
int motorB_speed = map(joystickValues[3], 0, 1023, -255, 255);
if (motorB_speed > 0) {
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
} else if (motorB_speed < 0) {
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
motorB_speed = -motorB_speed;
} else {
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
}
analogWrite(enB, motorB_speed);
// Servo control
int servoAngle = map(joystickValues[2], 0, 1023, 0, 180);
if (servoAngle != servoAngle) {
servoAngle = servoAngle;
if (servoAngle < 0) {
servoAngle = 0;
} else if (servoAngle > 180) {
servoAngle = 180;
}
servoAngle = servoAngle;
digitalWrite(servoPin, HIGH);
delayMicroseconds(500 + servoAngle * 2000 / 180);
digitalWrite(servoPin, LOW);
delay(20 - servoAngle * 20 / 180);
}
}
}
The below code is for the transmitting end .
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10); // NRF24L01 pins
// Joystick pins
int joystick1X = A0;
int joystick1Y = A1;
int joystick2X = A2;
int joystick2Y = A3;
void setup() {
// NRF24L01 setup
radio.begin();
radio.openWritingPipe(0xF0F0F0F0E1LL); // Address of the receiver
radio.setPALevel(RF24_PA_HIGH);
}
void loop() {
int joystick1XValue = analogRead(joystick1X);
int joystick1YValue = analogRead(joystick1Y);
int joystick2XValue = analogRead(joystick2X);
int joystick2YValue = analogRead(joystick2Y);
int joystickValues[4] = {joystick1XValue, joystick1YValue, joystick2XValue, joystick2YValue};
radio.write(&joystickValues, sizeof(joystickValues));
delay(10);
}