Problem with a void function

Hello, everyone

I have a problem with my code. When I insert code 1 in the if statement in the custom void function, everything works fine, but when I insert code 2, the sensors don't work properly anymore.

Code 1:

    digitalWrite(beeperPin, LOW);
    digitalWrite(brakePin, LOW);
    
    lcd.setCursor(14,0);
    lcd.print("!OFF!");

    lcd.setCursor(14,1);
    lcd.print("!OFF!");

code 2:

    lcd.setCursor(14,0);
    lcd.print(distanceBackRightM);
    lcd.setCursor(18,0);
    lcd.print("m");

    lcd.setCursor(14,1);
    lcd.print(distanceBackLeftM);
    lcd.setCursor(18,1);
    lcd.print("m");

main code:

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);

const int beeperPin = 2;
int beeperIntervallBackRight;
int beeperIntervallBackLeft;
const int maxDistanceForBeeper = 60;
const int minDistanceForBeeper = 2;
const int maxValForBeeperIntervall = 110;
const int minValForBeeperIntervall = 10;

const int ledPin = 3;

const int motorTempPin = A0;
int motorTemp;
float motorTempSensorVal;
const int motorTempTooHigh = 50; //Temp needs to be checked
const int motorTempTooLow = -5; //Temp needs to be checked

const int batteryTempPin = A1;
int batteryTemp;
float batteryTempSensorVal;
float batteryTempSensorValRaw; //(datatype float)needs to be checked
const int batteryTempTooHigh = 50;
const int batteryTempTooLow = -5;

const int trigPinBackRight = 4;
const int echoPinBackRight = 5;
long durationBackRight;
float distanceBackRightCm;
float distanceBackRightM;

const int trigPinBackLeft = 6;
const int echoPinBackLeft = 7;
long durationBackLeft;
float distanceBackLeftCm;
float distanceBackLeftM;

const int casBackSwitchPin = 8;
int casBackSwitchState;

const int brakePin = 9;
const int maxDistanceForBrake = 150;//distance needs to be reviwed

unsigned long previousTime;
unsigned long currentTime;

void setup() {

  
  lcd.begin();
  lcd.backlight();
           
  lcd.setCursor(0,0);
  lcd.print("casBackRight: ");
  lcd.setCursor(0,1);
  lcd.print("casBackLeft: ");
    
  lcd.setCursor(0,2);
  lcd.print("motorTemp: ");
  lcd.setCursor(0,3);
  lcd.print("batteryTemp: ");
  
  pinMode(beeperPin, OUTPUT);
  pinMode(trigPinBackRight, OUTPUT);
  pinMode(echoPinBackRight, INPUT);
  pinMode(trigPinBackLeft, OUTPUT);
  pinMode(echoPinBackLeft, INPUT);
  pinMode(casBackSwitchPin, INPUT);

  Serial.begin(9600);
  
}

void lcdPrinting() {

  if(casBackSwitchState == HIGH) {
  }
}
void loop() {
  
  casBackSwitchState = digitalRead(casBackSwitchPin);
  currentTime = millis();
 
  if(casBackSwitchState == HIGH) {
    
    digitalWrite(trigPinBackRight, LOW); 
    delayMicroseconds(2);
    digitalWrite(trigPinBackRight, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPinBackRight, LOW);
    durationBackRight = pulseIn(echoPinBackRight, HIGH);
    distanceBackRightCm = durationBackRight * 0.034 / 2;
    if(distanceBackRightCm <= 400) {
      distanceBackRightM = (distanceBackRightCm / 100.00);
    }
    
    digitalWrite(trigPinBackLeft, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPinBackLeft, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPinBackLeft, LOW);
    durationBackLeft = pulseIn(echoPinBackLeft, HIGH);
    distanceBackLeftCm = durationBackLeft * 0.034 / 2;
    if(distanceBackLeftCm <= 400) {
      distanceBackLeftM = (distanceBackLeftCm / 100.00);
    }

    Serial.print(distanceBackRightM);
    Serial.print("  ");
    Serial.println(distanceBackLeftM);

    if(distanceBackRightCm <= maxDistanceForBeeper || distanceBackLeftCm <= maxDistanceForBeeper) {

     constrain(distanceBackRightCm, minDistanceForBeeper, maxDistanceForBeeper);
     int beeperIntervallBackRight = map(distanceBackRightCm, minDistanceForBeeper, maxDistanceForBeeper, minValForBeeperIntervall, maxValForBeeperIntervall);  
     constrain(distanceBackLeftCm, minDistanceForBeeper, maxDistanceForBeeper);
     int beeperIntervallBackLeft = map(distanceBackLeftCm, minDistanceForBeeper, maxDistanceForBeeper, minValForBeeperIntervall, maxValForBeeperIntervall);

     if(distanceBackRightCm <= distanceBackLeftCm) {

      if(currentTime - previousTime >= beeperIntervallBackRight) {
        digitalWrite(beeperPin, HIGH);
        if(currentTime - previousTime >= (beeperIntervallBackRight * 2)) {
          digitalWrite(2, LOW);
          previousTime = currentTime;
        }
      }
     }

     else if(distanceBackRightCm > distanceBackLeftCm) {
      
      if(currentTime - previousTime >= beeperIntervallBackLeft) {
        digitalWrite(beeperPin, HIGH);
        if(currentTime - previousTime >= (beeperIntervallBackLeft * 2)) {
          digitalWrite(2, LOW);
          previousTime = currentTime;
        }
      }
     }
    }

    else {
      digitalWrite(beeperPin, LOW);
    }
    
    if(distanceBackRightCm <= maxDistanceForBrake || distanceBackLeftCm <= maxDistanceForBrake) {
      digitalWrite(brakePin, HIGH);
    }
    else {
      digitalWrite(brakePin, LOW);
    }
  }
  else {
        
    digitalWrite(beeperPin, LOW);
    digitalWrite(brakePin, LOW);
     
  }

  lcdPrinting();
  
}

