a code question
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

a code question

by RobertABT on Mon May 06, 2013 6:29 pm

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 | TOGGLE FULL SIZE
  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
             digitalWrite(relay, LOW);   // this sets the led as off if the switch isn't closed

Thanks for help :)
Posts: 6
Joined: Sat Jan 12, 2013 7:18 am

Re: a code question

by adafruit_support_mike on Mon May 06, 2013 8:02 pm

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 | TOGGLE FULL SIZE

int onTime = 0;

void loop () {
    if (digitalRead(2) == HIGH) {
        if (onTime <= 2) {
             digitalWrite(relay, HIGH);
             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.
When you void a product warranty, you give up your right to sue the manufacturer if something goes wrong and accept full responsibility for whatever happens next. And then you truly own the product.

Posts: 44231
Joined: Thu Feb 11, 2010 2:51 pm

Please be positive and constructive with your questions and comments.