Code doesn't work and port problem's

Hello,

I have 2 problems. First, on my private PC, I tried to run Arduino, but the port section was grayed out. I found out that I need the CH340 driver, so I downloaded it, but I still cannot select a port. Nevertheless, I am now using my school laptop instead.

Now to my main problem: I have a project, but the code doesn’t compile, and I get the exact error code. Regarding the functions: I use the funduino cube and a servo. The program uses a temperature sensor (DHT) to measure the temperature every 5 seconds. Depending on the measured temperature, different LEDs light up: the green LED indicates temperatures below 25°C, the yellow LED lights up for temperatures between 25°C and 29°C, and the red LED activates when the temperature reaches 30°C or higher. At 30°C or above, additional actions are triggered: the servo motor starts rotating 360° a warning message or danger symbol is displayed on the OLED screen, and a buzzer begins buzzing continuously. The buzzer stops automatically when the temperature drops below 30°C, and the LED behavior adjusts to reflect the new temperature range. And the button acts as a emergency button:

Now to my code: (with chatgpt) first the error code:
Arduino: 1.8.19 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"
exit status 1

Error compiling for Arduino Nano board.


#include <Wire.h>
#include <DHT.h>
#include <SSD1306Ascii.h>
#include <SSD1306AsciiWire.h>
#include <Servo.h>

#define DHTPIN A3          // DHT11 Sensor Pin
#define DHTTYPE DHT11
#define LED_GREEN 10       // Green LED
#define LED_YELLOW 11      // Yellow LED
#define LED_RED 12         // Red LED
#define SPEAKER 7          // Speaker
#define BUTTON 9           // Emergency Stop Button

SSD1306AsciiWire display;  // SSD1306Ascii Display with Wire (I2C)
DHT dht(A3, DHT11);
Servo fanServo;

bool emergencyMode = false;

void setup() {
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_YELLOW, OUTPUT);
  pinMode(LED_RED, OUTPUT);
  pinMode(SPEAKER, OUTPUT);
  pinMode(BUTTON, INPUT_PULLUP); // Button pin as input with pullup

  dht.begin();
  fanServo.attach(A1); // Attach servo to pin A1
  fanServo.write(0);   // Set servo to starting position

  // Initialize display
  Wire.begin();
  display.begin(SSD1306_128X64, 0x3C); // Initialize SSD1306 display
  display.setFont(System5x7);          // Standard font
  display.clear();
  display.display();
}

void loop() {
  static unsigned long lastReadTime = 0;

  // Check button
  if (digitalRead(BUTTON) == LOW) { // Button pressed
    activateEmergencyMode();        // Activate emergency stop mode
    return;                         // Skip everything else
  }

  if (emergencyMode) {
    // Activate emergency mode
    activateEmergencyMode();
  } else {
    // Regular mode
    if (millis() - lastReadTime >= 5000) { // Read temperature every 5 seconds
      lastReadTime = millis();
      float temp = dht.readTemperature();

      // Check temperature
      if (temp >= 30) {
        activateDangerState(temp);
      } else if (temp >= 25) {
        activateWarningState(temp);
      } else {
        activateNormalState(temp);
      }
    }
  }
}

// Functions
void activateDangerState(float temp) {
  setLEDState(HIGH, LOW, LOW);
  digitalWrite(SPEAKER, HIGH);
  fanServo.write(90); // Turn servo to 90°
  displayWarning(temp, "Danger!");
}

void activateWarningState(float temp) {
  setLEDState(LOW, HIGH, LOW);
  digitalWrite(SPEAKER, LOW);
  fanServo.write(0); // Reset servo to starting position (0°)
  displayWarning(temp, "Caution");
}

void activateNormalState(float temp) {
  setLEDState(LOW, LOW, HIGH);
  digitalWrite(SPEAKER, LOW);
  fanServo.write(0); // Reset servo to starting position (0°)
  displayWarning(temp, "Normal");
}

