Cyber Range ·TelecomunicazioniLaboratorio●●●○○

LAB3_SERIAL

Scope

Effettuare una comunicazione seriale tra ESP/ARDUINO/FREENOVE e RASPBERRYPI / PC

Installazione moduli necessari

Installazione Modulo Seriale di Python sul RaspberryPi / Pc

pip install pyserial

APP1

Codice per ESP/ARDUINO/FREENOVE (Arduino IDE)

void setup() {
  Serial.begin(9600); 
  delay(2000);        
}

void loop() {
  String message = "Hello from ESP32!";
  Serial.println(message); 
  delay(1000);            
}

Codice per RaspberryPi / PC (Python)

import serial

# Configura la porta seriale
ser = serial.Serial(
    port='/dev/serial0', 
    #port='/dev/ttyUSB0',
    baudrate=9600,        
    timeout=1            
)

print("Listening for messages from ESP32...")

try:
    while True:
        if ser.in_waiting > 0: 
            data = ser.readline().decode('utf-8').strip()
            print(f"Received: {data}")
except KeyboardInterrupt:
    print("\nExiting...")
finally:
    ser.close()

Codice Windows

import serial

# Configura la porta seriale
ser = serial.Serial(
    port='COM3', 
    baudrate=9600,        
    timeout=1            
)

print("Listening for messages from ESP32...")

try:
    while True:
        if ser.in_waiting > 0: 
            data = ser.readline().decode('utf-8').strip()
            print(f"Received: {data}")
except KeyboardInterrupt:
    print("\nExiting...")
finally:
    ser.close()

APP2

Client ESP/ARDUINO/FREENOVE

void setup() {
  Serial.begin(115200);
  //Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    String received_data = Serial.readStringUntil('\n');
    received_data.trim();
    Serial.print("Ricevuto: ");
    Serial.println(received_data);

     if (received_data == "ciao"){
          Serial.println("Ciao anche a te dal esp32!");
     } else if (received_data == "temperatura") {
          Serial.println("25 gradi");
     } else {
         Serial.println("comando sconosciuto");
     }

  }
  // Possibilità di inviare dati dall'ESP32 al PC
  // Serial.println("Dato dall'ESP32");
  delay(100); // Delay per evitare letture eccessive
}

Computer / RaspberryPi

import serial
import time

# Per windows
ser = serial.Serial('COM3', 115200, timeout=1)

# !! Per rapberry pi !!
#   1. Commentare la riga sopra
#   2. Scommentare le righe sottostanti

#ser = serial.Serial(
#    port='/dev/serial0', 
#    port='/dev/ttyUSB0',
#    baudrate=9600,        
#    timeout=1            
#)

try:
    while True:
         command = input("Inserisci il comando: ")
         ser.write((command + '\n').encode('utf-8'))
         time.sleep(0.1) # piccolo delay per permettere la scrittura
         line = ser.readline().decode('utf-8').strip()
         if line:
             print(f"ESP32 dice: {line}")

except KeyboardInterrupt:
        print("chiusura della connessione")
finally:
    ser.close()

Segna come completato

Hai studiato questa dispensa? Segna il completamento per sbloccare i nodi successivi.

Accedi per salvare il progresso.