Writing the Dimmer Code
Create a new project as before and open the Program.cs file in the main code editing window.
Now, type the following:
PWM led = new PWM(Pins.GPIO_PIN_D5);AnalogInput pot = new AnalogInput(Pins.GPIO_PIN_A0);
pot.SetRange(0, 100); int potValue = 0;
This line of code creates a PWM object using our digital pin D5. This lets you control the intensity of the LED by changing its duty cycle (percentage of time turned on vs. off).
The second and third lines of code set up the potentiometer as before, but this time with a range of 0 through 100. This will give you a percentage that you can use to set the LED’s intensity.
This line creates a variable named
potValue, which you’ll use to store and retrieve the potentiometer’s current position.
Now you need to write some code to change the LED’s intensity based on the value of the potentiometer. Add the following:
while (true) { // read ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access