a code question

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
RobertABT
 
Posts: 6
Joined: Sat Jan 12, 2013 7:18 am

a code question

Post by RobertABT »

hi,
my arduino is staying on for way too long when i run some code, either the crystal no longer works or it is picking up my bodily electromagnetic field.

The code below is programmed into my arduino, is there a way to get it to reset digitalRead on pin2 if it stays on for say 2 runs of the loop, or 12 seconds?

Code: Select all

/*
  Tech Work
  Turns on an LED on for one second, then off if a switch is presses.
 
  This example code is in the public domain.
 */
 
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int relay = 7;
// name your switch and give it a pin to work on
int trigger = 2;
//this is the return from the switch.
int power = 8;
//this powers the switch
 
// the setup routine runs once when you press reset:
void setup() {                
  // initialize the digital pin as an output.
  pinMode(relay, OUTPUT);
  // set up the switch as an input.  
  pinMode(trigger, INPUT);
  //this is the switch.
  pinMode(power, OUTPUT);
}
 
// the loop routine runs over and over again forever:
void loop() {                          //this continues forever
     digitalWrite(power, HIGH);
     if(digitalRead(2)==HIGH){         //this reads the status of the switch, then decides what to do
             digitalWrite(relay, HIGH);  //this sets led as on if the switch is on
             delay(6000);              //wait one second
             digitalWrite(relay, LOW);   //turn led off again afterwards
     }
     else{
             digitalWrite(relay, LOW);   // this sets the led as off if the switch isn't closed
         }
}
Thanks for help :)

User avatar
adafruit_support_mike
 
Posts: 67446
Joined: Thu Feb 11, 2010 2:51 pm

Re: a code question

Post by adafruit_support_mike »

First, I'm not sure what you mean when you say the Arduino is staying on too long. Microcontrollers generally run for as long as they have power.

WRT the code, it sounds like you want a guard variable to keep a condition from lasting indefinitely:

Code: Select all


int onTime = 0;

void loop () {
    if (digitalRead(2) == HIGH) {
        onTime++;
        if (onTime <= 2) {
             digitalWrite(relay, HIGH);
             delay(6000);
             digitalWrite(relay, LOW);
        }
    } else {
        onTime = 0;
    }
}
That's the general idea, though the timing would be pretty rough. The loop will execute in a few thousandths of a second if any condition other than the "send the output pin HIGH, wait six seconds, send the output pin LOW" case is true.

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”