In: Computer Science
Serial.flush() and Delay() are the two built-in functions. Place them in the following code to remove the garbage data printing as discussed in class.
Code:
char data;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
while(Serial.available()==NULL){
data = Serial.read();
Serial.print("given character is: ");
Serial.println(data);
}
Serial.end();
}
Serial.flush()
Serial.flush() is a built in arduino function which pause the running of the program untill transmission of outgoing serial data get completed. Every data that arduino sends to serial will get stored at buffer for transmission.serial is comparetively slow in transmission so after putting the data in buffer arduino will move to next line of the code.Data in buffer get automaticaly moves to serial in background.This feature helps arduino to saves it's valuble tiem.But sometimes this may cause to put some unwanted data in serial.The solution to this problem is wait until the transmission buffer to get clear before arduino execute next line.This is exactly Serial.flush do.It will stops execution of arduino until all data is sent to serial.
delay()
delay is an Ardunio function which stops the execution for a
specified time.This delay time can be specified as parameter to
thsi function in milli seconds
example :delay(1000) = stop for 1 second
CODE
Text version
char data;
void setup() {
Serial.begin(9600);
}
void loop() {
delay(500); //delaying execution for .5sec before each loop
while(Serial.available()==NULL){
data = Serial.read();
Serial.print("given character is: ");
Serial.println(data);
Serial.flush(); //stops exection until all data is succesfully
transmitted
}
Serial.end();
}