In this tutorial you will learn how to use digitalRead and digitalWrite by simulating Arduino connected to Switch and LED using Proteus. More specifically, we will read the switch state and blink a LED according to the switch state. This is simulation proteus and if you want to see real hardware connection then see How to read switch input in Arduino. If you are not familiar with Proteus simulation software then see Testing Arduino circuit and program using Proteus
Connect LED and Switch to Arduino pin 7 and pin 8 respectively. Connect the LED to ground via 220Ohm resistor and pin 8 to the ground on one side and to the 5V supply on the other side. This is shown below.
Double click on the Arduino board and then click on the Edit Firmware as shown below.
The program editor window will appear. In the editor write the following Arduino Sketch.
int SW = digitalRead(8);
if(SW == HIGH)
This program read switch state at pin 8 and and blink the LED accordingly which is connected to pin 7.
Now right click on the source file program and click on Build Project. This will compile the program into hex file into the Arduino board part on the schematic.
Now go back to the Schematic and click on the Run button at the button. The simulation will start. The LED is initially off because the button has not been clicked. Click on the button and observe the LED. The LED should turn on when the switch is clicked. When the switch is released the LED will turn on. See the animation below.
How the program works!
To understand how the switch state is read and how to LED is turned on we have to look back to the Program code above. In the program code, we used the digitalRead() function to read the state of the Switch. A variable named SW was created with int data type. This variable stores the value that is received in the pin 8. When the switch is in off state, the value is just 0(integer) and when the switch is closed or in the on state, the value stored in the variable SW is 1(integer). Then to turn on the LED on and off according to the switch state we send the value read to pin 7 using the if else statement. If the switch state is high then we send 1 to the pin 7 to turn on the LED otherwise we send 0 to the pin 7.
If you like this tutorial share it and don’t forget to subscribe.