I wrote a pre-emptive, multi-threaded OS for the AVR atmega 128 back in college as a sensor networking operating system called Mantis OS (mos). For anyone interested in this direction, it also provides a device layer and “drivers” for timers, ADCs, eeprom, serial port, networking, etc. A great group of folks kept improving it for years so there is a lot there to learn from just as a resource too.