Repository navigation
Expand file tree
/
Copy pathrqx71g_gpio_trigger.py
More file actions
151 lines (127 loc) · 5.55 KB
/
Copy pathrqx71g_gpio_trigger.py
File metadata and controls
151 lines (127 loc) · 5.55 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
#!/usr/bin/env python3
import subprocess
import time
import signal
import sys
import argparse
import os
import math
try:
import psutil # for CPU affinity
except ImportError:
print("Module 'psutil' not found! Please run 'sudo apt install python3-psutil'")
exit(1)
import ctypes # for real-time scheduling
import ctypes.util
# Real-time scheduling parameters
SCHED_FIFO = 1
MCL_CURRENT = 1
MCL_FUTURE = 2
class GPIOTrigger:
def __init__(self, frequency=10, chip_name="gpiochip0", line_numbers=[0, 19], cpu_core=3):
self.chip_name = chip_name
self.line_numbers = line_numbers
self.running = True
self.frequency = frequency
self.period = 1.0 / frequency
self.cpu_core = cpu_core
# Create gpioset command strings
self.set_high_cmd = f"gpioset {self.chip_name} " + " ".join(f"{pin}=1" for pin in self.line_numbers)
self.set_low_cmd = f"gpioset {self.chip_name} " + " ".join(f"{pin}=0" for pin in self.line_numbers)
# Set up signal handlers
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def lock_memory(self):
"""Lock process memory to prevent swapping"""
try:
libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
result = libc.mlockall(MCL_CURRENT | MCL_FUTURE)
if result != 0:
error = ctypes.get_errno()
raise OSError(error, f"mlockall failed: {os.strerror(error)}")
print("Successfully locked memory")
except Exception as e:
print(f"Warning: Could not lock memory: {str(e)}")
def set_realtime_priority(self):
"""Set high priority scheduling"""
try:
libc = ctypes.CDLL('libc.so.6')
class sched_param(ctypes.Structure):
_fields_ = [('sched_priority', ctypes.c_int)]
param = sched_param(99) # Maximum real-time priority
result = libc.sched_setscheduler(0, SCHED_FIFO, ctypes.byref(param))
if result == 0:
print("Successfully set real-time scheduling policy")
else:
print("Failed to set real-time scheduling policy. Are you running with sudo?")
except Exception as e:
print(f"Warning: Could not set real-time scheduling: {str(e)}")
def set_cpu_affinity(self):
"""Bind process to a specific CPU core"""
try:
process = psutil.Process()
process.cpu_affinity([self.cpu_core])
print(f"Successfully set CPU affinity to core {self.cpu_core}")
except Exception as e:
print(f"Warning: Could not set CPU affinity: {str(e)}")
def setup_gpio(self):
"""Initialize GPIO and system settings"""
if os.geteuid() != 0:
print("Error: This program must be run as root (sudo)")
sys.exit(1)
self.set_cpu_affinity()
self.set_realtime_priority()
self.lock_memory()
# Test GPIO access
try:
subprocess.run(self.set_low_cmd, shell=True, check=True)
print("GPIO setup successful")
except Exception as e:
print(f"GPIO setup error: {str(e)}")
sys.exit(1)
def run(self):
"""Main loop aligned with system clock"""
self.setup_gpio()
print(f"Starting synchronized GPIO trigger... (Frequency: {self.frequency} Hz)")
# Calculate the start of the next whole second
now = time.time()
next_trigger_time = math.ceil(now)
# Initial wait to align with the next whole second
print(f"Waiting to sync with system clock at {next_trigger_time}s...")
while time.time() < next_trigger_time:
time.sleep(0.001)
while self.running:
# Pulse Start
start_time = time.perf_counter()
subprocess.run(self.set_high_cmd, shell=True, check=True)
# Precise high pulse width (5ms)
pulse_end = start_time + 0.005
while time.perf_counter() < pulse_end:
pass
# Pulse End
subprocess.run(self.set_low_cmd, shell=True, check=True)
# Calculate next trigger time based on frequency
next_trigger_time += self.period
# Busy wait for the next period to maintain high precision
while time.time() < next_trigger_time:
# Use a small sleep if the gap is large to save CPU,
# but switch to busy wait when close (e.g., < 2ms)
if next_trigger_time - time.time() > 0.002:
time.sleep(0.001)
else:
pass
def signal_handler(self, signum, frame):
print("\nReceived termination signal, cleaning up...")
self.running = False
subprocess.run(self.set_low_cmd, shell=True, check=False)
sys.exit(0)
def parse_arguments():
parser = argparse.ArgumentParser(description='Clock-Synchronized GPIO Trigger')
parser.add_argument('-f', '--frequency', type=float, default=10.0, help='Hz (default: 10)')
parser.add_argument('--chip', type=str, default="gpiochip0", help='GPIO chip name')
parser.add_argument('--cpu-core', type=int, default=3, help='CPU core (default: 3)')
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
trigger = GPIOTrigger(frequency=args.frequency, chip_name=args.chip, cpu_core=args.cpu_core)
trigger.run()