I got my first Arduino board (and associated goodies) today, and spent a couple hours learning my way around it. Patching together some of the early tutorials, I built a circuit and sketch that caused an LED to fade in and out, at a rate regulated by a potentiometer, with the whole thing turned on & off by a momentary switch. Not earth-shattering, obviously, but I feel like it’s a good night’s play for someone who’s new to the environment and hasn’t wired anything on a breadboard in some years.
Layout is below (click for full size), sketch source after that. I’d post the circuit diagram, but I haven’t taken the time to make the diagram generated by Fritzing not look like ass, and I’m tired.
Next steps will be to bang through some more tutorials, working up to proofs-of-concept for some interactive art pieces I want to do.
1 2 3 |
/* Circuit: 9 -> 330ohm -> LED+ -> GND |
1 2 3 |
2 -> switch2 5V -> switch3 GND -> switch4 |
1 2 3 4 |
5V -> pot0 A0 -> pot1 GND -> pot2 */ |
1 2 |
const int LED = 9; const int BUTTON = 2; |
1 2 3 |
int brightness = 0; int fadeAmount = 5; int fadeSense = 1; |
1 2 |
int lastButtonState = LOW; boolean fadeRunning = false; |
1 2 3 4 |
void setup() { pinMode(LED, OUTPUT); pinMode(BUTTON, INPUT); } |
1 2 3 4 5 6 7 8 9 10 11 12 |
void loop() { int buttonState = digitalRead(BUTTON); if (buttonState != lastButtonState) { lastButtonState = buttonState; if (buttonState == HIGH) toggleFadeState(); if (!fadeRunning) digitalWrite(LED, LOW); accountForSwitchBounce(); } |
1 2 3 4 |
if (fadeRunning) { analogWrite(LED, brightness); int sensorValue = analogRead(A0); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fadeAmount = ((sensorValue / 1023.0) * 25.0); fadeAmount = max(fadeAmount, 1); fadeAmount *= fadeSense; brightness = brightness + fadeAmount; brightness = min(max(brightness, 0), 255); if (brightness <= 0) { fadeSense = 1; } else if (brightness >= 255) { fadeSense = -1; } delay(30); } } |
1 2 3 |
void accountForSwitchBounce() { delay(10); } |
1 2 3 |
boolean toggleFadeState() { return fadeRunning = !fadeRunning; } |