User Tools

Site Tools


courses:intro.prototyping.fall.2012.nov27

Some more for Arduino

Remember, when working with the Arduino, think of it in terms of what kind of input do we track, what kind of output do we want to create, and how do we imagine the interaction between them to be experienced. This is the basis for your program. How the different parts are connected is secondary and just a question of copying from the examples. The tricky and original part is the behaviour!

states

So far most of what we've done in both Processing and Arduino has been immediate reactions. If a button is pressed something changes immediatly. But what if you want to have something last because you made the choice? Like turning on the lights of your car or turning on the wipers. To do this we have to create what programmers call a state machine. What it really is, is that in programming we use variables to keep track of what state we are in. If the headlights are on or off. If the wipers are going up, going down or are turned off. And when something is changed (say button pressed again) you change that variable.

Remember the button example?

  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
 
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {     
    // turn LED on:    
    digitalWrite(ledPin, HIGH);  
  } 
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW); 
  }

Here the lit LED reacts immediatly to the press of the button.

To make it more about flicking it on or off with states we add a variable to keep track of that state. Lets make it an integer variable called litUp. We decide that in the program it will be 1 if the light should be on and 0 if the light should be off.

int litUp = 0;

Now we set up so that the buttonpress changes the variable instead of changing the light.

  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
 
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {     
    if(litUp == 0) //If our variable contains 0
    {
      litUp = 1; //Change it to 1
    }
    else //If it was 1
    {
      litUp = 0; //Change it to 0
    }
  } 

Finally we set up a similar IF-statement as before for lighting up the LED. But since it depends on the variable rather than the button, it will keep being on or off until the button is pressed again.

  if(litUp == 1)
  {
    digitalWrite(ledPin,HIGH);
  }
  else
  {
    digitalWrite(ledPin,LOW); 
  }

In this case we use the same button to turn on and off. But naturally we could instead hook up two or more buttons and change the state of the variable depending on which button is pressed.

courses/intro.prototyping.fall.2012.nov27.txt · Last modified: 2012/11/26 07:44 by 130.239.232.47