In this post on Arduino Tutorial For Beginners, this topic about how to use analogWrite() function on Arduino and although the function name is analogWrite() but it will output pulse signal(this function common called is PWM – Pulse Width Modulation). The application of analogWrite() in the video above will help us know how to control DC motor speed, dimming led, rgb led color control and many the other useful applications can be controled via PWM. I will explain you about PWM clearly in some next topics.
To use analogWrite(pwmpin,someuservalue) on Arduino, we just use some pin has tilde before: 3 5 6 9 10 11 as the picture
Only these pin are using for analogWrite() – PWM.
The first parameter in analogWrite() function is pwmpin, this is the PWM pin on Arduino we can use one of pins as the picture above, and the second parameter is someuservalue that is an integer from 0->255 (corresponding with analog range from 0->1023 – Different from the video, i was wrong when explained you about signal voltage, the PWM always output LOW or HIGH (0V or 5V). The 0 – > 255 is the duty cycle of the PWM , it’s not voltage signal. PLEASE KEEP IN MIND THIS). Now let’s try to use analogWrite() to control motor with the diagram below.
Because the Arduino’s PWM pins has not enough ampe(I) to operate the motor, so we will base on transistor’s application to use the 5V of Arduino to control motor, about NPN transistor we have some popular types (C1815,2N2222,..) C1815 is used in the video. When we connect as the diagram, to understand simply about transistor, when we has a high level at Base pins, the 5V from Collector pin will be transfer through Emitter pin to DC motor. You can read more about transistor here : Transistors
Trying this code, you will see the motor will be turn from slow to fast then fast to slow.
void setup()
{
// we don't need to setup analog pin
}
void loop()
{
for(int i = 0 ; i < 255 ; i+=10)
{
analogWrite(3,i); // turn slow -> fast
}
for(int k = 255 ; k >= 0 ; k-=10)
{
analogWrite(3,k); // turn fast -> slow
}
}
Trying above code to dimming LED as the diagram below
Last one, we will control RGB led via PWM pins. This topic will use the Anode RGB type, but some RGB led is Cathode. Attention about this if you don’t want to burn your Arduino
Connect as the diagram and try code to control RGB led color.
void setup()
{
// we don't need to setup analog pin
}
void loop()
{
for(int i = 0 ; i < 255 ; i++)
{
analogWrite(3,i);
analogWrite(5,i);
analogWrite(6,i);
}
for(int k = 255 ; k >= 0 ; k--)
{
analogWrite(3,k);
analogWrite(5,k);
analogWrite(6,k);
}
}
Leave a Reply