1.2 Digital Write¶
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.
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.
After finishing the circuit connection, connect the Mega2560 board to the computer. Run the Arduino software IDE and type in the following codes.
You can open the file
1.2_digitalWrite.inounder the path of
Or copy this code into Arduino IDE.
Upload the codes to the Mega2560 board, and you can see the blinking of LED.
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.
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.
If the level signal is changed to LOW, the ledPin’s signal will be returned to 0 V to turn LED off.
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.