This week we are sending and recieving data to Processing via the serial port. In this lab i moved a circle around the screen with a potentiometer. Here’s the code:
– Processing CODE –
/* Serial call-and-response
by Tom Igoe (with adjustments by Dano)
Sends a byte out the serial port, and reads 3 bytes in.
Sets foreground color, xpos, and ypos of a circle onstage
using the values returned from the serial port
Updated October 12, 2004
*/
import processing.serial.*;
Serial myPort; // The serial port
int redNess = 255; // fill color
int[] serialStuff= new int[3];; //where we keep all the incoming stuff
int serialCount = 0; // a count of how many bytes we receive
int xpos= width/2;; // Starting position of the ball
int shape =65;
void setup() {
size(255, 255); // stage size
noStroke(); // no border on the next thing drawn
myPort = new Serial(this, Serial.list()[0], 9600);
serialWrite(65); // send a capital A to start the MC sending
}
void draw() {
background(0);
fill(redNess,0,0);
// Draw the shape
if (shape==65){ //switch value is 65 or 66 (I added 65 to the normal values 0 and 1)
ellipse(xpos, 100, 50, 50);
}else{
rect(xpos,100,50,50);
}
}
void serialEvent() { //this function gets called when something happens involving the serial port
//serial is a special variable provided by processing to give you the oldest byte waiting to be read
// add the latest byte from the serial port into the correct slot in your byte array
serialStuff[serialCount] = myPort.read();
serialCount++;
// if we have 3 bytes, parse the string:
if (serialCount> 2 ) {
redNess = 2* serialStuff[0];
xpos = serialStuff[1];
shape = serialStuff[2];
// after you got them all, go back to putting the bytes in the first slot in the array again
serialCount = 0;
// get a number between 0 to 255 for the mouseX
//if your stage is bigger than 255 //int mouseXIn0to255 = 255*mouseX/width
//send out the mouseX to postion the servo motor
myPort.write(mouseX);
}
}
– PIC BASIC CODE –
DEFINE OSC 4
DEFINE ADC_BITS 8
DEFINE ADC_CLOCK 3
DEFINE ADC_SAMPLEuS 20
lightVar var byte
potVaR VAR BYTE
switchVar var byte
inByte var byte
input portb.7
main:
switchVar = portb.7 + 65 //make it readable
adcin 0, potvar
adcin 2, lightvar
serout2 portc.6, 16468, [lightVar,potVar,switchVar]
serin2 portc.7, 16468, [inbyte]
Pulsout portd.0, inByte
PAUSE 10
goto main