You have three void functions.

(It looks to me like you're pinging the ultrasound sensors too frequently)

    digitalWrite(trigPinBackRight, LOW); 
    delayMicroseconds(2);
    digitalWrite(trigPinBackRight, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPinBackRight, LOW);

I don't know who originally started to use this brain-dead example for driving ranger modules, but I'd really like to kill it off
The trigger pin is ALREADY LOW, so there's no need to waste time writing it low again.

Just write one non-void function to do the ranging, and pass it the pins you want to use for trigger and echo. (And don't call it too frequently)

But the code works just fine without or with the first code in the custom void function, and i don't understand why.

The first void function is setup, and I don't see any conditions in it

I men't the void lcdPrinting()

I guess it is this part the TO refers to:

void lcdPrinting() {

  if(casBackSwitchState == HIGH) {
  }
}

Actually I made just a few changes to the sketch to make it work on Wokwi for testing without the need to replicate the hardware setup in real. It works in the simulation environment:

https://wokwi.com/projects/331469548667535955

I commented my changes in capital letters so easy to find:

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 20, 4);

const int beeperPin = 2;
int beeperIntervallBackRight;
int beeperIntervallBackLeft;
const int maxDistanceForBeeper = 60;
const int minDistanceForBeeper = 2;
const int maxValForBeeperIntervall = 110;
const int minValForBeeperIntervall = 10;

const int ledPin = 3;

const int motorTempPin = A0;
int motorTemp;
float motorTempSensorVal;
const int motorTempTooHigh = 50; //Temp needs to be checked
const int motorTempTooLow = -5; //Temp needs to be checked

const int batteryTempPin = A1;
int batteryTemp;
float batteryTempSensorVal;
float batteryTempSensorValRaw; //(datatype float)needs to be checked
const int batteryTempTooHigh = 50;
const int batteryTempTooLow = -5;

const int trigPinBackRight = 4;
const int echoPinBackRight = 5;
long durationBackRight;
float distanceBackRightCm;
float distanceBackRightM;

const int trigPinBackLeft = 6;
const int echoPinBackLeft = 7;
long durationBackLeft;
float distanceBackLeftCm;
float distanceBackLeftM;

const int casBackSwitchPin = 8;
int casBackSwitchState;

const int brakePin = 9;
const int maxDistanceForBrake = 150;//distance needs to be reviwed

unsigned long previousTime;
unsigned long currentTime;

void setup() {

  
  lcd.begin(20,4,1);  // CHANGED THIS LINE TO COMPILE ON WOKWI
  lcd.backlight();
           
  lcd.setCursor(0,0);
  lcd.print("casBackRight: ");
  lcd.setCursor(0,1);
  lcd.print("casBackLeft: ");
    
  lcd.setCursor(0,2);
  lcd.print("motorTemp: ");
  lcd.setCursor(0,3);
  lcd.print("batteryTemp: ");
  
  pinMode(beeperPin, OUTPUT);
  pinMode(trigPinBackRight, OUTPUT);
  pinMode(echoPinBackRight, INPUT);
  pinMode(trigPinBackLeft, OUTPUT);
  pinMode(echoPinBackLeft, INPUT);
  pinMode(casBackSwitchPin, INPUT_PULLUP);

  Serial.begin(9600);
  Serial.println("Start");     // ADDED THIS LINE ON WOKWI TO OPEN SERIAL WINDOW
  
}

void lcdPrinting() {

  if(casBackSwitchState == HIGH) {
    // ADDED THESE LINES ON WOKWI
    lcd.setCursor(14,0);
    lcd.print(distanceBackRightM);
    lcd.setCursor(18,0);
    lcd.print("m");

    lcd.setCursor(14,1);
    lcd.print(distanceBackLeftM);
    lcd.setCursor(18,1);
    lcd.print("m");
    // UNTIL HERE
  }
}
void loop() {
  
  casBackSwitchState = digitalRead(casBackSwitchPin);
  currentTime = millis();
 
  if(casBackSwitchState == HIGH) {
    
    digitalWrite(trigPinBackRight, LOW); 
    delayMicroseconds(2);
    digitalWrite(trigPinBackRight, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPinBackRight, LOW);
    durationBackRight = pulseIn(echoPinBackRight, HIGH);
    distanceBackRightCm = durationBackRight * 0.034 / 2;
    if(distanceBackRightCm <= 400) {
      distanceBackRightM = (distanceBackRightCm / 100.00);
    }
    
    digitalWrite(trigPinBackLeft, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPinBackLeft, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPinBackLeft, LOW);
    durationBackLeft = pulseIn(echoPinBackLeft, HIGH);
    distanceBackLeftCm = durationBackLeft * 0.034 / 2;
    if(distanceBackLeftCm <= 400) {
      distanceBackLeftM = (distanceBackLeftCm / 100.00);
    }

    Serial.print(distanceBackRightM);
    Serial.print("  ");
    Serial.println(distanceBackLeftM);

    if(distanceBackRightCm <= maxDistanceForBeeper || distanceBackLeftCm <= maxDistanceForBeeper) {

     constrain(distanceBackRightCm, minDistanceForBeeper, maxDistanceForBeeper);
     int beeperIntervallBackRight = map(distanceBackRightCm, minDistanceForBeeper, maxDistanceForBeeper, minValForBeeperIntervall, maxValForBeeperIntervall);  
     constrain(distanceBackLeftCm, minDistanceForBeeper, maxDistanceForBeeper);
     int beeperIntervallBackLeft = map(distanceBackLeftCm, minDistanceForBeeper, maxDistanceForBeeper, minValForBeeperIntervall, maxValForBeeperIntervall);

     if(distanceBackRightCm <= distanceBackLeftCm) {

      if(currentTime - previousTime >= beeperIntervallBackRight) {
        digitalWrite(beeperPin, HIGH);
        if(currentTime - previousTime >= (beeperIntervallBackRight * 2)) {
          digitalWrite(2, LOW);
          previousTime = currentTime;
        }
      }
     }

     else if(distanceBackRightCm > distanceBackLeftCm) {
      
      if(currentTime - previousTime >= beeperIntervallBackLeft) {
        digitalWrite(beeperPin, HIGH);
        if(currentTime - previousTime >= (beeperIntervallBackLeft * 2)) {
          digitalWrite(2, LOW);
          previousTime = currentTime;
        }
      }
     }
    }

    else {
      digitalWrite(beeperPin, LOW);
    }
    
    if(distanceBackRightCm <= maxDistanceForBrake || distanceBackLeftCm <= maxDistanceForBrake) {
      digitalWrite(brakePin, HIGH);
    }
    else {
      digitalWrite(brakePin, LOW);
    }
  }
  else {
        
    digitalWrite(beeperPin, LOW);
    digitalWrite(brakePin, LOW);
     
  }

  lcdPrinting();
  
}

@anon73444976 : I fully agree with your assessment of the quality ...

P.S.: As I could not find an active beeper I just added a passive buzzer; it will not play the expected sound of course but "visualize" on Wokwi when it gets written to its pin.

If you've reached the "else", why are you testing again?
You already know that "distanceBackRightCm" is not less than or equal to "distanceBackLeftCm", and you've done nothing in the meantime to change the values, which means it can only be greater than.

It's just for choosing the smaler one, but you're right it doesn't need the if there

Here's a little gift - don't call it at a frequency above about 25Hz

float usRange (const byte trigPin, const byte echoPin)
{
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  return pulseIn(echoPin, HIGH) * 0.034 / 2;
}

Thank you

When i test it with the real hardware, the beeper does work but it's very unclean and with many bugs. But without any code in the if statement in the void lcdPrinting() it works perfect.

Usually something like "lcdprinting()" is called a function. The word "void" just informs the compiler (and human readers) that this function does not return any value ... :wink:

Your code is really hard to read as there are many if-else-clauses, some nested, some sequentially ... It would be helpful to clean it up, e.g. remove double functionality by using a single function (@anon73444976 has already given valuable hints ...).

The problem with too long and complex functions like you have in loop() is that it makes it very hard to identify bugs and also reasons for timing problems ...

I have worked a little bit on the Wokwi version and integrated @anon73444976 's input (like removing obsolete if's and the 25Hz for measurement intervals.

You can find the working version on

https://wokwi.com/projects/331470623222006354

Here is the sketch (there may be still room for improvement, but due to the time ...):

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 20, 4);

