-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIO.py
More file actions
444 lines (360 loc) · 15.7 KB
/
IO.py
File metadata and controls
444 lines (360 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
import sys
import tkinter as tk
from tkinter import ttk, messagebox
from pyftdi.gpio import GpioMpsseController
# ---- FT232H bit mapping in "wide" GPIO mode ----
# Low byte: bits 0..7 -> D0..D7 (ADBUS)
# High byte: bits 8..15 -> C0..C7 (ACBUS)
# Outputs on C-bus
C3 = 1 << 11
C4 = 1 << 12
C5 = 1 << 13
# Input on C-bus
C7 = 1 << 15
# Buzzer on MOSI / ADBUS1 / D1
D1 = 1 << 1
OUTS_C = C3 | C4 | C5
OUTS_ALL = OUTS_C | D1 # include buzzer pin as output
def normalize_read(raw):
"""pyftdi read() can return int or (value, direction). Normalize to int."""
return raw[0] if isinstance(raw, tuple) else raw
class Ft232hUI:
def __init__(self, root: tk.Tk):
self.root = root
self.root.title("Adafruit FT232H - C3/C4/C5 Out, C7 In + D1(MOSI) Buzzer")
self.root.geometry("760x560")
self.gpio = None
self.connected = False
# Connection
self.url_var = tk.StringVar(value="ftdi://ftdi:232h/1")
self.freq_hz = tk.DoubleVar(value=1e6) # avoid older pyftdi frequency bug
# Input polling
self.poll_ms = tk.IntVar(value=200)
self._poll_job = None
# Output state (we always write a full 16-bit value)
self.port_value = 0 # tracks C outs + D1 buzzer level
# Manual outputs
self.c3_var = tk.BooleanVar(self.root, value=False)
self.c4_var = tk.BooleanVar(self.root, value=False)
self.c5_var = tk.BooleanVar(self.root, value=False)
# One-hot cycle
self.cycle_enabled = tk.BooleanVar(self.root, value=False)
self.dwell_ms = tk.IntVar(value=500)
self._cycle_job = None
self._cycle_index = 0
self._cycle_pins = [C3, C4, C5]
# Buzzer / tone
self.tone_hz = tk.IntVar(value=300) # realistic for Tk timing
self.tone_ms = tk.IntVar(value=250)
self._tone_job = None
self._tone_end_ms = 0
self._tone_halfperiod_ms = 1
self._tone_level = 0
self._build_ui()
self._set_ui_connected(False)
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
# ---------------- UI ----------------
def _build_ui(self):
pad = {"padx": 10, "pady": 6}
frm_conn = ttk.LabelFrame(self.root, text="Connection")
frm_conn.pack(fill="x", padx=10, pady=10)
ttk.Label(frm_conn, text="FTDI URL:").grid(row=0, column=0, sticky="w", **pad)
ttk.Entry(frm_conn, textvariable=self.url_var, width=50).grid(row=0, column=1, sticky="we", **pad)
ttk.Label(frm_conn, text="MPSSE Freq (Hz):").grid(row=0, column=2, sticky="e", **pad)
ttk.Entry(frm_conn, textvariable=self.freq_hz, width=12).grid(row=0, column=3, sticky="w", **pad)
self.btn_connect = ttk.Button(frm_conn, text="Connect", command=self.toggle_connect)
self.btn_connect.grid(row=0, column=4, **pad)
self.lbl_status = ttk.Label(frm_conn, text="Disconnected", foreground="red")
self.lbl_status.grid(row=1, column=0, columnspan=5, sticky="w", padx=10, pady=(0, 10))
frm_conn.columnconfigure(1, weight=1)
# Outputs (C3/C4/C5)
frm_out = ttk.LabelFrame(self.root, text="Outputs (C3/C4/C5)")
frm_out.pack(fill="x", padx=10, pady=6)
self.chk_c3 = ttk.Checkbutton(frm_out, text="C3", variable=self.c3_var, command=self.apply_manual_outputs)
self.chk_c4 = ttk.Checkbutton(frm_out, text="C4", variable=self.c4_var, command=self.apply_manual_outputs)
self.chk_c5 = ttk.Checkbutton(frm_out, text="C5", variable=self.c5_var, command=self.apply_manual_outputs)
self.chk_c3.grid(row=0, column=0, padx=12, pady=10, sticky="w")
self.chk_c4.grid(row=0, column=1, padx=12, pady=10, sticky="w")
self.chk_c5.grid(row=0, column=2, padx=12, pady=10, sticky="w")
self.btn_all_off = ttk.Button(frm_out, text="All OFF", command=self.all_off)
self.btn_all_on = ttk.Button(frm_out, text="All ON", command=self.all_on)
self.btn_all_off.grid(row=0, column=3, padx=12, pady=10)
self.btn_all_on.grid(row=0, column=4, padx=12, pady=10)
# One-hot cycle
frm_cycle = ttk.LabelFrame(self.root, text="One-hot Cycle (C3 → C4 → C5)")
frm_cycle.pack(fill="x", padx=10, pady=6)
self.btn_cycle = ttk.Button(frm_cycle, text="Start Cycle", command=self.toggle_cycle)
self.btn_cycle.grid(row=0, column=0, padx=10, pady=10)
ttk.Label(frm_cycle, text="Dwell (ms):").grid(row=0, column=1, padx=10, pady=10, sticky="e")
self.spn_dwell = ttk.Spinbox(frm_cycle, from_=50, to=10000, textvariable=self.dwell_ms, width=8)
self.spn_dwell.grid(row=0, column=2, padx=10, pady=10, sticky="w")
ttk.Label(frm_cycle, text="Manual outputs disabled while cycling.").grid(
row=0, column=3, padx=10, pady=10, sticky="w"
)
frm_cycle.columnconfigure(3, weight=1)
# Input (C7)
frm_in = ttk.LabelFrame(self.root, text="Input (C7)")
frm_in.pack(fill="x", padx=10, pady=6)
ttk.Label(frm_in, text="C7 State:").grid(row=0, column=0, padx=10, pady=12, sticky="w")
self.lbl_c7 = ttk.Label(frm_in, text="—", font=("Segoe UI", 16, "bold"))
self.lbl_c7.grid(row=0, column=1, padx=10, pady=12, sticky="w")
ttk.Label(frm_in, text="Poll (ms):").grid(row=0, column=2, padx=10, pady=12, sticky="e")
self.spn_poll = ttk.Spinbox(frm_in, from_=50, to=5000, textvariable=self.poll_ms, width=8)
self.spn_poll.grid(row=0, column=3, padx=10, pady=12, sticky="w")
self.btn_read = ttk.Button(frm_in, text="Read Now", command=self.read_once)
self.btn_read.grid(row=0, column=4, padx=10, pady=12)
# Buzzer (D1 / MOSI)
frm_tone = ttk.LabelFrame(self.root, text="Buzzer (D1 / MOSI / ADBUS1) - Bit-banged")
frm_tone.pack(fill="x", padx=10, pady=6)
ttk.Label(frm_tone, text="Tone (Hz):").grid(row=0, column=0, padx=10, pady=12, sticky="e")
ttk.Entry(frm_tone, textvariable=self.tone_hz, width=10).grid(row=0, column=1, padx=10, pady=12, sticky="w")
ttk.Label(frm_tone, text="Duration (ms):").grid(row=0, column=2, padx=10, pady=12, sticky="e")
ttk.Entry(frm_tone, textvariable=self.tone_ms, width=10).grid(row=0, column=3, padx=10, pady=12, sticky="w")
self.btn_tone_play = ttk.Button(frm_tone, text="Play", command=self.play_tone)
self.btn_tone_stop = ttk.Button(frm_tone, text="Stop", command=self.stop_tone)
self.btn_tone_play.grid(row=0, column=4, padx=10, pady=12)
self.btn_tone_stop.grid(row=0, column=5, padx=10, pady=12)
ttk.Label(frm_tone, text="Note: Windows timing limits tones to ~300–500 Hz cleanly.").grid(
row=1, column=0, columnspan=6, padx=10, pady=(0, 10), sticky="w"
)
# Notes
frm_note = ttk.LabelFrame(self.root, text="Notes")
frm_note.pack(fill="both", expand=True, padx=10, pady=10)
note = (
"• C pins are 3.3V only. Use LED resistors.\n"
"• C7 input needs an external pull-up/down (~10k) to avoid floating.\n"
"• If the buzzer needs more current than a pin can provide, use a transistor driver.\n"
)
txt = tk.Text(frm_note, height=5, wrap="word")
txt.insert("1.0", note)
txt.configure(state="disabled")
txt.pack(fill="both", expand=True, padx=10, pady=10)
def _set_ui_connected(self, ok: bool):
self.connected = ok
if ok:
self.lbl_status.config(text="Connected", foreground="green")
self.btn_connect.config(text="Disconnect")
else:
self.lbl_status.config(text="Disconnected", foreground="red")
self.btn_connect.config(text="Connect")
self.lbl_c7.config(text="—")
state = "normal" if ok else "disabled"
for w in (
self.chk_c3, self.chk_c4, self.chk_c5,
self.btn_all_off, self.btn_all_on,
self.btn_cycle, self.spn_dwell,
self.btn_read, self.spn_poll,
self.btn_tone_play, self.btn_tone_stop
):
w.config(state=state)
self._update_manual_enable()
def _update_manual_enable(self):
manual_state = "normal" if (self.connected and not self.cycle_enabled.get()) else "disabled"
for w in (self.chk_c3, self.chk_c4, self.chk_c5, self.btn_all_off, self.btn_all_on):
w.config(state=manual_state)
# ---------------- Connect/Disconnect ----------------
def toggle_connect(self):
if self.connected:
self.disconnect()
else:
self.connect()
def connect(self):
url = self.url_var.get().strip()
if not url:
messagebox.showerror("Error", "Enter an FTDI URL like: ftdi://ftdi:232h/1")
return
try:
freq = float(self.freq_hz.get())
if freq <= 0:
raise ValueError()
except Exception:
messagebox.showerror("Error", "MPSSE frequency must be a positive number (e.g., 1000000).")
return
try:
self.gpio = GpioMpsseController()
# OUTS_ALL sets C3/C4/C5 and D1 as outputs. C7 stays input.
self.gpio.configure(url, direction=OUTS_ALL, frequency=freq, initial=0)
self.port_value = 0
self._set_ui_connected(True)
self.start_poll()
self._write_port()
except Exception as e:
self.gpio = None
self._set_ui_connected(False)
messagebox.showerror("Connection Failed", f"{e}")
def disconnect(self):
self.stop_tone()
self.stop_cycle()
self.stop_poll()
try:
if self.gpio:
try:
self.gpio.write(0)
except Exception:
pass
self.gpio.close()
finally:
self.gpio = None
self.port_value = 0
self._set_ui_connected(False)
# ---------------- Low-level write ----------------
def _write_port(self):
if not self.connected or not self.gpio:
return
try:
self.gpio.write(self.port_value & OUTS_ALL)
except Exception as e:
messagebox.showerror("Write Failed", str(e))
self.disconnect()
# ---------------- Outputs (C3/C4/C5) ----------------
def _set_c_outputs_from_vars(self):
# Clear C output bits
self.port_value &= ~OUTS_C
# Apply desired bits
if self.c3_var.get(): self.port_value |= C3
if self.c4_var.get(): self.port_value |= C4
if self.c5_var.get(): self.port_value |= C5
def apply_manual_outputs(self):
if not self.connected or not self.gpio or self.cycle_enabled.get():
return
self._set_c_outputs_from_vars()
self._write_port()
def all_on(self):
self.c3_var.set(True); self.c4_var.set(True); self.c5_var.set(True)
self.apply_manual_outputs()
def all_off(self):
self.c3_var.set(False); self.c4_var.set(False); self.c5_var.set(False)
self.apply_manual_outputs()
# ---------------- One-hot cycle ----------------
def toggle_cycle(self):
if not self.connected:
return
if self.cycle_enabled.get():
self.stop_cycle()
else:
self.start_cycle()
def start_cycle(self):
self.cycle_enabled.set(True)
self.btn_cycle.config(text="Stop Cycle")
self._update_manual_enable()
self._cycle_index = 0
self._cycle_step()
def stop_cycle(self):
self.cycle_enabled.set(False)
self.btn_cycle.config(text="Start Cycle")
self._update_manual_enable()
if self._cycle_job is not None:
try:
self.root.after_cancel(self._cycle_job)
except Exception:
pass
self._cycle_job = None
# Turn off C outputs but leave buzzer state untouched
self.port_value &= ~OUTS_C
self._write_port()
def _cycle_step(self):
if not self.connected or not self.gpio or not self.cycle_enabled.get():
return
# One-hot on C outputs
self.port_value &= ~OUTS_C
self.port_value |= self._cycle_pins[self._cycle_index]
self._write_port()
self._cycle_index = (self._cycle_index + 1) % len(self._cycle_pins)
dwell = max(50, int(self.dwell_ms.get()))
self._cycle_job = self.root.after(dwell, self._cycle_step)
# ---------------- Input (C7) ----------------
def read_once(self):
if not self.connected or not self.gpio:
return
try:
raw = self.gpio.read()
pins = normalize_read(raw)
state = bool(pins & C7)
self.lbl_c7.config(text="HIGH" if state else "LOW")
except Exception as e:
messagebox.showerror("Read Failed", str(e))
self.disconnect()
def _poll_step(self):
self.read_once()
period = max(50, int(self.poll_ms.get()))
self._poll_job = self.root.after(period, self._poll_step)
def start_poll(self):
self.stop_poll()
self._poll_job = self.root.after(100, self._poll_step)
def stop_poll(self):
if self._poll_job is not None:
try:
self.root.after_cancel(self._poll_job)
except Exception:
pass
self._poll_job = None
# ---------------- Buzzer (D1) ----------------
def play_tone(self):
if not self.connected or not self.gpio:
return
try:
hz = int(self.tone_hz.get())
dur = int(self.tone_ms.get())
if hz <= 0 or dur <= 0:
raise ValueError()
except Exception:
messagebox.showerror("Error", "Tone Hz and Duration ms must be positive integers.")
return
# Stop any existing tone first
self.stop_tone()
# Tk timing: half period in ms (clamp to >= 1ms)
half_ms = int(round(1000.0 / (2.0 * hz)))
self._tone_halfperiod_ms = max(1, half_ms)
# End time (monotonic-ish using tk's time base)
self._tone_end_ms = self.root.winfo_fpixels("1i") # dummy to ensure Tk init (harmless)
end_at = self.root.tk.call("after", "info") # not used; just avoid lint
# We'll use tk's internal clock via `after` chain + real time:
self._tone_end_time = self._now_ms() + dur
self._tone_level = 0
self._tone_step()
def stop_tone(self):
if self._tone_job is not None:
try:
self.root.after_cancel(self._tone_job)
except Exception:
pass
self._tone_job = None
# Force buzzer low (D1 off)
self.port_value &= ~D1
if self.connected and self.gpio:
self._write_port()
def _tone_step(self):
if not self.connected or not self.gpio:
return
# Stop on duration timeout
if self._now_ms() >= getattr(self, "_tone_end_time", 0):
self.stop_tone()
return
# Toggle D1
self._tone_level ^= 1
if self._tone_level:
self.port_value |= D1
else:
self.port_value &= ~D1
self._write_port()
self._tone_job = self.root.after(self._tone_halfperiod_ms, self._tone_step)
def _now_ms(self) -> int:
# Real time in ms (good enough for duration)
import time
return int(time.time() * 1000)
# ---------------- Close ----------------
def on_close(self):
self.disconnect()
self.root.destroy()
def main():
root = tk.Tk()
try:
style = ttk.Style()
if sys.platform.startswith("win"):
style.theme_use("vista")
except Exception:
pass
Ft232hUI(root)
root.mainloop()
if __name__ == "__main__":
main()