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() {
  size(600,600);
  stroke(255);
  generateSequence();
   }

void draw() {
  background(0);
  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<level+1; i++){
   background(0);
   
   if(gameSeq[i] == 0){
     //line(400, 500, 200, 100);
     println("negative");
     delay(1500);}
   else
    { println("positive");
      delay(1500);
     //line(400, 100, 200, 500);
  }
}
  println();
  println("Now, Your Turn!!");
  displayState = 1;
}

 
boolean detectChangeEvent() //detect change in state

{

  if(currentX == lastX)
  return false;
  else
  return true;
}

void generateSequence() //genetare random sequence of size = gameSize
{
  
  for(int i = 0; i< gameSize; i++){
      gameSeq[i] = int(random(0,2));}

}

void flashCorrect(){
println("correct!");

}

void reset()
{
  println("WRONG!!");
}

Notice this game has to keep track of many states: The Level, The State of the game(Simon Says Part, or the I Show You Back Part) , The state of the position the player is in sequence, and the current state of each move(is it a move to the left, right, or no move).

International Dance Party

Filed under: Will Not Count Towards Your Grade — Jesse @ 12:45 am

This the Int’l Dance Party (IDP) system I describe in class. 

Update: Boomboxes State Machine

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

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 
 */

//LIBRARIES

//GLOBAL VARIABLES
//pins
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;

//---SETUP-------------------------------------------------------------->

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
}

//---LOOP--------------------------------------------------------------->

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

  currentTilt = digitalRead(tiltPin);
  //Serial.println(currentTilt);
  //delay(100);
  //Serial.println(0);

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

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

}

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);
  frameRate(10);
  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 = port.read();                              // read it and store it in val
  }

  if (val == 1) {
    x++;
    background (200);
  }
}

Related Projects

Filed under: Brian Kish — bkish @ 1:53 pm

These are some projects that make use of ‘smart walls’ to modulate light.

final-project-proposal2.pdf

PhotoSensor State Machine

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

state-diagram.jpg

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);
  Serial.begin(9600);

}

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)photoSensor);
  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);
    digitalWrite(brightLED,LOW);
    Serial.println("Light is good");
  }
  // bright State
  if(photoSensor < potMin){
    digitalWrite(goodLED, LOW);
    digitalWrite(darkLED, LOW);
    digitalWrite(brightLED,HIGH);
    Serial.println("Too Bright");
  }

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

  }
}

PhotoSensor State Machine

Filed under: Will Not Count Towards Your Grade — bkish @ 1:43 pm

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);
  Serial.begin(9600); 
  }


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
  break;
 
case sQuestion:         //state is question:
  Serial.println("Push the lit button.");
  Serial.println();
  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;}
  break;
  
case sIncorrect:      //state is incorrect:
  Serial.println("Wrong.");
  Serial.println("Your score is:");
  Serial.println(score);      //print score
  Serial.println();  
  delay (500);
  if (digitalRead(participate)==LOW) //check if participate is off
    {state = sAttract;
     playPrint = 1;}
  else
    {state = sQuestion;}    //return to question state
  break;

case sCorrect:      //state is correct:
  Serial.println("Correct!");
  Serial.println("Your score is:");
  Serial.println(score);
  Serial.println();  
  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);
       }  
    }
}

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:

Code:

 


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

void setup()
{
  Serial.begin(9600);
  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
  blink();   

}

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);
    delay(1000);
    digitalWrite(ledPin, LOW);
    delay(1000);
}

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);
  Serial.begin(9600);
  val = analogRead(photoPin);
}

void loop() {

  switch (currentState) {
  case sOff:
    Serial.println("off");
    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; 
    }
    break;

  case sDim:
    Serial.println("dim");
    analogWrite(ledPin, 100);
    if (light > val*sens) {                   
      currentState = sOff;
    }
    else if (digitalRead(buttonPin) == HIGH) {
      currentState = sBright;
    }
    break;

  default:
    currentState = sOff;
    nextState = sBright;
    break;
  }
}
Next Page »

The Rubric Theme Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.