Calibrate works?

This commit is contained in:
jan 2016-07-10 00:36:44 -07:00
commit cc711c6343
1104 changed files with 636510 additions and 75 deletions

8
lib/serial/.classpath Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="library/jssc.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/processing-core"/>
<classpathentry kind="output" path="bin"/>
</classpath>

17
lib/serial/.project Normal file
View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>processing-serial</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,12 @@
#Sat Nov 12 10:56:44 CST 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6

Binary file not shown.

32
lib/serial/build.xml Normal file
View file

@ -0,0 +1,32 @@
<?xml version="1.0"?>
<project name="Processing Serial Library" default="build">
<target name="clean" description="Clean the build directories">
<delete dir="bin" />
<delete file="library/serial.jar" />
</target>
<target name="compile" description="Compile sources">
<condition property="core-built">
<available file="../../../core/library/core.jar" />
</condition>
<fail unless="core-built" message="Please build the core library first and make sure it sits in ../../../core/library/core.jar" />
<mkdir dir="bin" />
<javac source="1.8"
target="1.8"
srcdir="src" destdir="bin"
encoding="UTF-8"
includeAntRuntime="false"
classpath="../../../core/library/core.jar; library/jssc.jar"
nowarn="true"
compiler="org.eclipse.jdt.core.JDTCompilerAdapter">
<compilerclasspath path="../../mode/org.eclipse.jdt.core.jar;
../../mode/jdtCompilerAdapter.jar" />
</javac>
</target>
<target name="build" depends="compile" description="Build serial library">
<jar basedir="bin" destfile="library/serial.jar" />
</target>
</project>

View file