const int beeperPin = 2;
const int beeperFrequency = 1000;
const int maxDistanceForBeeper = 60;
const int minDistanceForBeeper = 2;
const int maxBeeperInterval = 1000;
const int minBeeperInterval = 200;
int beeperInterval;
boolean beeperActive = false;


const int ledPin = 3;

const int motorTempPin = A0;
int motorTemp;
float motorTempSensorVal;
const int motorTempTooHigh = 50; //Temp needs to be checked
const int motorTempTooLow = -5; //Temp needs to be checked

const int batteryTempPin = A1;
int batteryTemp;
float batteryTempSensorVal;
float batteryTempSensorValRaw; //(datatype float)needs to be checked
const int batteryTempTooHigh = 50;
const int batteryTempTooLow = -5;

const int casBackSwitchPin = 8;
int casBackSwitchState;

const int brakePin = 9;
const int maxDistanceForBrake = 50;//distance needs to be reviewed

unsigned long previousTime;
unsigned long currentTime;

struct USound {
      byte triggerPin;
      byte echoPin;
      float distanceCm;
      float distanceM;
      unsigned long lastTime;
      boolean isClose(){ return distanceCm <= maxDistanceForBeeper;};
      boolean mustBrake(){return distanceCm <= maxDistanceForBrake;};
};

