Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Example of how to parse and display incoming Serial data from an Arduino Uno.
- Serial setup is from the Processing.org Serial library reference.
- Serial data from the Arduino in this example is organized as such (without quotations):
- "data1|data2|data3"
- pipe character used as a delimiter, and newline (Serial.println();) is treated as the end-of-packet.
- By no means the only way to do it, but using a delimiter makes it easy to send variable length data & text in each chunk
- Example Arduino code:
- void loop()
- {
- int randBarData = random(0, 100);
- int randColorData = random(0, 255);
- Serial.print("Some Text");
- Serial.print('|');
- Serial.print(randColorData);
- Serial.print('|');
- Serial.print(randBarData);
- Serial.println();
- delay(100);
- }
- */
- import processing.serial.*;
- // Don't try to read from our serialData array if it's empty
- boolean dataValid = false;
- Serial myPort;
- // String array to hold the data chunks we recieve in each packet
- String[] serialData;
- // ASCII #10 = linefeed/newline
- int lf = 10;
- void setup()
- {
- size(400,200);
- // Open the first connected Serial port
- // If that fails, change to whichever port Arduino is connected to, for example "COM3"
- myPort = new Serial(this, Serial.list()[0], 9600);
- // Keep buffering data until we encounter linefeed (doing so triggers serialEvent)
- myPort.bufferUntil(lf);
- }
- void draw()
- {
- // Start with a black canvas
- background(0);
- // Don't do anything unless we have data
- if(dataValid)
- {
- fill(255);
- text("received: " + serialData[0], 10,20);
- text("received: " + serialData[1], 10,40);
- // Parse the 2nd data segment into an integer. Trim to remove any non-alphanumericals
- int colorData = parseInt(trim(serialData[1]));
- fill(colorData, 0, 0);
- rect(10, 80, 20, 20);
- fill(0, 255, 0);
- int barData = parseInt(trim(serialData[2]));
- // Map the 3rd data segment from (0 -> 100) into (0 -> width of canvas)
- float barLength = map(barData, 0, 100, 0, width);
- rect(0, 150, barLength, 50);
- }
- }
- void serialEvent(Serial p)
- {
- // Store the Serial buffer
- String tString = p.readString();
- // Split the String we recieved into individual chunks, using our pipe character as the delimiter token
- serialData = splitTokens(tString, "|");
- // serialData is no longer empty, we can allow drawing now
- dataValid = true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement