I am trying to write a simple LED "flickering" (like a candle almost) program for an ATTINY 13A and the program for the most part works well, but it would appear that after a period of time (65 "flickers" from my count), the LED just stays on. I have attached a diagram of my circuit (please excuse if it it is not up to scratch, but I'm kind of new to this). Code is below.
after about 65 times 500 milliseconds, passtime becomes 32500 and that's the maximum the 2 byte int field can have.
An int stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).
You may want to read the reference guide about int, unsigned int, long , etc.
Make it "unsigned int" and you get about 130 "flickers'
With "long" or even better "unsigned long' you can have it running for a (unsigned) loooong time
Alternatively use a pseudo random number generator for a non repeating sequence.
const int LED_PIN = 0;
const int FLICKER_TIME = 500;
#define LFSR_SEED (421) // seed starting value for pseudo random number generator routine
unsigned long passTime = 0;
void setup()
{
pinMode(LED_PIN, OUTPUT);
}
void loop()
{
if (millis() - passTime > FLICKER_TIME)
{
passTime = millis();
analogWrite(LED_PIN, (prng_lfsr16() % 230) + 25); //random value between 25 and (25 + 230)
}
}
static uint16_t prng_lfsr16(void) // pseudo random number generator
{
static uint16_t cnt16 = LFSR_SEED;
return (cnt16 = (cnt16 >> 1) ^ (-(cnt16 & 1) & 0xB400));
}
Yup... you're testing whether a number of type unsigned long (which can hold numbers up to 4.2something billion) is higher than a signed int. As soon as the total becomes higher than the maximum value of the signed integer, it will never be true.