Making Things Interactive

March 27, 2008

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;
  }
}
Advertisements

1 Comment »

  1. oh yea…i forgot to mention. instead of the ultrasonic sensor which i don’t have now, i used a pushbutton in its place.

    Comment by tyang1 — March 27, 2008 @ 8:03 am | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: