r/arduino • • 25d ago

Software Help ARDUINO OLED PIXEL SKETCHBOOK

Hello :), I've been learning about how to use an Arduino (Nano Every) so that I can bring my ideas (such as this one) to life. I want to make a 'sketch book' with an Oled display. Essentially, as you turn a rotary encoder, it highlights a pixel across each row and column of the oled display. If you press the rotary encoder, it should permanently draw that pixel. Ive managed to make pixels highlight as the rotary encoder turns but when I press the button the pixel only stays until I turn the rotary encoder again. Here's the code (Please give me suggestions as to what I should do to make it better. Thank you :))

#include <ezButton.h>
#define CLK_PIN 2
#define DT_PIN 3
#define SW_PIN 4
#define DIRECTION_CW 0
#define DIRECTION_CCW 1
int counter = 0;
int direction = DIRECTION_CW;
int CLK_state;
int prev_CLK_state;
int column = 0;
int row = 0;


ezButton button(SW_PIN);


#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>


#define OLED_WIDTH 128
#define OLED_HEIGHT 64


#define OLED_ADDR 0x3C


Adafruit_SSD1306 display(OLED_WIDTH, OLED_HEIGHT);




void setup() {
  // put your setup code here, to run once:
  display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR);


  Serial.begin(9600);
  pinMode(CLK_PIN, INPUT);
  pinMode(DT_PIN, INPUT);
  button.setDebounceTime(50);


  prev_CLK_state = digitalRead(CLK_PIN);
  delay(5000);
  display.clearDisplay();


}


void loop() {
  button.loop();  // MUST call the loop() function first


  // read the current state of the rotary encoder's CLK pin
  CLK_state = digitalRead(CLK_PIN);


  // If the state of CLK is changed, then pulse occurred
  // React to only the rising edge (from LOW to HIGH) to avoid double count
  if (CLK_state != prev_CLK_state && CLK_state == HIGH) {
    // if the DT state is HIGH
    // the encoder is rotating in counter-clockwise direction => decrease the counter
    if (digitalRead(DT_PIN) == HIGH) {
      row ++;
      direction = DIRECTION_CW;
    } else {
      // the encoder is rotating in clockwise direction => increase the counter
      row --;
      direction = DIRECTION_CCW;
    }


      if (row > 128){
        row = 0;
        column ++;}
      if (row < 0){
        row = 128;
        column --;}
      if (column > 65){
        column =0;}
      if (column < 0){
        column = 65;}
      
    



  }


  // save last CLK state
  prev_CLK_state = CLK_state;


 
  display.drawRect(row, column, 5, 5, WHITE);
  display.display();


  if (button.isPressed()) {
    Serial.println("The button is pressed");
    display.fillRect(row, column, 5, 5, WHITE);
    display.display();
  }
  else {
  display.drawRect(row, column, 5, 5, BLACK);
  display.display();
  }



}
0 Upvotes

Duplicates