Arduino cheat sheet: Difference between revisions

Line 452: Line 452:
Divide by PI: ((((uint32_t)A * (uint32_t)0x45F3) >> 16) + A) >> 1) >> 1
Divide by PI: ((((uint32_t)A * (uint32_t)0x45F3) >> 16) + A) >> 1) >> 1
Divide by √2: (((uint32_t)A * (uint32_t)0xB505) >> 16) >> 0
Divide by √2: (((uint32_t)A * (uint32_t)0xB505) >> 16) >> 0
</syntaxhighlight>
==== modulus (%) ====
[http://embeddedgurus.com/stack-overflow/2011/02/efficient-c-tip-13-use-the-modulus-operator-with-caution/ Efficient C Tip #13 – use the modulus (%) operator with caution « Stack Overflow]
<syntaxhighlight lang="c" enclose="div">
void display_value(uint16_t value)
{
uint8_t    msd, nsd, lsd;
if (value > 999)
{
value = 999;
}
lsd = value % 10;
value /= 10;
nsd = value % 10;
value /= 10;
msd = value;
/* Now display the digits */
}
</syntaxhighlight>
<syntaxhighlight lang="c" enclose="div">
void display_value(uint16_t value)
{
uint8_t    msd, nsd, lsd;
if (value > 999U)
{
  value = 999U;
}
msd = value / 100U;
value -= msd * 100U;
nsd = value / 10U;
value -= nsd * 10U;
lsd = value;
/* Now display the digits */
}
</syntaxhighlight>
</syntaxhighlight>