Sending char string from matlab to arduino using serial com

조회 수: 1 (최근 30일)
lewis mcmenemy
lewis mcmenemy 2019년 4월 10일
편집: lewis mcmenemy 2019년 4월 10일
Hi i am trying to simply send the character string '<180>' to arduino from matlab using serial communication in order to light a led. for some reason arduino isnt receiving the correct data. if i type <180> into the serial monitor on the arduino software the led lights up. any help is appreciated.
matlab code:
%% Serial communication with Arduino
x = serial('COM4','BAUD',9600);
fopen(x);
% a= input('Press 1 to turn ON LED & 0 to turn OFF:');
a = '<180>';
fprintf(x,'%s',a);
pause(4)
fclose(x);
Arduino code:
const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;
void setup() {
Serial.begin(9600);
Serial.println("<Arduino is ready>");
pinMode(13, OUTPUT);
}
void loop() {
recvWithStartEndMarkers();
showNewData();
}
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.print("This just in ... ");
Serial.println(receivedChars);
long number = atol(receivedChars);
if (number == 180){
digitalWrite(13, HIGH);
}
else {
digitalWrite(13, LOW);
}
newData = false;
}
}

답변 (0개)

카테고리

Help CenterFile Exchange에서 Instrument Control Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by