void activateEmergencyMode() {
  // Emergency stop: Turn everything off except the red LED
  setLEDState(HIGH, LOW, LOW); // Only red LED on
  digitalWrite(SPEAKER, LOW); // Turn speaker off
  fanServo.write(0);          // Reset servo to starting position
  displayMessage("EMERGENCY!");
}

void setLEDState(bool red, bool yellow, bool green) {
  digitalWrite(LED_RED, red);
  digitalWrite(LED_YELLOW, yellow);
  digitalWrite(LED_GREEN, green);
}

void displayWarning(float temp, const char *message) {
  display.clear();
  display.setCursor(0, 0);
  display.print("Temp: ");
  display.print(temp);
  display.println(" C");
  display.println(message);
  display.display();
}

void displayMessage(const char *message) {
  display.clear();
  display.setCursor(0, 0);
  display.setTextSize(2);  // Larger font for emergency messages
  display.println(message);
  display.display();
}

Thanks for everyones help!

Welcome to the forum

Is that the full error message copied from the IDE using the button provided for the purpose ?

Can you compile and upload a simple sketch such as the Blink example ?

I tried a blink and it works: I copy the whole error code: Arduino: 1.8.19 (Windows 10), Board: "Arduino Nano, ATmega328P"

In file included from C:\Users\OneDrive - \Dokumente\Arduino\libraries\DHT_sensor_library\DHT_U.cpp:15:0:
C:\Users\OneDrive - \Dokumente\Arduino\libraries\DHT_sensor_library\DHT_U.h:36:10: fatal error: Adafruit_Sensor.h: No such file or directory
#include <Adafruit_Sensor.h>
^~~~~~~~~~~~~~~~~~~
compilation terminated.
exit status 1
Error compiling for Arduino Nano board.

This report would be more detailed if the option
"Verbose output during compilation"
in File -> Preferences was enabled.

Have you installed the Adafruit_Sensor library and, if so, where is it located on your PC ?

idk why it shows windows 10 even if I have windows 11 idk if it means smth

idk if I have u mean the library shop inside arduino?

I assume that you mean the Library Manager. Yes, you can install the library from there. Which version of the IDE are you using ?

NOTE : I have seen reports previously about problems with Arduino files being held on OneDrive but try installing the library if you have not already done so


I dont find it in the library I use 1.8.19

Its name is confusing

Try installing this one

Ok I found it, should I include it in my code and if yes should I change it with some librarys I already have in?

Ok I included it in my code but now I have a new error that this:
SSD1306AsciiWire display; was not declared:
Arduino: 1.8.19 (Windows 10), Board: "Arduino Nano, ATmega328P"

C:\Users\OneDrive - \Desktop\projekt_test\newest_of_the_new\newest_of_the_new.ino: In function 'void setup()':
newest_of_the_new:36:17: error: 'SSD1306_128X64' was not declared in this scope
display.begin(SSD1306_128X64, 0x3C); // SSD1306 Display initialisieren
^~~~~~~~~~~~~~
C:\Users\OneDrive - \Desktop\projekt_test\newest_of_the_new\newest_of_the_new.ino:36:17: note: suggested alternative: 'SH1106_128x64'
display.begin(SSD1306_128X64, 0x3C); // SSD1306 Display initialisieren
^~~~~~~~~~~~~~
SH1106_128x64
newest_of_the_new:39:11: error: 'class SSD1306AsciiWire' has no member named 'display'; did you mean 'displayRows'?
display.display();
^~~~~~~
displayRows
C:\Users\OneDrive - \Desktop\projekt_test\newest_of_the_new\newest_of_the_new.ino: In function 'void displayWarning(float, const char*)':
newest_of_the_new:115:11: error: 'class SSD1306AsciiWire' has no member named 'display'; did you mean 'displayRows'?
display.display();
^~~~~~~
displayRows
C:\Users\OneDrive - \Desktop\projekt_test\newest_of_the_new\newest_of_the_new.ino: In function 'void displayMessage(const char*)':
newest_of_the_new:121:11: error: 'class SSD1306AsciiWire' has no member named 'setTextSize'; did you mean 'setStartLine'?
display.setTextSize(2); // Größere Schrift für Notfall
^~~~~~~~~~~
setStartLine
newest_of_the_new:123:11: error: 'class SSD1306AsciiWire' has no member named 'display'; did you mean 'displayRows'?
display.display();
^~~~~~~
displayRows
exit status 1
'SSD1306_128X64' was not declared in this scope

