Author Topic: Wrong delay!  (Read 3937 times)

thule.arch@gmail.com

  • Newbie
  • *
  • Posts: 6
Wrong delay!
« on: September 08, 2016, 01:41:22 pm »
Hi folks

I am struggling with the digispark attiny85. I am using the arduino IDE 1.6.5. My code works, kind of. It is supposed to go on and off on pin0 every 1sec but it takes around 8-10sec! I have been reading about the attiny not having a crystal and using an OSC being a problem with incorrect timing but reported error is 5-10%. Mine is a whopping 800-1000% error! I know, most likely I am doing something silly. Any help greatly appreciated.

Code below:

Code: [Select]
  int sw1=1;
  int sw2=2;
  int sw3=3;
  int sw4=4;
  int bz=0;
  unsigned long lastm=0;
  unsigned long curm=0;
  long interval=1000;
 
void setup() {
  // put your setup code here, to run once:
  for (int n=1;n<5;n++){
    pinMode(n, INPUT_PULLUP);
    }
  pinMode(bz,OUTPUT);
}

int timeforact(){
  curm=millis();
  if (curm-lastm>interval){
     lastm=curm;
     return 1;
  }
  else { return 0; }
}


void loop() {
  // put your main code here, to run repeatedly:
if (timeforact()==1) {digitalWrite(bz,HIGH); }
if (timeforact()==1) {digitalWrite(bz,LOW); }
}

thule.arch@gmail.com

  • Newbie
  • *
  • Posts: 6
Re: Wrong delay!
« Reply #1 on: September 10, 2016, 07:39:18 am »
Any takers?

thule.arch@gmail.com

  • Newbie
  • *
  • Posts: 6
Re: Wrong delay!
« Reply #2 on: September 12, 2016, 05:40:45 am »
Got it. Knew I did something silly! Thanks a lot and now I will go and figure out what to do.  :)

PeterF

  • Hero Member
  • *****
  • Posts: 881
Re: Wrong delay!
« Reply #3 on: September 14, 2016, 01:29:11 am »
//shameless plug  ;D

Also, have a look at the elapsedMillis library (which you can add via the Arduino IDE library manager). There is some sample code provided with it, and some more info on the supporting wiki page.

Using elapsedMillis, your code could look like this...

Code: [Select]
int sw1 = 1;
int sw2 = 2;
int sw3 = 3;
int sw4 = 4;
int bz = 5;

#include <elapsedMillis.h>

elapsedMillis timeToAct;
unsigned long interval = 1000;

// state of the LED = LOW is off, HIGH is on
boolean ledState = LOW;

void setup()
{
  for (int n = 1; n < 5; n++)
  {
    pinMode(n, INPUT_PULLUP);
  }

  pinMode(bz, OUTPUT);
  digitalWrite(bz, LOW); //ensure initial state is off
}

void loop()
{
  if (timeToAct > interval)
  {
    ledState = !ledState;         // toggle the state from HIGH to LOW, or from HIGH to LOW ...
    digitalWrite(bz, ledState);
    timeToAct = 0;                // reset the counter to 0 so the counting starts over...
  }
}

thule.arch@gmail.com

  • Newbie
  • *
  • Posts: 6
Re: Wrong delay!
« Reply #4 on: September 15, 2016, 08:09:24 pm »
Thanks for the plug though. For newbies every little helps.   ;D