In: Computer Science
Produce program code to facilitate LED and switch interface with a microcontroller-based development board (Arduino).
Explain the programming process and interface circuits required
Code:
int LED = 7;
int reed_switch = 4;
int reed_status;
void setup()
{
pinMode(LED, OUTPUT);
pinMode(reed_switch, INPUT);
}
void loop()
{
reed_status = digitalRead(reed_switch);
if (reed_status == 1)
digitalWrite(LED, LOW);
else
digitalWrite(LED, HIGH);
delay(1000);
}
Explanation:
The complete code for this Arduino reed switch project is given at the end of this article. The code is split into small meaningful chunks and explained below.
In this part of the code we have to define pins on which Reed switch and LED which is connected to Arduino. Reed switch is connected to digital pin 4 of Arduino and LED is connected to digital pin 7 of Arduino through a current limiting resistor. The variable “reed_status” is used to hold the status of reed switch.
int LED = 7; int reed_switch = 4; int reed_status;
In this part of the code, we have to set status of pins on which LED and reed switch is connected. Pin number 4 is set as input and pin number 7 is set as output.
void setup() { pinMode(LED, OUTPUT); pinMode(reed_switch, INPUT); }
Next, we have to read the status of reed switch. If it is equal to 1, switch is open and LED is turned off. If it is equal to 0, switch is closed and we have to turn on LED. This process is repeated every second. This task is accomplished with this part of the code below.
void loop() { reed_status = digitalRead(reed_switch); if (reed_status == 1) digitalWrite(LED, LOW); else digitalWrite(LED, HIGH); delay(1000); }
Working:
Arduino Uno is a open source microcontroller board based on ATmega328p microcontroller. It has 14 digital pins (out of which 6 pins can be used as PWM outputs), 6 analog inputs, on board voltage regulators etc. Arduino Uno has 32KB of flash memory, 2KB of SRAM and 1KB of EEPROM. It operates at the clock frequency of 16MHz. Arduino Uno supports Serial, I2C, SPI communication for communicating with other devices. The table below shows the technical specification of Arduino Uno.
Microcontroller |
ATmega328p |
Operating voltage |
5V |
Input Voltage |
7-12V (recommended) |
Digital I/O pins |
14 |
Analog pins |
6 |
Flash memory |
32KB |
SRAM |
2KB |
EEPROM |
1KB |
Clock speed |
16MHz |
To interface reed switch with Arduino we need to build a voltage divider circuit as shown in the figure below. Vo is +5V when the switch is open and 0V when the switch is closed. We are using a normally open reed switch in this project. Switch is closed in the presence of magnetic field and it is open in the absence of magnetic field.
Interface circuit: