User Tools

Site Tools


courses:intro.prototyping.fall2013.nov26

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
courses:intro.prototyping.fall2013.nov26 [2013/12/02 02:41]
rickard
courses:intro.prototyping.fall2013.nov26 [2013/12/03 08:11] (current)
rickard
Line 1: Line 1:
 +====== Serial communication between Arduino and Processing ======
  
 +Time to start connecting the physical world with the virtual.
 +
 +===Arduino transmitting ===
 +
 +Using the the Arduino example "​AnalogInOutSerial"​ we get a simple source of values to transmit.
 +However, start with cleaning up what's transmitted from:
 +
 +
 +<code java>
 +   ​Serial.print("​sensor = " );                       
 +   ​Serial.print(sensorValue); ​     ​
 +   ​Serial.print("​\t output = "​); ​     ​
 +   ​Serial.println(outputValue); ​
 +</​code>​
 +
 +to
 +
 +<code java>
 +  Serial.println(sensorValue); ​  
 +</​code>​
 +
 +and for TWO values:
 +
 +another variable, reading another pin, storing it in variable
 +and then...
 +
 +<code java>
 +  Serial.print(sensorValue1);​
 +  Serial.print(','​);​
 +  Serial.println(sensorValue2);​
 +  delay(20); //a little delay just to make sure Arduino doesn'​t ignore us when we want to reprogram
 +</​code>​
 +
 +more sensors? Repeat the the process.
 +
 +==Processing code to receive:==
 +<code java>
 +import processing.serial.*;​
 +
 +int linefeed = 10; // new line ASCII = 10
 +Serial myPort;
 + 
 +int value1 = 0; // We'll store value in this variable to draw a rectangle
 +
 +void setup () {
 +  size(800, 600);
 +  // change port!
 +  myPort =  new Serial(this,​ Serial.list()[2],​ 9600);
 +  // here we're saying that we need to buffer until 'line feed'
 +  myPort.bufferUntil(linefeed);​
 +  ​
 +  fill(150);
 +}
 +
 +void draw () 
 +
 +  background(0);​
 +  rect(100, 0, 100, value1);
 +}
 +
 +void serialEvent (Serial myPort) ​
 +{
 +  // read serial buffer as string
 +  String myString = myPort.readString();​
 +
 +  // if we have any other bytes than linefeed
 +  if (myString != null) 
 +  {
 +    // trim crap
 +    myString = trim(myString);​
 +    // split the string at commas ​
 +    // and convert sections into integers. ​
 +    String sensors[] = split(myString,​ ','​);​
 +    value1 = int(sensors[0]);​
 +    println(value1);​
 +  }
 +}
 +</​code>​
 +
 +For two values:
 +Prepare another variable to recieve, and in the code to deal with the serial event..
 +Where it previously said
 +
 +<code java>
 +    value1 = int(sensors[0]);​
 +</​code>​
 +
 +we now add the next reading
 +
 +<code java>
 +    value1 = int(sensors[0]);​
 +    value2 = int(sensors[1]);​
 +</​code>​
 +
 +But then it's of course up to you what magic in Processing you want to control with these values.
courses/intro.prototyping.fall2013.nov26.txt · Last modified: 2013/12/03 08:11 by rickard