Hardware Reference
In-Depth Information
protocols you'll use in this topic are ASCII-based. In
addition, ASCII is readable by humans, so you may find it
easier to send the data as ASCII. For Monski Pong, use the
ASCII-formatted version (the first example); later in this
chapter you'll see why it's the right choice.
If you haven't already done so, undo the changes you
made on page 54 to the Sensor Reader program and make
sure that it's working as it did originally. Once you've got
the microcontroller sending the sensor values consistently
to the terminal, it's time to send them to a program where
you can use them to display a pong game. This program
needs to run on a host computer that's connected to your
Arduino board. Processing will do this well.
Open the Processing
application and enter
Try It
/*
Serial String Reader
Context: Processing
this code.
*/
import processing.serial.*; // import the Processing serial library
Serial myPort; // The serial port
String resultString; // string for the results
void setup() {
size(480, 130); // set the size of the applet window
println(Serial.list()); // List all the available serial ports
// get the name of your port from the serial list.
// The first port in the serial list on my computer
// is generally my Arduino module, so I open Serial.list()[0].
// Change the 0 to the number of the serial port
// to which your microcontroller is attached:
String portName = Serial.list()[0];
// open the serial port:
myPort = new Serial(this, portName, 9600);
// read bytes into a buffer until you get a linefeed (ASCII 10):
myPort.bufferUntil('\n');
}
void draw() {
// set the background and fill color for the applet window:
background(#044f6f);
fill(#ffffff);
// show a string in the window:
if (resultString != null) {
text(resultString, 10, height/2);
}
}
// serialEvent method is run automatically by the Processing sketch
// whenever the buffer reaches the byte value set in the bufferUntil()
// method in the setup():
void serialEvent(Serial myPort) {
// read the serial buffer:
String inputString = myPort.readStringUntil('\n');
ยป
 
Search WWH ::




Custom Search