#include <Wire.h>
#include <avr/pgmspace.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET    -1
Adafruit_SSD1306 display(OLED_RESET);

const int hallEffectPin = 15;  // Pin connected to the Hall effect sensor
const int button1Pin = 12;     // Pin connected to the first momentary button
const int button2Pin = 13;     // Pin connected to the second momentary button

volatile unsigned int hallEffectValue = 0;
volatile bool button1Pressed = false;
volatile bool button2Pressed = false;
volatile unsigned int calibrationOffset = 0;

void setup() {
  Serial.begin(9600);

  // Initialize OLED
  if(!display.begin(SSD1306_I2C, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);
  }

  // Configure pins
  pinMode(hallEffectPin, INPUT);
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);

  // Attach interrupts for buttons
  attachInterrupt(digitalPinToInterrupt(button1Pin), button1ISR, FALLING);
  attachInterrupt(digitalPinToInterrupt(button2Pin), button2ISR, FALLING);
}

void loop() {
  // Read Hall effect sensor value
  hallEffectValue = analogRead(hallEffectPin);

  // Apply calibration offset
  unsigned int distance = hallEffectValue + calibrationOffset;

  // Display distance on OLED
  display.clearDisplay();
  display.setTextSize(2);
  display.setCursor(0,0);
  display.print("Distance:");
  display.setCursor(0,16);
  display.print(distance);
  display.print(" mm");
  display.display();

  delay(500);  // Adjust delay as needed
}

void button1ISR() {
  // Interrupt service routine for button 1
  button1Pressed = true;
}

void button2ISR() {
  // Interrupt service routine for button 2
  button2Pressed = true;
}

void calibrateDistance() {
  // Calibration routine
  display.clearDisplay();
  display.setTextSize(1);
  display.setCursor(0,0);
  display.println("Calibration Mode");
  display.println("Press and hold");
  display.println("Button 1 to decrease");
  display.println("Button 2 to increase");
  display.display();

  while (!button1Pressed && !button2Pressed) {
    // Wait for button press
  }

  if (button1Pressed) {
    calibrationOffset -= 10;  // Adjust as needed
  } else if (button2Pressed) {
    calibrationOffset += 10;  // Adjust as needed
  }

  button1Pressed = false;
  button2Pressed = false;
}
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
Loading
ds18b20