Page 89 - Programming the Photon Getting Started With the Internet of Things
P. 89
sets the duty cycle of a square wave depending on the value that you pass to it:
Writing a value of 0 with analogWrite() indicates that a square wave has a duty
cycle of 0% which shows the LED to be off.
Writing a value of 255 indicates that a square wave has a duty cycle of 100%, which
would show the LED as always on.
Writing a value of 127 indicates that a square wave has a duty cycle of 50%, which
would show the LED to be dim.
Let’s take a moment to think about what is actually happening here. We are not
changing the voltage to a value between 0 and 3.3 V; we are simply switching from 0 V to
3.3 V at a very high frequency and according to how often (the duty cycle) we switch it.
When you look at the LED, you don’t even notice the switching because it is happening at
such as fast rate that they eyes cannot process it fast enough, and the LED just seems
either a bit dim or brighter than normal.
DAC
An alternative method to producing analog signals from the Photon board is to use the
built-in DAC pins, which are pin A5 and the pin labeled DAC. The DAC produces an
output voltage proportional to its current input, and it is very fast and accurate when doing
so. This opens up more flexibility to your projects that regular PWM cannot do, such as
audio output, as well as being able to filter out any digital noise that can occur.
Let’s try the previous experiment where we dimmed an LED using PWM, but this time
we will use a DAC pin on the Photon board. We might not see a noticeable difference in
the two methods, but when the LED dims using PWM, sometimes you will notice some
sort of flickering, especially when the value nearly reaches zero. With DAC, we shouldn’t
see any flickering at all and the brightness should be smooth. The values we can write to
the DAC 12-bit output pin are between 0 and 4095 using the analogWrite function. The
Photon board will check to see if it has a DAC pin and execute HAL_DAC_Write instead of
the normal HAL_PWM_Write; this keeps the functionality and the coding simple to use.
int ledPin = DAC;
void setup() {
// nothing happens in setup
pinMode(ledPin, OUTPUT);
}
void loop() {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 4095; fadeValue ++) {