Dieser Bericht wäre detaillierter, wenn die Option
"Ausführliche Ausgabe während der Kompilierung"
in Datei -> Voreinstellungen aktiviert wäre.

May be borrow the code to set up the screen from the examples ?

Thanks! I don't have any compiler errors, but the code doesn't work as intended. When the DHT sensor detects a temperature over 30°C (for testing, I even set it to 40°C), the red LED turns on, the speaker activates, and the OLED displays 'Emergency.' However, when I upload the code, it goes into emergency mode even if the temperature is not 30°C or 40°C." and the speaker aint working

#include <SSD1306Ascii.h>
#include <SSD1306AsciiAvrI2c.h>
#include <SSD1306AsciiWire.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <Wire.h>
#include <Servo.h>

#define DHTPIN A3          // DHT11 Sensor Pin
#define DHTTYPE DHT11
#define LED_GRUEN 10        // Grüne LED
#define LED_GELB 11         // Gelbe LED
#define LED_ROT 12          // Rote LED
#define SPEAKER 7           // Lautsprecher
#define TASTER 9            // Not-Aus-Taster

SSD1306AsciiAvrI2c oled;  // SSD1306Ascii Display mit Wire (I2C)
DHT dht(A3, DHT11);
Servo fanServo;

bool emergencyMode = false;

void setup() {
  pinMode(LED_GRUEN, OUTPUT);
  pinMode(LED_GELB, OUTPUT);
  pinMode(LED_ROT, OUTPUT);
  pinMode(SPEAKER, OUTPUT);
  pinMode(TASTER, INPUT_PULLUP); // Taster-Pin als Eingang mit Pullup

  dht.begin();
  fanServo.attach(A1); // Servo an Pin A1 anschließen
  fanServo.write(0);  // Ausgangsposition des Servos

  // Display initialisieren
  Wire.begin();
  oled.begin(&SH1106_128x64, 0x3C); // SH1106 statt SSD1306_128x64 verwenden
  oled.setFont(System5x7); // Standard-Schriftart
  oled.clear();
  oled.displayRows();  // Zum Anzeigen des Displays
}

void loop() {
  static unsigned long lastReadTime = 0;

  // Taster abfragen
  if (digitalRead(TASTER) == LOW) { // Taster gedrückt
    activateEmergencyMode();        // Not-Aus-Modus aktivieren
    return;                         // Alles andere überspringen
  }

  if (emergencyMode) {
    // Notfallmodus aktivieren
    activateEmergencyMode();
  } else {
    // Regulärer Modus
    if (millis() - lastReadTime >= 5000) { // Alle 5 Sekunden Temperatur lesen
      lastReadTime = millis();
      float temp = dht.readTemperature();

      // Temperatur prüfen
      if (temp >= 40) {
        activateDangerState(temp);
      } else if (temp >= 25) {
        activateWarningState(temp);
      } else {
        activateNormalState(temp);
      }
    }
  }
}

// Funktionen
void activateDangerState(float temp) {
  setLEDState(HIGH, LOW, LOW);
  digitalWrite(SPEAKER, HIGH);
  fanServo.write(90); // Servo auf 90° drehen
  displayWarning(temp, "Danger!");
}

