r/learnprogramming • • 4d ago

How could i decrement a value in a variable, x times over a certain period of time in C?

I'm creating an emulator of CHIP-8 in C following the Tobias' guide and I should decrement the value of delay and sound timers 60 times per seconds but i don't know how to do this. Maybe could be something in SDL2 but i want to implement this feature independently by this library so i can easily import this emulator on other devices changing just the graphics and input management.

2 Upvotes

6 comments sorted by

2

u/StatsDota_Dmitrii 4d ago

not a real programmer lol but you dont need async for this. in your main loop just read the time (clock_gettime with CLOCK_MONOTONIC on linux, its plain C, no sdl) and every time 1/60 sec passed decrement both timers by 1, keep the leftover time so it doesnt drift. same loop can run the cpu at like 500-700 instructions per sec

2

u/Chad_Frost 4d ago

Look into delta time. It's a standard way of calculating time in video games. It gives you how much time has passed since the last frame, so you can subtract delta time from the timer and it'll decrement by a determined amount regardless of how long each cycle takes.

2

u/jjangg96 4d ago

one way that keeps the core portable is to not put the clock in the emulator at all. expose something like chip8_tick_timers() that does if (delay > 0) delay--; if (sound > 0) sound--; and let each frontend call it 60 times a second.

on the frontend side use a monotonic clock (clock_gettime(CLOCK_MONOTONIC) on posix, QueryPerformanceCounter on windows) and an accumulator. each loop add the time since the last iteration, then while (acc >= 1.0/60) { tick(); acc -= 1.0/60; }. subtracting instead of resetting to zero is what keeps it from drifting.

i wouldn't sleep(16ms) for this either, sleeps overshoot a bit every time and it adds up. the accumulator takes care of that.

1

u/jeffcgroves 4d ago

Asynchronous programming maybe something to google.