Here is my code:
main.cpp
#include <Arduino.h>
#include "SpaceInvaders.h"
SpaceInvaders spaceInvaders;
void setup() {
Serial.begin(9600);
spaceInvaders.setup();
}
void loop() {
spaceInvaders.run();
}
SpaceInvaders.cpp
#include "SpaceInvaders.h"
#include <Arduino.h>
#include "Button.h"
#include "Joystick.h"
#include "Sprites.h"
Button redButton(5);
Button blueButton(6);
Joystick joystick(A0, A1);
int screen[SCREEN_HEIGHT][SCREEN_WIDTH];
void SpaceInvaders::setup() {
u8g2.begin();
u8g2.setFont(u8g2_font_5x7_tf);
redButton.begin();
blueButton.begin();
joystick.begin();
}
void SpaceInvaders::start() {
Serial.println("start");
for (int i = 0; i < SCREEN_HEIGHT; ++i) {
for (int j = 0; j < SCREEN_WIDTH; ++j) screen[i][j] = 0;
}
screen[10][10] = 1;
}
void SpaceInvaders::readInputs() {
Serial.println("readInputs");
redButton.read();
blueButton.read();
joystick.read();
}
void SpaceInvaders::update() {
Serial.println("update");
}
void SpaceInvaders::drawScreen() {
Serial.println("drawScreen");
u8g2.clearBuffer();
for (int i = 0; i < SCREEN_HEIGHT; ++i) {
for (int j = 0; j < SCREEN_WIDTH; ++j) {
drawSprite((const unsigned char*)spaceInvadersSprites, GHOST, j*5, i*7);
}
}
u8g2.sendBuffer();
}
void SpaceInvaders::run() {
Serial.println("Game started.");
start();
while (1) {
readInputs();
update();
drawScreen();
delay(10);
}
Serial.println("Game ended.");
}
Looking at this code you would expect the start function to run before the while loop, but when I look at the Serial monitor I see this:
readInputs
update
drawScreen
readInputs
update
drawScreen
readInputs
update
drawScreen
readInputs
update
draGame started.
start
readInputs
update
drawScreen
readInputs
update
drawScreen
readInputs
update
drawScreen
It first run some iterations of the loop and then the start routine is called.
Any idea of why this occurs??
TY.