Project 1.03 Analog Write

In this project you will learn about a new function called analogWrite. This function is useful for setting the brightness of LEDs. It can also be used to set the speed of motors, servo motor position, generating audio tones, and more.

The MC Trainer can only produce values of 0v and 5v but what happens when you need 2.5v? Simply put, the MC trainer cannot produce 2.5v. Instead, what it can do is switch a pin between 0v and 5v very quickly and produce an average voltage of 2.5v. This process is known as PWM.

It is important to note that this can only be done with certain pins. In our case, LED1 and LED2 can be used to do PWM.

This also introduces the Idea of duty cycle. Duty cycle is the ratio of how long a signal is on VS how long a signal is off. In this case the duty cycle would be 50%.

Project Code:

/////////////////////////////////////////////////
// 1.03 - Analog Write

byte LED1 = 13;

void setup() {
  pinMode(LED1, OUTPUT);
  analogWrite(LED1, 127); 
}

void loop() {

}
/////////////////////////////////////////////////

*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.

The analogWrite function takes an 8-bit value between 0 – 255. 0 represents 0v and 255 represents 5v. The average voltage produced by that pin can be calculated with the equation: (analogValue * 5) / 255, with analogValue being the 8-bit number passed to the analogWrite function. For example, (127 * 5) / 255 = 2.49V. So, 127 will produce 2.49 volts.

analogWrite(LED1, 127); 

When you run the code, the LED will be at half brightness.

Use the simulator below to explore different duty cycles!

O-Scope
50%
5
Previous
Previous

Project 1.04 Pulse LED

Next
Next

Project 1.02 Simple LED Chase