Files
2026-09-03 06:40:39 +02:00

209 lines
6.4 KiB
Python

import time
import re
import math
import serial
import pyads
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# ==========================================
# KONFIGURATION
# ==========================================
COM_PORT = 'COM5'
BAUDRATE = 115200
AMS_NET_ID = "5.17.17.136.1.1"
NC_PORT = 501
NC_SYMBOL = 'Axes.EncoderTest.ActPos'
INTERVAL_MS = 200 # Abtastintervall in Millisekunden
LOG_FILENAME = "messung_twincat_heidenhain_auto_incr1.csv"
# Global gespeicherte Messdaten
timestamps = []
tc_values = []
hh_values = []
diff_values = []
records = []
# ==========================================
# HILFSFUNKTION: STRING ZU FLOAT PARSEN
# ==========================================
def parse_heidenhain_val(raw_str):
if not raw_str:
return None
clean_str = raw_str.replace(',', '.')
match = re.search(r'[-+]?\d*\.?\d+', clean_str)
if match:
try:
return float(match.group())
except ValueError:
return None
return None
# ==========================================
# HARDWARE-VERBINDUNGEN INITIATIVE
# ==========================================
plc = pyads.Connection(AMS_NET_ID, NC_PORT)
try:
plc.open()
print("TwinCAT ADS: Verbindung erfolgreich.")
except Exception as e:
print(f"Fehler ADS: {e}")
exit()
try:
ser = serial.Serial(
port=COM_PORT,
baudrate=BAUDRATE,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=1.0
)
print(f"Heidenhain ND 287: Verbindung auf {COM_PORT} erfolgreich.\n")
except serial.SerialException as e:
print(f"Fehler COM: {e}")
plc.close()
exit()
# ==========================================
# MATPLOTLIB SETUP (ECHTZEIT-PLOT)
# ==========================================
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6), sharex=True)
fig.suptitle("Echtzeit-Messung: TwinCAT vs. Heidenhain ND 287")
# Linien initialisieren
line_tc, = ax1.plot([], [], label="TwinCAT NC [mm]", color="blue")
line_hh, = ax1.plot([], [], label="Heidenhain ND 287 [mm]", color="orange", linestyle="--")
ax1.set_ylabel("Position [mm]")
ax1.legend(loc="upper left")
ax1.grid(True)
line_diff, = ax2.plot([], [], label="Abweichung (TC - HH) [mm]", color="red")
ax2.axhline(0, color="black", linestyle=":", linewidth=1)
ax2.set_xlabel("Zeitstempel")
ax2.set_ylabel("Differenz [mm]")
ax2.legend(loc="upper left")
ax2.grid(True)
# ==========================================
# UPDATE-FUNKTION FÜR JEDEN ZEITSCHRITT
# ==========================================
start_time = time.time()
def update(frame):
current_time_str = time.strftime("%H:%M:%S")
full_timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
tc_val, hh_val = None, None
# 1. TwinCAT lesen
try:
tc_val = plc.read_by_name(NC_SYMBOL, plc_datatype=pyads.PLCTYPE_LREAL)
tc_str = f"{tc_val:.4f}"
except Exception:
tc_str = "FEHLER"
# 2. Heidenhain lesen
try:
ser.reset_input_buffer()
ser.write(b'\x02')
time.sleep(0.03)
raw_response = ser.readline().decode('utf-8', errors='ignore').strip()
hh_val = parse_heidenhain_val(raw_response)
hh_str = f"{hh_val:.4f}" if hh_val is not None else "N/A"
except Exception:
hh_str = "FEHLER"
# 3. Differenz verarbeiten
if tc_val is not None and hh_val is not None:
diff = tc_val - hh_val
diff_str = f"{diff:+.4f}"
# Daten für Plot anhängen
timestamps.append(current_time_str)
tc_values.append(tc_val)
hh_values.append(hh_val)
diff_values.append(diff)
else:
diff_str = "N/A"
records.append((full_timestamp, tc_str, hh_str, diff_str))
# Maximal 50 Messwerte im Plot anzeigen (rollendes Fenster)
max_visible = 50
x_data = timestamps[-max_visible:]
line_tc.set_data(range(len(x_data)), tc_values[-max_visible:])
line_hh.set_data(range(len(x_data)), hh_values[-max_visible:])
line_diff.set_data(range(len(x_data)), diff_values[-max_visible:])
# Achsen-Grenzen anpassen
ax1.relim()
ax1.autoscale_view()
ax2.relim()
ax2.autoscale_view()
# X-Achsen Beschriftung
ax2.set_xticks(range(len(x_data)))
ax2.set_xticklabels(x_data, rotation=45, ha="right", fontsize=8)
return line_tc, line_hh, line_diff
# ==========================================
# AUTOMATISCHER EXPORT BEIM BEENDEN
# ==========================================
def on_close(event=None):
ser.close()
plc.close()
stat_lines = []
stat_lines.append("# " + "=" * 55)
stat_lines.append("# STATISTIK DER ABWEICHUNG")
stat_lines.append("# " + "=" * 55)
if diff_values:
count = len(diff_values)
mean_diff = sum(diff_values) / count
max_diff = max(diff_values)
min_diff = min(diff_values)
max_abs_diff = max(abs(d) for d in diff_values)
if count > 1:
variance = sum((x - mean_diff) ** 2 for x in diff_values) / (count - 1)
std_dev_str = f"{math.sqrt(variance):.4f} mm"
else:
std_dev_str = "N/A"
stat_lines.append(f"# Anzahl Messwerte: {count}")
stat_lines.append(f"# Mittelwert Differenz: {mean_diff:+.4f} mm")
stat_lines.append(f"# Maximale Abweichung (+): {max_diff:+.4f} mm")
stat_lines.append(f"# Minimale Abweichung (-): {min_diff:+.4f} mm")
stat_lines.append(f"# Max. Betragsabweichung: {max_abs_diff:.4f} mm")
stat_lines.append(f"# Standardabweichung (s): {std_dev_str}")
else:
stat_lines.append("# Keine gültigen Messdaten vorhanden.")
stat_lines.append("# " + "=" * 55)
try:
with open(LOG_FILENAME, mode='w', encoding='utf-8') as f:
f.write("Zeitstempel;TwinCAT_mm;Heidenhain_mm;Differenz_mm\n")
for rec in records:
f.write(f"{rec[0]};{rec[1]};{rec[2]};{rec[3]}\n")
f.write("\n")
for line in stat_lines:
f.write(line + "\n")
print(f"\n[INFO] Datei gespeichert unter: {LOG_FILENAME}")
except IOError as e:
print(f"\n[FEHLER] Datei konnte nicht geschrieben werden: {e}")
# Beenden per Fenster-Schließen abfangen
fig.canvas.mpl_connect('close_event', on_close)
# Animation starten
ani = animation.FuncAnimation(fig, update, interval=INTERVAL_MS, cache_frame_data=False)
plt.tight_layout()
plt.show()