Ollie Smeenk
Published

Using Magnetism to switch a Green LED on and off

In this tutorial you will learn how to control an actuator using a magnetic switch.

Full instructions provided1,075
Using Magnetism to switch a Green LED on and off

Things used in this project

Hardware components

SODAQ Moja
×1
0.5W Solar Panel
×1
1aH battery pack
×1
Grove Green LED
×1
Grove Magnetic Switch
×1
A (fridge) Magnet
×1
Grove w/o Buckle Cable (any length)
×2

Story

Read more

Code

code.c

C/C++
code.c
#define MAGNECTIC_SWITCH 2
#define LED 4
 
void setup()
{
 pinsInit();
}
 
void loop()
{
 if(isNearMagnet())  //if the magnetic switch is near the magnet?
 {
  turnOnLED();
 }
 else
 {
  turnOffLED();
 }
}
 
void pinsInit()
{
 pinMode(MAGNECTIC_SWITCH, INPUT);
 pinMode(LED,OUTPUT);
}
 
/*If the magnetic switch is near the magnet, it will return ture, */
/*otherwise it will return false */
 
boolean isNearMagnet()
{
 int sensorValue = digitalRead(MAGNECTIC_SWITCH);
 if(sensorValue == HIGH)   //if the sensor value is HIGH?
 {
  return true;   //yes,return true
 }
 else
 {
  return false;   //no,return false
 }
}
 
void turnOnLED()
{
 digitalWrite(LED,HIGH);
}
 
void turnOffLED()
{
 digitalWrite(LED,LOW);
}

Credits

Ollie Smeenk

Ollie Smeenk

8 projects • 6 followers
Business-oriented Tinkerer! Ready to engage in any project for- and not for profit!

Comments