USound BackRight {4,5,0,0,0};
USound BackLeft  {6,7,0,0,0};

void setup() {

  
  lcd.begin(20,4,1);  // CHANGED THIS LINE TO COMPILE ON WOKWI
  lcd.backlight();
           
  lcd.setCursor(0,0);
  lcd.print("casBackRight: ");
  lcd.setCursor(0,1);
  lcd.print("casBackLeft: ");
    
  lcd.setCursor(0,2);
  lcd.print("motorTemp: ");
  lcd.setCursor(0,3);
  lcd.print("batteryTemp: ");
  
  pinMode(beeperPin, OUTPUT);
  pinMode(brakePin, OUTPUT);
  pinMode(BackRight.triggerPin, OUTPUT);
  pinMode(BackRight.echoPin, INPUT);
  pinMode(BackLeft.triggerPin, OUTPUT);
  pinMode(BackLeft.echoPin, INPUT);
  pinMode(casBackSwitchPin, INPUT_PULLUP);

  Serial.begin(9600);
  Serial.println("Start");     // ADDED THIS LINE ON WOKWI TO OPEN SERIAL WINDOW
  
}


void loop() {
  
  casBackSwitchState = digitalRead(casBackSwitchPin);
  currentTime = millis();
 
  if(casBackSwitchState == HIGH) {
    Measure(BackRight);
    Measure(BackLeft);
    lcdPrinting();
    CheckForCloseDistance();
    CheckForBrake();
    BeepIfActive();
  } else {
    beeperActive = false;
    digitalWrite(brakePin, LOW);
  }
}

void lcdPrinting() {
    lcd.setCursor(14,0);
    lcd.print(BackRight.distanceM);
    lcd.setCursor(18,0);
    lcd.print("m");
    lcd.setCursor(14,1);
    lcd.print(BackLeft.distanceM);
    lcd.setCursor(18,1);
    lcd.print("m");
}  

