Demonstrates use of the SerialEvent()
function. SerialEvent()
is called after a loop()
, if there is serial data in the buffer.
MSP-EXP430G2 LaunchPad
None
This code demonstrates the use of the serialEvent()
function. In this code, serialEvent()
runs after each time loop()
processes. Since we are placing characters read from the Serial Monitor into a buffer, the serialEvent
will send characters received back into the main loop to be processed. The best way to demonstrate this is to place a delay at the end of the if statement in the main loop. The string read from the Serial monitor will be printed to the serial monitor with a delay. During the delay, if you type more characters into the Serial Monitor, the code will send these characters back into the main loop after the delay to be printed to the Serial Monitor.
/* Serial Event example When new serial data arrives, this sketch adds it to a String. When a newline is received, the loop prints the string and clears it. A good test for this is to try it with a GPS receiver that sends out NMEA 0183 sentences. Created 9 May 2011 by Tom Igoe Modified 24 April 2013 by Sean Alvarado This example code is in the public domain. */ String inputString = ""; // a string to hold incoming data boolean stringComplete = false; // whether the string is complete void setup() { // initialize serial: Serial.begin(9600); // reserve 200 bytes for the inputString: inputString.reserve(200); } void loop() { // print the string when a newline arrives: if (stringComplete) { Serial.println(inputString); // clear the string: inputString = ""; stringComplete = false; } } /* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */ void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; // if the incoming character is a newline, set a flag // so the main loop can do something about it: if (inChar == '\n') { stringComplete = true; } } }
Dimmer:move the mouse to change the brightness of an LED.
Graph:send data to the computer and graph it in Processing.
Physical Pixel:turn an LED on and off by sending data from Processing.
Virtual Color Mixer:send multiple variables from an LaunchPad to the computer and read them in Processing.
Serial Call Response:send multiple variables using a call and response (handshaking) method.
Serial Call and Response ASCII:send multiple vairables using a call-and-response (handshaking) method, and ASCII-encoding the values before sending.
Serial Input (Switch (case) Statement):how to take different actions based on characters received by the serial port.