Hello All,
I am having problems coding a sketch to take serial data from matlab (the number of steps to move the stepper motor, speed..) and send that to my Arduino Uno, using accelstepper libraries. I have plugged in an LED and resistor from one of the output pins on the arduino to monitor the trigger signals which would be sent to the motor shield.
Below is my Arduino Code:
#include <AccelStepper.h>
int matlab_command_steps;
// Define a stepper and the pins it will use
AccelStepper stepper; // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5
void setup()
{
Serial.begin(9600);
Serial.flush();
stepper.setMaxSpeed(5);
stepper.setAcceleration(3);
}
void loop()
{
while (Serial.available() == 0)
{};
if (Serial.available() > 0)
{
matlab_command_steps = Serial.read(); // read data from matlab
}
stepper.moveTo(20); //I would like matlab step input to go here
while (stepper.currentPosition() != 20)
stepper.run();
stepper.stop();
}
Here is my Matlab Code:
clear all
clc
arduino=serial('COM5','BaudRate',9600); % create serial communication object on port COM5
fopen(arduino); % initiate arduino communication
answer_steps=input('Enter number of steps to rotate: '); % ask user to enter steps
fwrite(arduino, answer_steps, 'uint8', 'sync'); % send steps variable content to arduino
fclose(arduino); % end communication with arduino
If I remove all the Serial. commands from my Arduino code and simple have the board loop with motor instructions, my LED blinks 5 times which is expected. If I try to input data and then run the motor commands, even if they are just set integers, the LED only turns on once. If someone could point out my errors I'd be so happy - I've searched for a long time and I can't figure it out. Thanks,
Darren