Skip to content

Instantly share code, notes, and snippets.

@Craigson
Created September 30, 2014 15:21
Show Gist options
  • Save Craigson/9b3845cb045fab86d0e6 to your computer and use it in GitHub Desktop.
Save Craigson/9b3845cb045fab86d0e6 to your computer and use it in GitHub Desktop.
Basic motion controller Processing sketch
import processing.serial.*; // import the Processing serial library
Serial myPort; // The serial port
float bgcolor; // Background color
float fgcolor; // Fill color
float xDegree, yDegree; // Starting position of the ball
boolean firstContact = false;
int buttonState;
// boolean button = false;
int x, y;
void setup() {
size(600, 600);
int x = 300;
int y = 300;
//println(Serial.list());
//define the serial port
String portName = "/dev/tty.usbmodem1411";
myPort = new Serial(this, portName, 9600);
myPort.bufferUntil('\n');
}
void draw() {
background(bgcolor);
if (xDegree < 160) {
x = x - 5;
} else if (xDegree > 360) {
x = x + 5;
} else {
x=x;
}
if (x < 0) {
x = 0;
} else if (x >width) {
x = width;
}
if (yDegree > 375) {
y = y - 5;
} else if (yDegree < 220) {
y = y + 5;
} else {
y = y;
}
if (y > height) {
y = height;
} else if (y < 0) {
y = 0;
}
if (buttonState == 0) {
fill(255);
} else {
fill(255, 0, 0);
}
ellipse(x, y, 20, 20);
println(xDegree, yDegree, buttonState);
}
void serialEvent(Serial myPort) {
// read the serial buffer:
String myString = myPort.readStringUntil('\n');
// if you got any bytes other than the linefeed:
if (myString != null) {
myString = trim(myString);
// if you haven't heard from the microncontroller yet, listen:
if (firstContact == false) {
if (myString.equals("hello")) {
myPort.clear(); // clear the serial port buffer
firstContact = true; // you've had first contact from the microcontroller
myPort.write('A'); // ask for more
}
}
// if you have heard from the microcontroller, proceed:
else {
// split the string at the commas
// and convert the sections into integers:
int sensors[] = int(split(myString, ','));
// print out the values you got:
for (int sensorNum = 0; sensorNum < sensors.length; sensorNum++) {
// print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t");
}
// add a linefeed after all the sensor values are printed:
println();
//println(xpos,ypos);
if (sensors.length > 1) {
xDegree = map(sensors[0], 270, 420, 0, width);
yDegree = map(sensors[1], 270, 420, 0, height);
buttonState = sensors[2];
}
}
// when you've parsed the data you have, ask for more:
myPort.write("A");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment