I'm trying to use a ball switch and an Arduino to turn on an LED. I only want the LED to turn on if the ball switch is closed for 20 seconds. Does anyone know how to do this? Thanks.

  • 4
    \$\begingroup\$ I think quite a few people know how to do this, but please be aware this site is not a free design house. You should start writing code yourself. If you're stuck, people here are happy to help assisting you doing the job. \$\endgroup\$ – Huisman Sep 21 at 19:51
  • 1
    \$\begingroup\$ Can you write a timer? if timeOff >= 20 minutes, turn on LED? \$\endgroup\$ – KingDuken Sep 21 at 19:51
  • 5
    \$\begingroup\$ are you asking about programming or about circuit design? \$\endgroup\$ – jsotola Sep 21 at 19:59

I haven't tried it. But it compiles without errors. Let me know whether it works or not, please :)

#include <time.h>

const int iBallSwitchPin = 2;     // the number of the Ball Switch pin
const int ledPin =  13;      // the number of the LED pin

int iBallSwitchState = 0;         // variable for reading the Ball Switch status

int iCurrentTime = 0;     // Current time
int iElapsedTime = 0;     // Elapsed time

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the Ball Switch pin as an input:
  pinMode(iBallSwitchPin, INPUT);

void loop() {
  // read the state of the Ball Switch value:
  iBallSwitchState = digitalRead(iBallSwitchPin);

  // check if the Ball Switch State is HIGH:
  if (iBallSwitchState == HIGH) {

    iCurrentTime = time(NULL);

    do {
    iElapsedTime = time(NULL);
    } while ( iBallSwitchState == HIGH && (iElapsedTime - iCurrentTime) < 20);     // Checks the time for 20 seconds

      if((iElapsedTime - iCurrentTime) >= 20)
        digitalWrite(ledPin, HIGH);     // turn Led on
        digitalWrite(ledPin, LOW);   
    } // end if 
    else {
    digitalWrite(ledPin, LOW);      // turn LED off

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.