void Measure(USound &US){
    if(millis()-US.lastTime > 40) {  // Measurement only every 40 msec => 25 Hz
      US.lastTime = millis();
      digitalWrite(US.triggerPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(US.triggerPin, LOW);
      uint16_t duration = pulseIn(US.echoPin, HIGH);
      US.distanceCm = duration * 0.034 / 2;
      if(US.distanceCm <= 400) {
        US.distanceM = (US.distanceCm / 100.00);
      } else US.distanceM = 0;
    }  
}

void CheckForCloseDistance(){
     if(BackRight.isClose() || BackLeft.isClose()) {
       beeperActive = true;
       if (BackRight.distanceCm <= BackLeft.distanceCm) CalcBeeperInterval(BackRight.distanceCm);
                                                   else CalcBeeperInterval(BackLeft.distanceCm);
     } else beeperActive = false;
}

void CheckForBrake(){
    if(BackRight.mustBrake() || BackLeft.mustBrake()) { 
      digitalWrite(brakePin, HIGH);
    } else{
      digitalWrite(brakePin, LOW);
    }
 } 

void CalcBeeperInterval(float value){
     constrain(value, minDistanceForBeeper, maxDistanceForBeeper);
     beeperInterval = map(value, minDistanceForBeeper, maxDistanceForBeeper, minBeeperInterval, maxBeeperInterval);  
}     

void BeepIfActive(){
  static unsigned long lastChange = 0;
  static boolean SoundOn = false;
  if (beeperActive){
    if (!SoundOn && millis()-lastChange > beeperInterval ) {
      lastChange = millis();
      Serial.println(beeperInterval);
      tone(beeperPin,beeperFrequency);
      SoundOn = true;
    } 
    if (SoundOn && millis()-lastChange > minBeeperInterval/2) {
      noTone(beeperPin);
      SoundOn = false;
    } 
  } else {
     noTone(beeperPin);
     SoundOn = false;
  }  
}

Main changes:

  • Used a struct for the ultrasound measurements
  • Split up the functionality into separate routines for better overview
  • Removed double functions
  • Reduced distance measurement to maximum 25 Hz (every 40 msec)
  • Used tone() / noTone() to create the sound (only useful if you have a passive speaker/buzzer)
    (in case you have an active buzzer just replace the tone() by digitalWrite(beeperPin, HIGH) and noTone() by digitalWrite(beeperPin, LOW); )

Hope it works after some adaptations to your hardware ...

Thank you very much for helping, i'll test it this afternoon.

I tried it and it worked. But now I've insertet the rest of my code and adjusted it a bit, and it doesn't work anymore. And because I don't quite understand the code, I can't tell what the problem is.

Here's my current code:

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 20, 4);

const int beeperPin = 2;
const int maxDistanceForBeeper = 60;
const int minDistanceForBeeper = 2;
const int maxBeeperInterval = 110;
const int minBeeperInterval = 10;
int beeperInterval;
boolean beeperActive = false;


const int ledPin = 3;

const int motorTempPin = A0;
int motorTemp;
float motorTempSensorVal;
const int motorTempTooHigh = 50; //Temp needs to be checked
const int motorTempTooLow = -5; //Temp needs to be checked

const int batteryTempPin = A1;
int batteryTemp;
float batteryTempSensorVal;
float batteryTempSensorValRaw; //(datatype float)needs to be checked
const int batteryTempTooHigh = 50;
const int batteryTempTooLow = -5;

const int casBackSwitchPin = 8;
int casBackSwitchState;

const int brakePin = 9;
const int maxDistanceForBrake = 50;//distance needs to be reviewed

unsigned long previousTime;
unsigned long currentTime;

struct USound {
      byte triggerPin;
      byte echoPin;
      float distanceCm;
      float distanceM;
      unsigned long lastTime;
      boolean isClose(){ return distanceCm <= maxDistanceForBeeper;};
      boolean mustBrake(){return distanceCm <= maxDistanceForBrake;};
};

USound BackRight {4,5,0,0,0};
USound BackLeft  {6,7,0,0,0};

void setup() {

  
  lcd.begin();  // CHANGED THIS LINE TO COMPILE ON WOKWI
  lcd.backlight();
           
  lcd.setCursor(0,0);
  lcd.print("casBackRight: ");
  lcd.setCursor(0,1);
  lcd.print("casBackLeft: ");
    
  lcd.setCursor(0,2);
  lcd.print("motorTemp: ");
  lcd.setCursor(0,3);
  lcd.print("batteryTemp: ");
  
  pinMode(beeperPin, OUTPUT);
  pinMode(brakePin, OUTPUT);
  pinMode(BackRight.triggerPin, OUTPUT);
  pinMode(BackRight.echoPin, INPUT);
  pinMode(BackLeft.triggerPin, OUTPUT);
  pinMode(BackLeft.echoPin, INPUT);
  pinMode(casBackSwitchPin, INPUT_PULLUP);

  Serial.begin(9600);
  
}


void loop() {
  
  casBackSwitchState = digitalRead(casBackSwitchPin);
  currentTime = millis();
 
  if(casBackSwitchState == HIGH) {
    Measure(BackRight);
    Measure(BackLeft);
    CheckForCloseDistance();
    CheckForBrake();
    BeepIfActive();
    lcdPrinting();
  } else {
    beeperActive = false;
    digitalWrite(brakePin, LOW);
  }
}
  
