Ultrasonic Sensor + Oled 1106 help

Hello.

I can't seem to get my project working.

Setup: Arduino nano + Maxbotix ultrasonic distancesensor + Oled 128x64 Display SH1106 I2C IIC

I am using this code for the distance sensor. It is working on the serial monitor. Now I want to show it on the OLED. I have tried to combine all sorts of codes, and now I must seek help.

const int anPin1 = 0;
long distance1;

void setup() {
  Serial.begin(9600);  // sets the serial port to 9600
}

void read_sensors(){
  /*
  Scale factor is (Vcc/1024) per 5mm. A 5V supply yields ~4.9mV/5mm
  Arduino analog pin goes from 0 to 1024, so the value has to be multiplied by 5 to get range in mm
  */
  distance1 = analogRead(anPin1)*5;
}

void print_all(){
  Serial.print("S1");
  Serial.print(" ");
  Serial.print(distance1);
  Serial.print("mm");
  Serial.println();
}

void loop() {
  read_sensors();
  print_all();
  delay(100); 
}

I ran a test on the OLED with this code, and it is working.

include "U8glib.h"


U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0 | U8G_I2C_OPT_NO_ACK | U8G_I2C_OPT_FAST); // Fast I2C / TWI

void setup() {  
  u8g.setFont(u8g_font_unifont);
  u8g.setColorIndex(1); // Instructs the display to draw with a pixel on. 
}

void loop() {  
  u8g.firstPage();
  do {  
    draw();
  } while( u8g.nextPage() );
  delay(1000);   
}
  
void draw(){
  u8g.drawStr( 0, 20, "Hello World");
    
}

What to do next?? How do I properly combine them?

Thank you so much for all your help!

What to do next??

Post your best attempt.

I think I finally solved it. This Is working.

#include <U8glib.h>
#include<NewPing.h>

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0 | U8G_I2C_OPT_NO_ACK | U8G_I2C_OPT_FAST); // Fast I2C / TWI

#define OLED_Address 0x3C 

const int anPin1 = 0;
long distance1;

void setup() {
  Serial.begin(9600);  // sets the serial port to 9600
}

void draw(int dist) {
  u8g.setFont(u8g_font_fur30);
  u8g.setPrintPos(0, 63);
  u8g.print(dist);
  u8g.print("cm");
}

void loop() {
  int dist = analogRead(anPin1)*5;
  dist = (dist/10);
  u8g.firstPage();
  do {
    draw(dist);
  }
  while (u8g.nextPage());

  delay(50);
}