Hello! I am trying to move the steering wheel with Arduino and joystick. I receive data with the joystick, but even though I do not get an error when I upload my Arduino code, I cannot use it with the joystick. Is there an error in my code? I'm just trying to understand it. I would be very happy if you could help me.
#include <ros.h>
#include <sensor_msgs/Joy.h>
#include <Stepper.h>
const int stepsPerRevolution = 100; // Number of steps per revolution for your stepper motor
int joy_input = 0; // Variable to store joystick input
Stepper myStepper(stepsPerRevolution, 27, 28, 29, 30); // Stepper motor setup
ros::NodeHandle nh; // Node handle for ROS communication
// Callback function to handle joystick messages
void joyCallback(const sensor_msgs::Joy& joy_msg) {
joy_input = joy_msg.axes[0]; // Reading the X-axis (left-right) joystick input
Serial.println("joy_input");
}
// Function to control the stepper motor based on joystick input
void stepperControl() {
if (joy_input < -0.1) { // If joystick is pushed left
myStepper.step(-stepsPerRevolution); // Rotate left
} else if (joy_input > 0.1) { // If joystick is pushed right
myStepper.step(stepsPerRevolution); // Rotate right
}
}
// Create a subscriber object for the joystick topic
ros::Subscriber<sensor_msgs::Joy> sub("joy", &joyCallback);
void setup() {
myStepper.setSpeed(40); // Set the stepper motor speed (RPM)
nh.initNode(); // Initialize the ROS node
nh.subscribe(sub); // Subscribe to the joystick topic
}
void loop() {
nh.spinOnce(); // Process ROS messages
stepperControl(); // Control the stepper motor based on joystick input
delay(100); // Small delay for smoother control
}