This is a follow on from Mixed mode simulation including C code and verilog - #21 by 2norderEDO
I’ve improved my mixed mode model and made it a little (not much) more user friendly. The intention is that you can run exactly the same control algorithm code on your microcontroller and your simulation.
mixed_mode_sim.zip (697.8 KB)
All code tested on Ubuntu 24.04, I don’t have a suitable Windows or Apple machine so I’d happily take suitable modifications from someone who does.
There’s a few more files in the pack. Ideally, if you want to simulate something with one 16 bit PWM channel and three 10 bit ADCs then you should only have to modify models.bus to set the PWM clock (currently 16MHz), the controller trigger clock (25kHz) and otherwise it’s just modify microcontroller.h, microcontroller.c and replace buck_controller.h and buck_controller.c with your own algorithm. If you want to add any more ADCs or PWM channels then you have to modify in_data_message, out_data_message, DIGITAL_IN and DIGITAL_OUT in microcontroller.h and add the adcs or PWMs in microcontroller.bus. The structs both use bit fields to make them the right size.
microcontroller.h and microcontroller.h are there to replace your microcontroller environment. Use this to set up any variables that need to be there for your controller. It also reads the file “parameters.p” which you can use to store things like set points and gains that you might want to change without recompiling the code. Ideally, you can take the control loop code that would be in your microcontroller and just “#include “controller.h”” without modifying anything. The control loop example is the one that’s running on an example DCDC I have running.
Buck converter:
Simulation of no load start up:
Measured no load start up:
XSPICE doesn’t appear to have buses. These would be useful to make the models easier to read and write so I’ve got a script that takes a “.bus” file and produces a “.lib” file by replacing any string with the format “_BUS_xxxn” where x is text and n is a number with "bus_xxx0 bus_xxx1… bus_xxx[n-1]. This is currently hard coded to work on microcontroller.bus and models.bus. Run “generate_buses.py”
As a reminder, you need kicad 8+ and gcc and yosys if you want to recompile the examples. Run “compile_all.sh” if you’re on a linux machine.
Before you run the example provided, you still need to change the text on the schematic to set the directory that it’s run from. Kicad 8.07 still doesn’t appear to set the directory correctly.
Any questions, please ask. Also, another big thanks to @uros and @holger for their work on ngspice.