I have a python code that sends strings like "1,1,20,1" where the first value is the motor selection, the second is the speed, then the steps and finally the direction.
I have tried to move the motors independently with arduino with the following code, the problem is that the speed does not change, for example I send the string "1,1,20,1", then "2,5,80,1", it starts with motor 1 moving at speed 1 and when I enter the second string, motor 2 starts to move but it is not until the steps of 1 are finished that it starts to move at speed 5.
#include <Stepper.h>// Define the number of steps per revolution for the stepper motorsconst int stepsPerRevolution = 200;// Initialize two instances of the Stepper class for two stepper motorsStepper motor1(stepsPerRevolution, 8, 9, 10, 11); // Motor 1Stepper motor2(stepsPerRevolution, 4, 5, 6, 7); // Motor 2// Define a struct to represent a sequence for each motorstruct Sequence { int motorId; // Motor identifier (1 or 2) int position; // Current position of the motor int targetPosition; // Target position for the motor to reach int speed; // Speed of the motor int direction; // Direction of movement (-1 or 1) bool active; // Flag indicating if the sequence is active};// Create an array to hold sequences for both motorsSequence sequences[2]; // Setup function runs once at the start of the programvoid setup() { // Initialize serial communication with a baud rate of 9600 Serial.begin(9600); // Initialize sequences array, setting all sequences to inactive for (int i = 0; i < 2; ++i) { sequences[i].active = false; }}// Function to update the sequence for a motorvoid updateSequence(Sequence &seq, Stepper &motor) { // Check if the sequence is active if (seq.active) { // Set the speed of the motor motor.setSpeed(seq.speed); // Move the motor one step in the specified direction motor.step(seq.direction); // Update the motor's position seq.position += seq.direction; // Check if the motor has reached its target position if (seq.position == seq.targetPosition) { // Deactivate the sequence if the target position is reached seq.active = false; } }}// Loop function continuously runs after setupvoid loop() { // Check if there is enough data available in the serial buffer if (Serial.available() >= 5) { // Read motor ID, speed, steps, and direction from the serial buffer char motorId = Serial.read(); int vel = Serial.parseInt(); int steps = Serial.parseInt(); int dir = Serial.parseInt(); Serial.read(); // Read and discard the newline character // Find an inactive sequence for (int i = 0; i < 2; ++i) { if (!sequences[i].active) { // Start the new sequence sequences[i].motorId = (motorId == '1') ? 1 : 2; sequences[i].position = 0; sequences[i].targetPosition = steps; sequences[i].speed = vel; sequences[i].direction = dir; sequences[i].active = true; break; } } } // Update sequences for both motors updateSequence(sequences[0], motor1); updateSequence(sequences[1], motor2);}