The background on this is that in early April I decided to crank out as many projects as I could to be able to get the boards made by JLC before the de minimus exemption for tariffs Chinese imports ended. On this particular project, I pretty much copied the schematic from something I made in the past and replaced the optocouplers with Toslink connectors and level translators. I only realized the issue after the boards were made, which means I've gotta deal with it in software.
As an aside, the first serious coding I did was writing algorithms to run on GPUs, where you take a big hit from thread divergence when you are evaluating conditionals. The habits I picked up from that have stayed with me. Even though the architecture is completely different here, with no opportunity for thread divergence, I had a physical reaction to the idea of evaluating a conditional inside a for loop that has to iterate over every bit you are sending.
I had originally thought of doing the encode with LUTs. I am using an STM32U575, so I have plenty of SRAM for the application. With a 512 byte LUT for all the 16-bit encoded values corresponding to each byte, you could do the encode in just a few instructions in an ISR, with or without DMA, or use a linked list with DMA to handle a number of bytes at a time. But when you're talking about 32-bit words, you are looking at a couple instructions per byte * 4 bytes. In either case, most of the CPU time would be spent on entering and exiting the ISR.
That said, this is UART, and the maximum baud rate is 1/8th of the APB clock up to (I think) 10 Mbit for the U575. I am planning on running at between 1 and 4 Mbit depending on various other things unrelated to this, with the MCU running at 40 to 80 MHz, so I will have plenty of CPU time for other tasks either way.
Sure, there's no reason not to effectively permute the bits in the process of encoding them.
Except ... you'll need to be really sure that you maintain synchronisation on the byte or word level. You need to think also about the effects of error bursts.
I agree, and I may end up implementing some error checking to deal with this. That said, I don't think the situation is any worse than with keeping the order of bits because losing synchronization will give you nonsense data on the rx end either way.
The point of all this is that you can do Manchester encoding in software at reasonably low cost without a LUT and that scales well to handle 4-byte data. Maybe I am the only person who has taken a "shoot first" approach to using Toslink for UART on STM32, but if not, perhaps this will be helpful.