Controlling an RGB LED with Nordic nRF51-DK (nRF51822/nRF51422)25 Jul 2015
In this project, we will control an RGB LED using the Nordic nRF51-DK over BLE. We will make use of PWM (Pulse Width Modulation) and NUS (Nordic UART Service) for this.
Before you read further, you might want to look at my previous articles on nRF51822 programming, since we’re going to use the same development setup here.
- External nRF51822 SWD Programming using the nRF51-DK
- nRF51-DK PWM & GPIOTE test with S110 SoftDevice
- Talking to Ultrasonic Distance Sensor HC-SR04 using nRF51822
In this project, we will be using a Common Cathode RGB LED. An RGB LED combines three LEDs - Red, Green and Blue, and by toggling each of these on in different proportions, you can get a huge variety of colors. This is done by varying the duty cycle of the PWM pulses to each of the R, G, B pins. (For example, 0% means the pin is off, 100% means it’s on all the time, and 50% means it’s on half the time.)
Here is how we hook up the RGB LED to the nRF-DK:
Note that I used 100 Ω resistors above. I have written about nRF51 PWM control before. This project uses the same methods to set PWM duty cycle to the each of the R, G and B pins.
To control the RGB LED over BLE, we use the Nordic nRFToolbox App. The app has a configurable keypad which send strings to the nRF51-DK over the Nordic UART Service when the buttons are pressed. We check for these strings and take appropriate action in the code as follows:
In the code above, nus_data_handler() is called every time data arrives to the chip via the Nordic UART Service over BLE. (You can see how this is set up in the full source code.)
The Main Loop
The main loop for the code just sits around varying the RGB LED colors by modifying the PWM duty cycle. As the buttons are pressed, it starts/stops PWM, and makes the color changes faster or slower as needed.
You can see above that we’re jumping through some hoops to stop and start the PWM. This is due to a known bug in the Nordic nRF51 SDK (as of version 9.0.0) which does not correctly set the pins to low when app_pwm_disable() is called. This issue has been discussed on the Nordic Developer Zone.
Once it’s all hooked up, you can see how it should work here:
You can get the complete source code for this project here:
- nRF51 Series Reference Manual Version 3.0.