Arduino and joystick

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
}

Welcome to the forum

Did you mean to say "even though I get no error when I upload my Arduino code" ?

If you do get an error then please post it here in full

Please post a schematic of your project showing the details of its components, how they are interconnected and how the project is powered

@UKHeliBob
Sorry. I want to say "I do not get an error". I just wondering İf there is a mistake on my code , how to solve it

What should happen when you run the sketch ?
What actually happens when you run the sketch ?

Please post the schematic of your project

Provide the link to these libraries.

I did. I don't get error from this. Actually I don't get any error

first of all, I installed ros bridge. I run the joy package with galactic and get data with topic using noetic. then I upload the arduino code. My goal is to move the wheels of a vehicle. And I do this step by step at the very beginning. I started by writing a simple code that controls the steering with a stepper motor. But it does not work


This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.