fbpx
Arduino පාඩම 04: Analog Write සමග වැඩ කිරීම
Arduino Lesson 4

4. Analog Write

Turn LED on/off from the input from an actuator

Components Required

Buy

Introduction

In this example you are learning how to turn on and off a LED or any other actuator which can be controlled by a digital output such as relay, bulb, motor.

Learning Outcomes

From this example, you’ll get an understanding about,
  • Pulse Width Modulation
  • Analog Write

Theory

To change the brightness of a LED we could change the voltage the LED is supplied with, but in a microcontroller, ability to change the voltage (converting a digital number to an analog voltage) is limited, so a method called PWM (Pulse Width Modulation) is used. What this does is pulsing on and off the pin in a high frequency. The length of the pulses creates the perception of brightness.

Duty cycle is a term used to describe the ratio between on and off times.

https://github.com/Ruwatech/docu-Magicbit/blob/master/Resources/image8.png?raw=true

 

In this example higher Duty cycle gives higher brightness & lower duty cycle gives lower brightness.

Methodology

Lets select green LED (which is wired to D16). We will use a for loop to generate the duty cycle (0 – 0% duty, 255-100% duty). And also to generate 255 cycles.

Code

 

#include <ESP32Servo.h>

void setup(){
      pinMode(16,OUTPUT);
}
void loop(){
      for(int i = 0; i < 256; i++){
      analogWrite(16, i);
      delay(10);
}

Explanation

 

for(int i=0; i<256; i++): There are 3 parameters in a for loop, first parameter we are defining a variable to store the value generated by the for loop. Second parameter specifies the condition that needs to be true to run the for loop(else it breaks out from the loop), third parameter specifies the change happens to the variable in each cycle, in this case 1, added to i.

 

analogWrite(pin number, pwm value): You can input the pin number you need to do pwm and then the pwm value you need to give to that pin. This assigns the corresponding duty cycle to the pin.

 

Note This example we have coded to increase the brightness, write a code to do the opposite of that, to fade the brightness of the led, & put both effects together to create a beautiful fade & light up effect.

Related Posts
Leave a Reply

Your email address will not be published.Required fields are marked *