Devices & Components
Jumper wires (generic)
ldr sensor module
LED Strip
Arduino UNO Mini Limited Edition
Software & Tools
Arduino IDE
Project description
Code
Code
c
1// Beginner-friendly: Read button on pin 6 and control a relay on pin 2 2// Wiring (recommended): 3// - Relay module VCC -> 5V 4// - Relay module GND -> GND 5// - Relay module IN -> Arduino digital pin 2 6// - Button one side -> Arduino pin 6 7// - Button other side -> GND 8// Note: This sketch uses INPUT_PULLUP, so button connects to GND when pressed. 9const int RELAY_PIN = 2; // Relay control pin 10const int BUTTON_PIN = 7; // Input pin (button or switch) 11// If your relay module is "active LOW" (common for many modules), set true. 12// If your relay turns ON when IN is HIGH, set false. 13const bool RELAY_ACTIVE_LOW = false; 14void setup() { 15Serial.begin(9600); // Optional: debug output to Serial Monitor 16pinMode(RELAY_PIN, OUTPUT); // Relay pin is an output 17pinMode(BUTTON_PIN, INPUT_PULLUP); // Use the internal pull-up resistor 18// Make sure relay starts OFF 19if (RELAY_ACTIVE_LOW) digitalWrite(RELAY_PIN, HIGH); // HIGH -> off for active-low relay 20else digitalWrite(RELAY_PIN, LOW); // LOW -> off for active-high relay 21Serial.println("Ready. Press the button to turn the relay ON."); 22} 23//Made By Rohan Barnwal 24void loop() { 25// Read the button. Because of INPUT_PULLUP, pressed == LOW. 26int raw = digitalRead(BUTTON_PIN); 27bool pressed = (raw == LOW); // true when button is pressed 28// Simple debounce: when we detect a press state change, wait briefly and re-read. 29static bool lastPressed = false; 30if (pressed != lastPressed) { 31delay(30); // small debounce delay (30 ms) 32raw = digitalRead(BUTTON_PIN); 33pressed = (raw == LOW); 34lastPressed = pressed; 35} 36// Turn relay on or off based on button 37if (pressed) { 38// Turn relay ON 39if (RELAY_ACTIVE_LOW) digitalWrite(RELAY_PIN, LOW); // active-low -> LOW turns ON 40else digitalWrite(RELAY_PIN, HIGH); // active-high -> HIGH turns ON 41Serial.println("Relay: ON"); 42} else { 43// Turn relay OFF 44if (RELAY_ACTIVE_LOW) digitalWrite(RELAY_PIN, HIGH); // active-low -> HIGH turns OFF 45else digitalWrite(RELAY_PIN, LOW); // active-high -> LOW turns OFF 46Serial.println("Relay: OFF"); 47} 48delay(100); // small loop delay to avoid flooding Serial 49}
Comments
Only logged in users can leave comments