I want to do a simple program which allows me to send an integer to the arduino UNO r3 and let the board to report back the integer.
The code is here:
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
int red = Serial.parseInt();
if (Serial.read() == '\n') {
Serial.print(red, HEX);
}
}
}
What I've got is just nothing, no report back. Is the program wrong? Can I use a USB wire to do the serial communication from the board (Plugged at the red circle in the attached picture) to my computer without using a UART to USB cable?
After you've extracted the int from the stream, the stream is empty. Why are you then expecting to be able to read a carriage return? Why not just print the value you read?
very simply stated Serial.parseInt() parses an integer with a timeout. as long as as digits are transmitted within the timeout, it will include them in the return.
if the function processes a non-numeric character, it will immediately return the integer
try entering these two numbers into the serial monitor while you run the program below:
-1234x
45
notice that the program waits the 1000ms default time out to return 45 and the 'x' will trigger another Serial.parsInt(), returning a zero, because your loop is built to do that.
void setup()
{
Serial.begin(9600);
}
void loop()
{
while (Serial.available() > 0)
{
int red = Serial.parseInt();
Serial.println(red, HEX);
Serial.println(red);
}
}
After you've extracted the int from the stream, the stream is empty. Why are you then expecting to be able to read a carriage return? Why not just print the value you read?
In the original program, I sent 1234 and nothing responded back.... but after I've tried the BulldogLowell's program, It works correctly
Thanks to you Bulldog
The different things from the previous and Bulldog's program is the line if (Serial.read() == '\n') in the original program. In the original one, does the "if statement" mean that if the program detects hitting enter button, the program will pickup integers from the stream and print it back??
parseInt() is part of the Stream class, FYI. Its functionality is to recognize what you wanted to do... collect the next group of digits and assemble them into an integer.
you would use
(Serial.read() == '\n')
if you were writing code to assemble the int from a stream of serial data, and wanted to use the new line character as your delimiter.