Read Serial Port 1

Read Data from the Serial Port
The first visualization example shows how to read the serial data in from the Arduino board and how to convert that data into the values that fit to the screen dimensions:

import processing.serial.*;
Serial port; // Create object from Serial class
float val; // Data received from the serial port
void setup() {
size(440, 220);
// The first serial port retrieved by Serial.list()
// should be your Arduino. If not, uncomment the next
// line by deleting the // before it. Run the sketch
// again to see a list of serial ports. Then, change
// the 0 in between [ and ] to the number of the port
// that your Arduino is connected to.
String arduinoPort = Serial.list()[0];
port = new Serial(this, arduinoPort, 9600);
void draw() {
if (port.available() > 0) { // If data is available,
val =; // read it and store it in val
val = map(val, 0, 255, 0, height); // Convert the value
rect(40, val-10, 360, 20);
The Serial library is imported on the first line and the serial port is opened in setup(). It may or may not be easy to get your Processing sketch to talk with the Arduino board; it depends on your hardware setup. There is often more than one device that the Processing sketch might try to communicate with. If the code doesn’t work the first time, read the comment in setup() carefully and follow the instructions.
Within draw(), the value is brought into the program with the read() method of the Serial object. The program reads the data from the serial port only when a new byte is available. The available() method checks to see if a new byte is ready and returns the number of bytes available.
This program is written so that a single new byte will be read each time through draw(). The map() function converts the incoming value from its initial range from 0 to 255 to a range from 0 to the height of the screen; in this program, it’s from 0 to 220.

Deixa un comentari

L'adreça electrònica no es publicarà Els camps necessaris estan marcats amb *


Un bloc a XTECBlocs