/* * Serial Net * by David A. Mellis * * A serial-to-network proxy. Relays data between a serial port and * network connections. Useful for interfacing an Arduino board or other * microcontroller with Flash. */ import processing.serial.*; import processing.net.*; // To specify the name of the serial port explicitly, un-comment this line, // change the name to that of your serial device (e.g. an Arduino), and use // the other serial = new Serial() line in setup() below. //String serial_port = "/dev/tty.usbserial-A3000Yj0"; // The network port on which to listen for incoming connections. You'll // need to specify this somewhere in your Flash movie. int network_port = 5331; // The baud rate to use for serial communication. This needs to match the // speed used by the microcontroller (e.g. the value passed to // Serial.begin() in an Arduino sketch). int serial_baud_rate = 9600; // Whether or not to print data coming from the serial port in Processing. boolean print_in_processing = true; // Whether or not to convert newlines (ASCII code 10) coming from the // serial port into nils (ASCII code 0). Set to true for use with Flash's // XmlSocket. boolean newlines_to_nils = true; // Whether or not to convert non-printing characters (ASCII code greater // than 127) into two UTF-8 bytes. Set to true for use with Flash's // XmlSocket. boolean utf8_encode = true; Server server; Serial serial; void setup() { // Print the available serial ports. println(Serial.list()); // Select the serial port by its location in the list. Change the // number in the [square brackets] to the one that corresponds to your // serial device (in the list printed by the preceding line). serial = new Serial(this, Serial.list()[0], serial_baud_rate); // Alternatively, select your serial port by name. To use, comment the // previous line and uncomment this one. Set the serial_port variable // above to the name of your serial device. //serial = new Serial(this, serial_port, serial_baud_rate); server = new Server(this, network_port); } void draw() { if (serial.available() > 0) { int c = serial.read(); if (print_in_processing) print((char) c); if (newlines_to_nils && c == '\n') c = 0; if (utf8_encode && c >= 0x80) { server.write(0xc0 | (c >> 6)); server.write(0x80 | (c & 0x3f)); } else { byte[] b = { (byte) c }; server.write(b); } } Client client = server.available(); if (client != null) { if (client.available() > 0) { serial.write(client.read()); } } }