When we left off we comparing computers to machine by calling it a universal machine.  The thrill  came from giving the same machine different things to  do.   With moveable type Guttenberg could build one machine to print books about cats one day and dogs the next.  Using categories this blog can be about dogs one second and cats the next so things have things are changing faster.   When things change this quickly we need to move beyond the comparison with machines to something more mutable and amorphous like “Media”  With universal media anyone can communicate anything to anyone at anytime.  In starting this class with physical computing we are still working on the anyTHING part of that.

Variables are the programming tool that allow the computer to vary or change so fast.  So this week you will start in with this last item in the holy trilogy — loops, if statements and now variables. Of the the three, variables take the longest time to get the knack of how and when and why to use them.  You can get started by thinking of them as storage spaces for keeping track of things as they change.  The hard part is being clever about noticing what things are changing in your system and how it might help to keep track of them.   Eventually you develop a knack for which changes to keep track of  but it does take time.

Variation in the World

You have already encountered a variation in your programs last week.  You watch a pin go from high to low in your program last week and we will get to more interesting range of variation this week with analog input and output.

if (digitalRead(7)== HIGH){
   digitalWrite(13, HIGH);



Intelligence Amplification

Reflecting a wider array of variation in the world is what microcontrollers are good at.  Starting by strapping your switches to weird things in your world puts us into the camp of  intelligence amplification (IA) where we are just trying to capture and transmit your expression.  This is compared to Artificial Intelligence (AI) where we are hoping the for the machine to originate the variation.  Musical instruments are the archetypal IA project where robots would be for AI.  You not may need a computer to simply reflect change in the world, the circuit from the first week with no computer involved does that.  But even with an musical instrument we are going to need to use variables in a computer to notice changes over time.  So the distinction between IA and AI is not so clear.

Variables : Tracking Variation over Time

postit PicknRollSeriesA

We might be mentally healthier if we spent more time in the present moment.  If only we could just listen to our breathing like a switch going on and off instead of obsessing about schemes for the future,  regrets about the past and multitasking on 5 things at once.  Variables, in concert with loops, allow computers to mimic our ability to suffer (and benefit) from attending to change over time.

For example, if you wanted to build a musical instrument you might want to strike the note once when you first pressed the button but not over and over while the button is pressed.  We couldn’t just reflect the state of the pin but rather look for the moment where it changes.  Our minds cull out events like this instantly and effortlessly.  It is hard to slow down your thinking and break it into steps in order to repeat it on the computer.  Here is a try at breaking your thinking into parts and using a variable as note pad.

  • Algorithm:  
    • Remember the state of the switch last time and check the current state against the last state.
  • Psuedo Code:
    • Make a variable the keeps track of the last state of the input pin
    • If the current state of the pin is different from what is stored in the variable from last time then play the sound.
    • Set the variable for last state to the current state so it can be check in the next go through the loop
  • Actual Code :
int lastTime = 0; 
//make a variable to keeping track of state of the button last loop 
void setup(){

void loop(){ 
  int nowButton = digitalRead(7); //store this temporarily (not entirely necessary) 
  if (nowButton == HIGH && lastTime == LOW ){ //if it is high now but was not last loop 
    digitalWrite(13,HIGH);//strike note 
    delay(100);  //terrible hack to make it so you see the LED for more than an instant
    digitalWrite(13,LOW); //in nature the note would stop by itself 
    //but the machine will only do what you tell it to do. 
  lastTime = nowButton; 
  //next time check against the current state. 


Syntax of Variables

Here is how you use variables for storing change:

    1. Declare the type of variable
    2. Initialize variable
    3. Vary the Variable



int input ; 
boolean pressed; 
byte color; 
int times = 100;  //declaring them and initializing all in one step


Type (size)

First you put the type of variable, int, byte, boolean etc.  In effect this sets the size of the storage area the computer will use for this variable.  int is bigger than byte which is bigger than boolean so you can probably be safe using “int” for most things.  (Sometimes functions are fussy about the types of variables you feed them as parameters or use to receive their return values.) Other language let you skip the declaration thing and head right to initializing but not this one.


Then you put a name.  Anything you want is okay as long as they start with a letter and have no spaces.  Your code will be more readable if you name them something that describes what is changing.  I would use things like pressure and heat and avoid things like a, b, c.  It has to be one word so people have different strategies for that like cat_fat or catFat.  Anyway you can name them anything you want.

Scope (where they work)

Declaring is typically done at the top of your program so any of your functions can use them.  If you do it inside a set of curly bracket, the variable will die after that closing curly bracket.  For now I would declare all your variables at the top in order to give them scope for the whole program.


int oldInput;  //just declared
int limit = 100;  //declared and initialized with a number;

void setup(){ 
  oldInput = digitalRead(7); //initialized with code

void loop(){


This is where you put something in them to start with.  As you might guess this is typically done in the setup function.  You can declare them and initialize them all at once at the top above the setup function if you are just putting a number in them.  If you are using a function (e.g. digitalRead) to  initialize them, you should do it in set up.   If you forget to put something in them, the computer will start them off with zero or false.


Finally you have to remember to vary your variable.  It is funny how many people forget to do this.  Sorry I had to cheat by introducing analogWrite (much more about this in  a minute) because I was getting bored with the only change being from zero to one.   It is pretty clear that the the LED would get brighter over time with this code.   It requires a variable to keep track of where in the fading up process you are.

int brightness =0; 
void setup(){

void loop(){
  brightness = brightness + 1; //or you could say brightness++
  if (brightness < 256){  //255 is biggest number analogWrite can take
  delay(20);//make it more noticable

Okay brightness of the LED is kind an obvious thing that is changing.  But what if you wanted the LED to fade up and down.  How would you do that?  Ask what is varying.  The brightness is still varying but you will need to add a slightly more conceptual variable which is the direction the brightness is heading in.  Knowing when to employ variables for these more “meta” changes is something that comes with time.

int brightness =0; 
int fadeDirection = 1;
void setup(){

void loop(){
  if (brightness == 255){  //255 is biggest number analogWrite can take
    fadeDirection = -1;
  else if (brightness == 0){
    fadeDirection = 1;
  brightness = brightness + fadeDirection; 
  //instead of always adding one, add a variable amount

  delay(10);//make it more noticeable


Lets say we have 3 leds, and we want to use our switch to control which one is on.  We can update our counter each time the button is pressed, and based on what number the counter is, we can then change which LED is on.

int buttonPin = 2;   
int ledRed = 7;
int ledYellow = 6;
int ledGreen = 5;

boolean buttonState = false; // boolean to see if button is pressed or not
boolean previousState = false; // boolean to see if we already pressed the button

int counter = 0; // determines what led will turn on

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledRed, OUTPUT);
  pinMode(ledYellow, OUTPUT);
  pinMode(ledGreen, OUTPUT);

void loop() {
  buttonState = digitalRead(buttonPin);

  if (buttonState == true) {
    if (previousState == false) {
      previousState = true;
      counter = counter + 1;
  } else {
    previousState = false;

  if (counter == 0) {
    digitalWrite(ledRed, HIGH);
  } else {
    digitalWrite(ledRed, LOW);

  if (counter == 1) {
    digitalWrite(ledYellow, HIGH);
  } else {
    digitalWrite(ledYellow, LOW);

  if (counter == 2) {
    digitalWrite(ledGreen HIGH);
  } else {
    digitalWrite(ledGreen, LOW);
  if (counter > 2){
    counter = 0;    // if we press the counter 3 times reset the counter to start over again




Up until now we’ve been using the delay() function to trigger different behavior in our code.  But the delay() function is a blocking function.  It halts all of your code until it is finished delaying.  If you are trying to trigger different behaviors at different times (like continuously reading a switch to blink an LED) we need to do a little more to organize our sequences.

Our algorithm for coding such a thing is as follows:

  • Set an interval for when your timer should go off.  Remember, in Arduino time is measured in milliseconds.
  • Set a boolean to tell us if our LED should be on or off
  • Start our timer by saving a “timestamp” in a variable (in the example its called lastCheckedTime).
  • At the beginning of our loop check if the button is pressed.  If its pressed make our interval small (for fast blinking).  If the button is not pressed blink the LED slower by making the interval longer
  • compare the “timestamp” to the current time.  The millis() function tells us what our current time is.
  • If we have waited longer than our interval, then change the state of the LED (using the boolean named “ledOn”)
  • At the end of the loop if our LED state is true turn the led on, if it is false turn the led off.
 long lastCheckedTime; // variable to compare our current time to
int interval = 1000;  // variable for how long our interval will be

int button = 2;
int led = 7; // variable to tell us which pin the led is connected to

boolean ledOn = false;

void setup() {
  pinMode(button, INPUT);
  pinMode(led, OUTPUT);


void loop() {
  if (digitalRead(button) == HIGH) {
    interval = 75;
  else {
    interval = 1000;

  if (millis() - lastCheckedTime > interval) { // if the currentTime - our last saved time is bigger than our interval
    ledOn = !ledOn ; // if we are past the interval the LED state is now the opposite of what it was
    lastCheckedTime = millis();    // reset our last checked time. otherwise this block will only execute on first start up

  if (ledOn == true) {
    digitalWrite(led, HIGH);
  } else if (ledOn == false) {
    digitalWrite(led, LOW);

Try your own timers and counters. Try making different timers and inputs for different leds.

Leave a Reply