I have some background music. If I put it at the top of the
void loop(), it'll first play the music and then execute the game code afterwards.
How do I have the code run while the background music is playing?
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It only takes a minute to sign up.Sign up to join this community
It all depends on the architecture of your game. The first games probably interleaved their music and gameplay, as the comment above says. This is probably the level of complexity you are looking for, on an Arduino.
First you need to pick some "framerate" that the game advances with. You could, for example, play 4 frames of music for every video frame, or something like that. It also depends how you are playing music. If you are just playing notes with the analog out, this approach would work. Here is some pseudocode that updates the PWM output 4 times faster than the game code:
set n = 0 set quit = false // main game loop while !quit // set music output pwm here if n % 4 == 0 // advance game here endif n++ endwhile
If you are playing music from something like an SD card, you are constrained by the bit rate of the music.
Also, here is an article on Arduino protothreading that might interest you. https://create.arduino.cc/projecthub/reanimationxp/how-to-multithread-an-arduino-protothreading-tutorial-dd2c37. My suggestion is to look at how the old game systems implemented their state machines.