Newcomers are sometimes unsure how to receive data into an Arduino sketch from the Serial Monitor or from a program running on a PC. I thought it would be helpful to write a demo sketch that illustrates a few useful techniques.
The sketch attached to this Post includes 5 self contained functions that illustrate different ways to deal with incoming data.
readSingleChar() reads and saves a single character and its byte value
readSingleDigit(); reads and saves as a number any of the digits 0-9
readSeveralChars(); reads several characters and saves them as a string in a character array
readOneFloat(); reads several numeric characters and saves them as a floating point value
readCSV(); reads a string, an integer and a float separated by commas
for example testing , 123 , 456.78
Newcomers should not be put off by the length of the total sketch. They should just concentrate on one function at a time. The comments will make more sense if the functions are studied in order.
To try (for example) the readSingleDigit() function it is only necessary to comment out all the other functions in loop() as follows
// readSingleChar(); readSingleDigit(); // readSeveralChars(); // readOneFloat(); // readCSV();
One thing that these simple examples do NOT have is the ability to identify the correct start and end to a message - it is possible for part of a message to be missed. This is unlikely in this demo because of the 1 second delay between iterations of loop() but it is a real risk in a working program that runs quickly. The demo sketch that I included in the first post of this Thread shows how to deal with this problem. Its technique can be combined with the techniques here.
DemoDataInput.ino (6.88 KB)