The QMdbSim2 Project – An Improved QSpice Micro-Controller Component Framework

What I see is that the PWM looks like it’s 10us/cycle. That suggests that the oscillator and QSpice clock are set up correctly for 40MHz/instruction. What imprecision are you seeing?

I did verify that the simulator supports native device PWM peripheral, at least according to the simulator documentation, so you might want to look into that.

The imprecision I mentioned was just because it was suppose to start with the voltage high, but it starts with a low voltage for just some fiew microseconds before getting to high voltage at each period.
Is there a way to solve that ?
O is not possible to solve it with delay methods?

Well, yes, we can reduce that startup delay…

  • The delay before the first rising edge is because we’re writing/compiling C code. There’s a whole thing loaded and executed before your first line of code called the C Runtime Library (aka CRT). This code copies values from read-only memory (the programmed memory) to volatile memory (RAM) and sets up stack frames. In more complicated programs, it does more and takes longer. Here, it’s around 1.5us of initialization.

  • For this simple program, we don’t really need the CRT – we don’t have function calls with stack frames; we don’t need to clear/initialize blocks of RAM; we don’t need to copy initial values into variables. In short, we can use assembler (ASM) to do everything that this code needs and reduce the startup overhead to about 25 machine instructions, around 640ns.

But I think there’s a more important consideration: Conceptually, there will always be a startup delay after power is applied before any circuit (digital or analog) becomes stable. Oscillators don’t start instantaneously. Capacitive and inductive elements in hardware will deviate from software simulations. Good design builds in allowances for such startup instabilities and ensures that they don’t release the “magic smoke” or cause persistent instability.

In this case, you might design the circuitry to wait until the first rising edge of the output before allowing it to drive whatever it drives. That, I suspect, should be your first focus.

I’ve attached some code to demonstrate the C vs ASM behavior.
main_c.c (3.7 KB)
main_asm.c (6.0 KB)

Hope this helped.

–robert

Thanks greatly sir. I will check and test the files and then comment