// tool libraries
#include <U8g2lib.h>
#define OLED_CENTER_X 64
#define OLED_CENTER_Y 64
#define OLED_MAX_X 128
#define OLED_MAX_Y 128
#define BOX_WIDTH 30
#define BOX_HEIGHT 10
#define BOX_MAX_X (OLED_MAX_X - BOX_WIDTH)
// How much the box moves per tick
#define BOX_VELOCITY 5
// Instantiate graphics library object
U8G2_SH1107_128X128_1_HW_I2C u8g2(U8G2_R0);
// buttons
#define LEFT_BUTTON_INPUT_PIN 8
#define LEFT_BUTTON_STATE_PIN 9
#define RIGHT_BUTTON_INPUT_PIN 7
#define RIGHT_BUTTON_STATE_PIN 6
#define DEBOUNCE_DELAY_MS 10
typedef struct button {
int buttonRawInputPin;
int buttonStateOutputPin;
int steadyButtonState;
int rawButtonState;
unsigned long lastTransTimeMs;
} button;
// Button pins - used to initialize and THEN used to keep button state;
button *left = malloc(sizeof(button));
button *right = malloc(sizeof(button));
// box variables
int boxX = 0;
// Setup at bottom of screen
int boxY = OLED_MAX_Y - BOX_HEIGHT;
void configButtonPin(int pin, int direction, button *btn) {
if (direction == INPUT) {
(*btn).buttonRawInputPin = pin;
pinMode((*btn).buttonRawInputPin, INPUT);
}
else if (direction == OUTPUT) {
(*btn).buttonStateOutputPin = pin;
pinMode((*btn).buttonStateOutputPin, OUTPUT);
}
}
void buttonUpdate(button *btn) {
int reading = digitalRead((*btn).buttonRawInputPin);
// reset debounce timer on transition
if (reading != (*btn).rawButtonState) {
(*btn).lastTransTimeMs = millis();
(*btn).rawButtonState = reading;
}
// Otherwise check for timer elapsing, button state can update
else if ((millis() - (*btn).lastTransTimeMs) > DEBOUNCE_DELAY_MS) {
(*btn).steadyButtonState = (*btn).rawButtonState;
}
// write output status pin
digitalWrite((*btn).buttonStateOutputPin, (*btn).steadyButtonState);
}
void setup() {
// Serial output baud config
Serial.begin(115200);
// button setup
configButtonPin(LEFT_BUTTON_INPUT_PIN, INPUT, left);
configButtonPin(LEFT_BUTTON_STATE_PIN, OUTPUT, left);
configButtonPin(RIGHT_BUTTON_INPUT_PIN, INPUT, right);
configButtonPin(RIGHT_BUTTON_STATE_PIN, OUTPUT, right);
u8g2.begin(); // begin the u8g2 library
u8g2.setContrast(255);
u8g2.setFont(u8g2_font_8x13B_mr);
u8g2.setDrawColor(1); // set the drawing color to white
}
void loop() {
// update button via debouncing utility
buttonUpdate(left);
buttonUpdate(right);
if ((*left).steadyButtonState == HIGH) {
if (boxX >= BOX_VELOCITY) {
boxX -= BOX_VELOCITY;
}
else {
boxX -= boxX;
}
Serial.print("New x-coor = ");
Serial.println(boxX);
}
if ((*right).steadyButtonState == HIGH) {
if ((BOX_MAX_X - boxX) >= BOX_VELOCITY) {
boxX += BOX_VELOCITY;
}
else {
boxX += (BOX_MAX_X - boxX);
}
Serial.print("New x-coor = ");
Serial.println(boxX);
}
u8g2.firstPage(); // select the first page of the display (page is 128x8px), since we are using the page drawing method of the u8g2 library
do { // draw
u8g2.drawBox(boxX, boxY, BOX_WIDTH, BOX_HEIGHT);
} while ( u8g2.nextPage() ); // go over all the pages until the whole display is updated
}
Loading
grove-oled-sh1107
grove-oled-sh1107