No title

#include <Wire.h>

#include <Adafruit_GFX.h>

#include <Adafruit_SSD1306.h>

#include <Servo.h>


#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64


Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);


Servo myServo;


// Rotary Encoder pins

#define CLK 2

#define DT 3


int lastCLK;

int angle = 90;


void setup() {

  pinMode(CLK, INPUT);

  pinMode(DT, INPUT);


  myServo.attach(9);

  myServo.write(angle);


  lastCLK = digitalRead(CLK);


  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {

    while (1);

  }


  display.clearDisplay();

}


void loop() {

  int currentCLK = digitalRead(CLK);


  if (currentCLK != lastCLK && currentCLK == HIGH) {

    if (digitalRead(DT) != currentCLK) {

      angle++;

    } else {

      angle--;

    }


    angle = constrain(angle, 0, 180);

    myServo.write(angle);

    drawUI(angle);

  }


  lastCLK = currentCLK;

}


void drawUI(int angleValue) {

  display.clearDisplay();


  // ---------- Progress Bar (UPPER) ----------

  int barX = 10;

  int barY = 6;

  int barWidth = 108;

  int barHeight = 12;


  display.drawRect(barX, barY, barWidth, barHeight, SSD1306_WHITE);


  int fillWidth = map(angleValue, 0, 180, 0, barWidth - 2);

  display.fillRect(barX + 1, barY + 1, fillWidth, barHeight - 2, SSD1306_WHITE);


  // ---------- Scale Numbers ----------

  display.setTextSize(1);

  display.setTextColor(SSD1306_WHITE);


  display.setCursor(8, 22);

  display.print("0");


  display.setCursor(58, 22);

  display.print("90");


  display.setCursor(104, 22);

  display.print("180");


  // ---------- Servo Angle Text (LOWER) ----------

  display.setTextSize(1);

  display.setCursor(15, 45);

  display.print("Servo Angle: ");


  display.setTextSize(2);

  display.setCursor(85, 40);

  display.print(angleValue);

  display.print((char)247); // degree symbol


  display.display();

Post a Comment

Previous Post Next Post

Contact Form