PyTmcStepper 0.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of PyTmcStepper might be problematic. Click here for more details.

@@ -0,0 +1,302 @@
1
+ Metadata-Version: 2.2
2
+ Name: PyTmcStepper
3
+ Version: 0.7
4
+ Summary: This is a Python libary to drive a stepper motor with a Trinamic stepper driver and a single board computer like a Raspberry Pi
5
+ Home-page: https://github.com/Chr157i4n/PyTmcStepper
6
+ Author: Christian Köhlke
7
+ Author-email: christian@koehlke.de
8
+ Project-URL: Bug Tracker, https://github.com/Chr157i4n/PyTmcStepper/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Natural Language :: English
15
+ Classifier: Topic :: System :: Hardware :: Hardware Drivers
16
+ Requires-Python: >=3.7
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: pyserial
20
+ Provides-Extra: raspberry-pi
21
+ Requires-Dist: RPi.GPIO; extra == "raspberry-pi"
22
+ Provides-Extra: raspberry-pi5
23
+ Requires-Dist: gpiozero; extra == "raspberry-pi5"
24
+ Provides-Extra: nvidia-jetson
25
+ Requires-Dist: Jetson.GPIO; extra == "nvidia-jetson"
26
+ Provides-Extra: luckfox-pico
27
+ Requires-Dist: python-periphery; extra == "luckfox-pico"
28
+ Provides-Extra: orange-pi
29
+ Requires-Dist: OPi.GPIO; extra == "orange-pi"
30
+
31
+ # TMC_2209_Raspberry_Pi
32
+
33
+ [![PyPI python version TMC-2209-Raspberry-Pi](https://badgen.net/pypi/python/TMC-2209-Raspberry-Pi)](https://pypi.org/project/TMC-2209-Raspberry-Pi)
34
+ [![PyPI version TMC-2209-Raspberry-Pi](https://badgen.net/pypi/v/TMC-2209-Raspberry-Pi)](https://pypi.org/project/TMC-2209-Raspberry-Pi)
35
+ [![PyPI downloads TMC-2209-Raspberry-Pi](https://img.shields.io/pypi/dm/TMC-2209-Raspberry-Pi)](https://pypi.org/project/TMC-2209-Raspberry-Pi)
36
+ [![GitHub issues](https://img.shields.io/github/issues/Chr157i4n/TMC2209_Raspberry_Pi.svg)](https://GitHub.com/Chr157i4n/TMC2209_Raspberry_Pi/issues/)
37
+
38
+ \
39
+ \
40
+ This is a library to drive a stepper motor with a TMC2209 stepper driver and a Raspberry Pi.
41
+
42
+ This code is still experimental, so use it on your own risk.
43
+
44
+ This library is programmed in pure Python. The performance of Python is not good enough to drive the motor with high speed.
45
+ So if you move the motor with high speed using this library the motor will lose steps.
46
+
47
+ Tested on a [Bigtreetech TMC2209 V1.2](https://github.com/bigtreetech/BIGTREETECH-Stepper-Motor-Driver/tree/master/TMC2209/V1.2) and [Bigtreetech TMC2209 V1.3](https://github.com/bigtreetech/BIGTREETECH-Stepper-Motor-Driver/tree/master/TMC2209/V1.3).
48
+
49
+ It has a rSense of 110 mOhm and it uses one Pin (PDN_UART) for UART RX and TX.
50
+ So the PDN_UART-Pin needs to be connected to the Raspberrry Pis RX-Pin directly and to the TX-Pin with an 1kOhm resistor.
51
+ You can read more about this in the datasheet from Trinamic.
52
+
53
+ Because the TMC2209 uses one shared pin for transmit and receive in the UART communication line, the Raspberry Pi also receives what it sends.
54
+ Well, the Pi receives 4 bytes from itself and 8 bytes from the driver. So the Pi receives a total of 12 bytes and only the last 8 are the reply, of which only 4 are data bytes.
55
+
56
+ The Documentation of the TMC2209 can be found here:
57
+ [TMC2209 - Datsheet](https://www.analog.com/media/en/technical-documentation/data-sheets/TMC2209_datasheet_rev1.09.pdf)
58
+
59
+ The code is also available on [PyPI](https://pypi.org/project/TMC-2209-Raspberry-Pi).
60
+
61
+ ## Installation
62
+
63
+ ### Installation with PIP
64
+
65
+ ```shell
66
+ pip3 install TMC-2209-Raspberry-Pi
67
+ ```
68
+
69
+ ### Installation with GIT
70
+
71
+ - clone this repo to your Raspberry Pi using
72
+
73
+ ```shell
74
+ git clone https://github.com/Chr157i4n/TMC2209_Raspberry_Pi
75
+ ```
76
+
77
+ - install the required modules
78
+
79
+ ```shell
80
+ pip3 install RPi.GPIO pyserial
81
+ ```
82
+
83
+ - enable the serial port in
84
+
85
+ ```shell
86
+ sudo raspi-config
87
+ ```
88
+
89
+ ### Board Support
90
+
91
+ The following table shows the supported boards and which libraries for GPIO access is beeing used for that board.
92
+
93
+ Library | Installation Parameter | Boards
94
+ ----------- | ------------------------- | -----------
95
+ RPi.GPIO | RASPBERRY_PI | Pi4, Pi3 etc.
96
+ gpiozero | RASPBERRY_PI5 | Pi5
97
+ Jetson.GPIO | NVIDIA_JETSON | Nvidia Jetson
98
+ pheriphery | LUCKFOX_PICO | Luckfox Pico
99
+ pheriphery | LUCKFOX_PICO | Luckfox Pico
100
+ OPi.GPIO | ORANGE_PI | Orange Pi
101
+
102
+ Those libraries are needed for this library to work. You can either install the correct library yourself.
103
+ You can also install the needed GPIO library by specifing the Installation Parameter while installing this library:
104
+
105
+ ```shell
106
+ pip3 install TMC-2209-Raspberry-Pi[RASPBERRY_PI]
107
+ ```
108
+
109
+ ## Driver Support
110
+
111
+ The currently supported drivers are:
112
+
113
+ Driver | Interface
114
+ -- | --
115
+ TMC2208 | UART
116
+ TMC2209 | UART
117
+ TMC2240 | SPI/UART
118
+
119
+ ## Submodules
120
+
121
+ with V0.7 the code for enabling the motor current output and the code for controling the motion of the drivers
122
+ is split into their own classes to be able to support the diverse methods.
123
+
124
+ ### EnableControl
125
+
126
+ EnableControl | Class | Driver | Notes
127
+ -- | -- | -- | --
128
+ Pin | TmcEnableControlPin | all | the EN Pin of the Driver needs to be connected to a GPIO of the Pi
129
+ TOff | TmcEnableControlToff | all | the EN Pin needs to be connected to GND.<br />On the TMC2209 this enables current Output on Startup!<br />On the TMC2240 this works fine, because TOff is per default 0 (off).
130
+
131
+ ### MotionControl
132
+
133
+ MotionControl | Class | Driver | Notes
134
+ -- | -- | -- | --
135
+ STEP/DIR | TmcMotionControlStepDir | all | the STEP and DIR pin of the driver must each be connected to a GPIO of the Pi
136
+ STEP/REG | TmcMotionControlStepReg | all | only the STEP pin needs to be connected to a GPIO of the Pi.<br />The direction is controlled via the Register.
137
+ VACTUAL | TmcMotionControlVActual | TMC220x | the Direction and Speed is controlled via Register. But VActual does only allow setting a speed and therefore cannot control positioning of the Motor.
138
+
139
+ Further methods of controlling a motor could be:
140
+
141
+ - using the built in Motion Controller of the TMC5130
142
+ - via a µC which controlls the Motor
143
+ - highperformance Step/Dir Library written in a compiled language (C/C++)
144
+
145
+ ### Com
146
+
147
+ Com | Class | Driver | Notes
148
+ -- | -- | -- | --
149
+ UART | TmcComUart | all | Communication via UART (RX, TX). See [Wiring](#uart)<br />[pyserial](https://pypi.org/project/pyserial) needs to be installed
150
+ SPI | TmcComSpi | TMC2240 | Communication via SPI (MOSI, MISO, CLK, CS). See [Wiring](#spi)<br />[spidev](https://pypi.org/project/spidev) needs to be installed
151
+
152
+ ## Wiring
153
+
154
+ ![wiring diagram](docs/images/wiring_diagram.png)
155
+
156
+ Pin TMC | Color | connect to | Function
157
+ -- | -- | -- | --
158
+ VDD | | 3,3V of Raspberry Pi | recommended, for forcing the TMC to use 3,3V logic level
159
+ GND | BLACK | GND of Raspberry Pi | GND for VDD and Signals
160
+ VM | RED | 12V or 24V of power supply | power for the motor
161
+ GND | BLACK | GND of power supply | power for the motor
162
+ EN | RED |GPIO21 of Raspberry Pi | enable the motor output
163
+ STEP | GREEN |GPIO16 of Raspberry Pi | moves the motor one step per pulse
164
+ DIR | WHITE |GPIO20 of Raspberry Pi | set the direction of the motor
165
+ DIAG | ORANGE | GPIO26 of Raspberry Pi | optional, for StallGuard
166
+
167
+ The GPIO pins can be specific when initiating the class.
168
+ If you test this on a breadboard, make sure to cut off the bottomside of the pins (Vref and DIAG) next to the EN pin, so that they are not shorted trough the breadboard.
169
+
170
+ ### UART
171
+
172
+ Pin TMC | Color | connect to | Function
173
+ -- | -- | -- | --
174
+ TX or PDN_UART with 1kOhm | YELLOW | TX of Raspberry Pi | send data to TMC via UART
175
+ RX or PDN_UART directly | YELLOW | RX of Raspberry Pi | receive data from TMC via UART
176
+
177
+ ### SPI
178
+
179
+ Pin TMC | Color | connect to | Function
180
+ -- | -- | -- | --
181
+ MOSI | | MOSI | Data from Pi to TMC
182
+ MISO | | MOSI | Data from TMC to Pi
183
+ SPI-CLK | | CLK | Clock for SPI
184
+ CS | | SPI CE0 (for the demo scripts) | Chipselect (2nd parameter of TmcComSpi "spi_dev")
185
+
186
+ ## Demo scripts
187
+
188
+ You can run the demo scripts files from the main directory with
189
+
190
+ ```shell
191
+ python3 -m demo.demo_script_01_uart_connection
192
+ ```
193
+
194
+ ### [demo_script_01_uart_connection.py](demo/demo_script_01_uart_connection.py)
195
+
196
+ This only communicates with the TMC driver over UART. It should set some settings in the driver and then outputs the settings.
197
+ When it outputs ```TMC2209: UART Communication Error```, you need to check the UART-connection.
198
+
199
+ ### [demo_script_02_pin_connection.py](demo/demo_script_02_pin_connection.py)
200
+
201
+ This script enables the raspberry GPIO output for the dir, en and step pin and then checks the TMC driver register,
202
+ whether the driver sees them as HIGH or LOW. Because the enabled pin is activated for a short time, the motor current ouput
203
+ will be also activated in this script for a short time.
204
+ This script should output:
205
+ Pin DIR: OK
206
+ Pin STEP: OK
207
+ Pin EN: OK
208
+ if not, check the connection of the pin.
209
+
210
+ ### [demo_script_03_basic_movement.py](demo/demo_script_03_basic_movement.py)
211
+
212
+ This script should move the motor 6 times, one revolution back and forth.
213
+
214
+ ### [demo_script_04_stallguard.py](demo/demo_script_04_stallguard.py)
215
+
216
+ In this script the stallguard feature of the TMC2209 is beeing setup.
217
+ A funtion will be called, if the driver detects a stall. The function stops the current movement.
218
+ The motor will be moved 10 revolutions. If the movement is finished unhindered, the script outputs ```Movement finished successfully```.
219
+ If you block the motor with pliers or something similar, the the motor will stop and the script outputs ```StallGuard!``` and ```Movement was not completed```
220
+
221
+ ### [demo_script_05_vactual.py](demo/demo_script_05_vactual.py)
222
+
223
+ VACTUAL allows moving the motor by UART control. It gives the motor velocity in +-(2^23)-1 [μsteps / t]
224
+
225
+ ### [demo_script_06_multiple_drivers.py](demo/demo_script_06_multiple_drivers.py)
226
+
227
+ Multiple drivers can be addressed via UART by setting different addresses with the MS1 and MS2 pins.
228
+ Simultaneous movement of multiple motors can be done with threaded movement.
229
+
230
+ ### [demo_script_07_threads.py](demo/demo_script_07_threads.py)
231
+
232
+ In this script, the movement of a stepper with threads is shown. This can be used to do other task while moving a motor, or to move several motors simultaneous.
233
+
234
+ ### [demo_script_08_log_to_file.py](demo/demo_script_08_log_to_file.py)
235
+
236
+ This script shows how you can alter the formatting of the TMC2209 log messages and redirect the log output to a file called `tmc2209_log_file.log` that will be created in the current directory.
237
+
238
+ \
239
+ \
240
+ For me these baudrates worked fine: 19200, 38400, 57600, 115200, 230400, 460800, 576000.
241
+
242
+ If the TMC2209 driver is connected to the Vmotor, the internal voltage regulator will create the Vio for the chip.
243
+ So you don't need to connect anything to the Vio pin of the driver.
244
+
245
+ ## Usage
246
+
247
+ ```python
248
+ from tmc_driver.tmc_2209 import *
249
+ tmc = Tmc2209(TmcEnableControlPin(21), TmcMotionControlStepDir(16, 20), TmcComUart("/dev/serial0"))
250
+
251
+ tmc.set_direction_reg(False)
252
+ tmc.set_current(300)
253
+ tmc.set_interpolation(True)
254
+ tmc.set_spreadcycle(False)
255
+ tmc.set_microstepping_resolution(2)
256
+ tmc.set_internal_rsense(False)
257
+
258
+ tmc.set_acceleration(2000)
259
+ tmc.set_max_speed(500)
260
+
261
+ tmc.set_motor_enabled(True)
262
+
263
+ tmc.run_to_position_steps(400)
264
+ tmc.run_to_position_steps(0)
265
+
266
+ tmc.set_motor_enabled(False)
267
+ ```
268
+
269
+ ## Troubleshoot
270
+
271
+ If you have questions please check out the [Wiki](https://github.com/Chr157i4n/TMC2209_Raspberry_Pi/wiki) and the other issues.
272
+
273
+ If you encounter any problems, feel free to open an issue (ENG/GER).
274
+ Please don't send any E-Mails to me. Pls use Github, so that i don't need to answer the same question multiple times.
275
+ I reserve the right not to answer E-Mails.
276
+
277
+ Problem | Solution
278
+ -- | --
279
+ FileNotFoundError: [Errno 2] No such file or directory: '/dev/serial0' | depending on your Raspberry Pi version, you need to enable the Serial Port <br /> run `sudo raspi-config` in your terminal. <br /> there go to '3 Interface Options' -> 'P3 Serial Port' <br /> Would you like a login shell to be accessible over serial? No <br /> Would you like the serial port hardware to be enabled? Yes <br /> Finish and then reboot
280
+ PermissionError: [Errno 13] <br /> Permission denied: '/dev/serial0' | you need to give the permission to acces the Serial Port to your current user <br /> You may need to add your user (pi) to the dialout group with `sudo usermod -a -G dialout pi` and then relog. <br /> If that does not work, make sure that your user has read/write permissions on the dev file `/dev/serial0` by calling `sudo chmod 660 /dev/serial0`.
281
+ "TMC2209: UART Communication Error" | You can use the 'debug_script_01_uart_connection' script to get a better reading on the received bytes and troubleshoot your problem
282
+ "TMC2209: UART Communication Error: 0 data bytes \| 4 total bytes" | only 4 total bytes received indicates, that the Raspberry Pi receives its own data, but nothing from the TMC driver. This happens if RX and TX are connected properly, but the TMC driver has no power
283
+ "TMC2209: UART Communication Error: 0 data bytes \| 0 total bytes" | 0 total bytes received indicates, a problem with your wiring or your Raspberry Pi. This happens if TX is not connected
284
+ "TMC2209: UART Communication Error: 4 data bytes \| 12 total bytes" | this indicates, the Raspberry Pi received only zeroes. This happens if only RX is connected and TX not
285
+ "the Raspberry Pi received only the sended bits" or<br /> inconsistent received bits | Make sure the UART ist properly connected to the TMC driver and the driver is powered and working. <br /> Make sure login shell (console) over serial is disabled.
286
+
287
+ ![wiring photo](docs/images/wiring_photo.jpg)
288
+
289
+ ## Acknowledgements
290
+
291
+ The code to run the stepper motor is based on the code of the [AccelStepper Library from Mike McCauley](http://www.airspayce.com/mikem/arduino/AccelStepper).
292
+
293
+ The code for the UART communication is based on this [code from troxel](https://github.com/troxel/TMC_UART).
294
+
295
+ My goal is to make a library, that can run a stepper motor with a TMC2209 stepper driver and can write the setting in the register of the TMC2209, entirely in Python.
296
+ The main focus for this are Test setups, as Python is not fast enough for high motor speeds.
297
+
298
+ ## Feedback/Contributing
299
+
300
+ If you encounter any problem, feel free to open an issue on the Github [issue page](https://github.com/Chr157i4n/TMC2209_Raspberry_Pi/issues).
301
+ Feedback will keep this project growing and I encourage all suggestions.
302
+ Feel free to submit a pull request on the dev branch.
@@ -0,0 +1,32 @@
1
+ tmc_driver/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ tmc_driver/_tmc_gpio_board.py,sha256=Sbpw2H3FD-faxMxcm7vqQFxMahjRpb3VXq6TJw2_m0I,10386
3
+ tmc_driver/_tmc_logger.py,sha256=I3DD7nHlJl9uxBGhEpzmibACZEiTAOMACi65NCw15pg,5497
4
+ tmc_driver/_tmc_math.py,sha256=QIi7Wxw75KUW9PaaNM4Aut32imtnuA-h5dbgNlr6OsU,2537
5
+ tmc_driver/_tmc_stepperdriver.py,sha256=_LUTAQuU091s3gtFly-1wVjNQE2Dz1504pXBfn4aghw,8994
6
+ tmc_driver/tmc_2208.py,sha256=QMJlIXq8RT9yejHF1O6aeVonoHdy8-YH1Lq33QlaBrs,207
7
+ tmc_driver/tmc_2209.py,sha256=r3OGSWg0piS7D5zxlyU0o-WlDbWpXZwlh_OAr8GZlZo,14453
8
+ tmc_driver/tmc_220x.py,sha256=1xeMxEzaS99J6jlDRKqtK_ED_sZYvD4mT7c4XHzEgBU,20714
9
+ tmc_driver/tmc_2240.py,sha256=iTEs11hOpwpR_fFbGLZatNJITb3cVOet50JlCnjImzo,25549
10
+ tmc_driver/com/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ tmc_driver/com/_tmc_com.py,sha256=zWxGGE_Fp2csbsNWT3iOOKBQP4qx-r_xFceSCrlTLTE,4216
12
+ tmc_driver/com/_tmc_com_spi.py,sha256=U-nw60Dzyjt2TCCQ2wLs8Z1SWb_D5dMITBSd6e4VB2U,5346
13
+ tmc_driver/com/_tmc_com_uart.py,sha256=hCBcWRDEA5FQQ93qDAHb22zATBi1e4fyuV82pw9qG90,11808
14
+ tmc_driver/enable_control/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ tmc_driver/enable_control/_tmc_ec.py,sha256=nbrNwf0HLlCUQHiQY17oA-Gz9RqzvjrxYU8KUyVmnZ0,521
16
+ tmc_driver/enable_control/_tmc_ec_pin.py,sha256=9hdA2pxFl6KrFQG0x3q8zlCpjTTdhHxUrvlBKiUlRuE,1249
17
+ tmc_driver/enable_control/_tmc_ec_toff.py,sha256=eY3o-g3qlF322XohVjArojSZ06DCTUDN7hmFrXWo4QA,883
18
+ tmc_driver/motion_control/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ tmc_driver/motion_control/_tmc_mc.py,sha256=zG_GiVJymiQuyZgpxCN_Dcbhe-GOMCCv1EW4NU-u-Rw,6211
20
+ tmc_driver/motion_control/_tmc_mc_step_dir.py,sha256=5kD3j7zDnezwRR_1qQjFDRPk9j2dVu0hgqkuzRTuDgQ,14647
21
+ tmc_driver/motion_control/_tmc_mc_step_reg.py,sha256=AXJb2CvoZkVvA3EDUPUN7Y0ey_K--iWXCIveNdfU9OQ,1712
22
+ tmc_driver/motion_control/_tmc_mc_vactual.py,sha256=VSIJkV_Kn6lbLsBsVghWZU566muGwHnzwmtAflgMp-Q,6718
23
+ tmc_driver/reg/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ tmc_driver/reg/_tmc2209_reg.py,sha256=hp5KX5nxGHbdCV3NnYxt9PU9rQS6dli8qag8nYcurcc,1609
25
+ tmc_driver/reg/_tmc220x_reg.py,sha256=JBC1DA-uBp1w6PHGEvqViYVN8oMF_IzJ46Fd-5sT09Y,6272
26
+ tmc_driver/reg/_tmc224x_reg.py,sha256=W6U7SbiWCo5-p908wCYxdURC8MiM_siFiTdyll96DPw,11515
27
+ tmc_driver/reg/_tmc_reg.py,sha256=Djg5VsR0IU5qyylA9lTFCBrt9k_LtPqHGSZF19BysXc,2850
28
+ pytmcstepper-0.7.dist-info/LICENSE,sha256=5QtJ8jDPUD8h_-39nWVfosUp1UZZWecO0LksihFjtm4,35305
29
+ pytmcstepper-0.7.dist-info/METADATA,sha256=Bqh0ZjQEvFm4fX2lN8LTdIAMEIwKXqsY8NHpFHfRDUc,15130
30
+ pytmcstepper-0.7.dist-info/WHEEL,sha256=52BFRY2Up02UkjOa29eZOS2VxUrpPORXg1pkohGGUS8,91
31
+ pytmcstepper-0.7.dist-info/top_level.txt,sha256=OVYu8yCk1L2oV0rbRfoSmsbWfnBzsPLY7rulc4jdi2w,11
32
+ pytmcstepper-0.7.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (76.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ tmc_driver
tmc_driver/__init__.py ADDED
File without changes
@@ -0,0 +1,321 @@
1
+ #pylint: disable=unused-import
2
+ #pylint: disable=ungrouped-imports
3
+ #pylint: disable=unknown-option-value
4
+ #pylint: disable=possibly-used-before-assignment
5
+ #pylint: disable=used-before-assignment
6
+ #pylint: disable=unnecessary-pass
7
+ #pylint: disable=abstract-method
8
+ #pylint: disable=no-member
9
+ """
10
+ Many boards have RaspberryPI-compatible PinOut,
11
+ but require to import special GPIO module instead RPI.GPIO
12
+
13
+ This module determines the type of board
14
+ and import the corresponding GPIO module
15
+
16
+ Can be extended to support BeagleBone or other boards
17
+ """
18
+
19
+ import types
20
+ from os.path import exists
21
+ from enum import Enum, IntEnum
22
+ from importlib import import_module
23
+ from ._tmc_logger import TmcLogger, Loglevel
24
+
25
+ # ------------------------------
26
+ # LIB | BOARD
27
+ # ------------------------------
28
+ # RPi.GPIO | Pi4, Pi3 etc.
29
+ # Jetson.GPIO | Nvidia Jetson
30
+ # gpiozero | Pi5
31
+ # pheriphery | Luckfox Pico
32
+ # OPi.GPIO | Orange Pi
33
+ # ------------------------------
34
+
35
+ class Board(Enum):
36
+ """board"""
37
+ UNKNOWN = 0
38
+ RASPBERRY_PI = 1 # all except Pi 5
39
+ RASPBERRY_PI5 = 2
40
+ NVIDIA_JETSON = 3
41
+ LUCKFOX_PICO = 4
42
+ ORANGE_PI = 5
43
+
44
+
45
+ class Gpio(IntEnum):
46
+ """GPIO value"""
47
+ LOW = 0
48
+ HIGH = 1
49
+
50
+ class GpioMode(IntEnum):
51
+ """GPIO mode"""
52
+ OUT = 0
53
+ IN = 1
54
+
55
+ class GpioPUD(IntEnum):
56
+ """Pull up Down"""
57
+ PUD_OFF = 20
58
+ PUD_UP = 22
59
+ PUD_DOWN = 21
60
+
61
+ BOARD = Board.UNKNOWN
62
+ dependencies_logger = TmcLogger(Loglevel.DEBUG, "DEPENDENCIES")
63
+
64
+
65
+ class BaseGPIOWrapper:
66
+ """Base class for GPIO wrappers"""
67
+
68
+ def init(self, gpio_mode=None):
69
+ """initialize GPIO library"""
70
+ raise NotImplementedError
71
+
72
+ def deinit(self):
73
+ """deinitialize GPIO library"""
74
+ raise NotImplementedError
75
+
76
+ def gpio_setup(self, pin:int, mode:GpioMode, initial:Gpio=Gpio.LOW, pull_up_down:GpioPUD=GpioPUD.PUD_OFF):
77
+ """setup GPIO pin"""
78
+ raise NotImplementedError
79
+
80
+ def gpio_cleanup(self, pin:int):
81
+ """cleanup GPIO pin"""
82
+ raise NotImplementedError
83
+
84
+ def gpio_input(self, pin:int):
85
+ """read GPIO pin"""
86
+ raise NotImplementedError
87
+
88
+ def gpio_output(self, pin:int, value):
89
+ """write GPIO pin"""
90
+ raise NotImplementedError
91
+
92
+ def gpio_add_event_detect(self, pin:int, callback:types.FunctionType):
93
+ """add event detect"""
94
+ raise NotImplementedError
95
+
96
+ def gpio_remove_event_detect(self, pin:int):
97
+ """remove event detect"""
98
+ raise NotImplementedError
99
+
100
+ class BaseRPiGPIOWrapper(BaseGPIOWrapper):
101
+ """RPI.GPIO base wrapper"""
102
+
103
+ def init(self, gpio_mode=None):
104
+ """initialize GPIO library"""
105
+ self.GPIO.setwarnings(False)
106
+ if gpio_mode is None:
107
+ gpio_mode = self.GPIO.BCM
108
+ self.GPIO.setmode(gpio_mode)
109
+
110
+ def deinit(self):
111
+ """deinitialize GPIO library"""
112
+ self.GPIO.cleanup()
113
+
114
+ def gpio_setup(self, pin:int, mode:GpioMode, initial:Gpio=Gpio.LOW, pull_up_down:GpioPUD=GpioPUD.PUD_OFF):
115
+ """setup GPIO pin"""
116
+ initial = int(initial)
117
+ pull_up_down = int(pull_up_down)
118
+ mode = int(mode)
119
+ if mode == GpioMode.OUT:
120
+ self.GPIO.setup(pin, mode, initial=initial)
121
+ else:
122
+ self.GPIO.setup(pin, mode, pull_up_down=pull_up_down)
123
+
124
+ def gpio_cleanup(self, pin:int):
125
+ """cleanup GPIO pin"""
126
+ self.GPIO.cleanup(pin)
127
+
128
+ def gpio_input(self, pin:int):
129
+ """read GPIO pin"""
130
+ return self.GPIO.input(pin)
131
+
132
+ def gpio_output(self, pin:int, value:int):
133
+ """write GPIO pin"""
134
+ self.GPIO.output(pin, value)
135
+
136
+ def gpio_add_event_detect(self, pin:int, callback:types.FunctionType):
137
+ """add event detect"""
138
+ self.GPIO.add_event_detect(pin, self.GPIO.RISING, callback=callback, bouncetime=300)
139
+
140
+ def gpio_remove_event_detect(self, pin:int):
141
+ """remove event detect"""
142
+ self.GPIO.remove_event_detect(pin)
143
+
144
+ class MockGPIOWrapper(BaseRPiGPIOWrapper):
145
+ """Mock.GPIO wrapper"""
146
+
147
+ def __init__(self):
148
+ """constructor, imports Mock.GPIO"""
149
+ self.GPIO = import_module('Mock.GPIO')
150
+ dependencies_logger.log("using Mock.GPIO for GPIO mocking", Loglevel.INFO)
151
+
152
+ class RPiGPIOWrapper(BaseRPiGPIOWrapper):
153
+ """RPi.GPIO wrapper"""
154
+
155
+ def __init__(self):
156
+ """constructor, imports RPi.GPIO"""
157
+ self.GPIO = import_module('RPi.GPIO')
158
+ dependencies_logger.log("using RPi.GPIO for GPIO control", Loglevel.INFO)
159
+
160
+ class JetsonGPIOWrapper(BaseRPiGPIOWrapper):
161
+ """Jetson.GPIO wrapper"""
162
+
163
+ def __init__(self):
164
+ """constructor, imports Jetson.GPIO"""
165
+ self.GPIO = import_module('Jetson.GPIO')
166
+ dependencies_logger.log("using Jetson.GPIO for GPIO control", Loglevel.INFO)
167
+
168
+ class OPiGPIOWrapper(BaseRPiGPIOWrapper):
169
+ """OPi.GPIO wrapper"""
170
+
171
+ def __init__(self):
172
+ """constructor, imports OPi.GPIO"""
173
+ self.GPIO = import_module('OPi.GPIO')
174
+ dependencies_logger.log("using OPi.GPIO for GPIO control", Loglevel.INFO)
175
+
176
+ class GpiozeroWrapper(BaseGPIOWrapper):
177
+ """gpiozero GPIO wrapper"""
178
+
179
+ def __init__(self):
180
+ """constructor, imports gpiozero"""
181
+ self.gpiozero = import_module('gpiozero')
182
+ dependencies_logger.log("using gpiozero for GPIO control", Loglevel.INFO)
183
+ self._gpios = [None] * 200
184
+
185
+ def init(self, gpio_mode=None):
186
+ """initialize GPIO library. pass on gpiozero"""
187
+ pass
188
+
189
+ def deinit(self):
190
+ """deinitialize GPIO library. pass on gpiozero"""
191
+ pass
192
+
193
+ def gpio_setup(self, pin:int, mode:GpioMode, initial:Gpio=Gpio.LOW, pull_up_down:GpioPUD=GpioPUD.PUD_OFF):
194
+ """setup GPIO pin"""
195
+ if mode == GpioMode.OUT:
196
+ self._gpios[pin] = self.gpiozero.DigitalOutputDevice(pin)
197
+ else:
198
+ self._gpios[pin] = self.gpiozero.DigitalInputDevice(pin)
199
+
200
+ def gpio_cleanup(self, pin:int):
201
+ """cleanup GPIO pin"""
202
+ self._gpios[pin].close()
203
+
204
+ def gpio_input(self, pin:int):
205
+ """read GPIO pin"""
206
+ return self._gpios[pin].value
207
+
208
+ def gpio_output(self, pin:int, value):
209
+ """write GPIO pin"""
210
+ self._gpios[pin].value = value
211
+
212
+ def gpio_add_event_detect(self, pin:int, callback:types.FunctionType):
213
+ """add event detect"""
214
+ self._gpios[pin].when_activated = callback
215
+
216
+ def gpio_remove_event_detect(self, pin:int):
217
+ """remove event detect"""
218
+ if self._gpios[pin].when_activated is not None:
219
+ self._gpios[pin].when_activated = None
220
+
221
+ class peripheryWrapper(BaseGPIOWrapper):
222
+ """periphery GPIO wrapper"""
223
+
224
+ def __init__(self):
225
+ """constructor, imports periphery"""
226
+ self.periphery = import_module('periphery')
227
+ dependencies_logger.log("using periphery for GPIO control", Loglevel.INFO)
228
+ self._gpios = [None] * 200
229
+
230
+ def init(self, gpio_mode=None):
231
+ """initialize GPIO library. pass on periphery"""
232
+ pass
233
+
234
+ def deinit(self):
235
+ """deinitialize GPIO library. pass on periphery"""
236
+ pass
237
+
238
+ def gpio_setup(self, pin:int, mode:GpioMode, initial:Gpio=Gpio.LOW, pull_up_down:GpioPUD=GpioPUD.PUD_OFF):
239
+ """setup GPIO pin"""
240
+ mode = 'out' if (mode == GpioMode.OUT) else 'in'
241
+ self._gpios[pin] = self.periphery.GPIO(pin, mode)
242
+
243
+ def gpio_cleanup(self, pin:int):
244
+ """cleanup GPIO pin"""
245
+ self._gpios[pin].close()
246
+
247
+ def gpio_input(self, pin:int):
248
+ """read GPIO pin"""
249
+ return self._gpios[pin].read()
250
+
251
+ def gpio_output(self, pin:int, value):
252
+ """write GPIO pin"""
253
+ self._gpios[pin].write(bool(value))
254
+
255
+
256
+ board_mapping = {
257
+ "raspberry pi 5": (GpiozeroWrapper, Board.RASPBERRY_PI5, "gpiozero", "https://gpiozero.readthedocs.io/en/stable/installing.html"),
258
+ "raspberry": (RPiGPIOWrapper, Board.RASPBERRY_PI, "RPi.GPIO", "https://sourceforge.net/p/raspberry-gpio-python/wiki/install"),
259
+ "jetson": (JetsonGPIOWrapper, Board.NVIDIA_JETSON, "jetson-gpio", "https://github.com/NVIDIA/jetson-gpio"),
260
+ "luckfox": (peripheryWrapper, Board.LUCKFOX_PICO, "periphery", "https://github.com/vsergeev/python-periphery"),
261
+ "orange": (OPiGPIOWrapper, Board.ORANGE_PI, "OPi.GPIO", "https://github.com/rm-hull/OPi.GPIO")
262
+ }
263
+
264
+
265
+
266
+ # Determine the board and instantiate the appropriate GPIO class
267
+ def get_board_model_name():
268
+ """get board model name from /proc/device-tree/model file"""
269
+ if not exists('/proc/device-tree/model'):
270
+ return "mock"
271
+ with open('/proc/device-tree/model', encoding="utf-8") as f:
272
+ return f.readline().lower()
273
+
274
+ def handle_module_not_found_error(err, board_name, module_name, install_link):
275
+ """handle module not found error"""
276
+ dependencies_logger.log(
277
+ (f"ModuleNotFoundError: {err}\n"
278
+ f"Board is {board_name} but module {module_name} isn't installed.\n"
279
+ f"Follow the installation instructions in the link below to resolve the issue:\n"
280
+ f"{install_link}\n"
281
+ "Exiting..."),
282
+ Loglevel.ERROR)
283
+ raise err
284
+
285
+ def handle_import_error(err, board_name, module_name, install_link):
286
+ """handle import error"""
287
+ dependencies_logger.log(
288
+ (f"ImportError: {err}\n"
289
+ f"Board is {board_name} but module {module_name} isn't installed.\n"
290
+ f"Follow the installation instructions in the link below to resolve the issue:\n"
291
+ f"{install_link}\n"
292
+ "Exiting..."),
293
+ Loglevel.ERROR)
294
+ raise err
295
+
296
+ def initialize_gpio():
297
+ """initialize GPIO"""
298
+ model = get_board_model_name()
299
+ dependencies_logger.log(f"Board model: {model}", Loglevel.INFO)
300
+ if model == "mock":
301
+ return MockGPIOWrapper(), Board.UNKNOWN
302
+
303
+
304
+ for key, (wrapper_class, board_enum, module_name, install_link) in board_mapping.items():
305
+ if key in model:
306
+ try:
307
+ return wrapper_class(), board_enum
308
+ except ModuleNotFoundError as err:
309
+ handle_module_not_found_error(err, key.capitalize(), module_name, install_link)
310
+ except ImportError as err:
311
+ handle_import_error(err, key.capitalize(), module_name, install_link)
312
+
313
+ dependencies_logger.log(
314
+ "The board is not recognized. Trying import default RPi.GPIO module...",
315
+ Loglevel.INFO)
316
+ try:
317
+ return RPiGPIOWrapper(), Board.UNKNOWN
318
+ except ImportError:
319
+ return MockGPIOWrapper(), Board.UNKNOWN
320
+
321
+ tmc_gpio, BOARD = initialize_gpio()