Skip to content

Commit 29b7550

Browse files
committed
pwm_tool: Add support for high-speed PWM pin updates
The output_pin module is only capable of updating an output pin at most once every 100ms. Add a new pwm_tool module that is capable of queuing updates in the micro-controller and thus allowing for much higher update rates. Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
1 parent 48a05ea commit 29b7550

File tree

8 files changed

+201
-17
lines changed

8 files changed

+201
-17
lines changed

config/sample-pwm-tool.cfg

+5-6
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@
22
# such as a laser or spindle.
33
# See docs/Using_PWM_Tools.md for a more detailed description.
44

5-
[output_pin TOOL]
5+
[pwm_tool TOOL]
66
pin: !ar9 # use your fan's pin number
7-
pwm: True
87
hardware_pwm: True
98
cycle_time: 0.001
109
shutdown_value: 0
@@ -36,9 +35,9 @@ gcode:
3635

3736
[menu __main __control __toolonoff]
3837
type: input
39-
enable: {'output_pin TOOL' in printer}
38+
enable: {'pwm_tool TOOL' in printer}
4039
name: Fan: {'ON ' if menu.input else 'OFF'}
41-
input: {printer['output_pin TOOL'].value}
40+
input: {printer['pwm_tool TOOL'].value}
4241
input_min: 0
4342
input_max: 1
4443
input_step: 1
@@ -47,9 +46,9 @@ gcode:
4746

4847
[menu __main __control __toolspeed]
4948
type: input
50-
enable: {'output_pin TOOL' in printer}
49+
enable: {'pwm_tool TOOL' in printer}
5150
name: Tool speed: {'%3d' % (menu.input*100)}%
52-
input: {printer['output_pin TOOL'].value}
51+
input: {printer['pwm_tool TOOL'].value}
5352
input_min: 0
5453
input_max: 1
5554
input_step: 0.01

docs/Config_Reference.md

