I have successfully been able to send values as in my code below.
Note:
fwrite send values as characters themselves so if i try to send "hello" it will send data through the serial port as
- h
- e
- l
- l
- o
whereas if you send values through the fprintf function as string type the same "hello" would be sent as
- h
- e
- l
- l
- o
- \n
thus an extra character would be sent to indicate the end of the sent ASCI values
Find Below my code on arduino and MATLAB
MATLAB
clear
s=serial('COM6','BaudRate',9600); %note your port and bitrate
fopen(s);
text=fscanf(s);
fprintf(s,"2200"); %firsrt character for motor number and 2-4 character number the number of steps
pause(5);
fclose(s);
Arduino
#include <AFMotor.h>
AF_Stepper m1(200, 1);
AF_Stepper m2(200, 2);
char data[4];
byte numByteAvailable;
String Steps = "";
int val = 0;
int steps;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
m1.setSpeed(10);
m2.setSpeed(10);
char a = 'b';
//Serial.println(" hello world ");
}
void loop() {
// put your main code here, to run repeatedly:
delay(100);
byte numByteAvailable = Serial.available();
//delay(100);
char garbage;
if (numByteAvailable > 1) {
//Serial.println("start");
int i;
for (i = 0; i < numByteAvailable-1; ++i) {
char raw = Serial.read();
data[i] = raw;
Serial.println(raw);
}
garbage = Serial.read();
//Serial.println("end if in");
steps= (data[1]-'0')*100+(data[2]-'0')*10+(data[3]-'0')*1;
//Serial.println(Serial.available());
//Serial.println(steps);
if (data[0] == '1') {
m1.step(steps, FORWARD, SINGLE);
}
else if (data[0] == '2') {
m2.step(steps, FORWARD, SINGLE);
}
//Serial.println("end if");
}
//Serial.println(data[val]);
//Serial.println(data[0]); Serial.println(data[1]); Serial.println(data[2]); Serial.println(data[3]);
}
Several part have been commented out you can use them to debug the code.
the variable garbage is required for removing the last value which is put through the MATLAB function fprintf.
IT IS VERY IMPORTANT TO PUT UP THE DELAY COMMAND AS IT TAKES TIME TO ENTER VALUES INTO THE HARDWARE'S BUFFER.