Lab 02

For our second lab we began to use our microcontrollers to control simple circuits powering LEDs with code.

digi-out

For my physical interface for a lock I decided that I wanted to be able to clap my hands four times, and a green LED would light up. I began working with a small piezo mic that came with my starter kit. Of course this didn't work. Next I tried using a photocell, so that if I moved my hand over it four times a light would turn on. Realizing that I was entering the realm of analog inputs I connected my photocell to pin A0.

The main challenge I had was a programming issue. I had to get comfortable with the fact that my program is continuously looping, rather then running sequentially or asynchronously. Since the program loops, keeping track of exactly four times my hand passed over the photocell was dificult. My solution was rather hacky.

int hit = 0;
void setup() {
  pinMode(A5, INPUT);
  pinMode(3, OUTPUT);
  pinMode(2, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (analogRead(A5) < 500 ) {
    hit = hit + 1;
  }
  if (hit > 600){
    digitalWrite(3,HIGH);
    digitalWrite(2,LOW);
    hit = hit+1;
  }else{
    digitalWrite(2,HIGH);
    digitalWrite(3,LOW);
  }
  if (hit == 1500){
    hit = 0;
  }
  Serial.println(hit);
}

This code starts with a red LED being lit and waits for my photocell to produce a resistence below 500 bytes. When it does, it increase the swipe/hit count. Because the program loops so quickly, covering the photocell for a second might result in hundreds of hits. To deal with this I added if statements to control LEDs based on the the hit rate. Once 600 hits is reached, I turn on the green LED and continuously add 1 to the hit rate. When the hit rate hits 1500, I reset the hits to 0. By doing this I can keep my light green for a set amount of time before it turns back to red.

Written on September 21, 2015