void activateWarningState(float temp) {
  setLEDState(LOW, HIGH, LOW);
  digitalWrite(SPEAKER, LOW);
  fanServo.write(0); // Servo in Ausgangsposition (0°)
  displayWarning(temp, "Caution");
}

void activateNormalState(float temp) {
  setLEDState(LOW, LOW, HIGH);
  digitalWrite(SPEAKER, LOW);
  fanServo.write(0); // Servo in Ausgangsposition (0°)
  displayWarning(temp, "Normal");
}

void activateEmergencyMode() {
  // Not-Aus: Alles ausschalten außer rote LED
  setLEDState(HIGH, LOW, LOW); // Nur rote LED an
  digitalWrite(SPEAKER, LOW); // Summer aus
  fanServo.write(0);          // Servo in Ausgangsposition
  displayMessage("EMERGENCY!");
}

void setLEDState(bool red, bool yellow, bool green) {
  digitalWrite(LED_ROT, red);
  digitalWrite(LED_GELB, yellow);
  digitalWrite(LED_GRUEN, green);
}

void displayWarning(float temp, const char *message) {
  oled.clear();
  oled.setCursor(0, 0);
  oled.print("Temp: ");
  oled.print(temp);
  oled.println(" C");
  oled.println(message);
  oled.displayRows();  // Zum Anzeigen des Displays
}

void displayMessage(const char *message) {
  oled.clear();
  oled.setCursor(0, 0);
  // OLED kann keine Textgröße direkt ändern, daher keine setTextSize verwenden
  oled.println(message);
  oled.displayRows();  // Zum Anzeigen des Displays
}

ditch the screen, the servo, the buzzer and focus on your algorithm.

Get it to work by printing stuff in the Seria monitor.

you might also benefit from studying state machines. Here is a small introduction to the topic: Yet another Finite State Machine introduction

structure of the code: (typed here based on your code)

#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>



#define DHTPIN A3          // DHT11 Sensor Pin
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHT11);

enum {NORMAL, WARNING, DANGER} state = NORMAL;

void checkSystem() {
  static unsigned long lastReadTime = 0;

  if (millis() - lastReadTime >= 5000) { // Alle 5 Sekunden Temperatur lesen
    lastReadTime = millis();
    float temp = dht.readTemperature();

    switch (state) {
      case NORMAL:
        // TO DO
        break;

      case WARNING:
        // TO DO
        break;

      case DANGER:
        // TO DO
        break;

    }
  }
}

void setup() {
  Serial.begin(115200);
  dht.begin();
  Serial.println("Ready");
}

void loop() {
  checkSystem();
}

Im working with that thanks I update if I get it running

@UKHeliBob @J-M-L
Okay, so I got the program running (I removed all the components and added them one by one). The only issue I have is with the button. I tried to stop the servo by pressing the button, turning off the speaker, or manually setting it to the "Normal" state, but none of these worked. When I tried the button, sometimes the speaker wouldn’t make a tone at all, or the servo stopped working altogether with the new button code. I feel like I can’t get the button functionality working properly in my code. Everything else seems to be working fine. Here my code:

// Einbindung der Bibliotheken
#include <SSD1306Ascii.h>
#include <SSD1306AsciiAvrI2c.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <Wire.h>
#include <Servo.h> // Servo-Bibliothek einbinden

// Definition der Pins
#define DHTPIN A3          // DHT11 Sensor Pin (angepasst auf A3)
#define DHTTYPE DHT11      // DHT-Typ definiert
#define LED_GRUEN 10       // Grüne LED
#define LED_GELB 11        // Gelbe LED
#define LED_ROT 12         // Rote LED
#define SUMMER 7           // Summer-Pin (angepasst von 9 auf 7)
#define SERVO_PIN A1       // Servo-Pin angepasst auf A1