void Measure(USound &US){
    if(millis()-US.lastTime > 40) {  // Measurement only every 40 msec => 25 Hz
      US.lastTime = millis();
      digitalWrite(US.triggerPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(US.triggerPin, LOW);
      uint16_t duration = pulseIn(US.echoPin, HIGH);
      US.distanceCm = duration * 0.034 / 2;
      if(US.distanceCm <= 400) {
        US.distanceM = (US.distanceCm / 100.00);
      } else US.distanceM = 0;
    }  
}

void CheckForCloseDistance(){
     if(BackRight.isClose() || BackLeft.isClose()) {
       beeperActive = true;
       if (BackRight.distanceCm <= BackLeft.distanceCm) CalcBeeperInterval(BackRight.distanceCm);
                                                   else CalcBeeperInterval(BackLeft.distanceCm);
     } else beeperActive = false;
}

void CheckForBrake(){
    if(BackRight.mustBrake() || BackLeft.mustBrake()) { 
      digitalWrite(brakePin, HIGH);
    } else{
      digitalWrite(brakePin, LOW);
    }
 } 

void CalcBeeperInterval(float value){
     constrain(value, minDistanceForBeeper, maxDistanceForBeeper);
     beeperInterval = map(value, minDistanceForBeeper, maxDistanceForBeeper, minBeeperInterval, maxBeeperInterval);  
}     

void BeepIfActive(){
  static unsigned long lastChange = 0;
  static boolean SoundOn = false;
  if (beeperActive){
    if (!SoundOn && millis()-lastChange > beeperInterval ) {
      lastChange = millis();
      Serial.println(beeperInterval);
      digitalWrite(beeperPin, HIGH);
      SoundOn = true;
    } 
    if (SoundOn && millis()-lastChange > minBeeperInterval/2) {
      digitalWrite(beeperPin, LOW);
      SoundOn = false;
    } 
  } else {
     digitalWrite(beeperPin, LOW);
     SoundOn = false;
  }  
}

void lcdPrinting() {
  if(casBackSwitchState == HIGH) {          
    lcd.setCursor(14,0);
    lcd.print(BackRight.distanceM);
    lcd.setCursor(18,0);
    lcd.print("m");

    lcd.setCursor(14,1);
    lcd.print(BackLeft.distanceM);
    lcd.setCursor(18,1);
    lcd.print("m");   
  }
  else {       
    lcd.setCursor(14,0);
    lcd.print("!OFF!");

    lcd.setCursor(14,1);
    lcd.print("!OFF!");
  }   
  motorTempSensorVal = analogRead(A0);
  motorTemp = (motorTempSensorVal) * 0.48848125;

  batteryTempSensorValRaw = analogRead(A1);
  batteryTempSensorVal = (batteryTempSensorValRaw / 1024.0) * 5.0;
  batteryTemp = (batteryTempSensorVal - 0.5) * 100; //Might be .5 instead of 0.5(kit)
   
  lcd.setCursor(16,2);
  lcd.print(motorTemp);

  if(motorTemp >= motorTempTooHigh) {
    digitalWrite(ledPin, HIGH);       
    lcd.setCursor(18,2);
    lcd.print("!");
  }
  else if(motorTemp <= motorTempTooLow) {
    digitalWrite(ledPin, HIGH);  
    lcd.setCursor(18,2);
    lcd.print("!");
  }
  else { 
    digitalWrite(ledPin, LOW);       
    lcd.setCursor(18,2);
    lcd.print("C");
  }
  
  lcd.setCursor(16,3);
  lcd.print(batteryTemp);
  
  if(batteryTemp >= batteryTempTooHigh) {
    digitalWrite(ledPin, HIGH);      
    lcd.setCursor(18,3);
    lcd.print("!");
  }
  else if(batteryTemp <= batteryTempTooLow) {
    digitalWrite(ledPin, HIGH);     
    lcd.setCursor(18,3);
    lcd.print("!");
  }
  else {
    digitalWrite(ledPin, LOW);
    lcd.setCursor(18,3);
    lcd.print("C");
  }
}

I would very much appreciate it if you looked at the code again.

I can do that, but will take a few days due to available time ...

Thank you very much, take your time.

Ok, this is a version that works on Wokwi and should also work in your environment (provided that your temperature calculations for battery and motor temp are correct, which I cannot check ...):

#undef WOKWI  // ADDED THIS LINE TO COMPILE ON WOKWI (#define) 
              // AND TO WORK IN ORIGINAL ENVIRONMENT WITH (#undef)

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);

const int beeperPin = 2;
const int maxDistanceForBeeper = 60;
const int minDistanceForBeeper = 2;
#ifdef WOKWI
  const int maxBeeperInterval = 1000;
  const int minBeeperInterval = 100;
