/* ------------------------------------------------ * SERIAL COM - HANDELING MULTIPLE BYTES inside ARDUINO - 02_complex version * by beltran berrocal * * this prog establishes a connection with the pc and waits for it to send him * a long string of characters like "hello Arduino!". * Then Arduino informs the pc that it heard the whole sentence * * It's different from the previous version in the way that it stores * the string incoming from the serial port into an array of bytes * to send it to the pc only later in the loop. * It is usefull if you want to send a bunch of "formatted" data to the pc all in one * instead of letting the pc handle the parsing process. * could be usefull to format NMEA strings incoming from a GPS module. ;) * * created 15 Decembre 2005; * copyleft 2005 Progetto25zero1 * * --------------------------------------------------- */ int serIn; // var that will hold the bytes-in read from the serialBuffer char serInString[100]; // array that will hold the different bytes 100=100characters; // -> you must state how long the array will be else it won't work. int serInIndx = 0; // index of serInString[] in which to inser the next incoming byte int serOutIndx = 0; // index of the outgoing serInString[] array; void setup() { beginSerial(9600); } //auto go_to_the_line function void printNewLine() { printByte(13); printByte(10); } void loop () { //simple feedback from Arduino printString("Hello World"); printNewLine(); // only if there are bytes in the serial buffer execute the following code if(serialAvailable()) { //keep reading from serial untill there are bytes in the serial buffer while (serialAvailable()){ serIn = serialRead(); //read Serial serInString[serInIndx] = serIn; //insert the byte you just read into the array at the specified index serInIndx++; //update the new index } //feedback that something was received printString ("Aduino heard what you said. but he's thinking about it before replying :)"); printNewLine(); } //do somenthing else perhaps wait for other data. printString ("------------ arduino is doing somenthing else "); printNewLine(); //print out later in the loop the sentence only if it has actually been collected; if( serInIndx > 0) { printString("Arduino memorized that you said: "); //loop through all bytes in the array and print them out for(serOutIndx=0; serOutIndx < serInIndx; serOutIndx++) { serialWrite( serInString[serOutIndx] ); //print out the byte at the specified index //serInString[serOutIndx] = ""; //optional: flush out the content } //reset all the functions to be able to fill the string back with content serOutIndx = 0; serInIndx = 0; printNewLine(); } printNewLine(); //slows down the visualization in the terminal delay(2000); }