@ -0,0 +1,150 @@
/**
* Serial Call-Response
* by Tom Igoe.
*
* Sends a byte out the serial port, and reads 3 bytes in.
* Sets foregound color, xpos, and ypos of a circle onstage
* using the values returned from the serial port.
* Thanks to Daniel Shiffman and Greg Shakar for the improvements.
*
* Note: This sketch assumes that the device on the other end of the serial
* port is going to send a single byte of value 65 (ASCII A) on startup.
* The sketch waits for that byte, then sends an ASCII A whenever
* it wants more data.
*/
import processing.serial.*;
int bgcolor; // Background color
int fgcolor; // Fill color
Serial myPort; // The serial port
int[] serialInArray = new int[3]; // Where we'll put what we receive
int serialCount = 0; // A count of how many bytes we receive
int xpos, ypos; // Starting position of the ball
boolean firstContact = false; // Whether we've heard from the microcontroller
void setup() {
size(256, 256); // Stage size
noStroke(); // No border on the next thing drawn
// Set the starting position of the ball (middle of the stage)
xpos = width/2;
ypos = height/2;
// Print a list of the serial ports, for debugging purposes:
printArray(Serial.list());
// I know that the first port in the serial list on my mac
// is always my FTDI adaptor, so I open Serial.list()[0].
// On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}
void draw() {
background(bgcolor);
fill(fgcolor);
// Draw the shape
ellipse(xpos, ypos, 20, 20);
}
void serialEvent(Serial myPort) {
// read a byte from the serial port:
int inByte = myPort.read();
// if this is the first byte received, and it's an A,
// clear the serial buffer and note that you've
// had first contact from the microcontroller.
// Otherwise, add the incoming byte to the array:
if (firstContact == false) {
if (inByte == 'A') {
myPort.clear(); // clear the serial port buffer
firstContact = true; // you've had first contact from the microcontroller
myPort.write('A'); // ask for more
}
}
else {
// Add the latest byte from the serial port to array:
serialInArray[serialCount] = inByte;
serialCount++;
// If we have 3 bytes:
if (serialCount > 2 ) {
xpos = serialInArray[0];
ypos = serialInArray[1];
fgcolor = serialInArray[2];
// print the values (for debugging purposes only):
println(xpos + "\t" + ypos + "\t" + fgcolor);
// Send a capital A to request new sensor readings:
myPort.write('A');
// Reset serialCount:
serialCount = 0;
}
}
}
/*
// Serial Call and Response
// by Tom Igoe
// Language: Wiring/Arduino
// This program sends an ASCII A (byte of value 65) on startup
// and repeats that until it gets some data in.
// Then it waits for a byte in the serial port, and
// sends three sensor values whenever it gets a byte in.
// Thanks to Greg Shakar for the improvements
// Created 26 Sept. 2005
// Updated 18 April 2008
int firstSensor = 0; // first analog sensor
int secondSensor = 0; // second analog sensor
int thirdSensor = 0; // digital sensor
int inByte = 0; // incoming serial byte
void setup()
{
// start serial port at 9600 bps:
Serial.begin(9600);
pinMode(2, INPUT); // digital sensor is on digital pin 2
establishContact(); // send a byte to establish contact until Processing responds
}
void loop()
{
// if we get a valid byte, read analog ins:
if (Serial.available() > 0) {
// get incoming byte:
inByte = Serial.read();
// read first analog input, divide by 4 to make the range 0-255:
firstSensor = analogRead(0)/4;
// delay 10ms to let the ADC recover:
delay(10);
// read second analog input, divide by 4 to make the range 0-255:
secondSensor = analogRead(1)/4;
// read switch, multiply by 155 and add 100
// so that you're sending 100 or 255:
thirdSensor = 100 + (155 * digitalRead(2));
// send sensor values:
Serial.write(firstSensor);
Serial.write(secondSensor);
Serial.write(thirdSensor);
}
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.write('A'); // send a capital A
delay(300);
}
}
*/

View file

@ -0,0 +1,50 @@
/**
* Serial Duplex
* by Tom Igoe.
*
* Sends a byte out the serial port when you type a key
* listens for bytes received, and displays their value.
* This is just a quick application for testing serial data
* in both directions.
*/
import processing.serial.*;
Serial myPort; // The serial port
int whichKey = -1; // Variable to hold keystoke values
int inByte = -1; // Incoming serial data
void setup() {
size(400, 300);
// create a font with the third font available to the system:
PFont myFont = createFont(PFont.list()[2], 14);
textFont(myFont);
// List all the available serial ports:
printArray(Serial.list());
// I know that the first port in the serial list on my mac
// is always my FTDI adaptor, so I open Serial.list()[0].
// In Windows, this usually opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}
void draw() {
background(0);
text("Last Received: " + inByte, 10, 130);
text("Last Sent: " + whichKey, 10, 100);
}
void serialEvent(Serial myPort) {
inByte = myPort.read();
}
void keyPressed() {
// Send the keystroke out:
myPort.write(key);
whichKey = key;
}

View file

@ -0,0 +1,86 @@
/**
* Many Serial Ports
*
* Read data from the multiple Serial Ports
*/
import processing.serial.*;
Serial[] myPorts = new Serial[2]; // Create a list of objects from Serial class
int[] dataIn = new int[2]; // a list to hold data from the serial ports
void setup() {
size(400, 300);
// print a list of the serial ports:
printArray(Serial.list());
// On my machine, the first and third ports in the list
// were the serial ports that my microcontrollers were
// attached to.
// Open whatever ports ares the ones you're using.
// get the ports' names:
String portOne = Serial.list()[0];
String portTwo = Serial.list()[2];
// open the ports:
myPorts[0] = new Serial(this, portOne, 9600);
myPorts[1] = new Serial(this, portTwo, 9600);
}
void draw() {
// clear the screen:
background(0);
// use the latest byte from port 0 for the first circle
fill(dataIn[0]);
ellipse(width/3, height/2, 40, 40);
// use the latest byte from port 1 for the second circle
fill(dataIn[1]);
ellipse(2*width/3, height/2, 40, 40);
}
/**
* When SerialEvent is generated, it'll also give you
* the port that generated it. Check that against a list
* of the ports you know you opened to find out where
* the data came from
*/
void serialEvent(Serial thisPort) {
// variable to hold the number of the port:
int portNumber = -1;
// iterate over the list of ports opened, and match the
// one that generated this event:
for (int p = 0; p < myPorts.length; p++) {
if (thisPort == myPorts[p]) {
portNumber = p;
}
}
// read a byte from the port:
int inByte = thisPort.read();
// put it in the list that holds the latest data from each port:
dataIn[portNumber] = inByte;
// tell us who sent what:
println("Got " + inByte + " from serial port " + portNumber);
}
/*
The following Wiring/Arduino code runs on both microcontrollers that
were used to send data to this sketch:
void setup()
{
// start serial port at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read analog input, divide by 4 to make the range 0-255:
int analogValue = analogRead(0)/4;
Serial.write(analogValue);
// pause for 10 milliseconds:
delay(10);
}
*/

View file

@ -0,0 +1,64 @@
/**
* Simple Read
*
* Read data from the serial port and change the color of a rectangle
* when a switch connected to a Wiring or Arduino board is pressed and released.
* This example works with the Wiring / Arduino program that follows below.
*/
import processing.serial.*;
Serial myPort; // Create object from Serial class
int val; // Data received from the serial port
void setup()
{
size(200, 200);
// I know that the first port in the serial list on my mac
// is always my FTDI adaptor, so I open Serial.list()[0].
// On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}
void draw()
{
if ( myPort.available() > 0) { // If data is available,
val = myPort.read(); // read it and store it in val
}
background(255); // Set background to white
if (val == 0) { // If the serial value is 0,
fill(0); // set fill to black
}
else { // If the serial value is not 0,
fill(204); // set fill to light gray
}
rect(50, 50, 100, 100);
}
/*
// Wiring / Arduino Code
// Code for sensing a switch status and writing the value to the serial port.
int switchPin = 4; // Switch connected to pin 4
void setup() {
pinMode(switchPin, INPUT); // Set pin 0 as an input
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
if (digitalRead(switchPin) == HIGH) { // If switch is ON,
Serial.write(1); // send 1 to Processing
} else { // If the switch is not ON,
Serial.write(0); // send 0 to Processing
}
delay(100); // Wait 100 milliseconds
}
*/

View file

@ -0,0 +1,67 @@
/**
* Simple Write.
*
* Check if the mouse is over a rectangle and writes the status to the serial port.
* This example works with the Wiring / Arduino program that follows below.
*/
import processing.serial.*;
Serial myPort; // Create object from Serial class
int val; // Data received from the serial port
void setup()
{
size(200, 200);
// I know that the first port in the serial list on my mac
// is always my FTDI adaptor, so I open Serial.list()[0].
// On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}
void draw() {
background(255);
if (mouseOverRect() == true) { // If mouse is over square,
fill(204); // change color and
myPort.write('H'); // send an H to indicate mouse is over square
}
else { // If mouse is not over square,
fill(0); // change color and
myPort.write('L'); // send an L otherwise
}
rect(50, 50, 100, 100); // Draw a square
}
boolean mouseOverRect() { // Test if mouse is over square
return ((mouseX >= 50) && (mouseX <= 150) && (mouseY >= 50) && (mouseY <= 150));
}
/*
// Wiring/Arduino code:
// Read data from the serial and turn ON or OFF a light depending on the value
char val; // Data received from the serial port
int ledPin = 4; // Set the pin to digital I/O 4
void setup() {
pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
while (Serial.available()) { // If data is available to read,
val = Serial.read(); // read it and store it in val
}
if (val == 'H') { // If H was received
digitalWrite(ledPin, HIGH); // turn the LED on
} else {
digitalWrite(ledPin, LOW); // Otherwise turn it OFF
}
delay(100); // Wait 100 milliseconds for next reading
}
*/

View file

@ -0,0 +1,3 @@
name = Serial
version = 1

BIN
lib/serial/library/jssc.jar Normal file

Binary file not shown.

View file

@ -0,0 +1,4 @@
This is using a modified version of Java Simple Serial Connector by Alexey Sokolov. See https://github.com/gohai/java-simple-serial-connector for details on the modifications.
To compile the C++ portion of the library on OS X:
g++ -shared [or: -dynamiclib?] -arch i386 -arch x86_64 -I/System/Library/Frameworks/IOKit.framework/Versions/A/Headers -I$JAVA_HOME/include -I$JAVA_HOME/include/darwin -framework IOKit -framework CoreFoundation -o libjSSC-2.6.jnilib jssc.cpp

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,683 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
PSerial - class for serial port goodness
Part of the Processing project - http://processing.org
Copyright (c) 2004-05 Ben Fry & Casey Reas
Reworked by Gottfried Haider as part of GSOC 2013
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.serial;
import processing.core.*;
import java.lang.reflect.*;
import java.util.Map;
import jssc.*;
/**
* ( begin auto-generated from Serial.xml )
*
* Class for sending and receiving data using the serial communication protocol.
*
* ( end auto-generated )
* @webref serial
* @brief Class for sending and receiving data using the serial communication protocol.
* @instanceName serial any variable of type Serial
* @usage Application
* @see_external LIB_serial/serialEvent
*/
public class Serial implements SerialPortEventListener {
PApplet parent;
public SerialPort port;
Method serialAvailableMethod;
Method serialEventMethod;
byte[] buffer = new byte[32768];
int inBuffer = 0;
int readOffset = 0;
int bufferUntilSize = 1;
byte bufferUntilByte = 0;
volatile boolean invokeSerialAvailable = false;
// Things we are currently not exposing:
// * hardware flow control
// * state of the RING, RLSD line
// * sending breaks
/**
* @param parent typically use "this"
*/
public Serial(PApplet parent) {
this(parent, "COM1", 9600, 'N', 8, 1);
}
/**
* @param baudRate 9600 is the default
*/
public Serial(PApplet parent, int baudRate) {
this(parent, "COM1", baudRate, 'N', 8, 1);
}
/**
* @param portName name of the port (COM1 is the default)
*/
public Serial(PApplet parent, String portName) {
this(parent, portName, 9600, 'N', 8, 1);
}
public Serial(PApplet parent, String portName, int baudRate) {
this(parent, portName, baudRate, 'N', 8, 1);
}
/**
* @param parity 'N' for none, 'E' for even, 'O' for odd, 'M' for mark, 'S' for space ('N' is the default)
* @param dataBits 8 is the default
* @param stopBits 1.0, 1.5, or 2.0 (1.0 is the default)
*/
public Serial(PApplet parent, String portName, int baudRate, char parity, int dataBits, float stopBits) {
this.parent = parent;
parent.registerMethod("dispose", this);
parent.registerMethod("pre", this);
// setup parity
if (parity == 'O') {
parity = SerialPort.PARITY_ODD;
} else if (parity == 'E') {
parity = SerialPort.PARITY_EVEN;
} else if (parity == 'M') {
parity = SerialPort.PARITY_MARK;
} else if (parity == 'S') {
parity = SerialPort.PARITY_SPACE;
} else {
parity = SerialPort.PARITY_NONE;
}
// setup stop bits
int stopBitsIdx = SerialPort.STOPBITS_1;
if (stopBits == 1.5f) {
stopBitsIdx = SerialPort.STOPBITS_1_5;
} else if (stopBits == 2) {
stopBitsIdx = SerialPort.STOPBITS_2;
}
port = new SerialPort(portName);
try {
// the native open() call is not using O_NONBLOCK, so this might block for certain operations (see write())
port.openPort();
port.setParams(baudRate, dataBits, stopBitsIdx, parity);
// we could register more events here
port.addEventListener(this, SerialPort.MASK_RXCHAR);
} catch (SerialPortException e) {
// this used to be a RuntimeException before, so stick with it
throw new RuntimeException("Error opening serial port " + e.getPortName() + ": " + e.getExceptionType());
}
serialEventMethod = findCallback("serialEvent");
serialAvailableMethod = findCallback("serialAvailable");
}
private Method findCallback(final String name) {
try {
return parent.getClass().getMethod(name, this.getClass());
} catch (Exception e) {
}
// Permit callback(Object) as alternative to callback(Serial).
try {
return parent.getClass().getMethod(name, Object.class);
} catch (Exception e) {
}
return null;
}
/**
* Used by PApplet to shut things down.
*/
public void dispose() {
stop();
}
/**
* Return true if this port is still active and hasn't run
* into any trouble.
*/
public boolean active() {
return port.isOpened();
}
public void pre() {
if (serialAvailableMethod != null && invokeSerialAvailable) {
invokeSerialAvailable = false;
try {
serialAvailableMethod.invoke(parent, this);
} catch (Exception e) {
System.err.println("Error, disabling serialAvailable() for "+port.getPortName());
System.err.println(e.getLocalizedMessage());
serialAvailableMethod = null;
}
}
}
/**
* @generate Serial_available.xml
* @webref serial:serial
* @usage web_application
*/
public int available() {
return (inBuffer-readOffset);
}
/**
* @generate Serial_buffer.xml
* @webref serial:serial
* @usage web_application
* @param size number of bytes to buffer
*/
public void buffer(int size) {
bufferUntilSize = size;
}
/**
* @generate Serial_bufferUntil.xml
* @webref serial:serial
* @usage web_application
* @param inByte the value to buffer until
*/
public void bufferUntil(int inByte) {
bufferUntilSize = 0;
bufferUntilByte = (byte)inByte;
}
/**
* @generate Serial_clear.xml
* @webref serial:serial
* @usage web_application
*/
public void clear() {
synchronized (buffer) {
inBuffer = 0;
readOffset = 0;
}
}
public boolean getCTS() {
try {
return port.isCTS();
} catch (SerialPortException e) {
throw new RuntimeException("Error reading the CTS line: " + e.getExceptionType());
}
}
public boolean getDSR() {
try {
return port.isDSR();
} catch (SerialPortException e) {
throw new RuntimeException("Error reading the DSR line: " + e.getExceptionType());
}
}
public static Map<String, String> getProperties(String portName) {
return SerialPortList.getPortProperties(portName);
}
/**
* @generate Serial_last.xml
* <h3>Advanced</h3>
* Same as read() but returns the very last value received
* and clears the buffer. Useful when you just want the most
* recent value sent over the port.
* @webref serial:serial
* @usage web_application
*/
public int last() {
if (inBuffer == readOffset) {
return -1;
}
synchronized (buffer) {
int ret = buffer[inBuffer-1] & 0xFF;
inBuffer = 0;
readOffset = 0;
return ret;
}
}
/**
* @generate Serial_lastChar.xml
* @webref serial:serial
* @usage web_application
*/
public char lastChar() {
return (char)last();
}
/**
* @generate Serial_list.xml
* @webref serial
* @usage web_application
*/
public static String[] list() {
// returns list sorted alphabetically, thus cu.* comes before tty.*
// this was different with RXTX
return SerialPortList.getPortNames();
}
/**
* @generate Serial_read.xml
* @webref serial:serial
* @usage web_application
*/
public int read() {
if (inBuffer == readOffset) {
return -1;
}
synchronized (buffer) {
int ret = buffer[readOffset++] & 0xFF;
if (inBuffer == readOffset) {
inBuffer = 0;
readOffset = 0;
}
return ret;
}
}
/**
* @generate Serial_readBytes.xml
* @webref serial:serial
* @usage web_application
*/
public byte[] readBytes() {
if (inBuffer == readOffset) {
return null;
}
synchronized (buffer) {
byte[] ret = new byte[inBuffer-readOffset];
System.arraycopy(buffer, readOffset, ret, 0, ret.length);
inBuffer = 0;
readOffset = 0;
return ret;
}
}
/**
* <h3>Advanced</h3>
* Return a byte array of anything that's in the serial buffer
* up to the specified maximum number of bytes.
* Not particularly memory/speed efficient, because it creates
* a byte array on each read, but it's easier to use than
* readBytes(byte b[]) (see below).
*
* @param max the maximum number of bytes to read
*/
public byte[] readBytes(int max) {
if (inBuffer == readOffset) {
return null;
}
synchronized (buffer) {
int length = inBuffer - readOffset;
if (length > max) length = max;
byte[] ret = new byte[length];
System.arraycopy(buffer, readOffset, ret, 0, length);
readOffset += length;
if (inBuffer == readOffset) {
inBuffer = 0;
readOffset = 0;
}
return ret;
}
}
/**
* <h3>Advanced</h3>
* Grab whatever is in the serial buffer, and stuff it into a
* byte buffer passed in by the user. This is more memory/time
* efficient than readBytes() returning a byte[] array.
*
* Returns an int for how many bytes were read. If more bytes
* are available than can fit into the byte array, only those
* that will fit are read.
*/
public int readBytes(byte[] dest) {
if (inBuffer == readOffset) {
return 0;
}
synchronized (buffer) {
int toCopy = inBuffer-readOffset;
if (dest.length < toCopy) {
toCopy = dest.length;
}
System.arraycopy(buffer, readOffset, dest, 0, toCopy);
readOffset += toCopy;
if (inBuffer == readOffset) {
inBuffer = 0;
readOffset = 0;
}
return toCopy;
}
}
/**
* @generate Serial_readBytesUntil.xml
* @webref serial:serial
* @usage web_application
* @param inByte character designated to mark the end of the data
*/
public byte[] readBytesUntil(int inByte) {
if (inBuffer == readOffset) {
return null;
}
synchronized (buffer) {
// look for needle in buffer
int found = -1;
for (int i=readOffset; i < inBuffer; i++) {
if (buffer[i] == (byte)inByte) {
found = i;
break;
}
}
if (found == -1) {
return null;
}
int toCopy = found-readOffset+1;
byte[] dest = new byte[toCopy];
System.arraycopy(buffer, readOffset, dest, 0, toCopy);
readOffset += toCopy;
if (inBuffer == readOffset) {
inBuffer = 0;
readOffset = 0;
}
return dest;
}
}
/**
* <h3>Advanced</h3>
* If dest[] is not big enough, then -1 is returned,
* and an error message is printed on the console.
* If nothing is in the buffer, zero is returned.
* If 'interesting' byte is not in the buffer, then 0 is returned.
* @param dest passed in byte array to be altered
*/
public int readBytesUntil(int inByte, byte[] dest) {
if (inBuffer == readOffset) {
return 0;
}
synchronized (buffer) {
// look for needle in buffer
int found = -1;
for (int i=readOffset; i < inBuffer; i++) {
if (buffer[i] == (byte)inByte) {
found = i;
break;
}
}
if (found == -1) {
return 0;
}
// check if bytes to copy fit in dest
int toCopy = found-readOffset+1;
if (dest.length < toCopy) {
System.err.println( "The buffer passed to readBytesUntil() is to small " +
"to contain " + toCopy + " bytes up to and including " +
"char " + (byte)inByte);
return -1;
}
System.arraycopy(buffer, readOffset, dest, 0, toCopy);
readOffset += toCopy;
if (inBuffer == readOffset) {
inBuffer = 0;
readOffset = 0;
}
return toCopy;
}
}
/**
* @generate Serial_readChar.xml
* @webref serial:serial
* @usage web_application
*/
public char readChar() {
return (char) read();
}
/**
* @generate Serial_readString.xml
* @webref serial:serial
* @usage web_application
*/
public String readString() {
if (inBuffer == readOffset) {
return null;
}
return new String(readBytes());
}
/**
* @generate Serial_readStringUntil.xml
*<h3>Advanced</h3>
* If you want to move Unicode data, you can first convert the
* String to a byte stream in the representation of your choice
* (i.e. UTF8 or two-byte Unicode data), and send it as a byte array.
*
* @webref serial:serial
* @usage web_application
* @param inByte character designated to mark the end of the data
*/
public String readStringUntil(int inByte) {
byte temp[] = readBytesUntil(inByte);
if (temp == null) {
return null;
} else {
return new String(temp);
}
}
/**
* @generate serialEvent.xml
* @webref serial:events
* @usage web_application
* @param event the port where new data is available
*/
public void serialEvent(SerialPortEvent event) {
if (event.getEventType() == SerialPortEvent.RXCHAR) {
int toRead;
try {
while (0 < (toRead = port.getInputBufferBytesCount())) {
// this method can be called from the context of another thread
synchronized (buffer) {
// read one byte at a time if the sketch is using serialEvent
if (serialEventMethod != null) {
toRead = 1;
}
// enlarge buffer if necessary
if (buffer.length < inBuffer+toRead) {
byte temp[] = new byte[buffer.length<<1];
System.arraycopy(buffer, 0, temp, 0, inBuffer);
buffer = temp;
}
// read an array of bytes and copy it into our buffer
byte[] read = port.readBytes(toRead);
System.arraycopy(read, 0, buffer, inBuffer, read.length);
inBuffer += read.length;
}
if (serialEventMethod != null) {
if ((0 < bufferUntilSize && bufferUntilSize <= inBuffer-readOffset) ||
(0 == bufferUntilSize && bufferUntilByte == buffer[inBuffer-1])) {
try {
// serialEvent() is invoked in the context of the current (serial) thread
// which means that serialization and atomic variables need to be used to
// guarantee reliable operation (and better not draw() etc..)
// serialAvailable() does not provide any real benefits over using
// available() and read() inside draw - but this function has no
// thread-safety issues since it's being invoked during pre in the context
// of the Processing applet
serialEventMethod.invoke(parent, this);
} catch (Exception e) {
System.err.println("Error, disabling serialEvent() for "+port.getPortName());
System.err.println(e.getLocalizedMessage());
serialEventMethod = null;
}
}
}
invokeSerialAvailable = true;
}
} catch (SerialPortException e) {
throw new RuntimeException("Error reading from serial port " + e.getPortName() + ": " + e.getExceptionType());
}
}
}
/**
* Set the DTR line
*/
public void setDTR(boolean state) {
// there is no way to influence the behavior of the DTR line when opening the serial port
// this means that at least on Linux and OS X, Arduino devices are always reset
try {
port.setDTR(state);
} catch (SerialPortException e) {
throw new RuntimeException("Error setting the DTR line: " + e.getExceptionType());
}
}
/**
* Set the RTS line
*/
public void setRTS(boolean state) {
try {
port.setRTS(state);
} catch (SerialPortException e) {
throw new RuntimeException("Error setting the RTS line: " + e.getExceptionType());
}
}
/**
* @generate Serial_stop.xml
* @webref serial:serial
* @usage web_application
*/
public void stop() {
try {
port.closePort();
} catch (SerialPortException e) {
// ignored
}
inBuffer = 0;
readOffset = 0;
}
/**
* @param src data to write
*/
public void write(byte[] src) {
try {
// this might block if the serial device is not yet ready (esp. tty devices under OS X)
port.writeBytes(src);
// we used to call flush() here
} catch (SerialPortException e) {
throw new RuntimeException("Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
}
}
/**
* <h3>Advanced</h3>
* This will handle both ints, bytes and chars transparently.
* @param src data to write
*/
public void write(int src) {
try {
port.writeInt(src);
} catch (SerialPortException e) {
throw new RuntimeException("Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
}
}
/**
* @generate Serial_write.xml
* <h3>Advanced</h3>
* Write a String to the output. Note that this doesn't account
* for Unicode (two bytes per char), nor will it send UTF8
* characters.. It assumes that you mean to send a byte buffer
* (most often the case for networking and serial i/o) and
* will only use the bottom 8 bits of each char in the string.
* (Meaning that internally it uses String.getBytes)
*
* If you want to move Unicode data, you can first convert the
* String to a byte stream in the representation of your choice
* (i.e. UTF8 or two-byte Unicode data), and send it as a byte array.
*
* @webref serial:serial
* @usage web_application
* @param src data to write
*/
public void write(String src) {
try {
port.writeString(src);
} catch (SerialPortException e) {
throw new RuntimeException("Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
}
}
}

View file

@ -0,0 +1,12 @@
void setup() {
Serial.begin(115200);
}
void loop() {
while (true) {
int in = Serial.read();
if (in != -1) {
Serial.write(in);
}
}
}

View file

@ -0,0 +1,53 @@
// Arduino Duemilanove (168) on OS X 10.9
// with either 115200 or 38400 bps
// on Processing 2.0.3 (cu & tty): 24 ms avg, 35 ms max
// on Processing 2.1b1 (cu & tty): 18 ms avg, 35 ms max
import processing.serial.*;
Serial serial;
int start;
byte out = '@';
int last_send = 0;
byte[] in = new byte[32768];
long num_fail = 0;
long num_recv = 0;
int max_latency = 0;
void setup() {
println(serial.list());
// change this accordingly
serial = new Serial(this, serial.list()[0], 115200);
start = millis();
}
void draw() {
background(255);
if (0 < serial.available()) {
int recv = serial.readBytes(in);
for (int i=0; i < recv; i++) {
if (in[i] == out) {
num_recv++;
int now = millis();
if (max_latency < now-last_send) {
max_latency = now-last_send;
}
last_send = 0;
}
}
}
if (last_send != 0 && 1000 < millis()-last_send) {
num_fail++;
last_send = 0;
println(num_fail+" bytes timed out");
}
if (last_send == 0) {
if (out == 'Z') {
out = '@';
}
serial.write(++out);
last_send = millis();
}
fill(0);
text(((millis()-start)/(float)num_recv+" ms avg"), 0, height/2);
text(max_latency+" ms max", 0, height/2+20);
}

View file

@ -0,0 +1,9 @@
void setup() {
Serial.begin(115200);
}
void loop() {
while (true) {
Serial.write('.');
}
}

View file

@ -0,0 +1,32 @@
import processing.serial.*;
Serial serial;
int start;
byte[] in = new byte[32768];
long num_ok = 0;
long num_fail = 0;
long num_recv = 0;
void setup() {
println(serial.list());
// change this accordingly
serial = new Serial(this, serial.list()[0], 115200);
start = millis();
}
void draw() {
background(255);
if (0 < serial.available()) {
int recv = serial.readBytes(in);
for (int i=0; i < recv; i++) {
if (in[i] == '.') {
num_ok++;
} else {
num_fail++;
println("Received "+num_fail+" unexpected bytes");
}
num_recv++;
}
}
fill(0);
text(num_recv/((millis()-start)/1000.0), 0, height/2);
}