Hi,
I have some issues with matlab fwrite to send char to arduino. basically, If I run the codes lines, arduino couldn't correctly receive the char from serial port and couldn't echo to it. Accordingly what matlab reads from serial port that arduino send back, looks like the char is not correctly sent to serial port. for example, the character sent is 't', arduino feedback is 'ð'. However, If manually run the codes line by line, the communication works. could you help debug what cause the issues? attached is the test code I used. Thank you in advance!
Arduino side:
bool state=0;
unsigned long startTime;
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(115200);
pinMode(A0, INPUT);
digitalWrite(A0, LOW) ;
}
void loop() {
if (Serial.available()) {
char var=Serial.read();
Serial.print("charater received: ");
Serial.println(var);
if (var=='t') {
Serial.println("Arduino is connected");
}
else if (var=='s') {
state=1;
}
else if (var=='e') {
state=0;
}
}
if (state==1) {
float sensorValue = analogRead(A0);
Serial.println(sensorValue);
}
}
Matlab side:
establish serial comm:
serialInfo = instrhwinfo('serial');
instrs=instrfind;
if ~isempty(instrs)
fclose(instrs);
delete(instrs);
end
ports=serialInfo.AvailableSerialPorts;
a=serial(ports{1},'Baudrate',115200,'InputBufferSize',50000,'OutputBufferSize',500);
Send command character to serial and read the feedback from arduino: if run the lines at once, even I put a pause(3) after fwrite(a,'t'), it often doesn't work. The arduino feedback suggest a wrong character was sent to it. however, if I run the code line by line once at a time, the serial communication will work.
if strcmp(a.Status,'closed')
try fopen(a)
disp('Connecting to Arduino')
if strcmp(a.Status,'open')
fwrite(a,'t')
pause(1)
while a.bytesavailable==0
end
while a.bytesavailable>0
strings=fgets(a);
disp([strings(1:end-2) ' via ' ports{1}]);
end
end
catch
disp(['fail to connect with Arduino via port: ' ports{1}])
end