Hi guys, totally new to programming, been playing around with this for a while, but there's a part I don't understand.
This is the 8-leds controlled by a shift register tutorial that comes with the arduino 2560 mega, and I understand about 99% of it, but one part I don't get.
Please correct me if I'm wrong, but this is how I'm understanding it:
We start by defining 'leds' as an 8 bit value. The 'for' function increments the variable 'i' by 1 as long as the value is less than 8 each time through the loop, and bitSet sets the relevant bit (defined by the variable i) from a zero to a 1 each time through.
So to start, leds is '00000000', all leds are off, then bitset sets bit 0 starting with the least significant bit, giving us '00000001'. Then the 'for' function increments 'i' by 1, so bitset will then set bit 1 as well, giving us '00000011'
This continues until all 8 bits are set '11111111', with all leds on.
Now the part I don't get. Once all bits are set and all LEDs are lit, the whole thing resets and starts over, and I don't see how that works
I think it's the 'for' function, but don't really understand how it works
for (int i = 0; i < 8; i++)
From what I've read, in plain english it says 'i = 0', 'if i is less than 8, then add 1'
As this function starts with i=0, I don't understand how it doesn't reset i to 0 each time through the loop, and also how it knows to start over at 0 once the number reaches 8, as the logic to me says that once it reaches 8, it should just stop incrementing, not reset to 0
If someone has the time to explain this to be I'd be very grateful...unfortunately I'm at the point where my knowledge is so basic, there are very few tutorials to cover something so simple.
Code below:
int latchPin = 5;
int clockPin = 6;
int dataPin = 4;
byte leds = 0;
void setup()
{
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
}
void loop()
{
leds = 0;
updateShiftRegister();
delay(500);
for (int i = 0; i < 8; i++)
{
bitSet(leds, i);
updateShiftRegister();
delay(500);
}
}
void updateShiftRegister()
{
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, leds);
digitalWrite(latchPin, HIGH);
}