Problem with Nema 23 motor's behaviour while using function "slave.run()"

Hi, I am doing a project using Arduino Uno. here is the code

#include <modbus.h>
#include <modbusDevice.h>
#include <modbusRegBank.h>
#include <modbusSlave.h>
modbusDevice regBank;
modbusSlave slave;

#define RS485TxEnablePin 2
#define RS485Baud 9600
#define RS485Format SERIAL_8E1

// Nema 23 
#include <AccelStepper.h>
AccelStepper stepper (AccelStepper::DRIVER, 9,8); 
int Speed = -1500;

// Vacuum Motor 
#define RPWM 5
#define LPWM 6
int Vacuumspeed = 150;

// seed counting
int A_V;
int seedcount=0;
int missing=0;
int flag=0;

void setup()
{ 
 //Assign the modbus device ID.  
 regBank.setId(1);

 //Add Analog Input registers to the register bank
 regBank.add(30001);  //Singulation
 regBank.add(30002);  //Seed Counted
 regBank.add(30003);  //Seed Missed
 regBank.add(30004);  //Seed doubled
 regBank.add(30005);  //seed to seed distance
 regBank.add(30007);  //Vacuum speed
 regBank.add(30009);  //Nema RPM
 
 slave._device = &regBank;  
 slave.setBaud(&Serial,RS485Baud,RS485Format,RS485TxEnablePin);   

 // Vacuum 
 pinMode(RPWM, OUTPUT);
 pinMode(LPWM, OUTPUT);
 analogWrite(LPWM, 0);

 //Nema 
 stepper.setMaxSpeed(1000);
 stepper.setSpeed(Speed);	
}

void loop()
{ 
  analogWrite(RPWM, Vacuumspeed); //vacuum 
  stepper.runSpeed(); //nema  
  //Seed
  A_V = analogRead(A0);
  //Serial.println(A_V);

  if (A_V >=30 && flag == 0) 
   {
      seedcount = seedcount+1;
      flag=1; 
      //Serial.println(seedcount);
    }

  else if (A_V < 15 && flag == 1)
    {
     flag = 0;
    }

  regBank.set(30002, (int) seedcount);
  regBank.set(30009, (int) Speed);
  regBank.set(30007, (int) Vacuumspeed); //from 0 - 1023
  slave.run();  
}


I am displaying the above values on Weintek HMI. when I comment out the "slave.run()" function, Nema 17 motor works smoothly. as soon as I run this function for Arduino's communication with HMI, Nema 23 stepper motor starts Jitter. Most probably due to the disturbance in steps delay. I need help resolving that issue. I already utilize the millis() phenomena but it does not work in this case. I am a beginner in programming and really need your help.
regards

It seems that you use the arduino-modbus-slave library. I would not recommend to use that library on AVR Arduinos as it uses malloc()/free() extensively which isn't recommended on MCU which that low on memory. It also does this on a global variable which leads to rather confusing code and might end in memory leaks.

Your problem arises because that library actively waiting (by delay()) for serial data to arrive. It waits 2.5ms for each character to arrive. If the motor assumes a high frequent response, this will heavily disturb it.

I recommend to change to the library of smarmengol for the Modbus slave functionality. It shouldn't show the same behavior.

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