Hi! I'm experiencing some really weird inconsistencies with an Adafruit 128x64 SSD1306 monochrome display which I'm using through i2c. I'm trying to make the game snake on the display, using a joystick as an input, which is working great. However, when I change one unrelated line of code, the display fails to initialise. First, here's my code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ArduinoSTL.h>
int posx = 0; // position of head of snake
int posy = 0;
int joyx = 0; // joystick position
int joyy = 0;
int fx = 2; // fruit position
int fy = 0;
int facing = 2; // snake movement direction
int timer = 0; // snake movement timer
std::vector<int> trail{0, 0, 8, 0, 16, 0, 24, 0}; // list of coordinates of the snake's tail
Adafruit_SSD1306 display(128, 64, &Wire, 4);
void setup() {
Serial.begin(9600);
pinMode(A0, INPUT);
pinMode(A1, INPUT);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // initialse display
Serial.println("Fail");
Serial.println(fx);
}
display.clearDisplay();
display.display();
}
void loop() {
joyx = analogRead(A0);
joyy = analogRead(A1);
if (joyx > 800 && abs(joyy - 512) < 200 && facing != 0) { // if right
facing = 2;
}
if (joyy < 200 && abs(joyx - 512) < 200 && facing != 3) { // if down
facing = 1;
}
if (joyx < 200 && abs(joyy - 512) < 200 && facing != 2) { // if left
facing = 0;
}
if (joyy > 800 && abs(joyx - 512) < 200 && facing != 1) { // if up
facing = 3;
}
timer++;
if (timer == 20) { // every 200ms ish
timer = 0;
if (facing == 0 || facing == 2) { // change snake head position
posx = posx + ((facing - 1) * 8);
} else {
posy = posy + ((facing - 2) * 8);
}
trail.push_back(posx); // move snake forward
trail.push_back(posy);
trail.erase(trail.begin()); // remove last square of snake
trail.erase(trail.begin());
display.clearDisplay();
for (int i = 0; i < trail.size(); i = i + 2) { // display all snake segments
display.fillRect(trail[i], trail[i + 1], 8, 8, SSD1306_WHITE);
}
display.drawCircle((fx * 8) + 4, (fy * 8) + 4, 4, SSD1306_WHITE); // draw the fruit
display.drawRect(0, 0, 128, 64, SSD1306_WHITE); // draw the game bounding box
display.display(); // refresh display
}
delay(10);
}
And this works perfectly, although the fruit position isn't randomised and is merely at grid reference (2, 0).
However, if I attempt to randomise the fruit position using the line int fx = random(0, 16)
at the beginning of the code instead of hardcoding it to 2
, the display fails to initialise and "Fail 7" is sent to the serial monitor. I simply don't understand why changing one line of code that is unrelated to the display should cause it to fail to start. (I'm using an Arduino UNO and am powering it with the USB cable.)
Please see my schematic below.
If you have any insights, it will be very helpful
Thank you!