Im trying to make pong/ breakout on an arduino uno, more specificly the inventor.io hero board, from scratch. I've *mostly got the base mechanics working, but the oled display keeps freezing up randomly. and the ball that i've made doesn't want to bounce on the left side of the screen.
here's the code:
#include <U8glib.h>
//rotary encoder
#define CLK2 2
#define DT2 3
int counter = 20; //keep track of steps
int CLKstate;
int lastCLKstate;
//display
U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE); //set this to whatever your using
int ballX = 64;
int ballY = 32;
int ballDir = 0;
int ballSpeed = 3;
void draw(void) {
u8g.drawBox(8, counter, 5, 25); //player
u8g.drawBox(ballX, ballY, 5, 5); //the ball
}
void setup(void) { //stuff for the rotary encoder
pinMode(CLK2, INPUT);
pinMode(DT2, INPUT);
lastCLKstate = digitalRead(CLK2);
attachInterrupt(digitalPinToInterrupt(CLK2), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(DT2), updateEncoder, CHANGE);
}
void moveBall() {
if (ballDir == 0) { // if moving to the right
if (ballX >= 123) {
ballDir = 4;
} else {
ballX += ballSpeed;
}
} else if (ballDir == 4) { // if moving to the left
if (ballDir <= 0) {
ballDir == 0;
} else {
ballX -= ballSpeed;
}
}
}
void updateEncoder() {
//read the state of clk
CLKstate = digitalRead(CLK2);
if (CLKstate != lastCLKstate && CLKstate == 1) {
if (digitalRead(DT2) != CLKstate) {
counter++; //clockwise
} else {
counter--; //counterclockwise
}
}
lastCLKstate = CLKstate;
}
void loop(void) {
moveBall();
// picture loop
u8g.firstPage();
do {
draw();
} while (u8g.nextPage());
}
i've connected a oled display to ground and 5v and sck to A5 and sda to A4. I also have a rotary encoder with power and gnd at power and ground, and CLK and DT at pins 2 and 3 respectivly. nothing else, Pls help!