// Initialisierung der Komponenten
SSD1306AsciiAvrI2c oled;  // SSD1306Ascii Display mit Wire (I2C)
DHT dht(DHTPIN, DHTTYPE);
Servo servoMotor; // Servo-Objekt erstellen

// Variablen für den Programmablauf
float lastTemperature = -100.0; // Initialisierung mit einem unmöglichen Wert
unsigned long lastToneTime = 0;
unsigned long lastOledUpdate = 0;
bool toneState = false;

void setup() {
    Wire.begin();
    oled.setFont(System5x7);
    oled.begin(&Adafruit128x64, 0x3C);
    
    pinMode(LED_GRUEN, OUTPUT);
    pinMode(LED_GELB, OUTPUT);
    pinMode(LED_ROT, OUTPUT);
    pinMode(SUMMER, OUTPUT);
    
    servoMotor.attach(SERVO_PIN); // Servo-Pin zuweisen (angepasst auf A1)
    servoMotor.write(0); // Startposition des Servos auf 0 setzen
    
    dht.begin();
}

void loop() {
    float temperature = dht.readTemperature();
    unsigned long currentMillis = millis();
    
    // OLED-Anzeige alle 5 Sekunden aktualisieren
    if (currentMillis - lastOledUpdate >= 5000) {
        oled.clear();
        oled.println("");
        oled.setFont(Arial_bold_14); // Größere Schrift für Temperaturanzeige
        oled.setCursor(32, 0); // Mittig ausrichten
        oled.print("TEMP: ");
        oled.print(temperature);
        oled.print(" C");
        oled.println("");
        
        if (temperature < 24) { // Angepasst von 25 auf 24
            oled.setCursor(32, 2);
            oled.println("NORMAL"); // Neuer Text für den normalen Zustand
            digitalWrite(LED_GRUEN, HIGH);
            digitalWrite(LED_GELB, LOW);
            digitalWrite(LED_ROT, LOW);
            noTone(SUMMER); // Summer aus
            servoMotor.write(0); // Servo bleibt auf 0
        } else if (temperature >= 24 && temperature < 26) { // Warnung ab 24°C, Notfall ab 26°C
            oled.setCursor(32, 2);
            oled.println("WARNUNG!"); // Nur ein Ausrufezeichen
            digitalWrite(LED_GRUEN, LOW);
            digitalWrite(LED_GELB, HIGH);
            digitalWrite(LED_ROT, LOW);
        } else {
            oled.setCursor(32, 2);
            oled.println("NOTFALL!"); // Nur ein Ausrufezeichen
            digitalWrite(LED_GRUEN, LOW);
            digitalWrite(LED_GELB, LOW);
            digitalWrite(LED_ROT, HIGH);
            
            // Servo kontinuierlich von 0 bis 180 und zurück bewegen (schnellere Bewegung)
            static bool servoDirection = true;
            if (servoDirection) {
                servoMotor.write(180);
            } else {
                servoMotor.write(0);
            }
            servoDirection = !servoDirection;
            delay(2000); // Verkürzte Bewegungsgeschwindigkeit auf ca. 2 Sekunden
        }
        lastOledUpdate = currentMillis;
    }
    
    // Summer unabhängig vom OLED-Refresh steuern
    if (temperature >= 24 && temperature < 26) { // Angepasst von 25-28 auf 24-26
        if (currentMillis - lastToneTime >= 5000) { // Alle 5 Sekunden piepen
            tone(SUMMER, 1000, 200);
            lastToneTime = currentMillis;
        }
    } else if (temperature >= 26) { // Angepasst von 28 auf 26
        if (currentMillis - lastToneTime >= 1000) { // Jede Sekunde piepen
            tone(SUMMER, 1000, 500);
            lastToneTime = currentMillis;
        }
    } else {
        noTone(SUMMER);
    }
}

Any call to delay() will basically mess up the UX, nothing happens while stuck there…

There is no button reading code in what you last posted.
Please post your best efforts with the button and describe in detail the issues you had.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.