Hi, I am using matlab to communicate with Arduino.
The idea is that a computer get some input and translate it into the steps of motors, then send the number of steps to arduino.
I feel really headache when I was trying to communicate.
I don't know how to send numbers bigger than 127 to arduino. Also, Serial.write doesn't have argument, I don't know how to sent large number out from Arduino.
The following CODE works well when sending numbers smaller than 127 from Matlab. LED turns on and off as planed, and Matlab can get correct response from Arduino as well.
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
}
void loop() {
if (Serial.available()) {
int inByte = Serial.read();
Serial.write(inByte);
if (inByte==1){digitalWrite(13,HIGH);delay(500);}
if (inByte==0){digitalWrite(13,LOW);delay(500);}
MATLAB CODE
arport=serial('com6','baudrate',9600,'databits',8);
fwrite(arport,1,'int8');
fread(arport,1,'int8');
pause(10);
fwrite(arport,0,'int8');
fread(arport,1,'int8');
fclose(arport);
delete(arport);
However, when I try to send a number bigger than 127, it doesn't work.
Here is the modified CODE.
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
}
void loop() {
if (Serial.available()) {
int inByte = Serial.read();
Serial.write(inByte);
if (inByte==32){digitalWrite(13,HIGH);delay(500);}
if (inByte==512){digitalWrite(13,LOW);delay(500);}
It seems Arduino can't read two bytes at a time.
So I used inByte=inByte<<5 to try the problem.
input 1 LED turns on, input 16 LED turns off. perfect!
But when I try to write shifted inByte ( 512) back to MATLAB, it doesn't work.
I also tried
Serial.write(512)
when I read from matlab with
fread(arport,1,'int8') //gives 0
fread(arport,2,'int8') //gives 0 and a Warning: The specified amount of data was not returned within the Timeout period.
fread(arport,1,'int16') //gives only the same warning.
512 = (00010000 00000000)2
fread(arport,2,'int8') should give 0 and 16, isn't it?
How to read and write 16 bits ToT help~