Arduino code for ultrasonic sensor and temperature


#include <OneWire.h>
#include <DallasTemperature.h>

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

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define ONE_WIRE_BUS 8  // pin 8
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);


float Temp;
int trigPin = 3;    // Trigger
int echoPin = 2;    // Echo
volatile unsigned long startTime, endTime;
volatile float distance_cm;
float distance_per_microseconds;



void startTrigger() {
  startTime = 0;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
}


void drawOled(float value, String unit) {
  display.clearDisplay();
  display.setTextSize(2);             // Normal 1:1 pixel scale
  display.setTextColor(WHITE);        // Draw white text
  display.setCursor(10,10);             // Start at top-left corner
  if (value < 400) {
    display.print(value);
    display.println(unit);
  } else {
    display.println("-----");
  }
  display.display();
}

void getEcho() {
  if (startTime == 0) {
    startTime = micros();
  } else {
    endTime = micros();
    distance_cm = (endTime - startTime) / distance_per_microseconds;  
  }
}
 

void setup() {

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    // Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }
  //Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  attachInterrupt(digitalPinToInterrupt(2),getEcho,CHANGE);    
  sensors.begin();
  delay(50);
  sensors.requestTemperatures();
  Temp = sensors.getTempCByIndex(0);
  if (Temp == -127) Temp = 25;
  distance_per_microseconds = 1/((331.5 + (0.61*Temp)) / 20000); // 1 cm in 58.19 micro-seconds at 20 degrees Celcius
  delay(100);
  drawOled(Temp, "C");
  delay(2000);

} // end setup


void loop() {
float Avg = 0;
float oldAvg;
float Total = 0;

for (int i=0; i < 5; i++) {
  startTrigger();
  if (distance_cm > 0) {
    Total++;
    oldAvg = Avg;
    Avg = oldAvg + (1/Total)*(distance_cm + oldAvg);
    distance_cm = 0;
  }
}
  drawOled(Avg, " cm");
  delay(250);

}