HowTo-Color (8) / Hacking Electronics / Simon Monk / 236-3 / Chapter 6
124
Hacking Electronics The sketch is quite similar to that in the previous section; however, we no longer use the Serial Monitor, so all that code is gone. We do need to define a new pin “ledPin” to use for the LED. The “loop” function still reads the raw value from the analog pin A3, but it then uses the “map” function to convert the “rawReading” value of between 0 to 1023 to a range of 100 to 500. The “map” function is a standard Arduino command that adjusts the range of the value passed in as the first parameter. The second and third parameters are the range of the raw value, while the fourth and fifth are the desired range you want to compress or expand the value into. We then flash the LED using this number (100 to 500) as the delay between turning the LED on and off. The end result of this is that the LED will flash faster the closer A3 is to 0V.
Software (Brightness) We can use exactly the same hardware, but with different software to control the brightness of the LED instead of its rate of flashing. This will use the Arduino “analogWrite” function to vary the power going to the pin. This feature is only available for those pins marked with a “~” on the Arduino board. Fortunately, we thought ahead and chose such a pin to connect the LED to. These pins can use a technique called pulse-width modulation (PWM) to control how much power goes to the output. This works by sending out a series of pulses, around 500 times per second. These pulses may be high for only a short time, in which case little power is delivered, or high until it’s nearly time for the next pulse, in which case lots of power is delivered. In the case of the LED, this means that in each cycle, the LED is either off, on for some of the time, or on the whole time. Our eyes cannot keep up with such a fast-changing event, so it just appears that the brightness of the LED varies. Load the sketch “variable_led_brightness” onto your Arduino. You should find that, now, the variable resistor controls the brightness of the LED rather than its rate of flashing. Most of the sketch is the same as the previous one, the difference lies in the “loop” function. void loop() { int rawReading = analogRead(voltsInPin); int brightness = rawReading / 4; analogWrite(ledPin, brightness); }
06-ch06.indd 124
1/2/13 11:55 AM