/* * Binary Counter * by Steven Lehrburger * 27 May 2008 * * Combines the Loop and Button examples to create an array of lights that counts * the number of times the switch has been pressed in binary. */ int pins[] = { 2, 3, 4, 5, 6, 7 }; // an array of pin numbers int num_pins = 6; // the number of pins (i.e. the length of the array) int count; int inputPin = 8; // choose the input pin (for a pushbutton) int val = 0; // variable for reading the pin status void setup() { pinMode(inputPin, INPUT); // declare pushbutton as input count = 0; // start the count at zero for (int i = 0; i < num_pins; i++) // declare each pin as output pinMode(pins[i], OUTPUT); } void loop() { val = digitalRead(inputPin); // get the button state if (val == HIGH) { // if the button was depressed count++; // increment the counter displayNumber(count); // illuminate the appropriate LEDs // turnOnAll(); delay(200); // so holding it down doesnt count too fast } } void turnOnAll() // was used for debugging - just turns on all the lights { for (int i = num_pins; i >= 0; i--) { digitalWrite(pins[i], HIGH); } } void displayNumber(int number) // illuminates the LEDs for the passed number { int remaining = number; for (int i = num_pins; i >= 0; i--) { // starting with the last pin (that has the largest value) and going down if ((remaining - exponent(2, i)) >= 0) { // if that pin is larger than the remaining value digitalWrite(pins[i], HIGH); // illuminate that pin remaining -= exponent(2, i); // and subtract the value from the number and keep going } else { digitalWrite(pins[i], LOW); // otherwise, the pin is off } } } int exponent(int base, int power) // simply calculates an exponent - perhaps there is a library with this { // but it was faster to rewrite it int result = 1; for (int i = 0; i < power; i++) { result *= base; } return(result); }