#define REDPIN 0 #define YELLOWPIN 1 #define GREENPIN 4 #define BUTTONPIN 2 #define NUMLIGHTS 3 /* For the arrays: - Red will be referenced by array index 0. - Yellow will be referenced by array index 1. - Green will be referenced by array index 2. */ //We will start with red in the "on" state, which will be represented by a 1. 0 is "off." int lightState[] = {1,0,0}; //All lights should start dim. int lightLuminosity[] = {0,0,0}; //We'll need some variables to monitor the button. int buttonState = LOW; int lastButtonReading = LOW; int lastButtonState=LOW; long lastDebounceTime = 0; long debounceDelay = 50; /* Set the pinMode for each of the ATTiny's pins. */ void setup() { pinMode(REDPIN, OUTPUT); pinMode(YELLOWPIN, OUTPUT); pinMode(GREENPIN, OUTPUT); pinMode(BUTTONPIN, INPUT); } /* Each time we loop through the program we should check the state of our pushbutton, then fade the lights. */ void loop() { monitorButton(); fadeLights(); } /* Each time we loop through the program, we check to see if the state (pressed or not pressed) of our pushbutton has changed. If it has changed, we call the buttonStateChanged() function. */ void monitorButton() { //Read the current state of the button. int reading = digitalRead(BUTTONPIN); if (reading != lastButtonReading) { lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { buttonState = reading; if (lastButtonState!=buttonState) { buttonStateChanged(); } lastButtonState = buttonState; } lastButtonReading = reading; } /* If the button state has changed to "not pressed", we want to advance the light state. Said a different way, we don't care when the user presses down on the button. We care when the user releases the button. */ void buttonStateChanged() { if (buttonState==LOW) { advanceLightState(); } } /* This function simply advances from red to green, from green to yellow, and finally from yellow to red. */ void advanceLightState() { //If red is on, turn it off and light up green. if (lightState[0]==1) { lightState[0]=0; lightState[2]=1; return; } //If yellow is on, turn it off and light up red. if (lightState[1]==1) { lightState[1]=0; lightState[0]=1; return; } //If green is on, turn it off and light up yellow. if (lightState[2]==1) { lightState[2]=0; lightState[1]=1; return; } } /* We don't want our lights to simply blink on and off instantly! We want them to fade pleasantly from off to on, and back again. We do this using pulse width modulation. If we analogWrite the value "0" to an LED, it will be fully dark. If we analogWrite the value "255" to an LED, it will be fully bright. If we analogWrite the value "128" to an LED, it will be about half-way bright. */ void fadeLights() { int i; //Loop through each light. If the light is set to "on," increase its brightness. Otherwise, decrease the brightness. for (i=0; i0) { lightLuminosity[i]--; } } } analogWrite(REDPIN, lightLuminosity[0]); analogWrite(YELLOWPIN, lightLuminosity[1]); analogWrite(GREENPIN, lightLuminosity[2]); }