I'm trying to send integer int from Matlab (R2013a) to Arduino DUE.
I'm sending 10 integers : 5 positive and 5 negative, but only the Red led is turning ON.
Do you have any idea of what I'm doing wrong?
Thanks
Here is the code I use.
int recue;
int ledR = 13;
int ledV = 10;
int ledJ = 9;
void setup()
{
Serial.begin(9600);
pinMode(ledR, OUTPUT);
pinMode(ledV, OUTPUT);
pinMode(ledJ, OUTPUT);
}
void loop()
{
while (Serial.available() > 0)
{
int compteur_resp = 0 ;
while (compteur_resp < 10) { // I want to read 10 integers
recue = Serial.read();
delay(20);
if (recue > 0 ){
digitalWrite(ledR, HIGH); // turn the Red LED on (HIGH is the voltage level)
delay(500); // wait for 0.5 second
digitalWrite(ledR, LOW); // turn the LED off by making the voltage LOW
delay(100);
}
else {
digitalWrite(ledJ, HIGH); // turn the Yellow LED on (HIGH is the voltage level)
delay(500); // wait for 0.5 second
digitalWrite(ledJ, LOW); // turn the LED off by making the voltage LOW
delay(100);
}
compteur_resp ++ ;
}
You are not receiving integers. You are receiving individual bytes, and those individual bytes are characters. There are no characters you can send with the Serial Monitor that will arrive on the Arduino's serial port as negative numbers. The numbers you are sending range in value from 48 through 57, which are the characters '0' through '9'; not the numeric values 0 through 9.
I'm trying to send integer int from Matlab (R2013a) to Arduino DUE.
I'm sending 10 integers : 5 positive and 5 negative, but only the Red led is turning ON.
Do you have any idea of what I'm doing wrong?
Thanks
This may be of some use to you:
// read a line of data from serial to a buffer, max bytes allowed = "limit".
// max bytes is 255 because of uint8_t. For larger input, use uint16_t
uint8_t readline (char *buffer, uint8_t limit)
{
char c;
uint8_t ptr = 0;
while (1) {
if (Serial.available()) {
c = Serial.read();
if ((c == 0x0D) || (c == 0x0A)) { // cr == end of line
*(buffer + ptr) = 0; // mark end of line
break; // return char count
}
if (c == 0x08) { // backspace
if (ptr) { // if not at the beginning
*(buffer + --ptr) = 0; // null backspaced char
Serial.print ( (char) 0x08); // erase backspaced char
Serial.print ( (char) 0x20); // print a space to erase
Serial.print ( (char) 0x08); // back up to account for space
} else {
Serial.print ( (char) 0x07); // ascii bel (beep) if terminal supports it
}
} else { // not a backspace, handle it
if (ptr < (limit - 1)) { // if not at the end of the line
Serial.print ( (char) c); // echo char
*(buffer + ptr++) = c; // put char into buffer
} else { // at end of line, can't add any more
Serial.print ( (char) 0x07); // ascii bel (beep) if terminal supports it
}
}
}
}
return ptr; // returns how many chars were received
}
Use this to get a string (like "10" or "-10" or whatever) then use atoi(buffer) to convert ASCII to INTEGER and there you have your serial converted into ints.