I am trying to control stepper motor via serial-port with c# winform app.
In my code i am generating real-time data with timer whose time interval is 30 ms. Generated data is 8 bits pixel number.
Baudrate is 250000. StepsPerRevolution is 240.
The code i use is for sending data to arduino is as given below. I am also using label to see pixel numbers and their difference.
private void SendDataToArduino()
{
int stepsperrpm = 360/240;
if (serialPort1.IsOpen)
{
if (currentPix <= previousPix)
{
serialPort1.Write("C," + Convert.ToString(stepsperrpm * (previousPix - currentPix)) + "," + Convert.ToString(25) + "\r\n");
}
else if (currentPix > previousPix)
{
serialPort1.Write("W," + Convert.ToString(stepsperrpm * (currentPix - previousPix)) + "," + Convert.ToString(25) + "\r\n");
}
}
}
The arduino code i am using is:
#include <Stepper.h>
int stepsPerRevolution = 12800; //12800;
Stepper stepper1 = Stepper(stepsPerRevolution, 2,3,4,5);//,3,7,8);
String data[3];
int index = 0;
float steps = 0.0;
void setup() {
stepper1.setSpeed(10);
Serial.begin(250000);
}
void loop() {
if (Serial.available()) {
data[index] = Serial.readStringUntil(',');
Serial.print("data read: "); Serial.println(data[index]);
index++;
if (index == 3) {
index = 0;
steps = stepsPerRevolution / 360.0 * data[1].toInt();
stepper1.setSpeed(data[2].toInt());
if (data[0] == "C") stepper1.step(steps);
else if (data[0] == "W") stepper1.step(-steps);
}
}
}
What is wrong with sending data to arduino from serial port? Stepper does not move at all or sometimes only rotates in one direction then stops.
In addition C# winform app is also freezing in time.I am sure that i am getting pixel numbers correctly as i show in picture.
I tried using serialPort.Write(), serialPort.WriteLine() and adding \r\n and of thecode to be sure that arduino receive the data correctly. But i am not able to be successed.