/* ------------------------------------------------ * SERIAL COM - HANDELING MULTIPLE BYTES inside ARDUINO - 03_function development * 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 * * the same as examlpe 03 but it deploys 2 reusable functions. * for doing the same job. * readSerialString() and printSerialString() * you just need to instantiate an array that will hold all the chars of the string * I've put a 100 value for excess, but if you exactly know how many bytes you are expecting * simply write it down inside the brackets [yourLengthHere] * * created 16 Decembre 2005; * copyleft 2005 Progetto25zero1 * * --------------------------------------------------- */ char serInString[100]; // array that will hold the different bytes of the string. 100=100characters; // -> you must state how long the array will be else it won't work properly //auto go_to_the_line function void printNewLine() { printByte(13); printByte(10); } //read a string from the serial and store it in an array //you must supply the array variable void readSerialString (char *strArray) { int i = 0; if(serialAvailable()) { printString("reading Serial String: "); //optional: for confirmation while (serialAvailable()){ strArray[i] = serialRead(); i++; serialWrite(strArray[(i-1)]); //optional: for confirmation } printNewLine(); //optional: for confirmation } } //Print the whole string at once - will be performed only if thers is data inside it //you must supply the array variable void printSerialString(char *strArray) { int i=0; if (strArray[i] != 0) { while(strArray[i] != 0) { serialWrite( strArray[i] ); strArray[i] = 0; // optional: flush the content i++; } } } //utility function to know wither an array is empty or not boolean isStringEmpty(char *strArray) { if (strArray[0] == 0) { return true; } else { return false; } } void setup() { beginSerial(9600); } void loop () { //simple feedback from Arduino printString("Hello World"); printNewLine(); //read the serial port and create a string out of what you read readSerialString(serInString); //do somenthing else perhaps wait for other data or read another Serial string printString ("------------ arduino is doing somenthing else "); printNewLine(); if( isStringEmpty(serInString) == false) { //this check is optional printString("Arduino recorded that you said: "); //try to print out collected information. it will do it only if there actually is some info. printSerialString(serInString); printNewLine(); } printNewLine(); //slows down the visualization in the terminal delay(2000); }