+20
Original file line numberDiff line numberDiff line change
@@ -3127,6 +3127,26 @@ pin:
31273127
# parameter.
31283128
```
31293129

3130+
### [pwm_tool]
3131+
3132+
Pulse width modulation digital output pins capable of high speed
3133+
updates (one may define any number of sections with an "output_pin"
3134+
prefix). Pins configured here will be setup as output pins and one may
3135+
modify them at run-time using "SET_PIN PIN=my_pin VALUE=.1" type
3136+
extended [g-code commands](G-Codes.md#output_pin).
3137+
3138+
```
3139+
[pwm_tool my_tool]
3140+
pin:
3141+
# The pin to configure as an output. This parameter must be provided.
3142+
#value:
3143+
#shutdown_value:
3144+
#cycle_time: 0.100
3145+
#hardware_pwm: False
3146+
#scale:
3147+
# See the "output_pin" section for the definition of these parameters.
3148+
```
3149+
31303150
### [static_digital_output]
31313151

31323152
Statically configured digital output pins (one may define any number

docs/G-Codes.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -834,7 +834,8 @@ commands to manage the LED's color settings).
834834
### [output_pin]
835835

836836
The following command is available when an
837-
[output_pin config section](Config_Reference.md#output_pin) is
837+
[output_pin config section](Config_Reference.md#output_pin) or
838+
[pwm_tool config section](Config_Reference.md#pwm_tool) is
838839
enabled.
839840

840841
#### SET_PIN

docs/Status_Reference.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,8 @@ is defined):
318318
## output_pin
319319

320320
The following information is available in
321-
[output_pin some_name](Config_Reference.md#output_pin) objects:
321+
[output_pin some_name](Config_Reference.md#output_pin) and
322+
[pwm_tool some_name](Config_Reference.md#pwm_tool) objects:
322323
- `value`: The "value" of the pin, as set by a `SET_PIN` command.
323324

324325
## palette2

docs/Using_PWM_Tools.md

+1-9
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Using PWM tools
22

33
This document describes how to setup a PWM-controlled laser or spindle
4-
using `output_pin` and some macros.
4+
using `pwm_tool` and some macros.
55

66
## How does it work?
77

@@ -26,14 +26,6 @@ so that when your host or MCU encounters an error, the tool will stop.
2626

2727
For an example configuration, see [config/sample-pwm-tool.cfg](/config/sample-pwm-tool.cfg).
2828

29-
## Current Limitations
30-
31-
There is a limitation of how frequent PWM updates may occur.
32-
While being very precise, a PWM update may only occur every 0.1 seconds,
33-
rendering it almost useless for raster engraving.
34-
However, there exists an [experimental branch](https://github.com/Cirromulus/klipper/tree/laser_tool) with its own tradeoffs.
35-
In long term, it is planned to add this functionality to main-line klipper.
36-
3729
## Commands
3830

3931
`M3/M4 S<value>` : Set PWM duty-cycle. Values between 0 and 255.

klippy/extras/pwm_tool.py

+157
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
# Queued PWM gpio output
2+
#
3+
# Copyright (C) 2017-2023 Kevin O'Connor <kevin@koconnor.net>
4+
#
5+
# This file may be distributed under the terms of the GNU GPLv3 license.
6+
import chelper
7+
8+
PIN_MIN_TIME = 0.100
9+
MAX_SCHEDULE_TIME = 5.0
10+
11+
class error(Exception):
12+
pass
13+
14+
class MCU_queued_pwm:
15+
def __init__(self, pin_params):
16+
self._mcu = pin_params['chip']
17+
self._hardware_pwm = False
18+
self._cycle_time = 0.100
19+
self._max_duration = 2.
20+
self._oid = self._mcu.create_oid()
21+
ffi_main, ffi_lib = chelper.get_ffi()
22+
self._stepqueue = ffi_main.gc(ffi_lib.stepcompress_alloc(self._oid),
23+
ffi_lib.stepcompress_free)
24+
self._mcu.register_stepqueue(self._stepqueue)
25+
self._stepcompress_queue_mq_msg = ffi_lib.stepcompress_queue_mq_msg
26+
self._mcu.register_config_callback(self._build_config)
27+
self._pin = pin_params['pin']
28+
self._invert = pin_params['invert']
29+
self._start_value = self._shutdown_value = float(self._invert)
30+
self._last_clock = self._cycle_ticks = 0
31+
self._pwm_max = 0.
32+
self._set_cmd_tag = None
33+
def get_mcu(self):
34+
return self._mcu
35+
def setup_max_duration(self, max_duration):
36+
self._max_duration = max_duration
37+
def setup_cycle_time(self, cycle_time, hardware_pwm=False):
38+
self._cycle_time = cycle_time
39+
self._hardware_pwm = hardware_pwm
40+
def setup_start_value(self, start_value, shutdown_value):
41+
if self._invert:
42+
start_value = 1. - start_value
43+
shutdown_value = 1. - shutdown_value
44+
self._start_value = max(0., min(1., start_value))
45+
self._shutdown_value = max(0., min(1., shutdown_value))
46+
def _build_config(self):
47+
if self._max_duration and self._start_value != self._shutdown_value:
48+
raise pins.error("Pin with max duration must have start"
49+
" value equal to shutdown value")
50+
cmd_queue = self._mcu.alloc_command_queue()
51+
curtime = self._mcu.get_printer().get_reactor().monotonic()
52+
printtime = self._mcu.estimated_print_time(curtime)
53+
self._last_clock = self._mcu.print_time_to_clock(printtime + 0.200)
54+
cycle_ticks = self._mcu.seconds_to_clock(self._cycle_time)
55+
mdur_ticks = self._mcu.seconds_to_clock(self._max_duration)
56+
if mdur_ticks >= 1<<31:
57+
raise pins.error("PWM pin max duration too large")
58+
if self._hardware_pwm:
59+
self._pwm_max = self._mcu.get_constant_float("PWM_MAX")
60+
self._mcu.add_config_cmd(
61+
"config_pwm_out oid=%d pin=%s cycle_ticks=%d value=%d"
62+
" default_value=%d max_duration=%d"
63+
% (self._oid, self._pin, cycle_ticks,
64+
self._start_value * self._pwm_max,
65+
self._shutdown_value * self._pwm_max, mdur_ticks))
66+
svalue = int(self._start_value * self._pwm_max + 0.5)
67+
self._mcu.add_config_cmd("queue_pwm_out oid=%d clock=%d value=%d"
68+
% (self._oid, self._last_clock, svalue),
69+
on_restart=True)
70+
self._set_cmd_tag = self._mcu.lookup_command(
71+
"queue_pwm_out oid=%c clock=%u value=%hu",
72+
cq=cmd_queue).get_command_tag()
73+
return
74+
# Software PWM
75+
if self._shutdown_value not in [0., 1.]:
76+
raise pins.error("shutdown value must be 0.0 or 1.0 on soft pwm")
77+
if cycle_ticks >= 1<<31:
78+
raise pins.error("PWM pin cycle time too large")
79+
self._mcu.add_config_cmd(
80+
"config_digital_out oid=%d pin=%s value=%d"
81+
" default_value=%d max_duration=%d"
82+
% (self._oid, self._pin, self._start_value >= 1.0,
83+
self._shutdown_value >= 0.5, mdur_ticks))
84+
self._mcu.add_config_cmd(
85+
"set_digital_out_pwm_cycle oid=%d cycle_ticks=%d"
86+
% (self._oid, cycle_ticks))
87+
self._cycle_ticks = cycle_ticks
88+
svalue = int(self._start_value * cycle_ticks + 0.5)
89+
self._mcu.add_config_cmd(
90+
"queue_digital_out oid=%d clock=%d on_ticks=%d"
91+
% (self._oid, self._last_clock, svalue), is_init=True)
92+
self._set_cmd_tag = self._mcu.lookup_command(
93+
"queue_digital_out oid=%c clock=%u on_ticks=%u",
94+
cq=cmd_queue).get_command_tag()
95+
def set_pwm(self, print_time, value):
96+
clock = self._mcu.print_time_to_clock(print_time)
97+
minclock = self._last_clock
98+
self._last_clock = clock
99+
if self._invert:
100+
value = 1. - value
101+
max_count = self._cycle_ticks
102+
if self._hardware_pwm:
103+
max_count = self._pwm_max
104+
v = int(max(0., min(1., value)) * max_count + 0.5)
105+
data = (self._set_cmd_tag, self._oid, clock & 0xffffffff, v)
106+
ret = self._stepcompress_queue_mq_msg(self._stepqueue, clock,
107+
data, len(data))
108+
if ret:
109+
raise error("Internal error in stepcompress")
110+
111+
class PrinterOutputPin:
112+
def __init__(self, config):
113+
self.printer = config.get_printer()
114+
ppins = self.printer.lookup_object('pins')
115+
# Determine pin type
116+
pin_params = ppins.lookup_pin(config.get('pin'), can_invert=True)
117+
self.mcu_pin = MCU_queued_pwm(pin_params)
118+
cycle_time = config.getfloat('cycle_time', 0.100, above=0.,
119+
maxval=MAX_SCHEDULE_TIME)
120+
hardware_pwm = config.getboolean('hardware_pwm', False)
121+
self.mcu_pin.setup_cycle_time(cycle_time, hardware_pwm)
122+
self.scale = config.getfloat('scale', 1., above=0.)
123+
self.last_print_time = 0.
124+
self.mcu_pin.setup_max_duration(0.)
125+
# Determine start and shutdown values
126+
self.last_value = config.getfloat(
127+
'value', 0., minval=0., maxval=self.scale) / self.scale
128+
self.shutdown_value = config.getfloat(
129+
'shutdown_value', 0., minval=0., maxval=self.scale) / self.scale
130+
self.mcu_pin.setup_start_value(self.last_value, self.shutdown_value)
131+
# Register commands
132+
pin_name = config.get_name().split()[1]
133+
gcode = self.printer.lookup_object('gcode')
134+
gcode.register_mux_command("SET_PIN", "PIN", pin_name,
135+
self.cmd_SET_PIN,
136+
desc=self.cmd_SET_PIN_help)
137+
def get_status(self, eventtime):
138+
return {'value': self.last_value}
139+
def _set_pin(self, print_time, value):
140+
if value == self.last_value:
141+
return
142+
print_time = max(print_time, self.last_print_time)
143+
self.mcu_pin.set_pwm(print_time, value)
144+
self.last_value = value
145+
self.last_print_time = print_time
146+
cmd_SET_PIN_help = "Set the value of an output pin"
147+
def cmd_SET_PIN(self, gcmd):
148+
# Read requested value
149+
value = gcmd.get_float('VALUE', minval=0., maxval=self.scale)
150+
value /= self.scale
151+
# Obtain print_time and apply requested settings
152+
toolhead = self.printer.lookup_object('toolhead')
153+
toolhead.register_lookahead_callback(
154+
lambda print_time: self._set_pin(print_time, value))
155+
156+
def load_config_prefix(config):
157+
return PrinterOutputPin(config)

test/klippy/pwm.cfg

+6
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ value: 0
1313
shutdown_value: 0
1414
cycle_time: 0.01
1515

16+
[pwm_tool test_pwm_tool]
17+
pin: PH4
18+
value: 0
19+
shutdown_value: 0
20+
cycle_time: 0.01
21+
1622
[mcu]
1723
serial: /dev/ttyACM0
1824

test/klippy/pwm.test

+8
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,11 @@ SET_PIN PIN=soft_pwm_pin VALUE=0.5 CYCLE_TIME=0.5
2828
SET_PIN PIN=soft_pwm_pin VALUE=0.5 CYCLE_TIME=0.5
2929
SET_PIN PIN=soft_pwm_pin VALUE=0.75 CYCLE_TIME=0.5
3030
SET_PIN PIN=soft_pwm_pin VALUE=0.75 CYCLE_TIME=0.75
31+
32+
# PWM tool
33+
# Basic test
34+
SET_PIN PIN=test_pwm_tool VALUE=0
35+
SET_PIN PIN=test_pwm_tool VALUE=0.5
36+
SET_PIN PIN=test_pwm_tool VALUE=0.5
37+
SET_PIN PIN=test_pwm_tool VALUE=0.25
38+
SET_PIN PIN=test_pwm_tool VALUE=1

0 commit comments

Comments
 (0)