see other all data is printing but furnace data is not printing by usinf this code
import serial
import openpyxl
import time
import re
import os
=== Step 1: Setup Serial Connection ===
serial_port = "COM6" # Update this to match your ESP32 port
baud_rate = 115200
try:
ser = serial.Serial(serial_port, baud_rate, timeout=1)
print(f"Connected to {serial_port} at {baud_rate} baud.")
except Exception as e:
print(f"Failed to connect to ESP32. Check the port! Error: {e}")
exit()
=== Step 2: Generate a Unique File Name for Each Experiment ===
timestamp = time.strftime("%Y%m%d_%H%M%S")
file_name = f"esp32_data_{timestamp}.xlsx"
folder_name = "Experiment_Data"
if not os.path.exists(folder_name):
os.makedirs(folder_name)
file_path = os.path.join(folder_name, file_name)
=== Step 3: Setup New Excel File ===
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["Timestamp", "Event", "Initial Temperature (°C)", "Furnace Temperature (°C)",
"Dwell Time (s)", "Pouring Temperature (°C)", "Pouring Time (s)"])
=== Step 4: Read Data and Write to Excel ===
temperature = None
furnace_temperature = None # New variable for furnace temp
dwell_time = None
pouring_temp = None
pouring_time = None
event = None
try:
while True:
line = ser.readline().decode("utf-8", errors="ignore").strip()
print(f"Raw data: {line}")
code
if not line:
continue
# Extract Initial Temperature
if "Ladle in Furnace" in line:
temp_match = re.search(r"Temperature: (\d+\.\d+)", line)
if temp_match:
temperature = temp_match.group(1)
event = "Ladle in Furnace"
# Extract Furnace Temperature (NEW SECTION)
elif "Furnace Temperature:" in line:
furnace_match = re.search(r"Furnace Temperature: (\d+\.\d+)", line)
if furnace_match:
furnace_temperature = furnace_match.group(1)
# Extract Dwell Time
elif "Dwell Time:" in line:
dwell_match = re.search(r"Dwell Time: (\d+\.\d+)", line)
if dwell_match:
dwell_time = dwell_match.group(1)
# Extract Pouring Temperature
elif "Pouring Temperature:" in line:
pouring_temp_match = re.search(r"Pouring Temperature: (\d+\.\d+)", line)
if pouring_temp_match:
pouring_temp = pouring_temp_match.group(1)
# Extract Pouring Time
elif "Pouring Time:" in line:
pouring_time_match = re.search(r"Pouring Time: (\d+\.\d+)", line)
if pouring_time_match:
pouring_time = pouring_time_match.group(1)
# Detect cycle completion
elif "Cycle Complete" in line:
event = "Cycle Complete"
# Check if all required data is available
if all([temperature, furnace_temperature, dwell_time, pouring_temp, pouring_time]):
current_time = time.strftime("%Y-%m-%d %H:%M:%S")
ws.append([
current_time,
event,
temperature,
furnace_temperature, # Added furnace temp
dwell_time,
pouring_temp,
pouring_time
])
wb.save(file_path)
print(f"Logged: {current_time}, {temperature}, {furnace_temperature}, {dwell_time}, {pouring_temp}, {pouring_time}")
# Reset variables for next cycle
temperature = None
furnace_temperature = None
dwell_time = None
pouring_temp = None
pouring_time = None
event = None
except KeyboardInterrupt:
print("\nStopped by User. Closing Excel file.")
wb.save(file_path)
ser.close()
Assistant
It appears your code is designed to read data from a serial port, extract specific values using regular expressions, and then write that data to an Excel file. The issue you're encountering is that the "Furnace Temperature" data is not being printed to the Excel file. Let's analyze the code and pinpoint potential causes and solutions.
Here's a breakdown of the problem and how to address it:
Potential Issues:
Data Not Received or Incorrect Format: The ESP32 might not be sending the furnace temperature data, or the format might not match the regular expression you're using.
Regular Expression Mismatch: The regular expression r"Furnace Temperature: (\d+\.\d+)" might not be correctly capturing the furnace temperature from the serial data.
Logic Flow and Variable Reset: The order in which data is received and processed, especially in relation to the Cycle Complete event, is crucial. Also, ensure variables are reset correctly after each cycle.
Missing Data Before "Cycle Complete": If any of the required data points (temperature, furnace_temperature, dwell_time, pouring_temp, pouring_time) are missing when the "Cycle Complete" event is detected, the data will not be written to the Excel file. The all() function checks for this.
Encoding Issues: Although you have error handling for decoding (errors="ignore"), there might still be subtle encoding problems that prevent the regular expressions from matching correctly.
Troubleshooting and Solutions:
Verify Serial Data:
Print Raw Data: You are already printing the raw data (print(f"Raw data: {line}")). Analyze this output carefully to confirm that the "Furnace Temperature" data is actually being sent by the ESP32 and that it matches the expected format (e.g., "Furnace Temperature: 750.5").
Example: If the output shows "The furnace is at 800 degrees", you'll need to adjust your regex.
Correct Regular Expression:
Adjust Regex: Modify the regular expression to accurately capture the furnace temperature. For example, if there are no decimal places, use r"Furnace Temperature: (\d+)". If there's extra text, adjust accordingly.
Be Precise: The regex r"Furnace Temperature: (\d+\.\d+)" expects a number with at least one digit before and after a decimal point. If the ESP32 sends integers (e.g., "Furnace Temperature: 800"), this regex will fail.
Ensure Data Availability Before Writing:
Check all() Condition: The if all([temperature, furnace_temperature, dwell_time, pouring_temp, pouring_time]) condition ensures that all variables have values before writing to the Excel file. If furnace_temperature is None (because the regex didn't match or the data wasn't received), the data will not be written.
Debugging: Temporarily comment out the all() condition to see if any data is being written to the Excel file. This helps isolate whether the problem is with the data extraction or the condition itself.
Check the order of data
Correct order: Ensure that the data that you are trying to extract is in the correct order. For example, the code is written to extract the data and then at the end of the cycle, write all of the extracted data to the excel sheet.
Encoding Issues:
Explicit Encoding: Try explicitly specifying the encoding when decoding the serial data: line = ser.readline().decode("utf-8", errors="ignore").strip(). Experiment with different encodings like "latin-1" or "ascii" if UTF-8 doesn't work.
Logging and Debugging:
Print Extracted Values: Add print statements after each regular expression match to confirm that the values are being extracted correctly. For example:
python
elif "Furnace Temperature:" in line:
furnace_match = re.search(r"Furnace Temperature: (\d+\.\d+)", line)
if furnace_match:
furnace_temperature = furnace_match.group(1)
print(f"Furnace Temperature extracted: {furnace_temperature}") # Debugging
Error Handling:
More Specific Error Handling: Instead of a broad try...except block at the beginning, consider adding more specific error handling around the serial reading and data extraction parts of your code. This will help you pinpoint exactly where errors are occurring.
Revised Code Snippet (with debugging and potential fixes):
python
import serial
import openpyxl
import time
import re
import os
# === Step 1: Setup Serial Connection ===
serial_port = "COM6" # Update this to match your ESP32 port
baud_rate = 115200
try:
ser = serial.Serial(serial_port, baud_rate, timeout=1)
print(f"Connected to {serial_port} at {baud_rate} baud.")
except Exception as e:
print(f"Failed to connect to ESP32. Check the port! Error: {e}")
exit()
# === Step 2: Generate a Unique File Name for Each Experiment ===
timestamp = time.strftime("%Y%m%d_%H%M%S")
file_name = f"esp32_data_{timestamp}.xlsx"
folder_name = "Experiment_Data"
if not os.path.exists(folder_name):
os.makedirs(folder_name)
file_path = os.path.join(folder_name, file_name)
# === Step 3: Setup New Excel File ===
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["Timestamp", "Event", "Initial Temperature (°C)", "Furnace Temperature (°C)",
"Dwell Time (s)", "Pouring Temperature (°C)", "Pouring Time (s)"])
# === Step 4: Read Data and Write to Excel ===
temperature = None
furnace_temperature = None # New variable for furnace temp
dwell_time = None
pouring_temp = None
pouring_time = None
event = None
try:
while True:
try:
line = ser.readline().decode("utf-8", errors="ignore").strip()
print(f"Raw data: {line}")
except serial.SerialException as e:
print(f"Serial read error: {e}")
continue # Skip to the next loop iteration
if not line:
continue
# Extract Initial Temperature
if "Ladle in Furnace" in line:
temp_match = re.search(r"Temperature: (\d+\.\d+)", line)
if temp_match:
temperature = temp_match.group(1)
print(f"Initial Temperature extracted: {temperature}")
event = "Ladle in Furnace"
# Extract Furnace Temperature (NEW SECTION)
elif "Furnace Temperature:" in line:
furnace_match = re.search(r"Furnace Temperature: (\d+\.\d+)", line) # Adjust regex if needed
if furnace_match:
furnace_temperature = furnace_match.group(1)
print(f"Furnace Temperature extracted: {furnace_temperature}")
else:
print("Furnace Temperature regex did not match.")
# Extract Dwell Time
elif "Dwell Time:" in line:
dwell_match = re.search(r"Dwell Time: (\d+\.\d+)", line)
if dwell_match:
dwell_time = dwell_match.group(1)
print(f"Dwell Time extracted: {dwell_time}")
# Extract Pouring Temperature
elif "Pouring Temperature:" in line:
pouring_temp_match = re.search(r"Pouring Temperature: (\d+\.\d+)", line)
if pouring_temp_match:
pouring_temp = pouring_temp_match.group(1)
print(f"Pouring Temperature extracted: {pouring_temp}")
# Extract Pouring Time
elif "Pouring Time:" in line:
pouring_time_match = re.search(r"Pouring Time: (\d+\.\d+)", line)
if pouring_time_match:
pouring_time = pouring_time_match.group(1)
print(f"Pouring Time extracted: {pouring_time}")
# Detect cycle completion
elif "Cycle Complete" in line:
event = "Cycle Complete"
# Check if all required data is available
if all([temperature, furnace_temperature, dwell_time, pouring_temp, pouring_time]): # Check all data
current_time = time.strftime("%Y-%m-%d %H:%M:%S")
ws.append([
current_time,
event,
temperature,
furnace_temperature, # Added furnace temp
dwell_time,
pouring_temp,
pouring_time
])
wb.save(file_path)
print(f"Logged: {current_time}, {temperature}, {furnace_temperature}, {dwell_time}, {pouring_temp}, {pouring_time}")
# Reset variables for next cycle
temperature = None
furnace_temperature = None
dwell_time = None
pouring_temp = None
pouring_time = None
event = None
else:
print("Incomplete data, skipping write to Excel:")
print(f"Temperature: {temperature}, Furnace Temp: {furnace_temperature}, Dwell Time: {dwell_time}, Pouring Temp: {pouring_temp}, Pouring Time: {pouring_time}")
except KeyboardInterrupt:
print("\nStopped by User. Closing Excel file.")
wb.save(file_path)
ser.close()
except Exception as e:
print(f"An unexpected error occurred: {e}")
wb.save(file_path) # attempt to save before exiting
ser.close()
Key changes and recommendations in the revised code:
More Specific Error Handling: Added try...except blocks around the serial reading to catch serial.SerialException errors.
Debugging Prints: Added print statements after each data extraction to confirm that the regular expressions are working correctly. Also added a print statement if the "Furnace Temperature" regex fails to match.
all() Condition Debugging: Added print statements to display which variables are None if the all() condition fails.
Descriptive messages: Added descriptive messages to the print statements.
Saving on exit: Added code to save the excel sheet before exiting.
By implementing these debugging steps and carefully analyzing the serial data, you should be able to identify the reason why the furnace temperature is not being captured and written to the Excel file. Remember to adjust the regular expressions and logic as needed to match the specific format of the data being sent by your ESP32.