Making Things Interactive

March 28, 2008

Simon Says: Macbook Tilt Edition

Filed under: 8: State Machine,Joshua Smith — jssmith44 @ 2:08 pm

Below is the processing code for the Simon Says game I made involving tilting your macbook along different axis. Im going to build a better GUI for it, and update the code with it soon.

import sms.*;

int gameSize = 100; //max sequence number
int[] gameSeq = new int[gameSize]; // generated sequence (0,1)
int level = 0;
int threshold = 100; // threshold value for tilt sense
int currentX = 0; // current state of tilt (0, 1, -1)
int lastX = 0; // last state of tilt
int userIndex = 0; // where player is in sequence
int displayState = 0; // should display sequence?

void setup() {

void draw() {
int[] vals = Unimotion.getSMSArray();
//println(vals[0] + ” ” + vals[1] + ” ” + vals[2]);
lastX = currentX;
if (vals[0] > threshold)
currentX = 1;
else if (vals[0] < (threshold *-1)) currentX = -1; else currentX = 0; if(displayState == 0) displaySequence(); // show values up to index, then say go! if(detectChangeEvent() && currentX != 0) evaluate(); } void evaluate() // determine if move matches sequence { if(currentX == 1 && gameSeq[userIndex] == 1){ flashCorrect(); if(userIndex < level) userIndex++; else {displayState = 0; level++; userIndex=0; currentX = 0; println(); println("Round: " + (level+1)); delay(2000);} } else if(currentX == -1 && gameSeq[userIndex] == 0){ flashCorrect(); if(userIndex < level) userIndex++; else {displayState = 0; level++; userIndex = 0; currentX = 0; println(); println("Round: " + (level+1)); delay(2000);} } else reset(); } void displaySequence() // show sequence up to userIndex { for(int i =0; i

Update: Boomboxes State Machine

Filed under: 8: State Machine,Assignments,Jesse Chorng — Jesse @ 12:10 am

I had some trouble with getting my state machine to work in class. I got home, went straight to Radio Shack and got headphone cable Y-adapter so I could hook up speakers to hear what’s actually being played. I don’t know what exactly went wrong in class but I suspect that the Shuffle’s output might have been different and wasn’t enough to cross the threshold from ‘Listening’ to ‘Audio Detected’

I got it to work simply by rechecking connections and being able to judge what state it should be in with the help of speakers. It goes from ‘listening’ (red LED), to ‘audio detected’ (blue LED), then to ‘party’ mode (dancing LED bar) via potentiometer,  back to ‘audio detected’, then to ‘party’, and once the music is paused back to ‘listening’  

March 27, 2008

digital book machine

Filed under: 8: State Machine,Assignments,Nadeem Haidary — nhaidary @ 5:00 pm

Was working better earlier but the tilt switch sometimes refuses to work without me flicking it angrily. This is a concept for a digital book that powers an electronic paper screen with each turn of the page (in this case an LED). Pages are refreshed with a combination of a tilt switch and motor input. The Processing display has been edited out of the video because of inconsistencies. Arduino:

 *   Digital Book Reader
 *   State Machine 
 *   Spring 2008
 *   Nadeem Haidary 


int motorPin = 0;                   // motor is connected to pin 0
int LEDPin = 9;                     // LED is connected to pin 9
int tiltPin = 8;                    // tilt switch is connected to pin 8

int motorValue;                     // the value read from the motor
int tiltValue;                      // the value read from the tilt switch
int currentTilt;                    // the current tilt value
int previousTilt;                   // the state of the tilt switch
int x = 0;


void setup() {
  pinMode(motorPin, INPUT);         // Set the motor pin as an input
  pinMode(LEDPin, OUTPUT);          // Set the LED pin as an output
  pinMode(tiltPin, INPUT);          // Set the tilt pin as an input

  //currentTilt = digitalRead(tiltPin);
  previousTilt = digitalRead(tiltPin);

  Serial.begin(9600);               // Start serial communications


void loop(){
  motorValue = analogRead(motorPin);      // Read the motor pin as an analog input 
  analogWrite(LEDPin, motorValue);

  currentTilt = digitalRead(tiltPin);

  if (motorValue > 30) {
    Serial.println ("Page" + x);
    //Serial.print(1, BYTE);                   // send 1 to Processing
    previousTilt = currentTilt;  

  else {                                     // If the switch is not ON,
    //Serial.print(0, BYTE);                   // send 0 to Processing



* Digital Book Reader
* State Machine
* Spring 2008
* Nadeem Haidary

import processing.serial.*;

PFont font;
Serial port; // Create object from Serial class
int val; // Data received from the serial port
int x = 0;

void setup() {

size (400, 600);
background (200);
fill (0);
println(Serial.list()); // Set up the serial communication
port = new Serial(this, Serial.list()[1], 9600); // Open the port that the board is connected to (in this case COM4 = [1])
// and use the same speed (9600 bps)
font = loadFont(“BookAntiqua-BoldItalic-48.vlw”);

void draw() {
textFont(font, 48);
text(x, 100, 100);

if (0 < port.available()) { // If data is available, val =; // read it and store it in val } if (val == 1) { x++; background (200); } } [/sourcecode]

PhotoSensor State Machine

Filed under: 8: State Machine,Brian Kish — bkish @ 1:49 pm


state-diagram.jpgThis a state machine that will be the basis for my final project of automated louvers. This uses 3 LEDs, a photoresistor, a potentiometer, and aservo to communicate. The user is able to set the light levels that they desire by turning a potentiometer. The machine then tells the person one of three things: Light is good, Its too Dark!, or Its too Bright. It glows 3 different LEDs to express which state it is in. There will be pictures and video to follow, once I find my camera :)

const int sGood= 0;
const int sBright = 1;
const int sDark = 2;

int servoPin = 2;     // Control pin for servo motor
int minPulse = 500;   // Minimum servo position
int maxPulse = 2500;  // Maximum servo position
int pulse = 0;        // Amount to pulse the servo
int goodLED= 6;
int darkLED= 7;
int brightLED = 5;

long lastPulse = 0;    // the time in milliseconds of the last pulse
int refreshTime = 20; // the time needed in between pulses

int photoSensor = 0;  // the value returned from the analog sensor
int sensorPin = 1;    // the analog pin that the sensor's on
int potSwitch = 0;
int potMin = 0;
int potMax = 0;
int potPin = 0;

void setup() {
  pinMode(servoPin, OUTPUT);  // Set servo pin as an output pin
  pinMode(potSwitch, INPUT);
  pinMode(goodLED, OUTPUT);
  pinMode(darkLED, OUTPUT);
  pinMode(brightLED, OUTPUT);
  pulse = minPulse;           // Set the motor position value to the minimum
  digitalWrite(goodLED, LOW);
  digitalWrite(darkLED, LOW);
  digitalWrite(brightLED, LOW);


void loop() {
  photoSensor = analogRead(sensorPin);      // read the analog input
  potSwitch = analogRead(potPin);
  pulse = (photoSensor *19)/10 + minPulse;    // convert the analog value
  // to a range between minPulse
  // and maxPulse. 

  potMin = potSwitch-25;
  potMax = potSwitch+50;

  Serial.println((int)potSwitch);  // pulse the servo again if rhe refresh time (20 ms) have passed:

  if (millis() - lastPulse >= refreshTime) {
    digitalWrite(servoPin, HIGH);   // Turn the motor on
    delayMicroseconds(pulse);       // Length of the pulse sets the motor position
    digitalWrite(servoPin, LOW);    // Turn the motor off
    lastPulse = millis();           // save the time of the last pulse

  //good State
  if(photoSensor <= potMax && photoSensor >= potMin){
    digitalWrite(goodLED, HIGH);
    digitalWrite(darkLED, LOW);
    Serial.println("Light is good");
  // bright State
  if(photoSensor < potMin){
    digitalWrite(goodLED, LOW);
    digitalWrite(darkLED, LOW);
    Serial.println("Too Bright");

  // dark State
  if(photoSensor > potMax){
    digitalWrite(goodLED, LOW);
    digitalWrite(darkLED, HIGH);
    Serial.println("Too Dark");


State machine

Filed under: 8: State Machine,Lea — tovelet @ 1:42 pm

I am not very good at this game, actually.

A blinky light game. Once a player has decided to “participate,”
the LED’s blink in turn. If a player hits the button that corresponds
to the currently lit LED, they gain a point, and the lights cycle slightly
faster. They can exit the game at any time, and the score and speed
reset for the next player.

int ledOne = 4;
int ledTwo = 7;
int buttonOne = 2;
int buttonTwo = 8;
int participate = 9;
int delayTime = 200;
int answer = 0; //”right” or “wrong” for any given round
int score = 0; //score tally, reset at the beginning of the game
int playPrint = 1; //should it print “Will you play?”

const int sAttract = 0;
const int sQuestion = 1;
const int sIncorrect = 2;
const int sCorrect = 3;

int state = 0;

void setup ()
pinMode(ledOne, OUTPUT);
pinMode(ledTwo, OUTPUT);
pinMode(buttonOne, INPUT);
pinMode(buttonTwo, INPUT);
pinMode(participate, INPUT);

void loop ()
switch (state)
case sAttract: //state is attract
digitalWrite (ledOne, LOW); //reset LEDs to off
digitalWrite (ledTwo, LOW);
if (playPrint == 1)
{Serial.println(“Will you play?”);}
score = 0; //reset score
delayTime = 200; //reset delayTime
if (digitalRead(participate)==HIGH)
{state = sQuestion;}
playPrint = 0; //only print it once

case sQuestion: //state is question:
Serial.println(“Push the lit button.”);
if (digitalRead(participate)==LOW) //check if participate is off
state = sAttract;
playPrint = 1;
answer = cycleLed(); //run the cycling lights, return correct or incorrect
score = score + answer; //tally score
if (answer == 0)
{state = sIncorrect;}
if (answer == 1)
{state = sCorrect;}

case sIncorrect: //state is incorrect:
Serial.println(“Your score is:”);
Serial.println(score); //print score
delay (500);
if (digitalRead(participate)==LOW) //check if participate is off
{state = sAttract;
playPrint = 1;}
{state = sQuestion;} //return to question state

case sCorrect: //state is correct:
Serial.println(“Your score is:”);
delay (500);
delayTime = (delayTime – (delayTime/(100-score))); //cycle lights faster next time
if (delayTime <= 50) {delayTime = 50;} //do not make it too hard if (digitalRead(participate)==LOW) {state = sAttract; playPrint = 1;} else {state = sQuestion;} break; default: Serial.println ("error"); //this shouldn't happen state = sAttract; playPrint = 1; break; } } int cycleLed () { while (true) { for (int i=0; i<=delayTime; i++) { digitalWrite(ledOne, HIGH); //ledOne is on digitalWrite(ledTwo, LOW); if (digitalRead(participate)==LOW) //make sure participate is high {state = sAttract; playPrint = 1; return (0);} if (digitalRead(buttonOne)==HIGH) {return (1);} //so if buttonOne is pressed, correct if (digitalRead(buttonTwo)==HIGH) {return (0);} //and if button Two is pressed, incorrect delay(1); } for (int i=0; i<=delayTime; i++) { digitalWrite(ledOne, LOW); //inverse of the other one digitalWrite(ledTwo, HIGH); if (digitalRead(participate)==LOW) {state = sAttract; playPrint = 1; return (0);} if (digitalRead(buttonOne)==HIGH) {return (0);} if (digitalRead(buttonTwo)==HIGH) {return (1);} delay(1); } } } [/sourcecode]

State Machine: Light Motor

Filed under: 8: State Machine,Assignments,Thomas Hendrickson — tphendrickson @ 1:06 pm

I created a circuit with a motor that will turn on if the amount of light surrounding it increases. I calibrated a photosensor to accomplish this, which also will help in my final project.

State Diagram:

Circuit Photo:



int motorPin = 4;
int ledPin = 13;
int photoPin = 0;
int readIn = 0;
int initialRead = 0;
int activateVal = 0;

void setup()
  pinMode(ledPin, OUTPUT);
  pinMode(motorPin, OUTPUT);
  pinMode(photoPin, INPUT);

  blink();     //blinks the status LED
  initialRead = analogRead(photoPin); //gets initial reading for photosensor
  activateVal = initialRead * 2;      //the activation value will be double the initial


void loop()
    readIn = analogRead(photoPin);    //gets the current sensor reading

    while (readIn >= activateVal)     //while loop turns on motor and status LED if current reading
    {                                 //is greater than the activation value
      digitalWrite(ledPin, HIGH);
      digitalWrite(motorPin, HIGH);

      readIn = analogRead(photoPin);  //checks the current value

    digitalWrite(ledPin, LOW);        //turns off motor and LED if current value is not great enough
    digitalWrite(motorPin, LOW);


void blink()
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin, LOW);

State Machine Code – Night Table

Filed under: 8: State Machine,Assignments — tyang1 @ 8:02 am

This is the code to follow my state machine schematic.  The three states: off, bright, dim.  The only thing that physically changes is the LED so there was no point in taking a video.   Circuit of State Diagram Monitor outputs for state machine


const int sOff = 0;
const int sBright = 1;
const int sDim = 2; 

int photoPin = 1;
int light;
float sens = 0.85;
int val = 0;
int pirPin = 3;
int ledPin = 11;
int buttonPin = 7;

int currentState = sOff;
int nextState = sBright;

void setup() {

  pinMode(photoPin, INPUT);
  pinMode(pirPin, INPUT);
  digitalWrite(pirPin, LOW);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  val = analogRead(photoPin);

void loop() {

  switch (currentState) {
  case sOff:
    analogWrite(ledPin, 0);
    light = analogRead(photoPin);
    if (light  val*sens) {                        // if ambient light is on...
      currentState = sOff;
    else if (digitalRead(pirPin) == LOW) {
      currentState = sOff;
    else if (digitalRead(pirPin) == HIGH) {
      currentState = sDim; 

  case sDim:
    analogWrite(ledPin, 100);
    if (light > val*sens) {                   
      currentState = sOff;
    else if (digitalRead(buttonPin) == HIGH) {
      currentState = sBright;

    currentState = sOff;
    nextState = sBright;

Boomboxes: State Machine

Filed under: 8: State Machine,Assignments,Jesse Chorng — Jesse @ 5:24 am

For assignment 8b, I created a state machine that I will work on for the next two weeks to improve for the final project. In this one, there are three states: Listening, Audio Detected, and Party (or dancing lights).  Using a stereo input, the Arduino waits for an incoming signal. Once an audio source is connected and playing music, the Arduino detects it and changes states. Here’s the code:
Boomboxes – Social Interaction Through Music
Small Undergraduate Research Grant

Jesse Chorng


const int sListening = 0; // The system is waiting for audio to be plugged in. Speakers/Lights are off
const int sAudioDetected = 1; // The system detects audio being played. Speakers/Lights are on
const int sParty = 3; // If there’s enough people around, party time! Lights dance to music

int currentState = sListening;
int nextState = sAudioDetected;

int audioPin = 1; // Audio signal in from stereo jack
int partySwitch = 2; // Push button to activate ‘party’ state

int listeningLed = 9; // LED to signal ‘listening’ state
int detectedLed = 10; // LED to signal audio signal detected; ‘detected’ state
int partyLed = 12; // LEDs start to pulse with music, ‘party’ state. IC3915 activated

int audioLevel = 0; // Incoming audio level

void setup() {

pinMode(audioPin, INPUT);
pinMode(partySwitch, INPUT);
pinMode(listeningLed, OUTPUT);
pinMode(detectedLed, OUTPUT);
pinMode(partyLed, OUTPUT);


void loop() {

//digitalWrite(partyLed, HIGH);

switch(currentState) {
case sListening: // Listening State
digitalWrite(listeningLed, HIGH); // Listening LED on
digitalWrite(detectedLed, LOW);
digitalWrite(partyLed, LOW);
AudioLevelCheck(); // Check incoming audio level
if (audioLevel > 1) { // If there is incoming audio, move to ‘detected’ state
currentState = sAudioDetected;

case sAudioDetected: // Audio Detected State
digitalWrite(detectedLed, HIGH); // Audio Detected LED on
digitalWrite(listeningLed, LOW);
digitalWrite(partyLed, LOW);
AudioLevelCheck(); // Check incoming audio level
if (audioLevel = 500) { // If push button pressed, go to ‘party’ state
currentState = sParty;

case sParty: // Party State
digitalWrite(partyLed, HIGH); // Party LEDs (motion) on
digitalWrite(listeningLed, LOW);
digitalWrite(detectedLed, LOW);
if (audioLevel < 1) { // Return to 'listening' state if no audio currentState = sListening; } if (analogRead(partySwitch) <= 500) { // Return to 'detected' state if no pushbutton currentState = sAudioDetected; } break; default: // Default Case aka Error Case Serial.println("ERROR: default state"); currentState = sListening; // Reset back to 'listening' state nextState = sAudioDetected; break; } } void AudioLevelCheck() { // Checks incoming Audio Level by taking int count = 0; // 5 input values in 1 second intervals for (int i = 0; i < 5; i++) { // then takes the average. count += analogRead(audioPin); delay(1000); } audioLevel = count / 5; // Audio Level stores the average } [/sourcecode]  For the final, I hope to replace the pushbutton with sensors that will detect activity. The Arduino will then sense how many people are using Boomboxes and interact by dancing lights when more people are around and/or moving. 

wash your hands v2

Filed under: 8: State Machine,Gaku Sato — ponkotsu @ 12:38 am

This is my bathroom rig.  It annoyingly advocates sanitation by locking the door when it senses a flush until it determines that the occupant has washed his/her hands.


The black button on the right is the flush button.  Once that is pressed, the “wash your hands” LED blinks and the door locks via a solenoid deadbolt (behind protodoor).  The occupant’s intent to leave is signified by the doorknob switch (optimally a proximity sensor so no touching is necessary).  Initially it would re-remind the occupant to “wash your hands.”  If the water, which is represented by the potentiometer faucet, is turned more than a specified min threshold, the system registers that the occupant has rinsed his/her hands, but not washed them.  Pushing the which soap button tells the system that soap has been dispensed, but unless the water is running after that, it determines that the occupant is trying to trick the system!  Once the occupant has properly washed, the door unlocks and the “Thanks” LED blinks.

wash your hands!


int flushpin = 12;
int soappin = 11;
int waterpin = 5;
int lockpin = 8;
int doorpin = 2;
int thankspin = 7;
int washpin = 6;
int rinsepin = 4;
int fakepin = 3;
int state = 0; // 0=off, 1=on, 2=rinse, 3=soap

void setup()
pinMode(flushpin, INPUT);
pinMode(soappin, INPUT);
pinMode(waterpin, INPUT);
pinMode(lockpin, OUTPUT);
pinMode(doorpin, INPUT);
pinMode(thankspin, OUTPUT);
pinMode(washpin, OUTPUT);
pinMode(rinsepin, OUTPUT);
pinMode(fakepin, OUTPUT);
digitalWrite(lockpin, LOW);
digitalWrite(thankspin, LOW);
digitalWrite(washpin, LOW);
digitalWrite(rinsepin, LOW);
digitalWrite(fakepin, LOW);

void loop()
if(digitalRead(flushpin)==HIGH) {blink(washpin); state=1;}
if(state>0) {digitalWrite(lockpin, HIGH);}
if(state==1 && digitalRead(doorpin)==HIGH) {blink(washpin);}
if(state==1 && analogRead(waterpin)<800) {state=2;} if(state==1 && digitalRead(soappin)==HIGH) {state=3;} if(state==2 && digitalRead(doorpin)==HIGH) {blink(rinsepin); state=1;} if(state==2 && digitalRead(soappin)==HIGH) {state=3;} if(state==3 && digitalRead(doorpin)==HIGH) {blink(fakepin); state=1;} if(state==3 && analogRead(waterpin)<800) { digitalWrite(lockpin, LOW); blink(thankspin); state=0; } } void blink(int pin) { digitalWrite(pin, HIGH); delay(100); digitalWrite(pin, LOW); delay(100); digitalWrite(pin, HIGH); delay(100); digitalWrite(pin, LOW); delay(100); digitalWrite(pin, HIGH); delay(100); digitalWrite(pin, LOW); } [/sourcecode]

State Machine Assignment (Assignment 9?)

Filed under: 8: State Machine,Assignments,Cat Adams — catadams @ 12:36 am

For my state machine, I wired and coded the attract and reward states for my recycler (everything except the actual recycling process). I used two button presses for the sensors, which I realize may be a bit simplistic. I have ordered a motion sensor but it did not arrive in time to do this assignment.

I made the mistake of assuming that once I wrote the code and fixed the stupid things like adding a space to an “int” within the code when it was declared without a space, everything would work fine. Also that I would get the wiring right the first time. It might be helpful if we could quickly go over in class why it would be good to declare an int globally. I thought it would be alright to declare it within a certain “for” statement, but eventually discovered I needed to declare it in the beginning of my code with the LED’s and the sensors. Anyway, it works now. In addition to the youtube video, here is an image of my state machine in idle state and excited state.

static int Idle = 0;
static int Excited = 1;
static int Angry = 2;
static int Recycling = 3;
static int BigReward = 4;
static int SmallReward = 5;

//regular ints
int redLED = 3;
int blueLED = 5;
int greenLED = 6;
int angryWait = 0;
int switchPin1 = 9;
int switchPin2 = 12;
int currentState = Idle;
int numberCycle = 0;

//program for pulsing just one LED at a time (to save space later on)
void PulseOne (int pin) {
for (int i=0; i=0; i–) {
analogWrite(pin, i);

void setup(){
pinMode(redLED, OUTPUT);
pinMode(blueLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(switchPin1, INPUT);
pinMode(switchPin2, INPUT);

void loop(){

//Idle State: all LED’s off, print “Idle” on computer screen
if (currentState == Idle) {
//turn all the LEDs off (in case a later state does not turn an led off)
digitalWrite(blueLED, LOW);
digitalWrite(redLED, LOW);
digitalWrite(greenLED, LOW);
if (digitalRead(switchPin1) == HIGH){ //if the switch is pressed, i.e. if a person is detected (I do not have the proper sensor yet…)
currentState = Excited;
else{ //if no one is around, do nothing
currentState = Idle;

//Excited State: pulse all three LED’s, print “Excited”

if (currentState == Excited){
for(int value = 0 ; value =0; value-=5)
analogWrite(blueLED, value);
analogWrite(greenLED, value);
analogWrite(redLED, value);
if (digitalRead(switchPin2) == HIGH){ //if a recyclable is detected, start recycling it
currentState = Recycling;
else{ //if nothing happens, the machine gets angry
currentState = Angry;

//Angry State: pulse red LED and print “Angry!!”

if (currentState == Angry){
delay (2000);
if (digitalRead (switchPin2) == HIGH){ //if a recyclable is detected
currentState = Recycling;
else{ //if nothing happens, assume the person has walked away with a guilt conscience
currentState = Idle;

//Recycling: this is the state during which the entire recycling process happens.
//this will have a lot more code for the final
if(currentState == Recycling){
if (numberCycle <=5) { //self-explanatory currentState = SmallReward; } else{ currentState = BigReward; } } //Small Reward: print "Small Reward" and pulse the blue LED then the green LED if (currentState == SmallReward){ Serial.println("Small Reward"); PulseOne(blueLED); PulseOne(greenLED); currentState = Idle; } //Big Reward: print "Big Reward" and pulse the blue then green then red LED if (currentState == BigReward){ Serial.println("Big Reward"); PulseOne(blueLED); PulseOne(greenLED); PulseOne(redLED); currentState = Idle; } } [/sourcecode]

Next Page »

Create a free website or blog at