#else
  const int maxBeeperInterval = 110;
  const int minBeeperInterval = 10;
#endif      

int beeperInterval;
boolean beeperActive = false;

const int ledPin = 3;

const int motorTempPin = A0;
int motorTemp;
const int motorTempTooHigh = 50; //Temp needs to be checked
const int motorTempTooLow = -5; //Temp needs to be checked

const int batteryTempPin = A1;
int batteryTemp;
const int batteryTempTooHigh = 50;
const int batteryTempTooLow = -5;

const int casBackSwitchPin = 8;
int casBackSwitchState;

const int brakePin = 9;
const int maxDistanceForBrake = 50;//distance needs to be reviewed

unsigned long previousTime;
unsigned long currentTime;

struct USound {
      byte triggerPin;
      byte echoPin;
      float distanceCm;
      float distanceM;
      unsigned long lastTime;
      boolean isClose(){ return distanceCm <= maxDistanceForBeeper;};
      boolean mustBrake(){return distanceCm <= maxDistanceForBrake;};
};

USound BackRight {4,5,0,0,0};
USound BackLeft  {6,7,0,0,0};

void setup() {

#ifdef WOKWI  
   lcd.begin(20,4,1);  
#else
   lcd.begin();  
#endif
  lcd.backlight();
           
  lcd.setCursor(0,0);
  lcd.print("casBackRight: ");
  lcd.setCursor(0,1);
  lcd.print("casBackLeft: ");
    
  lcd.setCursor(0,2);
  lcd.print("motorTemp: ");
  lcd.setCursor(0,3);
  lcd.print("batteryTemp: ");
  
  pinMode(ledPin, OUTPUT);        // Must be declared as output!
  pinMode(beeperPin, OUTPUT);
  pinMode(brakePin, OUTPUT);
  pinMode(BackRight.triggerPin, OUTPUT);
  pinMode(BackRight.echoPin, INPUT);
  pinMode(BackLeft.triggerPin, OUTPUT);
  pinMode(BackLeft.echoPin, INPUT);
  pinMode(casBackSwitchPin, INPUT_PULLUP);

  Serial.begin(9600);
  
}


void loop() {
  
  casBackSwitchState = digitalRead(casBackSwitchPin);
  currentTime = millis();
 
  if(casBackSwitchState == HIGH) {
    Measure(BackRight);
    Measure(BackLeft);
    CheckForCloseDistance();
    CheckForBrake();
    BeepIfActive();
    ReadMotorTemp();
    ReadBatteryTemp();
    lcdPrinting();
  } else {
    beeperActive = false;
    digitalWrite(brakePin, LOW);
  }
}
  
