Analogwrite (pin, value)
First follow the connection number Circuit
This time, we will use Arduino and a set of three-color lamps (red, yellow, and green) to Apply PWM. First, let's take a look at the Arduino board. There are six PWM interfaces in total, they are digital interfaces 3, 5, 6, 9, 10, and 11. For convenience, we use the continuous PWM interfaces 9, 10, and 11. During program writing, we will use analog write analogwrite (PWM interface, analog value function, for analog write analogwrite () function, the modulation frequency of PWM is set to 30 kHz.
Now we can write a program, so we can slowly turn on the three small lights and then slowly turn off, so that the reciprocating cycle.
Int redpin = 11; // defines the LED Interface
Int yellowpin = 10;
Int greenpin = 9;
Int redval; // defines the LED variable.
Int yellowval;
Int greenval;
Int I = 0;
Void setup ()
{
Pinmode (redpin, output); // set the LED interface to the output interface
Pinmode (yellowpin, output );
Pinmode (greenpin, output );
Pinmode (redval, input); // set the LED variable to the input value
Pinmode (yellowval, input );
Pinmode (greenval, input );
Serial. Begin (9600); // connect to the serial port with a baud rate of 9600
}
Void loop ()
{
I ++;
If (I <200)
{
Redval + = 1; // The red light turns on
Greenval-= 1; // dimmed green light
Yellowval = 1; // the yellow light remains unchanged
}
Else if (I <400)
{
Redval-= 1; // the red light is dimmed.
Greenval = 1; // the green light remains unchanged
Yellowval + = 1; // the yellow light turns on
}
Else if (I <600)
{
Redval = 1; // The red light remains unchanged
Greenval + = 1; // the green light turns on
Yellowval-= 1; // the yellow light is dimmed.
}
Else
{
I = 0; // assign a new value to I for a new loop
}
Analogwrite (redpin, redval); // simulate the value for the LED Interface
Analogwrite (yellowpin, yellowval );
Analogwrite (greenpin, greenval );
Serial. Print (I, DEC); // display the I value
Serial. Print ("R:"); // The simulated values of each LED are displayed.
Serial. Print (redval, DEC );
Serial. Print ("Y :");
Serial. Print (yellowval, DEC );
Serial. Print ("G :");
Serial. println (greenval, DEC );
}
Now we can see the result of the gradual change of the simulation output.