I'm trying to understand what happens 'under the hood' when you turn an LED on an Arduino Uno on/off.
The basic Hello World with hardware projects seems to be blinking of an onboard LED. In the case of an Arduino, there's an LED connected to pin 12.
I took a look at the source code for digitalWrite
:
void digitalWrite(uint8_t pin, uint8_t val)
{
uint8_t timer = digitalPinToTimer(pin);
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
volatile uint8_t *out;
if (port == NOT_A_PIN)
return;
// If the pin that support PWM output, we need to turn it off
// before doing a digital write.
if (timer != NOT_ON_TIMER)
turnOffPWM(timer);
out = portOutputRegister(port);
uint8_t oldSREG = SREG;
cli();
if (val == LOW) {
*out &= ~bit;
}
else {
*out |= bit;
}
SREG = oldSREG;
}
What's going on here?
In particular, the bit twiddling bits at the end of the function.