void Measure(USound &US){
    if(millis()-US.lastTime > 40) {  // Measurement only every 40 msec => 25 Hz
      US.lastTime = millis();
      digitalWrite(US.triggerPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(US.triggerPin, LOW);
      uint16_t duration = pulseIn(US.echoPin, HIGH);
      US.distanceCm = duration * 0.034 / 2;
      if(US.distanceCm <= 400) {
        US.distanceM = (US.distanceCm / 100.00);
      } else US.distanceM = 0;
    }  
}

void CheckForCloseDistance(){
     if(BackRight.isClose() || BackLeft.isClose()) {
       beeperActive = true;
       if (BackRight.distanceCm <= BackLeft.distanceCm) CalcBeeperInterval(BackRight.distanceCm);
                                                   else CalcBeeperInterval(BackLeft.distanceCm);
     } else beeperActive = false;
}

void CheckForBrake(){
    if(BackRight.mustBrake() || BackLeft.mustBrake()) { 
      digitalWrite(brakePin, HIGH);
    } else{
      digitalWrite(brakePin, LOW);
    }
 } 

void CalcBeeperInterval(float value){
     constrain(value, minDistanceForBeeper, maxDistanceForBeeper);
     beeperInterval = map(value, minDistanceForBeeper, maxDistanceForBeeper, minBeeperInterval, maxBeeperInterval);  
}     

void BeepIfActive(){
  static unsigned long lastChange = 0;
  static boolean SoundOn = false;
  if (beeperActive){
    if (!SoundOn && millis()-lastChange > beeperInterval ) {
      lastChange = millis();
     //Serial.println(beeperInterval);
#ifdef WOKWI
      tone(beeperPin,1000);
#else
      digitalWrite(beeperPin, HIGH);
#endif      
      SoundOn = true;
    } 
    if (SoundOn && millis()-lastChange > minBeeperInterval/2) {
#ifdef WOKWI
      noTone(beeperPin);
#else
      digitalWrite(beeperPin, HIGH);
#endif      
      SoundOn = false;
    } 
  } else {
#ifdef WOKWI
      noTone(beeperPin);
#else
      digitalWrite(beeperPin, HIGH);
#endif      
     SoundOn = false;
  }  
}

void ReadMotorTemp(){
#ifdef WOKWI
   motorTemp = map(analogRead(A0),0,1023,-10,60);  // Maps slide potentiometer to temp in Wokwi simulation
#else
  motorTemp = float(analogRead(A0)) * 0.48848125;
#endif  
}

void ReadBatteryTemp(){
#ifdef WOKWI
   batteryTemp = map(analogRead(A1),0,1023,-10,60); // Maps slide potentiometer to temp in Wokwi simulation
#else
  float batteryTempSensorVal = (float(5.0 * analogRead(A1)) / 1024.0);
  batteryTemp = (batteryTempSensorVal - 0.5) * 100; //Might be .5 instead of 0.5(kit)
#endif  
}


void lcdPrinting() {
  // if switch state == HIGH print left and right distance 
  if(casBackSwitchState == HIGH) {          
    lcd.setCursor(14,0);
    lcd.print(BackRight.distanceM);
    lcd.setCursor(18,0);
    lcd.print("m");

    lcd.setCursor(14,1);
    lcd.print(BackLeft.distanceM);
    lcd.setCursor(18,1);
    lcd.print("m");   
  }
  else {       
  // if switch state == LOW print "!OFF" instead of left/right distance
    lcd.setCursor(14,0);
    lcd.print("!OFF!");

    lcd.setCursor(14,1);
    lcd.print("!OFF!");
  }   


  // print motor temperature
  
  lcdPrintFloat(motorTemp,12,2);
  // if motor temp too high or too low print "!" instead of "C"
  // and switch LED on
  lcd.setCursor(18,2);
  if(motorTemp >= motorTempTooHigh || motorTemp <= motorTempTooLow ) {
      digitalWrite(ledPin, HIGH);       
      lcd.print("!");
  }  else {
  // if motor temp inside the limits print "C" 
  // and switch LED off
      digitalWrite(ledPin, LOW);       
      lcd.print("C");
  }
  
  // print battery temperature
  lcdPrintFloat(batteryTemp,12,3);
  // if battery temp too high or too low print "!" instead of "C"
  // and switch LED on
   lcd.setCursor(18,3);  
  if(batteryTemp >= batteryTempTooHigh || batteryTemp <= batteryTempTooLow) {
    digitalWrite(ledPin, HIGH);      
    lcd.print("!");
  } else {
  // if battery temp inside the limits print "C" 
  // and switch LED off
    digitalWrite(ledPin, LOW);
    lcd.print("C");
  }
}

void lcdPrintFloat(float value,byte col, byte row){
    char buffer[5];
    dtostrf(value, 3, 1, buffer);
    lcd.setCursor(col,row);
    if (value>=0) lcd.print(" ");
    lcd.print(buffer);
}

You can find it on

https://wokwi.com/projects/331822212056089172

The slide potentiometers simulate in the Wokwi version the temperature sensor inputs from A0 and A1 and are mapped from -10 to +60 °C.

I

  • added pinmode for ledPin as output to setup()
  • added separate functions to read the temp sensors
  • removed those functions from lcdPrinting() to keep it "clean" from other functions
  • added a function to format and print floats to LCD which also takes care of negative values ... This way the commas of all output data are also in the same column ...

There is still room for improvement (like avoiding to rewrite the lcd if the data have not changed).

But give it a try and good luck :wink:

Thank you for your help,

I noticed that the beeper was always HIGH so i corrected it. But now i have the problem that it seems as if the beeping wouldn't get faster and I don't understand why.

void BeepIfActive(){
  static unsigned long lastChange = 0;
  static boolean SoundOn = false;
  if (beeperActive){
    if (!SoundOn && millis()-lastChange > beeperInterval ) {
      lastChange = millis();
     //Serial.println(beeperInterval);
#ifdef WOKWI
      tone(beeperPin,1000);
#else
      digitalWrite(beeperPin, HIGH);
#endif      
      SoundOn = true;
    } 
    if (SoundOn && millis()-lastChange > minBeeperInterval/2) {
#ifdef WOKWI
      noTone(beeperPin);
#else
      digitalWrite(beeperPin, LOW);
#endif      
      SoundOn = false;
    } 
  } else {
#ifdef WOKWI
      noTone(beeperPin);
#else
      digitalWrite(beeperPin, LOW);
#endif      
     SoundOn = false;
  }  
}