Skip to content

Instantly share code, notes, and snippets.

@dakhnod
Last active October 7, 2024 11:57
Show Gist options
  • Select an option

  • Save dakhnod/8ac9150a547ade51653b5275c9f1d748 to your computer and use it in GitHub Desktop.

Select an option

Save dakhnod/8ac9150a547ade51653b5275c9f1d748 to your computer and use it in GitHub Desktop.
One-liner Arduino binary counter

One-line arduino binary counter

let's talk about how this works. Firstly, the rightmost expression calculates the passed seconds using millis(). millis() returns the milliseconds since boot of the arduino. By dividing through 1000 we get the number of seconds passed, as int.

Now about the PORTB register: This register controls the data on the output pins. Looking at pinouts, we can determine that Arduino UNO pins 8, 9, and 10 (and so forth) are connected to PB0, PB1, PB2, ..., or PORTB in general. Thus, setting the first bit of PORTB to 1 will lead to voltage being applied to pin 8. Here are some example values:

  • 0b000: 8 off, 9 off, 10 off
  • 0b110: 0 off, 9 on, 10 on

Now consider that any data in memory is stored in binary. So writing a number to PORTB will naturally have it represented in binary.

What do the double equal signs do? Well, they assign the rightmost value to all operands. So, a = b = c = x will just copy x to a, b, and c.

Lastly, we need to talk about DDRB. This register controls whether pins are OUTPUT or INPUT. Again, here are some examples:

  • 0b000 8, 9 and 10 are INPUT
  • 0b011 8 INPUT, 9, 10 OUTPUT.

Again, looking at our expression, we just set every bit to OUTPUT that should be HIGH. We also set all LOW pins back to INPUT, but eh...

void setup() {
}
void loop() {
DDRB = PORTB = millis() / 1000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment