1.2 Digital Write

Overview

The digitalWrite() statement here is used to write high level or low level to pins and to let LED and active buzzer 「work 」or 「stop」. In this lesson, we will take LED as an example to introduce the experiment phenomenon.

Components Required

../_images/list_1.2.png

Fritzing Circuit

In this example, we use digital pin 9 to drive the LED. Attach one side of the resistor to the digital pin 9 and the longer pin (anode) of the LED to the other side of the resistor. Connect the shorter pin (cathode) of the LED to GND.

../_images/image30.png

Schematic Diagram

../_images/image401.png

Code

After finishing the circuit connection, connect the Mega2560 board to the computer. Run the Arduino software IDE and type in the following codes.

Note

  • You can open the file 1.2_digitalWrite.ino under the path of sunfounder_vincent_kit_for_arduino\code\1.2_digitalWrite directly.

  • Or copy this code into Arduino IDE.

Upload the codes to the Mega2560 board, and you can see the blinking of LED.

Code Analysis

Here, we connect the LED to the digital pin 9, so we need to declare an int variable called ledpin at the beginning of the program and assign a value of 9.

const int ledPin = 9;

Now, initialize the pin in the setup() function, where you need to initialize the pin to OUTPUT mode.

pinMode(ledPin, OUTPUT);

In loop(), digitalWrite() is used to provide 5V high level signal for ledpin, which will cause voltage difference between LED pins and light LED up.

digitalWrite(ledPin, HIGH);

If the level signal is changed to LOW, the ledPin’s signal will be returned to 0 V to turn LED off.

digitalWrite(ledPin, LOW);

An interval between on and off is required to allow people to see the change, so we use a delay(1000) code to let the controller do nothing for 1000 ms.

delay(1000);

Phenomenon Picture

../_images/image36.jpeg