Practical Use 1 2 - Doing trigonometry
Want to use sine and cosine in your programs? They are very expensive operations on an 8bit integer only CPU.
So instead of doing those calculations, create a lookup table of their fixed point equivalents. Your fixed point velocity vectors can now add and multiply fixed point sine/cosine values to create circular motion, or to generate angles towards targets.
Generate the lookup table using something else on a more powerful machine, do not compute it at runtime! For added speed and efficiency, use 255 degrees in a circle instead of 360. The result will be less accurate, but on an 8bit computer’s screen you’re unlikely to notice.
Python to generate sine table
This code will compute a cosine table based on 256 degrees per circle. The fixed point value is a signed value.
#!/usr/bin/python3
import math
print ("const int16_t cosTab[] = [")
for x in range (0,256):
c = math.cos(x * math.pi / 128)
cfixed = math.floor(c * 256)
print (hex(cfixed), end=",")
if (x > 0 and x % 16 == 0):
print ("")
print ("];")
C code to use sine table
These macros will let you access the cosine table to extract sine and cosine values. Notice how the value being looked up is cast to an unisigned int so the lookup wraps around. This means store your angle as an unsigned 8 bit integer.
#define COS(x) cosTab[(uint8_t)x]
#define SIN(x) cosTab[(uint8_t)(x-64)]