Interaction Lab Documentation 10-Kurt Xu

WorkShop: Serial Communication

Exercise:

Arduino to Processing

processing

import processing.serial.*;

String myString = null;
Serial myPort;


int NUM_OF_VALUES = 3;
int[] sensorValues;
float cl=255;

void setup() 
{
  size(500, 500);
  background(0);
  setupSerial();
}


void draw() 
{
  updateSerial();
  printArray(sensorValues);
  background(0);
  colorMode(HSB);
  if (sensorValues[2]==1) 
  {
    cl=random(20, 255);
    fill(cl);
    ellipse(250, 250, sensorValues[0]/2.048, sensorValues[1]/2.048);
  }
}


void setupSerial() 
{
  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[0], 9600);
  myPort.clear();
  myString = myPort.readStringUntil( 10 );
  myString = null;
  sensorValues = new int[NUM_OF_VALUES];
}

void updateSerial() 
{
  while (myPort.available() > 0) 
  {
    myString = myPort.readStringUntil( 10 );
    if (myString != null) 
    {
      String[] serialInArray = split(trim(myString), ",");
      if (serialInArray.length == NUM_OF_VALUES) 
      {
        for (int i=0; i<serialInArray.length; i++) 
        {
          sensorValues[i] = int(serialInArray[i]);
        }
      }
    }
  }
}

Arduino

void setup() 
{
  Serial.begin(9600);
  pinMode(9, INPUT);
  pinMode(3, OUTPUT);
}

void loop() 
{
  int sensor1 = analogRead(A0)+1;
  int sensor2 = analogRead(A1)+1;
  int sensor3 = digitalRead(9);
  Serial.print(sensor1);
  Serial.print(","); 
  Serial.print(sensor2);
  Serial.print(",");
  Serial.print(sensor3);
  Serial.println();
  if (sensor3==1)
  {
    analogWrite(3, HIGH);
  } else
  {
    analogWrite(3, LOW);
  }
  delay(100);
}

Leave a Reply