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.

tmc_driver/tmc_220x.py ADDED
@@ -0,0 +1,684 @@
1
+ #pylint: disable=too-many-arguments
2
+ #pylint: disable=too-many-public-methods
3
+ #pylint: disable=too-many-branches
4
+ #pylint: disable=too-many-instance-attributes
5
+ #pylint: disable=too-many-positional-arguments
6
+ #pylint: disable=bare-except
7
+ #pylint: disable=no-member
8
+ #pylint: disable=unused-import
9
+ #pylint: disable=wildcard-import
10
+ #pylint: disable=unused-wildcard-import
11
+ """Tmc220X stepper driver module
12
+
13
+ this module has two different functions:
14
+ 1. change setting in the TMC-driver via UART
15
+ 2. move the motor via STEP/DIR pins
16
+ """
17
+
18
+ import logging
19
+ import threading
20
+ import time
21
+ import typing
22
+ from ._tmc_stepperdriver import *
23
+ from .com._tmc_com import TmcCom
24
+ from .com._tmc_com_uart import TmcComUart
25
+ from .com._tmc_com_spi import TmcComSpi
26
+ from .motion_control._tmc_mc_step_reg import TmcMotionControlStepReg
27
+ from .enable_control._tmc_ec_toff import TmcEnableControlToff
28
+ from .motion_control._tmc_mc_vactual import TmcMotionControlVActual
29
+ from ._tmc_logger import TmcLogger, Loglevel
30
+ from .reg._tmc220x_reg import *
31
+ from . import _tmc_math as tmc_math
32
+
33
+
34
+
35
+
36
+
37
+ class Tmc220x(TmcStepperDriver):
38
+ """Tmc220X
39
+
40
+ this class has two different functions:
41
+ 1. change setting in the TMC-driver via UART
42
+ 2. move the motor via STEP/DIR pins
43
+ """
44
+
45
+ tmc_com:TmcComUart = None
46
+
47
+
48
+ # Constructor/Destructor
49
+ # ----------------------------
50
+ def __init__(self,
51
+ tmc_ec:TmcEnableControl,
52
+ tmc_mc:TmcMotionControl,
53
+ tmc_com:TmcCom = None,
54
+ driver_address:int = 0,
55
+ gpio_mode = None,
56
+ loglevel:Loglevel = Loglevel.INFO,
57
+ logprefix:str = None,
58
+ log_handlers:list = None,
59
+ log_formatter:logging.Formatter = None
60
+ ):
61
+ """constructor
62
+
63
+ Args:
64
+ tmc_ec (TmcEnableControl): enable control object
65
+ tmc_mc (TmcMotionControl): motion control object
66
+ tmc_com (TmcCom, optional): communication object. Defaults to None.
67
+ driver_address (int, optional): driver address [0-3]. Defaults to 0.
68
+ gpio_mode (enum, optional): gpio mode. Defaults to None.
69
+ loglevel (enum, optional): loglevel. Defaults to None.
70
+ logprefix (str, optional): log prefix (name of the logger).
71
+ Defaults to None (standard TMC prefix).
72
+ log_handlers (list, optional): list of logging handlers.
73
+ Defaults to None (log to console).
74
+ log_formatter (logging.Formatter, optional): formatter for the log messages.
75
+ Defaults to None (messages are logged in the format
76
+ '%(asctime)s - %(name)s - %(levelname)s - %(message)s').
77
+ """
78
+ super().__init__(tmc_ec, tmc_mc, gpio_mode, loglevel, logprefix, log_handlers, log_formatter)
79
+
80
+ self.tmc_logger.set_logprefix(f"TMC2209 {driver_address}")
81
+
82
+ if tmc_com is not None:
83
+ self.tmc_com = tmc_com
84
+ self.tmc_com.tmc_logger = self.tmc_logger
85
+ self.tmc_com.mtr_id = driver_address
86
+
87
+ self.tmc_com.init()
88
+
89
+ if hasattr(self.tmc_mc, "tmc_com"):
90
+ self.tmc_mc.tmc_com = tmc_com
91
+
92
+ if hasattr(self.tmc_ec, "tmc_com"):
93
+ self.tmc_ec.tmc_com = tmc_com
94
+
95
+ registers_classes = {
96
+ GConf,
97
+ GStat,
98
+ IfCnt,
99
+ Ioin,
100
+ IHoldIRun,
101
+ TPowerDown,
102
+ TStep,
103
+ VActual,
104
+ MsCnt,
105
+ ChopConf,
106
+ DrvStatus
107
+ }
108
+
109
+ self.tmc_registers = {}
110
+
111
+ for register_class in registers_classes:
112
+ register = register_class(self.tmc_com)
113
+ name = register.name.lower()
114
+ self.tmc_registers[name] = register
115
+
116
+ def create_getter(name):
117
+ def getter(self):
118
+ return self.tmc_registers[name]
119
+ return getter
120
+
121
+ setattr(self.__class__, name, property(create_getter(name)))
122
+
123
+
124
+ if tmc_com is not None:
125
+ # Setup Registers
126
+ self.tmc_com.tmc_registers = self.tmc_registers
127
+
128
+ if self.tmc_mc is not None:
129
+ self.read_steps_per_rev()
130
+ self.clear_gstat()
131
+ self.tmc_com.flush_serial_buffer()
132
+
133
+
134
+ self.max_speed_fullstep = 100
135
+ self.acceleration_fullstep = 100
136
+
137
+ self.tmc_logger.log("TMC220x Init finished", Loglevel.INFO)
138
+
139
+
140
+
141
+ def __del__(self):
142
+ """destructor"""
143
+ if self.tmc_com is not None:
144
+ del self.tmc_com
145
+ super().__del__()
146
+
147
+
148
+
149
+ def set_deinitialize_true(self):
150
+ """set deinitialize to true"""
151
+ self._deinit_finished = True
152
+
153
+
154
+ # Tmc220x methods
155
+ # ----------------------------
156
+ def read_steps_per_rev(self) -> int:
157
+ """returns how many steps are needed for one revolution.
158
+ this reads the value from the tmc driver.
159
+
160
+ Returns:
161
+ int: Steps per revolution
162
+ """
163
+ self.read_microstepping_resolution()
164
+ return self.tmc_mc.steps_per_rev
165
+
166
+
167
+
168
+ def read_drv_status(self) -> DrvStatus:
169
+ """read the register Adress "DRV_STATUS" and logs the reg valuess
170
+
171
+ Returns:
172
+ DRV_STATUS Register instance
173
+ """
174
+ self.drvstatus.read()
175
+ self.drvstatus.log(self.tmc_logger)
176
+ return self.drvstatus
177
+
178
+
179
+
180
+ def read_gconf(self) -> GConf:
181
+ """read the register Adress "GCONF" and logs the reg values
182
+
183
+ Returns:
184
+ GCONF Register instance
185
+ """
186
+ self.gconf.read()
187
+ self.gconf.log(self.tmc_logger)
188
+ return self.gconf
189
+
190
+
191
+
192
+ def read_gstat(self) -> GStat:
193
+ """read the register Adress "GSTAT" and logs the reg values
194
+
195
+ Returns:
196
+ GSTAT Register instance
197
+ """
198
+ self.gstat.read()
199
+ self.gstat.log(self.tmc_logger)
200
+ return self.gstat
201
+
202
+
203
+
204
+ def clear_gstat(self):
205
+ """clears the "GSTAT" register"""
206
+ self.tmc_logger.log("clearing GSTAT", Loglevel.INFO)
207
+ self.gstat.read()
208
+
209
+ self.gstat.reset = True
210
+ self.gstat.drv_err = True
211
+ self.gstat.uv_cp = True
212
+
213
+ self.gstat.write_check()
214
+
215
+
216
+
217
+ def read_ioin(self) -> Ioin:
218
+ """read the register Adress "IOIN" and logs the reg values
219
+
220
+ Returns:
221
+ IOIN Register instance
222
+ """
223
+ self.ioin.read()
224
+ self.ioin.log(self.tmc_logger)
225
+ return self.ioin
226
+
227
+
228
+
229
+ def read_chopconf(self) -> ChopConf:
230
+ """read the register Adress "CHOPCONF" and logs the reg values
231
+
232
+ Returns:
233
+ CHOPCONF Register instance
234
+ """
235
+ self.chopconf.read()
236
+ self.chopconf.log(self.tmc_logger)
237
+ return self.chopconf
238
+
239
+
240
+
241
+ def get_direction_reg(self) -> bool:
242
+ """returns the motor shaft direction: False = CCW; True = CW
243
+
244
+ Returns:
245
+ bool: motor shaft direction: False = CCW; True = CW
246
+ """
247
+ self.gconf.read()
248
+ return self.gconf.shaft
249
+
250
+
251
+
252
+ def set_direction_reg(self, direction:bool):
253
+ """sets the motor shaft direction to the given value: False = CCW; True = CW
254
+
255
+ Args:
256
+ direction (bool): direction of the motor False = CCW; True = CW
257
+ """
258
+ self.gconf.modify("shaft", direction)
259
+
260
+
261
+
262
+ def get_iscale_analog(self) -> bool:
263
+ """return whether Vref (True) or 5V (False) is used for current scale
264
+
265
+ Returns:
266
+ en (bool): whether Vref (True) or 5V (False) is used for current scale
267
+ """
268
+ self.gconf.read()
269
+ return self.gconf.i_scale_analog
270
+
271
+
272
+
273
+ def set_iscale_analog(self,en:bool):
274
+ """sets Vref (True) or 5V (False) for current scale
275
+
276
+ Args:
277
+ en (bool): True=Vref, False=5V
278
+ """
279
+ self.gconf.modify("i_scale_analog", en)
280
+
281
+
282
+
283
+ def get_vsense(self) -> bool:
284
+ """returns which sense resistor voltage is used for current scaling
285
+ False: Low sensitivity, high sense resistor voltage
286
+ True: High sensitivity, low sense resistor voltage
287
+
288
+ Returns:
289
+ bool: whether high sensitivity should is used
290
+ """
291
+ self.chopconf.read()
292
+ return self.chopconf.vsense
293
+
294
+
295
+
296
+ def set_vsense(self,en:bool):
297
+ """sets which sense resistor voltage is used for current scaling
298
+ False: Low sensitivity, high sense resistor voltage
299
+ True: High sensitivity, low sense resistor voltage
300
+
301
+ Args:
302
+ en (bool):
303
+ """
304
+ self.chopconf.modify("vsense", en)
305
+
306
+
307
+
308
+ def get_internal_rsense(self) -> bool:
309
+ """returns which sense resistor voltage is used for current scaling
310
+ False: Operation with external sense resistors
311
+ True Internal sense resistors. Use current supplied into
312
+ VREF as reference for internal sense resistor. VREF
313
+ pin internally is driven to GND in this mode.
314
+
315
+ Returns:
316
+ bool: which sense resistor voltage is used
317
+ """
318
+ self.gconf.read()
319
+ return self.gconf.internal_rsense
320
+
321
+
322
+
323
+ def set_internal_rsense(self,en:bool):
324
+ """sets which sense resistor voltage is used for current scaling
325
+ False: Operation with external sense resistors
326
+ True: Internal sense resistors. Use current supplied into
327
+ VREF as reference for internal sense resistor. VREF
328
+ pin internally is driven to GND in this mode.
329
+
330
+ Args:
331
+ en (bool): which sense resistor voltage is used; true will propably destroy your tmc
332
+
333
+ """
334
+ if en:
335
+ self.tmc_logger.log("activated internal sense resistors.",
336
+ Loglevel.INFO)
337
+ self.tmc_logger.log("VREF pin internally is driven to GND in this mode.",
338
+ Loglevel.INFO)
339
+ self.tmc_logger.log("This will most likely destroy your driver!!!",
340
+ Loglevel.INFO)
341
+ raise SystemExit
342
+
343
+
344
+ self.gconf.modify("internal_rsense", en)
345
+
346
+
347
+
348
+ def _set_irun_ihold(self, ihold:int, irun:int, ihold_delay:int):
349
+ """sets the current scale (CS) for Running and Holding
350
+ and the delay, when to be switched to Holding current
351
+
352
+ Args:
353
+ ihold (int): multiplicator for current while standstill [0-31]
354
+ irun (int): current while running [0-31]
355
+ ihold_delay (int): delay after standstill for switching to ihold [0-15]
356
+
357
+ """
358
+ self.ihold_irun.read()
359
+
360
+ self.ihold_irun.ihold = ihold
361
+ self.ihold_irun.irun = irun
362
+ self.ihold_irun.ihold_delay = ihold_delay
363
+
364
+ self.ihold_irun.write_check()
365
+
366
+
367
+
368
+ def _set_pdn_disable(self,pdn_disable:bool):
369
+ """disables PDN on the UART pin
370
+ False: PDN_UART controls standstill current reduction
371
+ True: PDN_UART input function disabled. Set this bit,
372
+ when using the UART interface!
373
+
374
+ Args:
375
+ pdn_disable (bool): whether PDN should be disabled
376
+ """
377
+ self.gconf.modify("pdn_disable", pdn_disable)
378
+
379
+
380
+
381
+ def set_current(self, run_current:int, hold_current_multiplier:float = 0.5,
382
+ hold_current_delay:int = 10, pdn_disable:bool = True):
383
+ """sets the current flow for the motor.
384
+
385
+ Args:
386
+ run_current (int): current during movement in mA
387
+ hold_current_multiplier (int):current multiplier during standstill (Default value = 0.5)
388
+ hold_current_delay (int): delay after standstill after which cur drops (Default value = 10)
389
+ pdn_disable (bool): should be disabled if UART is used (Default value = True)
390
+
391
+ """
392
+ cs_irun = 0
393
+ rsense = 0.11
394
+ vfs = 0
395
+
396
+ self.set_iscale_analog(False)
397
+
398
+ vfs = 0.325
399
+ cs_irun = 32.0*1.41421*run_current/1000.0*(rsense+0.02)/vfs - 1
400
+
401
+ # If Current Scale is too low, turn on high sensitivity VSsense and calculate again
402
+ if cs_irun < 16:
403
+ self.tmc_logger.log("CS too low; switching to VSense True", Loglevel.INFO)
404
+ vfs = 0.180
405
+ cs_irun = 32.0*1.41421*run_current/1000.0*(rsense+0.02)/vfs - 1
406
+ self.set_vsense(True)
407
+ else: # If CS >= 16, turn off high_senser
408
+ self.tmc_logger.log("CS in range; using VSense False", Loglevel.INFO)
409
+ self.set_vsense(False)
410
+
411
+ cs_irun = min(cs_irun, 31)
412
+ cs_irun = max(cs_irun, 0)
413
+
414
+ cs_ihold = hold_current_multiplier * cs_irun
415
+
416
+ cs_irun = round(cs_irun)
417
+ cs_ihold = round(cs_ihold)
418
+ hold_current_delay = round(hold_current_delay)
419
+
420
+ self.tmc_logger.log(f"cs_irun: {cs_irun}", Loglevel.INFO)
421
+ self.tmc_logger.log(f"CS_IHold: {cs_ihold}", Loglevel.INFO)
422
+ self.tmc_logger.log(f"Delay: {hold_current_delay}", Loglevel.INFO)
423
+
424
+ # return (float)(CS+1)/32.0 * (vsense() ? 0.180 : 0.325)/(rsense+0.02) / 1.41421 * 1000;
425
+ run_current_actual = (cs_irun+1)/32.0 * (vfs)/(rsense+0.02) / 1.41421 * 1000
426
+ self.tmc_logger.log(f"actual current: {round(run_current_actual)} mA",
427
+ Loglevel.INFO)
428
+
429
+ self._set_irun_ihold(cs_ihold, cs_irun, hold_current_delay)
430
+
431
+ self._set_pdn_disable(pdn_disable)
432
+
433
+
434
+
435
+ def get_spreadcycle(self) -> bool:
436
+ """reads spreadcycle
437
+
438
+ Returns:
439
+ bool: True = spreadcycle; False = stealthchop
440
+ """
441
+ self.gconf.read()
442
+ return self.gconf.spreadcycle
443
+
444
+
445
+
446
+ def set_spreadcycle(self,en:bool):
447
+ """enables spreadcycle (1) or stealthchop (0)
448
+
449
+ Args:
450
+ en (bool): true to enable spreadcycle; false to enable stealthchop
451
+
452
+ """
453
+ self.gconf.modify("spreadcycle", en)
454
+
455
+
456
+
457
+ def get_interpolation(self) -> bool:
458
+ """return whether the tmc inbuilt interpolation is active
459
+
460
+ Returns:
461
+ en (bool): true if internal µstep interpolation is enabled
462
+ """
463
+ self.chopconf.read()
464
+ return self.chopconf.intpol
465
+
466
+
467
+
468
+ def set_interpolation(self, en:bool):
469
+ """enables the tmc inbuilt interpolation of the steps to 256 µsteps
470
+
471
+ Args:
472
+ en (bool): true to enable internal µstep interpolation
473
+ """
474
+ self.chopconf.modify("intpol", en)
475
+
476
+
477
+
478
+ def get_toff(self) -> int:
479
+ """returns the TOFF register value
480
+
481
+ Returns:
482
+ int: TOFF register value
483
+ """
484
+ self.chopconf.read()
485
+ return self.chopconf.toff
486
+
487
+
488
+
489
+ def set_toff(self, toff:int):
490
+ """Sets TOFF register to value
491
+
492
+ Args:
493
+ toff (uint8_t): value of toff (must be a four-bit value)
494
+ """
495
+ self.chopconf.modify("toff", toff)
496
+
497
+
498
+
499
+ def read_microstepping_resolution(self) -> int:
500
+ """returns the current native microstep resolution (1-256)
501
+ this reads the value from the driver register
502
+
503
+ Returns:
504
+ int: µstep resolution
505
+ """
506
+ self.chopconf.read()
507
+
508
+ mres = self.chopconf.mres_ms
509
+ if self.tmc_mc is not None:
510
+ self.tmc_mc.mres = mres
511
+
512
+ return mres
513
+
514
+
515
+
516
+ def get_microstepping_resolution(self) -> int:
517
+ """returns the current native microstep resolution (1-256)
518
+ this returns the cached value from this module
519
+
520
+ Returns:
521
+ int: µstep resolution
522
+ """
523
+ return self.tmc_mc.mres
524
+
525
+
526
+
527
+ def set_microstepping_resolution(self, mres:int):
528
+ """sets the current native microstep resolution (1,2,4,8,16,32,64,128,256)
529
+
530
+ Args:
531
+ mres (int): µstep resolution; has to be a power of 2 or 1 for fullstep
532
+ """
533
+ if self.tmc_mc is not None:
534
+ self.tmc_mc.mres = mres
535
+
536
+ self.chopconf.read()
537
+ self.chopconf.mres_ms = mres
538
+ self.chopconf.write_check()
539
+
540
+ self.set_mstep_resolution_reg_select(True)
541
+
542
+
543
+
544
+ def set_mstep_resolution_reg_select(self, en:bool):
545
+ """sets the register bit "mstep_reg_select" to 1 or 0 depending to the given value.
546
+ this is needed to set the microstep resolution via UART
547
+ this method is called by "set_microstepping_resolution"
548
+
549
+ Args:
550
+ en (bool): true to set µstep resolution via UART
551
+ """
552
+ self.gconf.modify("mstep_reg_select", en)
553
+
554
+
555
+
556
+ def get_interface_transmission_counter(self) -> int:
557
+ """reads the interface transmission counter from the tmc register
558
+ this value is increased on every succesfull write access
559
+ can be used to verify a write access
560
+
561
+ Returns:
562
+ int: 8bit IFCNT Register
563
+ """
564
+ self.ifcnt.read()
565
+ ifcnt = self.ifcnt.ifcnt
566
+ self.tmc_logger.log(f"Interface Transmission Counter: {ifcnt}", Loglevel.INFO)
567
+ return ifcnt
568
+
569
+
570
+
571
+ def get_tstep(self) -> int:
572
+ """reads the current tstep from the driver register
573
+
574
+ Returns:
575
+ int: TStep time
576
+ """
577
+ self.chopconf.read()
578
+ return self.chopconf.tstep
579
+
580
+
581
+
582
+ def set_vactual(self, vactual:int):
583
+ """sets the register bit "VACTUAL" to to a given value
584
+ VACTUAL allows moving the motor by UART control.
585
+ It gives the motor velocity in +-(2^23)-1 [μsteps / t]
586
+ 0: Normal operation. Driver reacts to STEP input
587
+
588
+ Args:
589
+ vactual (int): value for VACTUAL
590
+ """
591
+ self.vactual.vactual = vactual
592
+ self.vactual.write_check()
593
+
594
+
595
+
596
+ def get_microstep_counter(self) -> int:
597
+ """returns the current Microstep counter.
598
+ Indicates actual position in the microstep table for CUR_A
599
+
600
+ Returns:
601
+ int: current Microstep counter
602
+ """
603
+ self.mscnt.read()
604
+ return self.mscnt.mscnt
605
+
606
+
607
+
608
+ def get_microstep_counter_in_steps(self, offset:int=0) -> int:
609
+ """returns the current Microstep counter.
610
+ Indicates actual position in the microstep table for CUR_A
611
+
612
+ Args:
613
+ offset (int): offset in steps (Default value = 0)
614
+
615
+ Returns:
616
+ step (int): current Microstep counter convertet to steps
617
+ """
618
+ step = (self.get_microstep_counter()-64)*(self.tmc_mc.mres*4)/1024
619
+ step = (4*self.tmc_mc.mres)-step-1
620
+ step = round(step)
621
+ return step+offset
622
+
623
+
624
+
625
+ def test_pin(self, pin, ioin_reg_bp):
626
+ """tests one pin
627
+
628
+ this function checks the connection to a pin
629
+ by toggling it and reading the IOIN register
630
+ """
631
+ pin_ok = True
632
+
633
+ # turn on all pins
634
+ tmc_gpio.gpio_output(self.tmc_mc.pin_dir, Gpio.HIGH)
635
+ tmc_gpio.gpio_output(self.tmc_mc.pin_step, Gpio.HIGH)
636
+ tmc_gpio.gpio_output(self.tmc_ec.pin_en, Gpio.HIGH)
637
+
638
+ # check that the selected pin is on
639
+ ioin = self.read_ioin()
640
+ if not ioin.data_int >> ioin_reg_bp & 0x1:
641
+ pin_ok = False
642
+
643
+ # turn off only the selected pin
644
+ tmc_gpio.gpio_output(pin, Gpio.LOW)
645
+ time.sleep(0.1)
646
+
647
+ # check that the selected pin is off
648
+ ioin = self.read_ioin()
649
+ if ioin.data_int >> ioin_reg_bp & 0x1:
650
+ pin_ok = False
651
+
652
+ return pin_ok
653
+
654
+
655
+
656
+ def test_dir_step_en(self):
657
+ """tests the EN, DIR and STEP pin
658
+
659
+ this sets the EN, DIR and STEP pin to HIGH, LOW and HIGH
660
+ and checks the IOIN Register of the TMC meanwhile
661
+ """
662
+ # test each pin on their own
663
+ pin_dir_ok = self.test_pin(self.tmc_mc.pin_dir, 9)
664
+ pin_step_ok = self.test_pin(self.tmc_mc.pin_step, 7)
665
+ pin_en_ok = self.test_pin(self.tmc_ec.pin_en, 0)
666
+
667
+ self.set_motor_enabled(False)
668
+
669
+ self.tmc_logger.log("---")
670
+ self.tmc_logger.log(f"Pin DIR: \t{'OK' if pin_dir_ok else 'not OK'}")
671
+ self.tmc_logger.log(f"Pin STEP: \t{'OK' if pin_step_ok else 'not OK'}")
672
+ self.tmc_logger.log(f"Pin EN: \t{'OK' if pin_en_ok else 'not OK'}")
673
+ self.tmc_logger.log("---")
674
+
675
+
676
+
677
+ def test_com(self):
678
+ """test method"""
679
+ self.tmc_logger.log("---")
680
+ self.tmc_logger.log("TEST COM")
681
+
682
+ ioin = Ioin(self.tmc_com)
683
+
684
+ return self.tmc_com.test_com(ioin.addr)