/*
사용 라이브러리 : u8glib
라이브러리 링크 : https://github.com/olikraus/u8glib
가상시뮬레이션 주소 :
https://wokwi.com/projects/426934996381468673
*/
#include <U8glib.h>
// 빠른 통신 객체 선언 방법
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0 | U8G_I2C_OPT_NO_ACK | U8G_I2C_OPT_FAST); // Fast I2C / TWI
// 그래프 값 변수
int graphValue = 0;
int barHeight = 10; // 막대 그래프 높이 (10픽셀)
void setup()
{
// 시리얼 통신 초기화
Serial.begin(9600);
Serial.println("OLED -x/+x Bar Graph Example");
// OLED 초기화
if (u8g.getMode() == U8G_MODE_R3G3B2)
{
u8g.setColorIndex(255); // white
}
else if (u8g.getMode() == U8G_MODE_GRAY2BIT)
{
u8g.setColorIndex(3); // max intensity
}
else if (u8g.getMode() == U8G_MODE_BW)
{
u8g.setColorIndex(1); // pixel on
}
// 랜덤 시드 초기화
randomSeed(analogRead(0));
}
void loop()
{
// 랜덤 값 생성 (-30 ~ +30)
graphValue = random(-30, 31);
// 화면 그리기 시작
u8g.firstPage();
do
{
drawAxisAndLabels();
drawBarGraph(graphValue);
} while (u8g.nextPage());
// 화면 갱신 대기 시간
delay(1000);
}
// 중앙 축과 라벨 그리기
void drawAxisAndLabels()
{
// 중앙 수직선 그리기
u8g.drawVLine(64, 0, 64); // 중앙 수직선 (x=64, y=0, height=64)
// -x, +x 라벨 표시
u8g.setFont(u8g_font_6x10);
u8g.drawStr(50, 10, "-x");
u8g.drawStr(70, 10, "+x");
}
// 막대 그래프 그리기
void drawBarGraph(int value)
{
int centerX = 64; // 화면 중앙 x좌표
int centerY = 32; // 화면 중앙 y좌표
if (value < 0)
{
// 음수 값인 경우 왼쪽에 그리기
int barWidth = abs(value);
u8g.drawBox(centerX - barWidth, centerY - barHeight / 2, barWidth, barHeight);
}
else if (value > 0)
{
// 양수 값인 경우 오른쪽에 그리기
u8g.drawBox(centerX, centerY - barHeight / 2, value, barHeight);
}
// 현재 값 표시
char valueStr[10];
sprintf(valueStr, "%d", value);
u8g.drawStr(centerX - u8g.getStrWidth(valueStr) / 2, centerY + barHeight + 10, valueStr);
}