// simple project using Arduino UNO and 128x32 SSD1306 IIC OLED Display to show compass (driven by potentiometer)
//Font: https://github.com/olikraus/u8g2/wiki/fntgrpfontstruct#lucasfont_alternate
#include <Arduino.h>
#include <U8g2lib.h> // u8g2 library is used to draw graphics on the OLED display
#include <Wire.h> // library required for IIC communication
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // initialization for the 128x64px OLED display
//U8G2_SSD1306_128X32_UNIVISION_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // initialization for the 128x32px OLED display, [full framebuffer, size = 512 bytes]
int compass_degrees; // 0-360° -- compass heading, for now, this value is taken from the potentiometer value
char buffer[20]; // helper buffer for displaying strings on the display
int xpos_offset; // x offset of all the tickmarks
int xpos_with_offset; // x position of the tickmark with applied offset
int mxpos_offset; // x offset of all the tickmarks
int mxpos_with_offset; // x position of the tickmark with applied offset
float mxpos_final; // final x position for the tickmark
int heading = 100;
void setup(void) {
u8g2.begin(); // start the u8g2 library
pinMode(A0, INPUT); // set the analog input pin A0 as input
}
void loop(void) {
compass_degrees = map(analogRead(A0), 0, 1023, 0, 360); // use the potentiometer to set the degrees between 0-360°
xpos_offset = round((360 - compass_degrees) / 360.0 * 240.0); // calculate the X offset for all the tickmarks, max offset is 10(px)*24(tickmarks) = 240px
mxpos_offset = round((360 - heading) / 360.0 * 240.0);
u8g2.clearBuffer(); // clear the internal memory
for (int i = 0; i < 24; i++) { // go over all 24 tickmarks
xpos_with_offset = (64 + (i * 10) + xpos_offset) % 240; //calculate the x pos of the tick marks
u8g2.drawLine(xpos_with_offset, 15, xpos_with_offset, 20); //draw tick mark.Tick mark lengt=5px
//dispay the smaller increments of the degre values under the ticks
//u8g2.setFont(u8g2_font_blipfest_07_tr);
u8g2.setFont(u8g2_font_amstrad_cpc_extended_8f); // set font
sprintf(buffer, "%d", i * 20); // convert compass degree integer to string, add the ' symbol
u8g2.setFontDirection(1); //turn the font 90 degrees
u8g2.drawStr(xpos_with_offset - 4,24,buffer);
}
//display compass degrees at the top
//u8g2.setFont(u8g2_font_4x6_tr); // set font
u8g2.setFont(u8g2_font_amstrad_cpc_extended_8f); // set font
//u8g2.setFont(u8g2_font_blipfest_07_tr);
sprintf(buffer, "%d", compass_degrees); // convert compass degree integer to string, add the ' symbol that (somehow) looks like degree symbol (degree symbol is not present in the font)
u8g2.drawStr(64-4,0,buffer);
u8g2.sendBuffer(); // transfer internal memory to the display
delay(20);
}