← Back to context

Comment by vectorcrumb

10 days ago

How would you go about setting this up? Do you mock out low level calls or are you running some sort of emulator?

Sorry, I somehow missed your comment until now. Didn't get any notifications. I tend to do it more like what you first said, mocking low-level calls.

I typically put all hardware-specific code for one platform into its own directory. Then I can have multiple directories for different hardware implementations, like MCU #1, MCU #2, and PC. I just implement the same API in all three. It's basically just a HAL. Each build only compiles one of those directories -- the one that matches the architecture I'm building for.

For example I might have a function that does an SPI transaction. On the two hardware builds it will actually communicate with the SPI peripheral in the MCU, but on the PC build it will talk to something I've written to pretend to be the SPI device. So it does take a little bit of up-front work writing code that pretends to be the various devices. In some ways you could call that an emulator, but not in the way you were asking I think.

You can make it as simple or complex as you want to. You could do a full-fledged object-oriented SPI class in C++ (or "class" in C), with different class implementations for different hardware builds. Or you could just make a single function that does SPI stuff and reimplement it for each hardware build.

In one case I have a Qt GUI that pretends to be the UI for the device so the PC hardware-specific code ends up providing its own main() and runs the actual shared codebase in a separate thread. So that particular codebase has a provision to rename the shared main() to not actually be main() on the PC build so it plays nicely with Qt needing to actually provide main().

One downside is you won't catch certain bugs on the PC. There have been a few bugs that slipped past because the hardware build was 32-bit but my PC build was 64-bit for example. But those errors are fairly rare. I probably should be doing the PC build as 32-bit to make it more similar anyway. Still, it wouldn't catch every little problem that might pop up on hardware. It definitely accelerates my productivity though!