Compare commits
276 Commits
v0.12.0
...
work-heate
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1feb47dbd | ||
|
|
36b5595290 | ||
|
|
d7d9092a92 | ||
|
|
ba2a149e9a | ||
|
|
13c75ea876 | ||
|
|
cb15d0fec6 | ||
|
|
055f07c638 | ||
|
|
c0095812ff | ||
|
|
0844388d70 | ||
|
|
12cd1d9e81 | ||
|
|
6848843224 | ||
|
|
bd1dbc8af3 | ||
|
|
7603953ef7 | ||
|
|
0087f04cc3 | ||
|
|
c84d78f3f1 | ||
|
|
248d3dbf8b | ||
|
|
00cb683def | ||
|
|
34732f857a | ||
|
|
9318901f19 | ||
|
|
4d21ffc1d6 | ||
|
|
6d70050261 | ||
|
|
2d73211190 | ||
|
|
d89722056b | ||
|
|
9fa0fb1a0e | ||
|
|
7149bb1b6d | ||
|
|
ba529996ea | ||
|
|
4ac283cc0e | ||
|
|
a19d64febd | ||
|
|
a19af08894 | ||
|
|
2c7e09cfa6 | ||
|
|
fc0f17b920 | ||
|
|
c7b7c11cc3 | ||
|
|
f2df011c68 | ||
|
|
0a14e33150 | ||
|
|
11f04ba1ba | ||
|
|
863a463cb2 | ||
|
|
ae227d485c | ||
|
|
433fcb6f24 | ||
|
|
beba2c2d33 | ||
|
|
fcf064ba68 | ||
|
|
aa0dbf6ee6 | ||
|
|
49f511e679 | ||
|
|
429aa2b2a6 | ||
|
|
bf1bc1ee0f | ||
|
|
1591a51f76 | ||
|
|
8de7153952 | ||
|
|
0d87bec159 | ||
|
|
589bd64ce0 | ||
|
|
36b8831c7e | ||
|
|
17c645f000 | ||
|
|
d4bae4dffe | ||
|
|
931d1ce8f4 | ||
|
|
93245b3678 | ||
|
|
068d2a9f5a | ||
|
|
f72f94e299 | ||
|
|
58753e58a2 | ||
|
|
abfe3675d6 | ||
|
|
e780049a74 | ||
|
|
f4adb29999 | ||
|
|
982a50c70a | ||
|
|
de9798fb5b | ||
|
|
f9a2920cee | ||
|
|
292512f813 | ||
|
|
6ea5b94d1e | ||
|
|
6f6122a576 | ||
|
|
8fc11b4a2e | ||
|
|
bec47e0492 | ||
|
|
12f92c55f1 | ||
|
|
49c0ad6369 | ||
|
|
6cd174208b | ||
|
|
3078912f1d | ||
|
|
b6a0063235 | ||
|
|
4a92727eab | ||
|
|
37482178b5 | ||
|
|
4709f1fad5 | ||
|
|
04c562941c | ||
|
|
cb6cce3934 | ||
|
|
3dc7c9ab29 | ||
|
|
6fac654352 | ||
|
|
29bfbd02f9 | ||
|
|
236d780a0a | ||
|
|
5d52b32e64 | ||
|
|
2efde0111e | ||
|
|
faee2c0e52 | ||
|
|
b7f7b8a346 | ||
|
|
694d38c791 | ||
|
|
dae8b8cacf | ||
|
|
e0cbd7b5fc | ||
|
|
ed8dca8df0 | ||
|
|
5249d955bb | ||
|
|
0f3f29101c | ||
|
|
1ca1054957 | ||
|
|
f01c8853ca | ||
|
|
472d8e5b66 | ||
|
|
80b55d3528 | ||
|
|
8f510da12b | ||
|
|
79930ed99a | ||
|
|
434770eaf9 | ||
|
|
7e8c7f46a9 | ||
|
|
af149b4781 | ||
|
|
d8d072b375 | ||
|
|
7b490f3ec1 | ||
|
|
b1eec53ff4 | ||
|
|
0b329c5d28 | ||
|
|
c3ec4af6cc | ||
|
|
2f6e94c94c | ||
|
|
713b509698 | ||
|
|
28faf81414 | ||
|
|
819599362c | ||
|
|
abb7910316 | ||
|
|
9ceaae3847 | ||
|
|
56829b07d2 | ||
|
|
f73e6dcd12 | ||
|
|
144af05270 | ||
|
|
95fdb68587 | ||
|
|
c106955850 | ||
|
|
12e9b633d8 | ||
|
|
2425a74638 | ||
|
|
36f9b26ef9 | ||
|
|
75d7c17656 | ||
|
|
c37329e9e2 | ||
|
|
4cfa266e00 | ||
|
|
a8b493a1ae | ||
|
|
b09897245e | ||
|
|
30e0fddbbf | ||
|
|
28281c595b | ||
|
|
13b2926e0c | ||
|
|
b0d90fd013 | ||
|
|
d84fc431a1 | ||
|
|
da2b258441 | ||
|
|
b8f1df3a96 | ||
|
|
acdf8bb108 | ||
|
|
fa5fa74761 | ||
|
|
01c7befacb | ||
|
|
b029d04668 | ||
|
|
6f16e11197 | ||
|
|
24c884e9f3 | ||
|
|
75a40e817d | ||
|
|
5e280680c5 | ||
|
|
67c152745e | ||
|
|
9e1cbdcee3 | ||
|
|
0aacbc3973 | ||
|
|
bedec55154 | ||
|
|
239f8e59e0 | ||
|
|
e37b007f67 | ||
|
|
d9043345b6 | ||
|
|
40728e9231 | ||
|
|
de1cf216ac | ||
|
|
e6df93fcf8 | ||
|
|
235b75be3c | ||
|
|
78a15b6d81 | ||
|
|
bfb71bc2dc | ||
|
|
09a78c31bb | ||
|
|
0291a1554c | ||
|
|
d99d1a8463 | ||
|
|
bb512ef5d7 | ||
|
|
bddefdde36 | ||
|
|
0105aa330f | ||
|
|
18de421c4a | ||
|
|
71604b712a | ||
|
|
31de734d19 | ||
|
|
b98375b360 | ||
|
|
a77d07907f | ||
|
|
28f06a104b | ||
|
|
72b301a285 | ||
|
|
4f00f21991 | ||
|
|
c92732e4f1 | ||
|
|
2f7b234189 | ||
|
|
b2ac0f1ce3 | ||
|
|
9a940ffccb | ||
|
|
0aaabf1904 | ||
|
|
0cd16e956d | ||
|
|
1b24f6a2ad | ||
|
|
6ce6fbbce0 | ||
|
|
9f41f53c5e | ||
|
|
16a7b50ce9 | ||
|
|
600e89ae8c | ||
|
|
5e3daa6f21 | ||
|
|
5e433fff06 | ||
|
|
f1982edcd5 | ||
|
|
44e79e0c37 | ||
|
|
23c5b20f5b | ||
|
|
55e46aa625 | ||
|
|
43a9685c58 | ||
|
|
fd2feff67d | ||
|
|
1baa45913f | ||
|
|
7abafb575b | ||
|
|
4115ea128a | ||
|
|
2e8b54ae5f | ||
|
|
f653db9c88 | ||
|
|
daf875e6e4 | ||
|
|
d785b396a7 | ||
|
|
d853c19811 | ||
|
|
6f0e91f69f | ||
|
|
2dc4cfc5df | ||
|
|
266e96621c | ||
|
|
dc6182f3b3 | ||
|
|
95e1a290f1 | ||
|
|
5ff555a705 | ||
|
|
3275614b89 | ||
|
|
83d0d2f19b | ||
|
|
94719fe327 | ||
|
|
1d92be71da | ||
|
|
6cc409f6fb | ||
|
|
d633ef2cfc | ||
|
|
43d0dba4b4 | ||
|
|
7a74888b43 | ||
|
|
3d3b87f97f | ||
|
|
447a88eb08 | ||
|
|
1ea9f3aa35 | ||
|
|
dab39c02cd | ||
|
|
96ab906946 | ||
|
|
84aa3caa45 | ||
|
|
49315b3cc4 | ||
|
|
1a1568c38b | ||
|
|
b50d6669a8 | ||
|
|
0665dc8976 | ||
|
|
92fe8f15b8 | ||
|
|
25bc649cd2 | ||
|
|
9847b44901 | ||
|
|
d7f6348ae6 | ||
|
|
b502558052 | ||
|
|
6f686ddee3 | ||
|
|
c716edafe2 | ||
|
|
3370134593 | ||
|
|
95c753292d | ||
|
|
acde3720a4 | ||
|
|
ffd44c0219 | ||
|
|
f4c8f0bf88 | ||
|
|
3f84501955 | ||
|
|
43ce7c0b9a | ||
|
|
d6a4669ce0 | ||
|
|
e67cbbe5c1 | ||
|
|
978c294741 | ||
|
|
644f7e0872 | ||
|
|
fe56bf36c9 | ||
|
|
77619e912c | ||
|
|
147492b253 | ||
|
|
71ab6240f2 | ||
|
|
547bfbf818 | ||
|
|
3417940fd8 | ||
|
|
2defd7374a | ||
|
|
1e5f688b53 | ||
|
|
19862bc3b7 | ||
|
|
f0753bd338 | ||
|
|
6676c1df86 | ||
|
|
2c2bb720fa | ||
|
|
1a83845c9f | ||
|
|
fe7082e4a8 | ||
|
|
c5bd813d8b | ||
|
|
62bf52bfcf | ||
|
|
99d7af87fd | ||
|
|
c491ea669f | ||
|
|
b7b13588c7 | ||
|
|
9e574c3497 | ||
|
|
93cd8834f3 | ||
|
|
bafb126abd | ||
|
|
5bd32e2984 | ||
|
|
d929be487b | ||
|
|
7ed3c679dc | ||
|
|
0ccf5f8e47 | ||
|
|
fc102edc24 | ||
|
|
05d5451347 | ||
|
|
795ce490a0 | ||
|
|
38221df83a | ||
|
|
03f69cd81a | ||
|
|
ea2f6bc0f5 | ||
|
|
bb4711c5d3 | ||
|
|
187cc2f1b8 | ||
|
|
3c8f202dfa | ||
|
|
83df4a8627 | ||
|
|
29b7550ce5 | ||
|
|
48a05eaa54 | ||
|
|
4688c21c54 | ||
|
|
3f8f30d612 | ||
|
|
74473322e5 |
96
.github/workflows/stale-issue-bot.yaml
vendored
96
.github/workflows/stale-issue-bot.yaml
vendored
@@ -62,54 +62,54 @@ jobs:
|
||||
state: 'closed'
|
||||
});
|
||||
}
|
||||
# Close tickets marked with "reviewer needed" label for 2+ weeks
|
||||
close_reviewer_needed:
|
||||
if: github.repository == 'Klipper3d/klipper'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v6
|
||||
with:
|
||||
script: |
|
||||
const issues = await github.rest.issues.listForRepo({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
state: 'open',
|
||||
labels: 'reviewer needed',
|
||||
assignee: 'none',
|
||||
per_page: 100,
|
||||
page: 1
|
||||
});
|
||||
msg = "Unfortunately a reviewer has not assigned themselves to"
|
||||
+ " this GitHub Pull Request and it is therefore being"
|
||||
+ " closed. It is a good idea to move"
|
||||
+ " further discussion to the [Klipper Discourse]"
|
||||
+ "(https://www.klipper3d.org/Contact.html#discourse-forum)"
|
||||
+ " server. Reviewers can reach out on that forum to let you"
|
||||
+ " know if they are interested and when they are available."
|
||||
+ "\n\n"
|
||||
+ "Best regards,\n"
|
||||
+ "~ Your friendly GitIssueBot"
|
||||
+ "\n\n"
|
||||
+ "PS: I'm just an automated script, not a human being.";
|
||||
const expireMillis = 1000 * 60 * 60 * 24 * 14;
|
||||
const curtime = new Date().getTime();
|
||||
for (const issue of issues.data.values()) {
|
||||
const updatetime = new Date(issue.updated_at).getTime();
|
||||
if (curtime < updatetime + expireMillis)
|
||||
continue;
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
body: msg
|
||||
});
|
||||
await github.rest.issues.update({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
state: 'closed'
|
||||
});
|
||||
}
|
||||
# # Close tickets marked with "reviewer needed" label for 2+ weeks
|
||||
# close_reviewer_needed:
|
||||
# if: github.repository == 'Klipper3d/klipper'
|
||||
# runs-on: ubuntu-latest
|
||||
# steps:
|
||||
# - uses: actions/github-script@v6
|
||||
# with:
|
||||
# script: |
|
||||
# const issues = await github.rest.issues.listForRepo({
|
||||
# owner: context.repo.owner,
|
||||
# repo: context.repo.repo,
|
||||
# state: 'open',
|
||||
# labels: 'reviewer needed',
|
||||
# assignee: 'none',
|
||||
# per_page: 100,
|
||||
# page: 1
|
||||
# });
|
||||
# msg = "Unfortunately a reviewer has not assigned themselves to"
|
||||
# + " this GitHub Pull Request and it is therefore being"
|
||||
# + " closed. It is a good idea to move"
|
||||
# + " further discussion to the [Klipper Discourse]"
|
||||
# + "(https://www.klipper3d.org/Contact.html#discourse-forum)"
|
||||
# + " server. Reviewers can reach out on that forum to let you"
|
||||
# + " know if they are interested and when they are available."
|
||||
# + "\n\n"
|
||||
# + "Best regards,\n"
|
||||
# + "~ Your friendly GitIssueBot"
|
||||
# + "\n\n"
|
||||
# + "PS: I'm just an automated script, not a human being.";
|
||||
# const expireMillis = 1000 * 60 * 60 * 24 * 14;
|
||||
# const curtime = new Date().getTime();
|
||||
# for (const issue of issues.data.values()) {
|
||||
# const updatetime = new Date(issue.updated_at).getTime();
|
||||
# if (curtime < updatetime + expireMillis)
|
||||
# continue;
|
||||
# await github.rest.issues.createComment({
|
||||
# owner: context.repo.owner,
|
||||
# repo: context.repo.repo,
|
||||
# issue_number: issue.number,
|
||||
# body: msg
|
||||
# });
|
||||
# await github.rest.issues.update({
|
||||
# owner: context.repo.owner,
|
||||
# repo: context.repo.repo,
|
||||
# issue_number: issue.number,
|
||||
# state: 'closed'
|
||||
# });
|
||||
# }
|
||||
# Mark unassigned PRs that are idle for 2 weeks
|
||||
mark_reviewer_needed:
|
||||
if: github.repository == 'Klipper3d/klipper'
|
||||
|
||||
7
Makefile
7
Makefile
@@ -29,10 +29,11 @@ dirs-y = src
|
||||
cc-option=$(shell if test -z "`$(1) $(2) -S -o /dev/null -xc /dev/null 2>&1`" \
|
||||
; then echo "$(2)"; else echo "$(3)"; fi ;)
|
||||
|
||||
CFLAGS := -I$(OUT) -Isrc -I$(OUT)board-generic/ -std=gnu11 -O2 -MD \
|
||||
-Wall -Wold-style-definition $(call cc-option,$(CC),-Wtype-limits,) \
|
||||
CFLAGS := -iquote $(OUT) -iquote src -iquote $(OUT)board-generic/ \
|
||||
-std=gnu11 -O2 -MD -Wall \
|
||||
-Wold-style-definition $(call cc-option,$(CC),-Wtype-limits,) \
|
||||
-ffunction-sections -fdata-sections -fno-delete-null-pointer-checks
|
||||
CFLAGS += -flto -fwhole-program -fno-use-linker-plugin -ggdb3
|
||||
CFLAGS += -flto=auto -fwhole-program -fno-use-linker-plugin -ggdb3
|
||||
|
||||
OBJS_klipper.elf = $(patsubst %.c, $(OUT)src/%.o,$(src-y))
|
||||
OBJS_klipper.elf += $(OUT)compile_time_request.o
|
||||
|
||||
223
config/generic-I3DBEEZ9.cfg
Normal file
223
config/generic-I3DBEEZ9.cfg
Normal file
@@ -0,0 +1,223 @@
|
||||
# This file contains common pin mappings for the I3DBEEZ9 V1.0.
|
||||
# To use this config, the firmware should be compiled for the
|
||||
# STM32F407 with a "32KiB bootloader".
|
||||
|
||||
# The "make flash" command does not work on the I3DBEEZ9. Instead,
|
||||
# after running "make", copy the generated "out/klipper.bin" file to a
|
||||
# file named "firmware.bin" on an SD card and then restart the I3DBEEZ9
|
||||
# with that SD card.
|
||||
|
||||
# See docs/Config_Reference.md for a description of parameters.
|
||||
|
||||
[stepper_x]
|
||||
step_pin: PE9
|
||||
dir_pin: PF1
|
||||
enable_pin: !PF2
|
||||
microsteps: 16
|
||||
rotation_distance: 40
|
||||
endstop_pin: PB10
|
||||
position_endstop: 0
|
||||
position_max: 200
|
||||
homing_speed: 50
|
||||
|
||||
[stepper_y]
|
||||
step_pin: PE11
|
||||
dir_pin: PE1
|
||||
enable_pin: !PD7
|
||||
microsteps: 16
|
||||
rotation_distance: 40
|
||||
endstop_pin: PE12
|
||||
position_endstop: 0
|
||||
position_max: 200
|
||||
homing_speed: 50
|
||||
|
||||
[stepper_z]
|
||||
step_pin: PE13
|
||||
dir_pin: PC2
|
||||
enable_pin: !PC0
|
||||
microsteps: 16
|
||||
rotation_distance: 8
|
||||
endstop_pin: PG8
|
||||
position_endstop: 0
|
||||
position_max: 200
|
||||
|
||||
[extruder]
|
||||
step_pin: PE14
|
||||
dir_pin: PA0
|
||||
enable_pin: !PC3
|
||||
microsteps: 16
|
||||
rotation_distance: 33.500
|
||||
nozzle_diameter: 0.400
|
||||
filament_diameter: 1.750
|
||||
heater_pin: PB1 # Heat0
|
||||
sensor_pin: PF4 # T1 Header
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
control: pid
|
||||
pid_Kp: 22.2
|
||||
pid_Ki: 1.08
|
||||
pid_Kd: 114
|
||||
min_temp: 0
|
||||
max_temp: 250
|
||||
|
||||
#[extruder1]
|
||||
#step_pin: PD15
|
||||
#dir_pin: PE7
|
||||
#enable_pin: !PA3
|
||||
#heater_pin: PD14 # Heat1
|
||||
#sensor_pin: PF5 # T2
|
||||
#...
|
||||
|
||||
#[extruder2]
|
||||
#step_pin: PD13
|
||||
#dir_pin: PG9
|
||||
#enable_pin: !PF0
|
||||
#heater_pin: PB0 # Heat2
|
||||
#sensor_pin: PF6 # T3
|
||||
#...
|
||||
|
||||
#[stepper_z1]
|
||||
#step_pin: PE4
|
||||
#dir_pin: PE3
|
||||
#enable_pin: !PC13
|
||||
#microsteps: 16
|
||||
#rotation_distance: 8
|
||||
#endstop_pin: PD0
|
||||
#position_endstop: 0.5
|
||||
#position_max: 200
|
||||
|
||||
[heater_bed]
|
||||
heater_pin: PD12
|
||||
sensor_pin: PF3 # T0
|
||||
sensor_type: ATC Semitec 104GT-2
|
||||
control: watermark
|
||||
min_temp: 0
|
||||
max_temp: 130
|
||||
|
||||
[fan]
|
||||
pin: PC8
|
||||
|
||||
[heater_fan fan1]
|
||||
pin: PE5
|
||||
|
||||
#[heater_fan fan2]
|
||||
#pin: PE6
|
||||
|
||||
[mcu]
|
||||
serial: /dev/serial/by-id/usb-Klipper_Klipper_firmware_12345-if00
|
||||
|
||||
[printer]
|
||||
kinematics: cartesian
|
||||
max_velocity: 300
|
||||
max_accel: 3000
|
||||
max_z_velocity: 5
|
||||
max_z_accel: 100
|
||||
|
||||
|
||||
########################################
|
||||
# TMC2208 configuration
|
||||
########################################
|
||||
|
||||
#[tmc2208 stepper_x]
|
||||
#uart_pin: PA15
|
||||
#run_current: 0.800
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2208 stepper_y]
|
||||
#uart_pin: PB8
|
||||
#run_current: 0.800
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2208 stepper_z]
|
||||
#uart_pin: PB9
|
||||
#run_current: 0.650
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2208 extruder]
|
||||
#uart_pin: PB3
|
||||
#run_current: 0.800
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2208 extruder1]
|
||||
#uart_pin: PG15
|
||||
#run_current: 0.800
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2208 extruder2]
|
||||
#uart_pin: PG12
|
||||
#run_current: 0.800
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2208 stepper_z1]
|
||||
#uart_pin: PE2
|
||||
#run_current: 0.650
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
########################################
|
||||
# TMC2130 configuration
|
||||
########################################
|
||||
|
||||
#[tmc2130 stepper_x]
|
||||
#cs_pin: PA15
|
||||
#spi_bus: spi3a
|
||||
##diag1_pin: PB10
|
||||
#run_current: 0.800
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2130 stepper_y]
|
||||
#cs_pin: PB8
|
||||
#spi_bus: spi3a
|
||||
##diag1_pin: PE12
|
||||
#run_current: 0.800
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2130 stepper_z]
|
||||
#cs_pin: PB9
|
||||
#spi_bus: spi3a
|
||||
##diag1_pin: PG8
|
||||
#run_current: 0.650
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2130 extruder]
|
||||
#cs_pin: PB3
|
||||
#spi_bus: spi3a
|
||||
##diag1_pin: PE15
|
||||
#run_current: 0.800
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2130 extruder1]
|
||||
#cs_pin: PG15
|
||||
#spi_bus: spi3a
|
||||
##diag1_pin: PE10
|
||||
#run_current: 0.800
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2130 extruder2]
|
||||
#cs_pin: PG12
|
||||
#spi_bus: spi3a
|
||||
##diag1_pin: PG5
|
||||
#run_current: 0.800
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
#[tmc2130 stepper_z1]
|
||||
#cs_pin: PE2
|
||||
#spi_bus: spi3a
|
||||
##diag1_pin: PD0
|
||||
#run_current: 0.650
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
|
||||
########################################
|
||||
# EXP1 / EXP2 (display) pins
|
||||
########################################
|
||||
|
||||
[board_pins]
|
||||
aliases:
|
||||
# EXP1 header
|
||||
EXP1_1=PG4, EXP1_3=PD11, EXP1_5=PG2, EXP1_7=PG6, EXP1_9=<GND>,
|
||||
EXP1_2=PA8, EXP1_4=PD10, EXP1_6=PG3, EXP1_8=PG7, EXP1_10=<5V>,
|
||||
# EXP2 header
|
||||
EXP2_1=PB14, EXP2_3=PG10, EXP2_5=PF11, EXP2_7=PF12, EXP2_9=<GND>,
|
||||
EXP2_2=PB13, EXP2_4=PB12, EXP2_6=PB15, EXP2_8=<RST>, EXP2_10=PF13
|
||||
# Pins EXP2_1, EXP2_6, EXP2_2 are also MISO, MOSI, SCK of bus "spi2"
|
||||
|
||||
# See the sample-lcd.cfg file for definitions of common LCD displays.
|
||||
@@ -85,11 +85,10 @@ uart_pin: PC11
|
||||
tx_pin: PC10
|
||||
uart_address: 3
|
||||
run_current: 0.650
|
||||
stealthchop_threshold: 999999
|
||||
|
||||
[heater_bed]
|
||||
heater_pin: PC9
|
||||
sensor_type: ATC Semitec 104GT-2
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
sensor_pin: PC4
|
||||
control: pid
|
||||
pid_Kp: 54.027
|
||||
|
||||
241
config/generic-ldo-leviathan-v1.2.cfg
Normal file
241
config/generic-ldo-leviathan-v1.2.cfg
Normal file
@@ -0,0 +1,241 @@
|
||||
# This file contains common pin mappings for the LDO Leviathan v1.2.
|
||||
|
||||
# To use this config, during "make menuconfig", select "Enable
|
||||
# low-level configuration options", select the STM32F446 micro-controller,
|
||||
# select a "32KiB bootloader", and select a "12Mhz crystal".
|
||||
|
||||
# See docs/Config_Reference.md for a description of parameters.
|
||||
|
||||
# HV-STEPPER-0
|
||||
[stepper_x]
|
||||
step_pin: PB10
|
||||
dir_pin: PB11
|
||||
enable_pin: !PG0
|
||||
microsteps: 32
|
||||
rotation_distance: 40
|
||||
endstop_pin: PC1 # X-ENDSTOP
|
||||
position_endstop: 0
|
||||
position_max: 200
|
||||
homing_speed: 50
|
||||
|
||||
[tmc5160 stepper_x]
|
||||
spi_bus: spi4
|
||||
cs_pin: PE15
|
||||
#diag0_pin: PG1
|
||||
interpolate: False
|
||||
sense_resistor: 0.075
|
||||
run_current: 0.8
|
||||
stealthchop_threshold: 0
|
||||
|
||||
# HV-STEPPER-1
|
||||
[stepper_y]
|
||||
step_pin: PF15
|
||||
dir_pin: PF14
|
||||
enable_pin: !PE9
|
||||
microsteps: 32
|
||||
rotation_distance: 40
|
||||
endstop_pin: PC2 # Y-ENDSTOP
|
||||
position_endstop: 0
|
||||
position_max: 200
|
||||
homing_speed: 50
|
||||
|
||||
[tmc5160 stepper_y]
|
||||
spi_bus: spi4
|
||||
cs_pin: PE11
|
||||
#diag0_pin: PE10
|
||||
interpolate: False
|
||||
sense_resistor: 0.075
|
||||
run_current: 0.8
|
||||
stealthchop_threshold: 0
|
||||
|
||||
# STEPPER-0
|
||||
[stepper_z]
|
||||
step_pin: PD4
|
||||
dir_pin: PD3
|
||||
enable_pin: !PD7
|
||||
microsteps: 32
|
||||
rotation_distance: 8
|
||||
endstop_pin: PC3 # Z-ENDSTOP
|
||||
position_endstop: 0
|
||||
position_max: 200
|
||||
|
||||
[tmc2209 stepper_z]
|
||||
uart_pin: PD5
|
||||
#diag_pin: PD6
|
||||
interpolate: False
|
||||
run_current: 0.6
|
||||
stealthchop_threshold: 999999
|
||||
|
||||
# The Leviathan was developed for Voron printers. It therefore has several
|
||||
# steppers for the z-axes, but only one heater for one extruder.
|
||||
|
||||
# STEPPER-1
|
||||
#[stepper_z1]
|
||||
#step_pin: PC12
|
||||
#dir_pin: PC11
|
||||
#enable_pin: !PD2
|
||||
#microsteps: 32
|
||||
#rotation_distance: 8
|
||||
#
|
||||
#[tmc2209 stepper_z1]
|
||||
#uart_pin: PD5
|
||||
##diag_pin: PD6
|
||||
#interpolate: False
|
||||
#run_current: 0.6
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
# STEPPER-2
|
||||
#[stepper_z2]
|
||||
#step_pin: PC9
|
||||
#dir_pin: PC8
|
||||
#enable_pin: !PC10
|
||||
#microsteps: 32
|
||||
#rotation_distance: 8
|
||||
#
|
||||
#[tmc2209 stepper_z2]
|
||||
#uart_pin: PA8
|
||||
##diag_pin: PA15
|
||||
#interpolate: False
|
||||
#run_current: 0.6
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
# STEPPER-3
|
||||
#[stepper_z3]
|
||||
#step_pin: PG7
|
||||
#dir_pin: PG6
|
||||
#enable_pin: !PC7
|
||||
#microsteps: 32
|
||||
#rotation_distance: 8
|
||||
#
|
||||
#[tmc2209 stepper_z2]
|
||||
#uart_pin: PG8
|
||||
##diag_pin: PC6
|
||||
#interpolate: False
|
||||
#run_current: 0.6
|
||||
#stealthchop_threshold: 999999
|
||||
|
||||
# STEPPER-4
|
||||
[extruder]
|
||||
step_pin: PD10
|
||||
dir_pin: PD9
|
||||
enable_pin: !PD13
|
||||
microsteps: 32
|
||||
rotation_distance: 22.67
|
||||
nozzle_diameter: 0.400
|
||||
filament_diameter: 1.750
|
||||
heater_pin: PG10 # HEATER
|
||||
sensor_pin: PA2 # TH1
|
||||
sensor_type: ATC Semitec 104NT-4-R025H42G
|
||||
pullup_resistor: 2200
|
||||
control: pid
|
||||
pid_Kp: 36.787
|
||||
pid_Ki: 4.716
|
||||
pid_Kd: 71.735
|
||||
min_temp: 0
|
||||
max_temp: 250
|
||||
|
||||
[tmc2209 stepper_z]
|
||||
uart_pin: PD11
|
||||
#diag_pin: PD12
|
||||
interpolate: False
|
||||
run_current: 0.5
|
||||
stealthchop_threshold: 0
|
||||
|
||||
#[filament_switch_sensor material_0]
|
||||
#switch_pin: PC0 # FILAMENT-SENSOR
|
||||
|
||||
[heater_bed]
|
||||
heater_pin: PG11 # HEATBED
|
||||
sensor_pin: PA1 # TH0
|
||||
sensor_type: ATC Semitec 104GT-2
|
||||
pullup_resistor: 2200
|
||||
control: pid
|
||||
pid_kp: 56.723
|
||||
pid_ki: 5.561
|
||||
pid_kd: 144.642
|
||||
min_temp: 0
|
||||
max_temp: 130
|
||||
|
||||
[fan]
|
||||
pin: PB7 # FAN0
|
||||
#tachometer_pin: PB0
|
||||
|
||||
#[heater_fan fan1]
|
||||
#pin: PB3
|
||||
#tachometer_pin: PB4
|
||||
|
||||
#[heater_fan fan2]
|
||||
#pin: PF7
|
||||
#tachometer_pin: PF6
|
||||
|
||||
#[controller_fan fan3]
|
||||
#pin: PF9
|
||||
#tachometer_pin: PF8
|
||||
|
||||
[mcu]
|
||||
serial: /dev/serial/by-id/usb-Klipper_Klipper_firmware_12345-if00
|
||||
# CAN bus is also available on this board
|
||||
|
||||
[printer]
|
||||
kinematics: cartesian
|
||||
max_velocity: 300
|
||||
max_accel: 3000
|
||||
max_z_velocity: 5
|
||||
max_z_accel: 100
|
||||
|
||||
[board_pins]
|
||||
aliases:
|
||||
# EXP1 header
|
||||
EXP1_1=PG9, EXP1_2=PG12,
|
||||
EXP1_3=PG13, EXP1_4=PG14,
|
||||
EXP1_5=PC13, EXP1_6=PC14,
|
||||
EXP1_7=PC15, EXP1_8=PF0,
|
||||
EXP1_9=<GND>, EXP1_10=<5V>,
|
||||
|
||||
# EXP2 header
|
||||
EXP2_1=PA6, EXP2_2=PA5,
|
||||
EXP2_3=PE2, EXP2_4=PE4,
|
||||
EXP2_5=PE3, EXP2_6=PA7,
|
||||
EXP2_7=PE5, EXP2_8=<RST>,
|
||||
EXP2_9=<GND>, EXP2_10=PE4,
|
||||
|
||||
# See the sample-lcd.cfg file for definitions of common LCD displays.
|
||||
|
||||
# EXTENSION PORT
|
||||
EXP3_1=<5V>, EXP3_2=<5V>, # max. 0.5A
|
||||
EXP3_3=<GND>, EXP3_4=<GND>,
|
||||
EXP3_5=<3.3V>, EXP3_6=<3.3V>, # max. 0.5A
|
||||
EXP3_7=PF5, EXP3_8=PF4,
|
||||
EXP3_9=PF3, EXP3_10=PF2,
|
||||
EXP3_11=PC4, EXP3_12=PC5, # EXP3_11 and EXP3_12 are ADC inputs
|
||||
EXP3_13=PB0, EXP3_14=PB1, # EXP3_13 and EXP3_14 are ADC inputs
|
||||
EXP3_15=PE8, EXP3_16=PE7, # EXP3_15 is UART5_TX, EXP3_16 is UART5_RX
|
||||
EXP3_17=PG5, EXP3_18=PG4,
|
||||
EXP3_19=PG3, EXP3_20=PG2,
|
||||
EXP3_21=PD15, EXP3_22=PD14,
|
||||
EXP3_23=PB15, EXP3_24=PB14, # EXP3_23 is SPI2_MOSI
|
||||
# EXP3_24 is SPI2_MISO
|
||||
EXP3_25=PB13, EXP3_26=PB12, # EXP3_25 is SPI2_SCK + CAN2_TX
|
||||
# EXP3_26 is SPI2_CS + CAN2_RX
|
||||
EXP3_27=<GND>, EXP3_28=<GND>,
|
||||
EXP3_29=<24V>, EXP3_30=<24V>, # max. 0.5A
|
||||
|
||||
#[probe]
|
||||
#sensor_pin: PF1 # Z-PROBE
|
||||
#z_offset: 0
|
||||
|
||||
#[led my_led]
|
||||
#white_pin: PE6 # LED-Strip
|
||||
|
||||
#[neopixel my_neopixel]
|
||||
#pin: PF10 # NEOPIXEL
|
||||
|
||||
#[temperature_sensor TH2]
|
||||
#sensor_type: ATC Semitec 104GT-2
|
||||
#sensor_pin: PA0 # TH2
|
||||
#pullup_resistor: 2200
|
||||
|
||||
#[temperature_sensor TH3]
|
||||
#sensor_type: ATC Semitec 104GT-2
|
||||
#sensor_pin: PA3 # TH3
|
||||
#pullup_resistor: 2200
|
||||
@@ -84,7 +84,7 @@ pwm: True
|
||||
scale: 2.0
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.3
|
||||
value: 1.3
|
||||
|
||||
[output_pin stepper_z_current]
|
||||
pin: PL4
|
||||
@@ -92,7 +92,7 @@ pwm: True
|
||||
scale: 2.0
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.3
|
||||
value: 1.3
|
||||
|
||||
[output_pin stepper_e_current]
|
||||
pin: PL5
|
||||
@@ -100,7 +100,7 @@ pwm: True
|
||||
scale: 2.0
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.25
|
||||
value: 1.25
|
||||
|
||||
[static_digital_output stepper_config]
|
||||
pins:
|
||||
|
||||
@@ -97,7 +97,7 @@ max_z_accel: 30
|
||||
|
||||
[output_pin case_light]
|
||||
pin: PH5
|
||||
static_value: 1.0
|
||||
value: 1.0
|
||||
|
||||
# Motor current settings.
|
||||
[output_pin stepper_xy_current]
|
||||
@@ -107,7 +107,7 @@ scale: 2.000
|
||||
# Max power setting.
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.200
|
||||
value: 1.200
|
||||
# Power adjustment setting.
|
||||
|
||||
[output_pin stepper_z_current]
|
||||
@@ -116,7 +116,7 @@ pwm: True
|
||||
scale: 2.000
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.200
|
||||
value: 1.200
|
||||
|
||||
[output_pin stepper_e_current]
|
||||
pin: PL3
|
||||
@@ -124,4 +124,4 @@ pwm: True
|
||||
scale: 2.000
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.250
|
||||
value: 1.250
|
||||
|
||||
@@ -89,7 +89,7 @@ pwm: True
|
||||
scale: 2.0
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.3
|
||||
value: 1.3
|
||||
|
||||
[output_pin stepper_z_current]
|
||||
pin: PL4
|
||||
@@ -97,7 +97,7 @@ pwm: True
|
||||
scale: 2.0
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.3
|
||||
value: 1.3
|
||||
|
||||
[output_pin stepper_e_current]
|
||||
pin: PL3
|
||||
@@ -105,7 +105,7 @@ pwm: True
|
||||
scale: 2.0
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.25
|
||||
value: 1.25
|
||||
|
||||
[display]
|
||||
lcd_type: st7920
|
||||
|
||||
@@ -126,7 +126,6 @@ restart_method: arduino
|
||||
kinematics: cartesian
|
||||
max_velocity: 150
|
||||
max_accel: 3000
|
||||
max_accel_to_decel: 1500
|
||||
max_z_velocity: 7
|
||||
max_z_accel: 50
|
||||
square_corner_velocity: 5
|
||||
|
||||
@@ -118,7 +118,7 @@ cycle_time: 0.00005 #20kHz
|
||||
|
||||
[output_pin enable_pin]
|
||||
pin: PB6
|
||||
static_value: 1
|
||||
value: 1
|
||||
#This pin enables the bed, hotend, extruder fan, part fan.
|
||||
|
||||
[mcu]
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
# To build the firmware, use the following configuration:
|
||||
# - Micro-controller: Huada Semiconductor HC32F460
|
||||
# - Communication interface: Serial (PA3 & PA2) - Anycube
|
||||
# - Clock Speed: 200 MHz
|
||||
#
|
||||
# Installation:
|
||||
# 1. Rename the klipper bin to `firmware.bin` and copy it to an SD Card.
|
||||
@@ -144,10 +145,9 @@ max_temp: 120
|
||||
pause_on_runout: True
|
||||
switch_pin: !PC13
|
||||
|
||||
[heater_fan controller_fan]
|
||||
[controller_fan controller_fan]
|
||||
pin: PA14
|
||||
heater: heater_bed
|
||||
heater_temp: 45.0
|
||||
|
||||
[heater_fan hotend_fan]
|
||||
pin: PA13
|
||||
|
||||
126
config/printer-artillery-genius-pro-2022.cfg
Normal file
126
config/printer-artillery-genius-pro-2022.cfg
Normal file
@@ -0,0 +1,126 @@
|
||||
# This file contains pin mappings for the Artillery Genius Pro (2022)
|
||||
# with a Artillery_Ruby-v1.2 board. To use this config, during "make menuconfig"
|
||||
# select the STM32F401 with "No bootloader" and USB (on PA11/PA12)
|
||||
# communication.
|
||||
|
||||
# To flash this firmware, set the physical bridge between +3.3V and Boot0 PIN
|
||||
# on Artillery_Ruby mainboard. Then run the command:
|
||||
# make flash FLASH_DEVICE=/dev/serial/by-id/usb-Klipper_stm32f401xc_*-if00
|
||||
|
||||
# See docs/Config_Reference.md for a description of parameters.
|
||||
|
||||
[extruder]
|
||||
max_extrude_only_distance: 700.0
|
||||
step_pin: PA7
|
||||
dir_pin: PA6
|
||||
enable_pin: !PC4
|
||||
microsteps: 16
|
||||
rotation_distance: 7.1910
|
||||
nozzle_diameter: 0.400
|
||||
filament_diameter: 1.750
|
||||
heater_pin: PC9
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
sensor_pin: PC0
|
||||
min_temp: 0
|
||||
max_temp: 250
|
||||
control: pid
|
||||
pid_Kp: 23.223
|
||||
pid_Ki: 1.518
|
||||
pid_Kd: 88.826
|
||||
|
||||
[stepper_x]
|
||||
step_pin: !PB14
|
||||
dir_pin: PB13
|
||||
enable_pin: !PB15
|
||||
microsteps: 16
|
||||
rotation_distance: 40
|
||||
endstop_pin: !PA2
|
||||
position_endstop: 0
|
||||
position_max: 220
|
||||
homing_speed: 60
|
||||
|
||||
[stepper_y]
|
||||
step_pin: PB10
|
||||
dir_pin: PB2
|
||||
enable_pin: !PB12
|
||||
microsteps: 16
|
||||
rotation_distance: 40
|
||||
endstop_pin: !PA1
|
||||
position_endstop: 0
|
||||
position_max: 220
|
||||
homing_speed: 60
|
||||
|
||||
[stepper_z]
|
||||
step_pin: PB0
|
||||
dir_pin: !PC5
|
||||
enable_pin: !PB1
|
||||
microsteps: 16
|
||||
rotation_distance: 8
|
||||
endstop_pin: probe:z_virtual_endstop
|
||||
position_max: 250
|
||||
position_min: -5
|
||||
|
||||
[heater_bed]
|
||||
heater_pin: PA8
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
sensor_pin: PC1
|
||||
min_temp: 0
|
||||
max_temp: 130
|
||||
control: pid
|
||||
pid_Kp: 23.223
|
||||
pid_Ki: 1.518
|
||||
pid_Kd: 88.826
|
||||
|
||||
[bed_screws]
|
||||
screw1: 38,45
|
||||
screw2: 180,45
|
||||
screw3: 180,180
|
||||
screw4: 38,180
|
||||
|
||||
[fan]
|
||||
pin: PC8
|
||||
off_below: 0.1
|
||||
|
||||
[heater_fan hotend_fan]
|
||||
pin: PC7
|
||||
heater: extruder
|
||||
heater_temp: 50.0
|
||||
|
||||
[controller_fan stepper_fan]
|
||||
pin: PC6
|
||||
idle_timeout: 300
|
||||
|
||||
[mcu]
|
||||
serial: /dev/serial/by-id/usb-Klipper_stm32f401xc_
|
||||
|
||||
[printer]
|
||||
kinematics: cartesian
|
||||
max_velocity: 500
|
||||
max_accel: 4000
|
||||
max_z_velocity: 50
|
||||
square_corner_velocity: 5.0
|
||||
max_z_accel: 100
|
||||
|
||||
[bltouch]
|
||||
sensor_pin: PC2
|
||||
control_pin: PC3
|
||||
x_offset:27.25
|
||||
y_offset:-12.8
|
||||
z_offset: 0.25
|
||||
speed:10
|
||||
samples:1
|
||||
samples_result:average
|
||||
|
||||
[bed_mesh]
|
||||
speed: 800
|
||||
mesh_min: 30, 20
|
||||
mesh_max: 210, 200
|
||||
probe_count: 5,5
|
||||
algorithm: bicubic
|
||||
move_check_distance: 3.0
|
||||
|
||||
[safe_z_home]
|
||||
home_xy_position: 110,110
|
||||
speed: 100
|
||||
z_hop: 10
|
||||
z_hop_speed: 5
|
||||
188
config/printer-artillery-sidewinder-x3-plus-2024.cfg
Normal file
188
config/printer-artillery-sidewinder-x3-plus-2024.cfg
Normal file
@@ -0,0 +1,188 @@
|
||||
# For the Artillery Sidewinder X3 Pro/Plus that came factory installed with V1.29 firmware, follow these steps.
|
||||
# - Compile with the processor model STM32F401.
|
||||
# - Select the 48KiB bootloader,
|
||||
# - Select USB PA11/PA12 for USB communication interface.
|
||||
# - Select USART2 PA3/PA2 for UART communication via the Wi-Fi Tx/Rx pins
|
||||
# To set 48KiB bootloader, you need to make a change to make menuconfig Kconfig file
|
||||
# Here is a link to a how-to video: https://youtu.be/dpc76zN7Dh0
|
||||
# Rename klipper.bin to yuntu.bin
|
||||
# Copy the file out/yuntu.bin to an SD card and then restart the printer with that SD card
|
||||
#
|
||||
# For models that did not come with V1.29 installed
|
||||
# - Compile with the processor model STM32F401.
|
||||
# - Select the NO BOOTLOADER
|
||||
# - Select USB PA11/PA12 for USB communication interface.
|
||||
# - Select USART2 PA3/PA2 for UART communication via the Wi-Fi Tx/Rx pins
|
||||
# - quit, save, make
|
||||
# - Connect your printer to a computer running Pronterface, Octoprint, Repetier, BedLeveler5000 (anything with Console capability)
|
||||
# - Power on the machine and send M997 through console into Marlin, this will put the board into "DFU" mode
|
||||
# - DO NOT TURN OFF THE PRINTER
|
||||
# - Connect your Linux/Klipper device to the USB port
|
||||
# - Run lsusb and verify that the STM32 DFU device is visible (Bus 001 Device 006: ID 0483:df11 STMicroelectronics STM Device in DFU Mode)
|
||||
# - Run sudo make flash 0483:df11
|
||||
# - Run lsusb again and there should be two devices:
|
||||
# Bus 001 Device 007: ID 1d50:614e OpenMoko, Inc. stm32f401xc
|
||||
# Bus 001 Device 003: ID 0cf3:e010 Qualcomm Atheros Communications stm32f401xc
|
||||
# See docs/Config_Reference.md for a description of parameters.
|
||||
|
||||
[mcu]
|
||||
serial: /dev/ttyACM0
|
||||
restart_method: command
|
||||
|
||||
[printer]
|
||||
kinematics: cartesian
|
||||
max_velocity: 300
|
||||
max_accel: 3000
|
||||
max_z_velocity: 15
|
||||
max_z_accel: 100
|
||||
square_corner_velocity: 5
|
||||
|
||||
[led LED_Light]
|
||||
white_pin: PC2
|
||||
initial_white: 1.0
|
||||
|
||||
[neopixel hotend_neopixel]
|
||||
pin: PD2
|
||||
color_order: GRB
|
||||
initial_RED: 1.0
|
||||
initial_GREEN: 1.0
|
||||
initial_BLUE: 1.0
|
||||
|
||||
[stepper_x]
|
||||
step_pin: PA8
|
||||
dir_pin: PC9
|
||||
enable_pin: !PA15
|
||||
microsteps: 16
|
||||
rotation_distance: 40
|
||||
endstop_pin: !PB9
|
||||
position_min: 0
|
||||
position_endstop: 0
|
||||
position_max: 315
|
||||
homing_speed: 50
|
||||
|
||||
[stepper_y]
|
||||
step_pin: PC7
|
||||
dir_pin: !PC6
|
||||
enable_pin: !PC8
|
||||
microsteps: 16
|
||||
rotation_distance: 40
|
||||
endstop_pin: !PB8
|
||||
position_endstop: 0
|
||||
position_max: 315
|
||||
homing_speed: 50
|
||||
|
||||
[stepper_z]
|
||||
step_pin: PB10
|
||||
dir_pin: !PA4
|
||||
enable_pin: !PC4
|
||||
rotation_distance: 8
|
||||
microsteps: 16
|
||||
position_min: -1
|
||||
position_max: 400
|
||||
endstop_pin: probe:z_virtual_endstop # Use Z- as endstop
|
||||
#homing_speed: 10.0
|
||||
|
||||
[extruder]
|
||||
max_extrude_only_distance: 100.0
|
||||
step_pin: PC11
|
||||
dir_pin: !PC10
|
||||
enable_pin: !PC12
|
||||
microsteps: 64
|
||||
nozzle_diameter: 0.400
|
||||
filament_diameter: 1.750
|
||||
heater_pin: PA6
|
||||
sensor_type: EPCOS 100K B57560G104F #Generic 3950
|
||||
sensor_pin: PC5
|
||||
min_extrude_temp: 170
|
||||
min_temp: 0
|
||||
max_temp: 300
|
||||
# Calibrate E-Steps https://www.klipper3d.org/Rotation_Distance.html#calibrating-rotation_distance-on-extruders
|
||||
rotation_distance: 17.75
|
||||
# Calibrate PID: https://www.klipper3d.org/Config_checks.html#calibrate-pid-settings
|
||||
# - Example: PID_CALIBRATE HEATER=extruder TARGET=200
|
||||
control: pid
|
||||
pid_kp: 30.356
|
||||
pid_ki: 1.857
|
||||
pid_kd: 124.081
|
||||
# Calibrate PA: https://www.klipper3d.org/Pressure_Advance.html
|
||||
|
||||
[heater_bed]
|
||||
heater_pin: PA7
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
sensor_pin: PC0
|
||||
max_temp: 100
|
||||
min_temp: 0
|
||||
# Calibrate PID: https://www.klipper3d.org/Config_checks.html#calibrate-pid-settings
|
||||
# - Example: PID_CALIBRATE HEATER=heater_bed TARGET=60
|
||||
control: pid
|
||||
pid_kp: 64.230
|
||||
pid_ki: 0.723
|
||||
pid_kd: 1425.905
|
||||
|
||||
[heater_fan hotend_fan]
|
||||
pin: PB1
|
||||
heater: extruder
|
||||
heater_temp: 50.0
|
||||
|
||||
[fan]
|
||||
pin: PB0
|
||||
|
||||
[temperature_fan Artillery_MCU]
|
||||
sensor_type: temperature_mcu
|
||||
pin: PA5
|
||||
max_temp: 60.0
|
||||
target_temp: 40.0
|
||||
min_temp: 0
|
||||
shutdown_speed: 0.0
|
||||
kick_start_time: 0.5
|
||||
off_below: 0.19
|
||||
max_speed: 1.0
|
||||
min_speed: 0.0
|
||||
control: watermark
|
||||
|
||||
[filament_switch_sensor filament_sensor]
|
||||
pause_on_runout: true
|
||||
switch_pin: PC1
|
||||
|
||||
[probe]
|
||||
pin: PC14
|
||||
x_offset:45.2
|
||||
y_offset:11.6
|
||||
speed:5
|
||||
lift_speed:15
|
||||
z_offset: 2.350
|
||||
|
||||
[safe_z_home]
|
||||
home_xy_position: 110, 145 # X, Y coordinate (e.g. 100, 100) where the Z homing should be
|
||||
speed: 300.0
|
||||
z_hop: 10
|
||||
z_hop_speed: 15.0
|
||||
|
||||
[bed_mesh]
|
||||
speed: 300
|
||||
horizontal_move_z: 6
|
||||
mesh_min: 46,15
|
||||
mesh_max: 300,300
|
||||
probe_count: 10, 10
|
||||
fade_start: 1.0
|
||||
fade_end: 0.0
|
||||
algorithm: bicubic
|
||||
|
||||
[screws_tilt_adjust]
|
||||
screw1: 120, 153
|
||||
screw1_name: center reference
|
||||
screw2: 7, 45
|
||||
screw2_name: front left
|
||||
screw3: 210, 45
|
||||
screw3_name: front right
|
||||
screw4: 227, 145
|
||||
screw4_name: right center
|
||||
screw5: 210, 245
|
||||
screw5_name: rear right
|
||||
screw6: 7, 245
|
||||
screw6_name: rear left
|
||||
screw7: 7, 145
|
||||
screw7_name: left center
|
||||
horizontal_move_z: 8
|
||||
speed: 300
|
||||
screw_thread: CW-M4
|
||||
@@ -98,7 +98,6 @@ max_temp: 100
|
||||
|
||||
[output_pin led]
|
||||
pin: PC14
|
||||
static_value: 0
|
||||
|
||||
# Neopixel LED support
|
||||
# [neopixel led_neopixel]
|
||||
|
||||
@@ -98,6 +98,10 @@ z_offset: 0.0
|
||||
speed: 2.0
|
||||
samples: 5
|
||||
|
||||
[safe_z_home]
|
||||
home_xy_position: 117, 117
|
||||
z_hop: 10
|
||||
|
||||
[filament_switch_sensor filament_sensor]
|
||||
pause_on_runout: true
|
||||
switch_pin: ^!PA7
|
||||
|
||||
@@ -98,6 +98,10 @@ z_offset: 0.0
|
||||
speed: 2.0
|
||||
samples: 5
|
||||
|
||||
[safe_z_home]
|
||||
home_xy_position: 117, 117
|
||||
z_hop: 10
|
||||
|
||||
[filament_switch_sensor filament_sensor]
|
||||
pause_on_runout: true
|
||||
switch_pin: ^!PA7
|
||||
|
||||
170
config/printer-creality-ender5-s1-2023.cfg
Normal file
170
config/printer-creality-ender5-s1-2023.cfg
Normal file
@@ -0,0 +1,170 @@
|
||||
# Creality Ender 5 S1 (HW version: CR4NS200141C13)
|
||||
#
|
||||
# printer_size: 220x220x280
|
||||
# To use this config, during "make menuconfig" select the STM32F401
|
||||
# with a "64KiB bootloader" and serial (on USART1 PA10/PA9)
|
||||
# communication.
|
||||
#
|
||||
# Flash this firmware by creating a directory named "STM32F4_UPDATE"
|
||||
# on an SD card, copying the "out/klipper.bin" to it and then turn
|
||||
# on the printer with the card inserted. The firmware filename must
|
||||
# end in ".bin" and must not match the last filename that was flashed.
|
||||
#
|
||||
# See docs/Config_Reference.md for a description of parameters.
|
||||
|
||||
[stepper_x]
|
||||
step_pin: PC2
|
||||
dir_pin: !PB9
|
||||
enable_pin: !PC3
|
||||
rotation_distance: 40
|
||||
microsteps: 16
|
||||
endstop_pin: !PA5
|
||||
position_endstop: 220
|
||||
position_max: 222
|
||||
homing_speed: 80
|
||||
|
||||
[stepper_y]
|
||||
step_pin: PB8
|
||||
dir_pin: !PB7
|
||||
enable_pin: !PC3
|
||||
rotation_distance: 40
|
||||
microsteps: 16
|
||||
endstop_pin: !PA6
|
||||
position_endstop: 220
|
||||
position_max: 220
|
||||
homing_speed: 80
|
||||
|
||||
[stepper_z]
|
||||
step_pin: PB6
|
||||
dir_pin: PB5
|
||||
enable_pin: !PC3
|
||||
rotation_distance: 8
|
||||
microsteps: 16
|
||||
endstop_pin: probe:z_virtual_endstop
|
||||
position_max: 280
|
||||
homing_speed: 20
|
||||
second_homing_speed: 1
|
||||
homing_retract_dist: 2.0
|
||||
|
||||
[extruder]
|
||||
step_pin: PB4
|
||||
dir_pin: PB3
|
||||
enable_pin: !PC3
|
||||
rotation_distance: 7.5
|
||||
microsteps: 16
|
||||
nozzle_diameter: 0.400
|
||||
filament_diameter: 1.750
|
||||
heater_pin: PA1
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
sensor_pin: PC5
|
||||
control: pid # tuned for stock hardware with 210 degree Celsius target
|
||||
pid_kp: 20.749
|
||||
pid_ki: 1.064
|
||||
pid_kd: 101.153
|
||||
min_temp: 0
|
||||
max_temp: 305
|
||||
|
||||
[heater_bed]
|
||||
heater_pin: PA7
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
sensor_pin: PC4
|
||||
control: pid # tuned for stock hardware with 60 degree Celsius target
|
||||
pid_kp: 66.566
|
||||
pid_ki: 0.958
|
||||
pid_kd: 1155.761
|
||||
min_temp: 0
|
||||
max_temp: 110
|
||||
|
||||
# Part cooling fan
|
||||
[fan]
|
||||
pin: PA0
|
||||
kick_start_time: 0.5
|
||||
|
||||
# Hotend fan
|
||||
# set fan runnig when extruder temperature is over 60
|
||||
[heater_fan heatbreak_fan]
|
||||
pin: PC0
|
||||
heater:extruder
|
||||
heater_temp: 60
|
||||
fan_speed: 0.8
|
||||
|
||||
[filament_switch_sensor filament_sensor]
|
||||
pause_on_runout: true
|
||||
switch_pin: ^!PC15
|
||||
|
||||
# Stock CR Touch bed sensor
|
||||
[bltouch]
|
||||
sensor_pin: ^PC14
|
||||
control_pin: PC13
|
||||
x_offset: -13
|
||||
y_offset: 27
|
||||
z_offset: 2.0
|
||||
speed: 10
|
||||
stow_on_each_sample: true # Occasional bed crashes when false
|
||||
samples: 4
|
||||
sample_retract_dist: 2
|
||||
samples_result: average
|
||||
probe_with_touch_mode: true
|
||||
|
||||
[bed_mesh]
|
||||
speed: 150
|
||||
mesh_min: 3,28 # need to handle head distance with bl_touch
|
||||
mesh_max: 205,218
|
||||
mesh_pps: 3
|
||||
probe_count: 4,4
|
||||
fade_start: 1
|
||||
fade_end: 10
|
||||
fade_target: 0
|
||||
|
||||
[mcu]
|
||||
serial: /dev/serial/by-id/usb-1a86_USB_Serial-if00-port0
|
||||
restart_method: command
|
||||
|
||||
[safe_z_home]
|
||||
home_xy_position: 123,83
|
||||
speed: 200
|
||||
z_hop: 10
|
||||
z_hop_speed: 10
|
||||
|
||||
# Many Ender 5 S1 printers appear to suffer from a slight twist
|
||||
# in the X axis. This twist can be measured, and compensated for
|
||||
# using the AXIS_TWIST_COMPENSATION_CALIBRATE G-Code command. See
|
||||
# https://www.klipper3d.org/Axis_Twist_Compensation.html for more
|
||||
# information. This section provides the setup for this optional
|
||||
# calibration step.
|
||||
[axis_twist_compensation]
|
||||
calibrate_start_x: 3
|
||||
calibrate_end_x: 207
|
||||
calibrate_y: 110
|
||||
|
||||
# Probe locations for assisted bed screw adjustment.
|
||||
[screws_tilt_adjust]
|
||||
screw1: 38,6
|
||||
screw1_name: Front Left Screw
|
||||
screw2: 215,6
|
||||
screw2_name: Front Right Screw
|
||||
screw3: 215,175
|
||||
screw3_name: Rear Right Screw
|
||||
screw4: 38,175
|
||||
screw4_name: Rear Left Screw
|
||||
horizontal_move_z: 5
|
||||
speed: 100
|
||||
screw_thread: CW-M4
|
||||
|
||||
[bed_screws]
|
||||
screw1: 25,25
|
||||
screw1_name: Front Left Screw
|
||||
screw2: 195,25
|
||||
screw2_name: Front Right Screw
|
||||
screw3: 195,195
|
||||
screw3_name: Rear Right Screw
|
||||
screw4: 25,195
|
||||
screw4_name: Rear Left Screw
|
||||
|
||||
[printer]
|
||||
kinematics: cartesian
|
||||
max_velocity: 300
|
||||
max_accel: 5000
|
||||
max_z_velocity: 5
|
||||
max_z_accel: 100
|
||||
square_corner_velocity: 5.0
|
||||
@@ -71,25 +71,21 @@ pid_Kp: 39
|
||||
pid_Ki: 2
|
||||
pid_Kd: 210
|
||||
|
||||
[extruder1]
|
||||
[extruder_stepper e1]
|
||||
extruder:
|
||||
step_pin: PA0
|
||||
dir_pin: !PB6
|
||||
enable_pin: !PA1
|
||||
microsteps: 16
|
||||
rotation_distance: 32
|
||||
nozzle_diameter: 0.4
|
||||
filament_diameter: 1.75
|
||||
shared_heater: extruder
|
||||
|
||||
[extruder2]
|
||||
[extruder_stepper e2]
|
||||
extruder:
|
||||
step_pin: PB2
|
||||
dir_pin: !PB11
|
||||
enable_pin: !PC4
|
||||
microsteps: 16
|
||||
rotation_distance: 32
|
||||
nozzle_diameter: 0.4
|
||||
filament_diameter: 1.75
|
||||
shared_heater: extruder
|
||||
|
||||
[heater_bed]
|
||||
heater_pin: PB1
|
||||
|
||||
@@ -125,7 +125,7 @@ pwm: True
|
||||
scale: 2.0
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.300
|
||||
value: 1.300
|
||||
|
||||
[output_pin stepper_z_current]
|
||||
pin: PL4
|
||||
@@ -133,7 +133,7 @@ pwm: True
|
||||
scale: 2.0
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.630
|
||||
value: 1.630
|
||||
|
||||
[output_pin stepper_e_current]
|
||||
pin: PL5
|
||||
@@ -141,7 +141,7 @@ pwm: True
|
||||
scale: 2.0
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.250
|
||||
value: 1.250
|
||||
|
||||
[static_digital_output stepper_config]
|
||||
# Microstepping pins
|
||||
|
||||
@@ -199,7 +199,6 @@ algorithm: bicubic
|
||||
bicubic_tension: 0.15
|
||||
fade_start: 0.5
|
||||
fade_end: 2.5
|
||||
relative_reference_index: 60
|
||||
|
||||
[bed_screws]
|
||||
screw1: 0,0
|
||||
|
||||
@@ -19,7 +19,7 @@ restart_method: command
|
||||
kinematics: cartesian
|
||||
max_velocity: 300
|
||||
max_accel: 1000
|
||||
max_accel_to_decel: 1000
|
||||
minimum_cruise_ratio: 0.0
|
||||
max_z_velocity: 5
|
||||
max_z_accel: 100
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ microsteps: 16
|
||||
rotation_distance: 40
|
||||
endstop_pin: tmc2209_stepper_x:virtual_endstop
|
||||
position_endstop: 0
|
||||
position_max: 225
|
||||
position_max: 220
|
||||
homing_speed: 40
|
||||
homing_retract_dist: 0
|
||||
|
||||
@@ -50,7 +50,7 @@ microsteps: 16
|
||||
rotation_distance: 40
|
||||
endstop_pin: tmc2209_stepper_y:virtual_endstop
|
||||
position_endstop: 0
|
||||
position_max: 225
|
||||
position_max: 220
|
||||
homing_speed: 40
|
||||
homing_retract_dist: 0
|
||||
|
||||
@@ -72,7 +72,7 @@ microsteps: 16
|
||||
rotation_distance: 4
|
||||
endstop_pin: probe:z_virtual_endstop
|
||||
position_min: -4
|
||||
position_max: 261
|
||||
position_max: 250
|
||||
homing_speed: 4
|
||||
|
||||
[tmc2209 stepper_z]
|
||||
@@ -127,7 +127,7 @@ pin: PA0
|
||||
|
||||
[probe]
|
||||
pin: PB1
|
||||
x_offset: 28
|
||||
x_offset: 27
|
||||
y_offset: -20
|
||||
z_offset: 0
|
||||
samples: 2
|
||||
|
||||
147
config/printer-sovol-sv06-plus-2023.cfg
Normal file
147
config/printer-sovol-sv06-plus-2023.cfg
Normal file
@@ -0,0 +1,147 @@
|
||||
# This file contains pin mappings for the stock Sovol SV06 Plus
|
||||
# To use this config, during "make menuconfig" select the
|
||||
# STM32F103 with a "28KiB bootloader" and serial (on USART1 PA10/PA9) communication.
|
||||
# Also, since it is using the GD32F103, please select Disable SWD at startup
|
||||
#
|
||||
# Flash this firmware by copying "out/klipper.bin" to a SD card and
|
||||
# turning on the printer with the card inserted. The firmware
|
||||
# filename must end in ".bin" and must not match the last filename
|
||||
# that was flashed.
|
||||
#
|
||||
# Note: The stock LCD display does not currently work with Klipper
|
||||
#
|
||||
# See docs/Config_Reference.md for a description of parameters.
|
||||
[mcu]
|
||||
serial: /dev/serial/by-id/usb-1a86_USB2.0-Serial-if00-port0
|
||||
restart_method: command
|
||||
|
||||
[printer]
|
||||
kinematics: cartesian
|
||||
max_velocity: 500
|
||||
max_accel: 2000
|
||||
max_z_velocity: 10
|
||||
max_z_accel: 100
|
||||
|
||||
[stepper_x]
|
||||
step_pin: PC2
|
||||
dir_pin: !PB9
|
||||
enable_pin: !PC3
|
||||
microsteps: 16
|
||||
rotation_distance: 40
|
||||
endstop_pin: tmc2209_stepper_x:virtual_endstop
|
||||
position_endstop: 0
|
||||
position_max: 305
|
||||
homing_speed: 40
|
||||
homing_retract_dist: 0
|
||||
|
||||
[tmc2209 stepper_x]
|
||||
uart_pin: PC1
|
||||
run_current: 0.860
|
||||
sense_resistor: 0.150
|
||||
uart_address: 3
|
||||
driver_SGTHRS: 86
|
||||
diag_pin: PA5
|
||||
|
||||
[stepper_y]
|
||||
step_pin: PB8
|
||||
dir_pin: PB7
|
||||
enable_pin: !PC3
|
||||
microsteps: 16
|
||||
rotation_distance: 40
|
||||
endstop_pin: tmc2209_stepper_y:virtual_endstop
|
||||
position_endstop: 0
|
||||
position_max: 305
|
||||
homing_speed: 40
|
||||
homing_retract_dist: 0
|
||||
|
||||
[tmc2209 stepper_y]
|
||||
uart_pin: PC0
|
||||
run_current: 0.900
|
||||
sense_resistor: 0.150
|
||||
uart_address: 3
|
||||
driver_SGTHRS: 110
|
||||
diag_pin: PA6
|
||||
|
||||
[stepper_z]
|
||||
step_pin: PB6
|
||||
dir_pin: !PB5
|
||||
enable_pin: !PC3
|
||||
microsteps: 16
|
||||
rotation_distance: 4
|
||||
endstop_pin: probe:z_virtual_endstop
|
||||
position_min: -4
|
||||
position_max: 350
|
||||
homing_speed: 4
|
||||
|
||||
[tmc2209 stepper_z]
|
||||
uart_pin: PA15
|
||||
run_current: 1.000
|
||||
interpolate: False
|
||||
sense_resistor: 0.150
|
||||
uart_address: 3
|
||||
diag_pin: PA7
|
||||
|
||||
[extruder]
|
||||
max_extrude_only_distance: 100.0
|
||||
step_pin: PB4
|
||||
dir_pin: !PB3
|
||||
enable_pin: !PC3
|
||||
microsteps: 16
|
||||
rotation_distance: 4.56
|
||||
nozzle_diameter: 0.400
|
||||
filament_diameter: 1.750
|
||||
heater_pin: PA1
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
sensor_pin: PC5
|
||||
control: pid
|
||||
pid_kd: 41.96
|
||||
pid_kp: 15.66
|
||||
pid_ki: 1.49
|
||||
min_temp: 0
|
||||
max_temp: 300
|
||||
|
||||
[tmc2209 extruder]
|
||||
uart_pin: PC14
|
||||
run_current: 0.550
|
||||
stealthchop_threshold: 0
|
||||
interpolate: False
|
||||
sense_resistor: 0.150
|
||||
uart_address: 3
|
||||
|
||||
[heater_bed]
|
||||
heater_pin: PA2
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
sensor_pin: PC4
|
||||
control: pid
|
||||
pid_kp: 186.38
|
||||
pid_ki: 36.12
|
||||
pid_kd: 637.30
|
||||
min_temp: 0
|
||||
max_temp: 130
|
||||
|
||||
[fan]
|
||||
pin: PA0
|
||||
|
||||
[probe]
|
||||
pin: PB1
|
||||
x_offset: 28
|
||||
y_offset: -20
|
||||
z_offset: 0
|
||||
|
||||
[safe_z_home]
|
||||
home_xy_position: 123,170
|
||||
z_hop: 10
|
||||
z_hop_speed: 5
|
||||
|
||||
[bed_mesh]
|
||||
speed: 120
|
||||
mesh_min: 28, 20
|
||||
mesh_max: 270, 270
|
||||
probe_count: 5
|
||||
algorithm: bicubic
|
||||
fade_end: 10
|
||||
fade_target: 0
|
||||
|
||||
[filament_switch_sensor filament_runout_sensor]
|
||||
switch_pin: PA4
|
||||
pause_on_runout: True
|
||||
138
config/printer-tronxy-crux1-2022.cfg
Normal file
138
config/printer-tronxy-crux1-2022.cfg
Normal file
@@ -0,0 +1,138 @@
|
||||
# Klipper configuration for the TronXY Crux1 printer
|
||||
# CXY-V10.1-220921 mainboard, GD32F4XX or STM32F446 MCU
|
||||
#
|
||||
# =======================
|
||||
# BUILD AND FLASH OPTIONS
|
||||
# =======================
|
||||
#
|
||||
# MCU-architecture: STMicroelectronics
|
||||
# Processor model: STM32F446
|
||||
# Bootloader offset: 64KiB
|
||||
# Comms interface: Serial on USART1 PA10/PA9
|
||||
#
|
||||
# Build the firmware with these options
|
||||
# Rename the resulting klipper.bin into fmw_tronxy.bin
|
||||
# Put the file into a directory called "update" on a FAT32 formatted SD card.
|
||||
# Turn off the printer, plug in the SD card and turn the printer back on
|
||||
# Flashing will start automatically and progress will be indicated on the LCD
|
||||
# Once the flashing is completed the display will get stuck on the white Tronxy logo bootscreen
|
||||
# The LCD display will NOT work anymore after flashing Klipper onto this printer
|
||||
|
||||
[mcu]
|
||||
serial: /dev/serial/by-id/usb-1a86_USB_Serial-if00-port0
|
||||
restart_method: command
|
||||
|
||||
[printer]
|
||||
kinematics: cartesian
|
||||
max_velocity: 250
|
||||
max_accel: 1500
|
||||
square_corner_velocity: 5
|
||||
max_z_velocity: 15
|
||||
max_z_accel: 100
|
||||
|
||||
[controller_fan drivers_fan]
|
||||
pin: PD7
|
||||
|
||||
[pwm_cycle_time BEEPER_pin]
|
||||
pin: PA8
|
||||
value: 0
|
||||
shutdown_value: 0
|
||||
cycle_time: 0.001
|
||||
|
||||
[safe_z_home]
|
||||
home_xy_position: 0, 0
|
||||
speed: 100
|
||||
z_hop: 10
|
||||
z_hop_speed: 5
|
||||
|
||||
[stepper_x]
|
||||
step_pin: PE5
|
||||
dir_pin: PF1
|
||||
enable_pin: !PF0
|
||||
microsteps: 16
|
||||
rotation_distance: 20
|
||||
endstop_pin: ^!PC15
|
||||
position_endstop: -1
|
||||
position_min: -1
|
||||
position_max: 180
|
||||
homing_speed: 100
|
||||
homing_retract_dist: 10
|
||||
second_homing_speed: 25
|
||||
|
||||
[stepper_y]
|
||||
step_pin: PF9
|
||||
dir_pin: !PF3
|
||||
enable_pin: !PF5
|
||||
microsteps: 16
|
||||
rotation_distance: 20
|
||||
endstop_pin: ^!PC14
|
||||
position_endstop: -3
|
||||
position_min: -3
|
||||
position_max: 180
|
||||
homing_retract_dist: 10
|
||||
homing_speed: 100
|
||||
second_homing_speed: 25
|
||||
|
||||
[stepper_z]
|
||||
step_pin: PA6
|
||||
dir_pin: !PF15
|
||||
enable_pin: !PA5
|
||||
microsteps: 16
|
||||
rotation_distance: 4
|
||||
endstop_pin: ^!PC13
|
||||
position_endstop: 0
|
||||
position_max: 180
|
||||
position_min: 0
|
||||
|
||||
[extruder]
|
||||
step_pin: PB1
|
||||
dir_pin: PF13
|
||||
enable_pin: !PF14
|
||||
microsteps: 16
|
||||
rotation_distance: 16.75
|
||||
nozzle_diameter: 0.400
|
||||
filament_diameter: 1.750
|
||||
heater_pin: PG7
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
sensor_pin: PC3
|
||||
control: pid
|
||||
pid_kp: 22.2
|
||||
pid_ki: 1.08
|
||||
pid_kd: 114.00
|
||||
min_temp: 0
|
||||
max_temp: 250
|
||||
min_extrude_temp: 170
|
||||
max_extrude_only_distance: 450
|
||||
|
||||
[heater_fan hotend_fan]
|
||||
heater: extruder
|
||||
heater_temp: 50.0
|
||||
pin: PG9
|
||||
|
||||
[fan]
|
||||
pin: PG0
|
||||
|
||||
[filament_switch_sensor filament_sensor]
|
||||
pause_on_runout: True
|
||||
switch_pin: ^!PE6
|
||||
|
||||
[heater_bed]
|
||||
heater_pin: PE2
|
||||
sensor_type: EPCOS 100K B57560G104F
|
||||
sensor_pin: PC2
|
||||
min_temp: 0
|
||||
max_temp: 130
|
||||
control: pid
|
||||
pid_kp: 10.00
|
||||
pid_ki: 0.023
|
||||
pid_kd: 305.4
|
||||
|
||||
[bed_screws]
|
||||
screw1: 17.5, 11
|
||||
screw1_name: front_left
|
||||
screw2: 162.5, 11
|
||||
screw2_name: front_right
|
||||
screw3: 162.5, 162.5
|
||||
screw3_name: back_right
|
||||
screw4: 17.5, 162.5
|
||||
screw4_name: back_left
|
||||
@@ -86,7 +86,7 @@ pwm: True
|
||||
scale: 2.782
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.2
|
||||
value: 1.2
|
||||
|
||||
[output_pin stepper_z_current]
|
||||
pin: PL4
|
||||
@@ -94,7 +94,7 @@ pwm: True
|
||||
scale: 2.782
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.2
|
||||
value: 1.2
|
||||
|
||||
[output_pin stepper_e_current]
|
||||
pin: PL3
|
||||
@@ -102,7 +102,7 @@ pwm: True
|
||||
scale: 2.782
|
||||
cycle_time: .000030
|
||||
hardware_pwm: True
|
||||
static_value: 1.0
|
||||
value: 1.0
|
||||
|
||||
[display]
|
||||
lcd_type: ssd1306
|
||||
|
||||
@@ -61,12 +61,10 @@ gcode:
|
||||
# P is the tone duration, S the tone frequency.
|
||||
# The frequency won't be pitch perfect.
|
||||
|
||||
[output_pin BEEPER_pin]
|
||||
[pwm_cycle_time BEEPER_pin]
|
||||
pin: ar37
|
||||
# Beeper pin. This parameter must be provided.
|
||||
# ar37 is the default RAMPS/MKS pin.
|
||||
pwm: True
|
||||
# A piezo beeper needs a PWM signal, a DC buzzer doesn't.
|
||||
value: 0
|
||||
# Silent at power on, set to 1 if active low.
|
||||
shutdown_value: 0
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
# such as a laser or spindle.
|
||||
# See docs/Using_PWM_Tools.md for a more detailed description.
|
||||
|
||||
[output_pin TOOL]
|
||||
[pwm_tool TOOL]
|
||||
pin: !ar9 # use your fan's pin number
|
||||
pwm: True
|
||||
hardware_pwm: True
|
||||
cycle_time: 0.001
|
||||
shutdown_value: 0
|
||||
@@ -36,9 +35,9 @@ gcode:
|
||||
|
||||
[menu __main __control __toolonoff]
|
||||
type: input
|
||||
enable: {'output_pin TOOL' in printer}
|
||||
enable: {'pwm_tool TOOL' in printer}
|
||||
name: Fan: {'ON ' if menu.input else 'OFF'}
|
||||
input: {printer['output_pin TOOL'].value}
|
||||
input: {printer['pwm_tool TOOL'].value}
|
||||
input_min: 0
|
||||
input_max: 1
|
||||
input_step: 1
|
||||
@@ -47,9 +46,9 @@ gcode:
|
||||
|
||||
[menu __main __control __toolspeed]
|
||||
type: input
|
||||
enable: {'output_pin TOOL' in printer}
|
||||
enable: {'pwm_tool TOOL' in printer}
|
||||
name: Tool speed: {'%3d' % (menu.input*100)}%
|
||||
input: {printer['output_pin TOOL'].value}
|
||||
input: {printer['pwm_tool TOOL'].value}
|
||||
input_min: 0
|
||||
input_max: 1
|
||||
input_step: 0.01
|
||||
|
||||
@@ -282,6 +282,22 @@ window" interface. Parsing content from the G-Code terminal output is
|
||||
discouraged. Use the "objects/subscribe" endpoint to obtain updates on
|
||||
Klipper's state.
|
||||
|
||||
### heaters/set_target_temperature
|
||||
|
||||
This endpoint is used to asynchronously set the target temperature for
|
||||
a heater. For example:
|
||||
`{"id": 123, "method": "heaters/set_target_temperature", "params":
|
||||
{"heater":"heater_generic my_heater", "target": 100.3}}`
|
||||
|
||||
This endpoint is similar to the `SET_HEATER_TEMPERATURE` G-Code
|
||||
command, but the target temperature takes effect immediately. It does
|
||||
not wait for pending G-Code commands to complete.
|
||||
|
||||
If this endpoint is issued for a heater while a `WAIT_TEMPERATURE`
|
||||
command (or `M109`, `M190`) is pending for that heater, then the
|
||||
requested target temperature will be set and the `WAIT_TEMPERATURE`
|
||||
command will exit with an error.
|
||||
|
||||
### motion_report/dump_stepper
|
||||
|
||||
This endpoint is used to subscribe to Klipper's internal stepper
|
||||
@@ -364,6 +380,36 @@ and might later produce asynchronous messages such as:
|
||||
The "header" field in the initial query response is used to describe
|
||||
the fields found in later "data" responses.
|
||||
|
||||
### hx71x/dump_hx71x
|
||||
|
||||
This endpoint is used to subscribe to raw HX711 and HX717 ADC data.
|
||||
Obtaining these low-level ADC updates may be useful for diagnostic
|
||||
and debugging purposes. Using this endpoint may increase Klipper's
|
||||
system load.
|
||||
|
||||
A request may look like:
|
||||
`{"id": 123, "method":"hx71x/dump_hx71x",
|
||||
"params": {"sensor": "load_cell", "response_template": {}}}`
|
||||
and might return:
|
||||
`{"id": 123,"result":{"header":["time","counts"]}}`
|
||||
and might later produce asynchronous messages such as:
|
||||
`{"params":{"data":[[3292.432935, 562534], [3292.4394937, 5625322]]}}`
|
||||
|
||||
### ads1220/dump_ads1220
|
||||
|
||||
This endpoint is used to subscribe to raw ADS1220 ADC data.
|
||||
Obtaining these low-level ADC updates may be useful for diagnostic
|
||||
and debugging purposes. Using this endpoint may increase Klipper's
|
||||
system load.
|
||||
|
||||
A request may look like:
|
||||
`{"id": 123, "method":"ads1220/dump_ads1220",
|
||||
"params": {"sensor": "load_cell", "response_template": {}}}`
|
||||
and might return:
|
||||
`{"id": 123,"result":{"header":["time","counts"]}}`
|
||||
and might later produce asynchronous messages such as:
|
||||
`{"params":{"data":[[3292.432935, 562534], [3292.4394937, 5625322]]}}`
|
||||
|
||||
### pause_resume/cancel
|
||||
|
||||
This endpoint is similar to running the "PRINT_CANCEL" G-Code command.
|
||||
@@ -401,3 +447,130 @@ might return:
|
||||
|
||||
As with the "gcode/script" endpoint, this endpoint only completes
|
||||
after any pending G-Code commands complete.
|
||||
|
||||
### bed_mesh/dump_mesh
|
||||
|
||||
Dumps the configuration and state for the current mesh and all
|
||||
saved profiles.
|
||||
|
||||
For example:
|
||||
`{"id": 123, "method": "bed_mesh/dump_mesh"}`
|
||||
|
||||
might return:
|
||||
|
||||
```
|
||||
{
|
||||
"current_mesh": {
|
||||
"name": "eddy-scan-test",
|
||||
"probed_matrix": [...],
|
||||
"mesh_matrix": [...],
|
||||
"mesh_params": {
|
||||
"x_count": 9,
|
||||
"y_count": 9,
|
||||
"mesh_x_pps": 2,
|
||||
"mesh_y_pps": 2,
|
||||
"algo": "bicubic",
|
||||
"tension": 0.5,
|
||||
"min_x": 20,
|
||||
"max_x": 330,
|
||||
"min_y": 30,
|
||||
"max_y": 320
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"default": {
|
||||
"points": [...],
|
||||
"mesh_params": {
|
||||
"min_x": 20,
|
||||
"max_x": 330,
|
||||
"min_y": 30,
|
||||
"max_y": 320,
|
||||
"x_count": 9,
|
||||
"y_count": 9,
|
||||
"mesh_x_pps": 2,
|
||||
"mesh_y_pps": 2,
|
||||
"algo": "bicubic",
|
||||
"tension": 0.5
|
||||
}
|
||||
},
|
||||
"eddy-scan-test": {
|
||||
"points": [...],
|
||||
"mesh_params": {
|
||||
"x_count": 9,
|
||||
"y_count": 9,
|
||||
"mesh_x_pps": 2,
|
||||
"mesh_y_pps": 2,
|
||||
"algo": "bicubic",
|
||||
"tension": 0.5,
|
||||
"min_x": 20,
|
||||
"max_x": 330,
|
||||
"min_y": 30,
|
||||
"max_y": 320
|
||||
}
|
||||
},
|
||||
"eddy-rapid-test": {
|
||||
"points": [...],
|
||||
"mesh_params": {
|
||||
"x_count": 9,
|
||||
"y_count": 9,
|
||||
"mesh_x_pps": 2,
|
||||
"mesh_y_pps": 2,
|
||||
"algo": "bicubic",
|
||||
"tension": 0.5,
|
||||
"min_x": 20,
|
||||
"max_x": 330,
|
||||
"min_y": 30,
|
||||
"max_y": 320
|
||||
}
|
||||
}
|
||||
},
|
||||
"calibration": {
|
||||
"points": [...],
|
||||
"config": {
|
||||
"x_count": 9,
|
||||
"y_count": 9,
|
||||
"mesh_x_pps": 2,
|
||||
"mesh_y_pps": 2,
|
||||
"algo": "bicubic",
|
||||
"tension": 0.5,
|
||||
"mesh_min": [
|
||||
20,
|
||||
30
|
||||
],
|
||||
"mesh_max": [
|
||||
330,
|
||||
320
|
||||
],
|
||||
"origin": null,
|
||||
"radius": null
|
||||
},
|
||||
"probe_path": [...],
|
||||
"rapid_path": [...]
|
||||
},
|
||||
"probe_offsets": [
|
||||
0,
|
||||
25,
|
||||
0.5
|
||||
],
|
||||
"axis_minimum": [
|
||||
0,
|
||||
0,
|
||||
-5,
|
||||
0
|
||||
],
|
||||
"axis_maximum": [
|
||||
351,
|
||||
358,
|
||||
330,
|
||||
0
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The `dump_mesh` endpoint takes one optional parameter, `mesh_args`.
|
||||
This parameter must be an object, where the keys and values are
|
||||
parameters available to [BED_MESH_CALIBRATE](#bed_mesh_calibrate).
|
||||
This will update the mesh configuration and probe points using the
|
||||
supplied parameters prior to returning the result. It is recommended
|
||||
to omit mesh parameters unless it is desired to visualize the probe points
|
||||
and/or travel path before performing `BED_MESH_CALIBRATE`.
|
||||
|
||||
@@ -6,23 +6,64 @@ PRU.
|
||||
## Building an OS image
|
||||
|
||||
Start by installing the
|
||||
[Debian 9.9 2019-08-03 4GB SD IoT](https://beagleboard.org/latest-images)
|
||||
[Debian 11.7 2023-09-02 4GB microSD IoT](https://beagleboard.org/latest-images)
|
||||
image. One may run the image from either a micro-SD card or from
|
||||
builtin eMMC. If using the eMMC, install it to eMMC now by following
|
||||
the instructions from the above link.
|
||||
|
||||
Then ssh into the Beaglebone machine (`ssh debian@beaglebone` --
|
||||
password is `temppwd`) and install Klipper by running the following
|
||||
password is `temppwd`).
|
||||
|
||||
Before start installing Klipper you need to free-up additional space.
|
||||
there are 3 options to do that:
|
||||
1. remove some BeagleBone "Demo" resources
|
||||
2. if you did boot from SD-Card, and it's bigger than 4Gb - you can expand
|
||||
current filesystem to take whole card space
|
||||
3. do option #1 and #2 together.
|
||||
|
||||
To remove some BeagleBone "Demo" resources execute these commands
|
||||
```
|
||||
sudo apt remove bb-node-red-installer
|
||||
sudo apt remove bb-code-server
|
||||
```
|
||||
|
||||
To expand filesystem to full size of your SD-Card execute this command, reboot is not required.
|
||||
```
|
||||
sudo growpart /dev/mmcblk0 1
|
||||
sudo resize2fs /dev/mmcblk0p1
|
||||
```
|
||||
|
||||
|
||||
Install Klipper by running the following
|
||||
commands:
|
||||
|
||||
```
|
||||
git clone https://github.com/Klipper3d/klipper
|
||||
git clone https://github.com/Klipper3d/klipper.git
|
||||
./klipper/scripts/install-beaglebone.sh
|
||||
```
|
||||
|
||||
## Install Octoprint
|
||||
After installing Klipper you need to decide what kind of deployment do you need,
|
||||
but take a note that BeagleBone is 3.3v based hardware and in most cases you can't
|
||||
directly connect pins to 5v or 12v based hardware without conversion boards.
|
||||
|
||||
One may then install Octoprint:
|
||||
As Klipper have multimodule architecture on BeagleBone you can achieve many different use cases,
|
||||
but general ones are following:
|
||||
|
||||
Use case 1: Use BeagleBone only as a host system to run Klipper and additional software
|
||||
like OctoPrint/Fluidd + Moonraker/... and this configuration will be driving
|
||||
external micro-controllers via serial/usb/canbus connections.
|
||||
|
||||
Use case 2: Use BeagleBone with extension board (cape) like CRAMPS board.
|
||||
in this configuration BeagleBone will host Klipper + additional software, and
|
||||
it will drive extension board with BeagleBone PRU cores (2 additional cores 200Mh, 32Bit).
|
||||
|
||||
Use case 3: It's same as "Use case 1" but additionally you want to drive
|
||||
BeagleBone GPIOs with high speed by utilizing PRU cores to offload main CPU.
|
||||
|
||||
|
||||
## Installing Octoprint
|
||||
|
||||
One may then install Octoprint or fully skip this section if desired other software:
|
||||
```
|
||||
git clone https://github.com/foosel/OctoPrint.git
|
||||
cd OctoPrint/
|
||||
@@ -51,25 +92,89 @@ Then start the Octoprint service:
|
||||
```
|
||||
sudo systemctl start octoprint
|
||||
```
|
||||
|
||||
Make sure the OctoPrint web server is accessible - it should be at:
|
||||
Wait 1-2 minutes and make sure the OctoPrint web server is accessible - it should be at:
|
||||
[http://beaglebone:5000/](http://beaglebone:5000/)
|
||||
|
||||
## Building the micro-controller code
|
||||
|
||||
To compile the Klipper micro-controller code, start by configuring it
|
||||
for the "Beaglebone PRU":
|
||||
## Building the BeagleBone PRU micro-controller code (PRU firmware)
|
||||
This section is required for "Use case 2" and "Use case 3" mentioned above,
|
||||
you should skip it for "Use case 1".
|
||||
|
||||
Check that required devices are present
|
||||
|
||||
```
|
||||
sudo beagle-version
|
||||
```
|
||||
You should check that output contains successful "remoteproc" drivers loading and presence of PRU cores,
|
||||
in Kernel 5.10 they should be "remoteproc1" and "remoteproc2" (4a334000.pru, 4a338000.pru)
|
||||
Also check that many GPIOs are loaded they will look like "Allocated GPIO id=0 name='P8_03'"
|
||||
Usually everything is fine and no hardware configuration is required.
|
||||
If something is missing - try to play with "uboot overlays" options or with cape-overlays
|
||||
Just for reference some output of working BeagleBone Black configuration with CRAMPS board:
|
||||
```
|
||||
model:[TI_AM335x_BeagleBone_Black]
|
||||
UBOOT: Booted Device-Tree:[am335x-boneblack-uboot-univ.dts]
|
||||
UBOOT: Loaded Overlay:[BB-ADC-00A0.bb.org-overlays]
|
||||
UBOOT: Loaded Overlay:[BB-BONE-eMMC1-01-00A0.bb.org-overlays]
|
||||
kernel:[5.10.168-ti-r71]
|
||||
/boot/uEnv.txt Settings:
|
||||
uboot_overlay_options:[enable_uboot_overlays=1]
|
||||
uboot_overlay_options:[disable_uboot_overlay_video=0]
|
||||
uboot_overlay_options:[disable_uboot_overlay_audio=1]
|
||||
uboot_overlay_options:[disable_uboot_overlay_wireless=1]
|
||||
uboot_overlay_options:[enable_uboot_cape_universal=1]
|
||||
pkg:[bb-cape-overlays]:[4.14.20210821.0-0~bullseye+20210821]
|
||||
pkg:[bb-customizations]:[1.20230720.1-0~bullseye+20230720]
|
||||
pkg:[bb-usb-gadgets]:[1.20230414.0-0~bullseye+20230414]
|
||||
pkg:[bb-wl18xx-firmware]:[1.20230414.0-0~bullseye+20230414]
|
||||
.............
|
||||
.............
|
||||
|
||||
```
|
||||
|
||||
To compile the Klipper micro-controller code, start by configuring it for the "Beaglebone PRU",
|
||||
for "BeagleBone Black" additionally disable options "Support GPIO Bit-banging devices" and disable "Support LCD devices"
|
||||
inside the "Optional features" because they will not fit in 8Kb PRU firmware memory,
|
||||
then exit and save config:
|
||||
```
|
||||
cd ~/klipper/
|
||||
make menuconfig
|
||||
```
|
||||
|
||||
To build and install the new micro-controller code, run:
|
||||
To build and install the new PRU micro-controller code, run:
|
||||
```
|
||||
sudo service klipper stop
|
||||
make flash
|
||||
sudo service klipper start
|
||||
```
|
||||
After previous commands was executed your PRU firmware should be ready and started
|
||||
to check if everything was fine you can execute following command
|
||||
```
|
||||
dmesg
|
||||
```
|
||||
and compare last messages with sample one which indicate that everything started properly:
|
||||
```
|
||||
[ 71.105499] remoteproc remoteproc1: 4a334000.pru is available
|
||||
[ 71.157155] remoteproc remoteproc2: 4a338000.pru is available
|
||||
[ 73.256287] remoteproc remoteproc1: powering up 4a334000.pru
|
||||
[ 73.279246] remoteproc remoteproc1: Booting fw image am335x-pru0-fw, size 97112
|
||||
[ 73.285807] remoteproc1#vdev0buffer: registered virtio0 (type 7)
|
||||
[ 73.285836] remoteproc remoteproc1: remote processor 4a334000.pru is now up
|
||||
[ 73.286322] remoteproc remoteproc2: powering up 4a338000.pru
|
||||
[ 73.313717] remoteproc remoteproc2: Booting fw image am335x-pru1-fw, size 188560
|
||||
[ 73.313753] remoteproc remoteproc2: header-less resource table
|
||||
[ 73.329964] remoteproc remoteproc2: header-less resource table
|
||||
[ 73.348321] remoteproc remoteproc2: remote processor 4a338000.pru is now up
|
||||
[ 73.443355] virtio_rpmsg_bus virtio0: creating channel rpmsg-pru addr 0x1e
|
||||
[ 73.443727] virtio_rpmsg_bus virtio0: msg received with no recipient
|
||||
[ 73.444352] virtio_rpmsg_bus virtio0: rpmsg host is online
|
||||
[ 73.540993] rpmsg_pru virtio0.rpmsg-pru.-1.30: new rpmsg_pru device: /dev/rpmsg_pru30
|
||||
```
|
||||
take a note about "/dev/rpmsg_pru30" - it's your future serial device for main mcu configuration
|
||||
this device is required to be present, if it's absent - your PRU cores did not start properly.
|
||||
|
||||
## Building and installing Linux host micro-controller code
|
||||
This section is required for "Use case 2" and optional for "Use case 3" mentioned above
|
||||
|
||||
It is also necessary to compile and install the micro-controller code
|
||||
for a Linux host process. Configure it a second time for a "Linux process":
|
||||
@@ -83,12 +188,24 @@ sudo service klipper stop
|
||||
make flash
|
||||
sudo service klipper start
|
||||
```
|
||||
take a note about "/tmp/klipper_host_mcu" - it will be your future serial device for "mcu host"
|
||||
if that file don't exist - refer to "scripts/klipper-mcu.service" file, it was installed by
|
||||
previous commands, and it's responsible for it.
|
||||
|
||||
|
||||
Take a note for "Use case 2" about following: when you will define printer configuration you should always
|
||||
use temperature sensors from "mcu host" because ADCs not present in default "mcu" (PRU cores).
|
||||
Sample configuration of "sensor_pin" for extruder and heated bed are available in "generic-cramps.cfg"
|
||||
You can use any other GPIO directly from "mcu host" by referencing them this way "host:gpiochip1/gpio17"
|
||||
but that should be avoided because it will be creating additional load on main CPU and most probably
|
||||
you can't use them for stepper control.
|
||||
|
||||
|
||||
## Remaining configuration
|
||||
|
||||
Complete the installation by configuring Klipper and Octoprint
|
||||
Complete the installation by configuring Klipper
|
||||
following the instructions in
|
||||
the main [Installation](Installation.md#configuring-klipper) document.
|
||||
the main [Installation](Installation.md#configuring-octoprint-to-use-klipper) document.
|
||||
|
||||
## Printing on the Beaglebone
|
||||
|
||||
@@ -97,4 +214,111 @@ OctoPrint well. Print stalls have been known to occur on complex
|
||||
prints (the printer may move faster than OctoPrint can send movement
|
||||
commands). If this occurs, consider using the "virtual_sdcard" feature
|
||||
(see [Config Reference](Config_Reference.md#virtual_sdcard) for
|
||||
details) to print directly from Klipper.
|
||||
details) to print directly from Klipper
|
||||
and disable any DEBUG or VERBOSE logging options if you did enable them.
|
||||
|
||||
|
||||
## AVR micro-controller code build
|
||||
This environment have everything to build necessary micro-controller code except AVR,
|
||||
AVR packages was removed because of conflict with PRU packages.
|
||||
if you still want to build AVR micro-controller code in this environment you need to remove
|
||||
PRU packages and install AVR packages by executing following commands
|
||||
|
||||
```
|
||||
sudo apt-get remove gcc-pru
|
||||
sudo apt-get install avrdude gcc-avr binutils-avr avr-libc
|
||||
```
|
||||
if you need to restore PRU packages - then remove ARV packages before that
|
||||
```
|
||||
sudo apt-get remove avrdude gcc-avr binutils-avr avr-libc
|
||||
sudo apt-get install gcc-pru
|
||||
```
|
||||
|
||||
|
||||
## Hardware Pin designation
|
||||
BeagleBone is very flexible in terms of pin designation, same pin can be configured for different function
|
||||
but always single function for single pin, same function can be present on different pins.
|
||||
So you can't have multiple functions on single pin or have same function on multiple pins.
|
||||
Example:
|
||||
P9_20 - i2c2_sda/can0_tx/spi1_cs0/gpio0_12/uart1_ctsn
|
||||
P9_19 - i2c2_scl/can0_rx/spi1_cs1/gpio0_13/uart1_rtsn
|
||||
P9_24 - i2c1_scl/can1_rx/gpio0_15/uart1_tx
|
||||
P9_26 - i2c1_sda/can1_tx/gpio0_14/uart1_rx
|
||||
|
||||
Pin designation is defined by using special "overlays" which will be loaded during linux boot
|
||||
they are configured by editing file /boot/uEnv.txt with elevated permissions
|
||||
```
|
||||
sudo editor /boot/uEnv.txt
|
||||
```
|
||||
and defining which functionality to load, for example to enable CAN1 you need to define overlay for it
|
||||
```
|
||||
uboot_overlay_addr4=/lib/firmware/BB-CAN1-00A0.dtbo
|
||||
```
|
||||
This overlay BB-CAN1-00A0.dtbo will reconfigure all required pins for CAN1 and create CAN device in Linux.
|
||||
Any change in overlays will require system reboot to be applied.
|
||||
If you need to understand which pins are involved in some overlay - you can analyze source files in
|
||||
this location: /opt/sources/bb.org-overlays/src/arm/
|
||||
or search info in BeagleBone forums.
|
||||
|
||||
|
||||
## Enabling hardware SPI
|
||||
BeagleBone usually have multiple hardware SPI buses, for example BeagleBone Black can have 2 of them,
|
||||
they can work up to 48Mhz, but usually they are limited to 16Mhz by Kernel Device-tree.
|
||||
By default, in BeagleBone Black some of SPI1 pins are configured for HDMI-Audio output,
|
||||
to fully enable 4-wire SPI1 you need to disable HDMI Audio and enable SPI1
|
||||
To do that edit file /boot/uEnv.txt with elevated permissions
|
||||
```
|
||||
sudo editor /boot/uEnv.txt
|
||||
```
|
||||
uncomment variable
|
||||
```
|
||||
disable_uboot_overlay_audio=1
|
||||
```
|
||||
|
||||
next uncomment variable and define it this way
|
||||
```
|
||||
uboot_overlay_addr4=/lib/firmware/BB-SPIDEV1-00A0.dtbo
|
||||
```
|
||||
Save changes in /boot/uEnv.txt and reboot the board.
|
||||
Now you have SPI1 Enabled, to verify its presence execute command
|
||||
```
|
||||
ls /dev/spidev1.*
|
||||
```
|
||||
Take a note that BeagleBone usually is 3.3v based hardware and to use 5V SPI devices
|
||||
you need to add Level-Shifting chip, for example SN74CBTD3861, SN74LVC1G34 or similar.
|
||||
If you are using CRAMPS board - it already contains Level-Shifting chip and SPI1 pins
|
||||
will become available on P503 port, and they can accept 5v hardware,
|
||||
check CRAMPS board Schematics for pin references.
|
||||
|
||||
## Enabling hardware I2C
|
||||
BeagleBone usually have multiple hardware I2C buses, for example BeagleBone Black can have 3 of them,
|
||||
they support speed up-to 400Kbit Fast mode.
|
||||
By default, in BeagleBone Black there are two of them (i2c-1 and i2c-2) usually both are already configured and
|
||||
present on P9, third ic2-0 usually reserved for internal use.
|
||||
If you are using CRAMPS board then i2c-2 is present on P303 port with 3.3v level,
|
||||
If you want to obtain I2c-1 in CRAMPS board - you can get them on Extruder1.Step, Extruder1.Dir pins,
|
||||
they also are 3.3v based, check CRAMPS board Schematics for pin references.
|
||||
Related overlays, for [Hardware Pin designation](#hardware-pin-designation):
|
||||
I2C1(100Kbit): BB-I2C1-00A0.dtbo
|
||||
I2C1(400Kbit): BB-I2C1-FAST-00A0.dtbo
|
||||
I2C2(100Kbit): BB-I2C2-00A0.dtbo
|
||||
I2C2(400Kbit): BB-I2C2-FAST-00A0.dtbo
|
||||
|
||||
## Enabling hardware UART(Serial)/CAN
|
||||
BeagleBone have up to 6 hardware UART(Serial) buses (up to 3Mbit)
|
||||
and up to 2 hardware CAN(1Mbit) buses.
|
||||
UART1(RX,TX) and CAN1(TX,RX) and I2C2(SDA,SCL) are using same pins - so you need to chose what to use
|
||||
UART1(CTSN,RTSN) and CAN0(TX,RX) and I2C1(SDA,SCL) are using same pins - so you need to chose what to use
|
||||
All UART/CAN related pins are 3.3v based, so you will need to use Transceiver chips/boards like SN74LVC2G241DCUR (for UART),
|
||||
SN65HVD230 (for CAN), TTL-RS485 (for RS-485) or something similar which can convert 3.3v signals to appropriate levels.
|
||||
|
||||
Related overlays, for [Hardware Pin designation](#hardware-pin-designation)
|
||||
CAN0: BB-CAN0-00A0.dtbo
|
||||
CAN1: BB-CAN1-00A0.dtbo
|
||||
UART0: - used for Console
|
||||
UART1(RX,TX): BB-UART1-00A0.dtbo
|
||||
UART1(RTS,CTS): BB-UART1-RTSCTS-00A0.dtbo
|
||||
UART2(RX,TX): BB-UART2-00A0.dtbo
|
||||
UART3(RX,TX): BB-UART3-00A0.dtbo
|
||||
UART4(RS-485): BB-UART4-RS485-00A0.dtbo
|
||||
UART5(RX,TX): BB-UART5-00A0.dtbo
|
||||
|
||||
351
docs/Bed_Mesh.md
351
docs/Bed_Mesh.md
@@ -44,10 +44,9 @@ probe_count: 5, 3
|
||||
|
||||
- `mesh_max: 240, 198`\
|
||||
_Required_\
|
||||
The probed coordinate farthest farthest from the origin. This is not
|
||||
necessarily the last point probed, as the probing process occurs in a
|
||||
zig-zag fashion. As with `mesh_min`, this coordinate is relative to
|
||||
the probe's location.
|
||||
The probed coordinate farthest from the origin. This is not necessarily
|
||||
the last point probed, as the probing process occurs in a zig-zag fashion.
|
||||
As with `mesh_min`, this coordinate is relative to the probe's location.
|
||||
|
||||
- `probe_count: 5, 3`\
|
||||
_Default Value: 3, 3_\
|
||||
@@ -142,7 +141,7 @@ bicubic_tension: 0.2
|
||||
integer pair, and also may be specified a single integer that is applied
|
||||
to both axes. In this example there are 4 segments along the X axis
|
||||
and 2 segments along the Y axis. This evaluates to 8 interpolated
|
||||
points along X, 6 interpolated points along Y, which results in a 13x8
|
||||
points along X, 6 interpolated points along Y, which results in a 13x9
|
||||
mesh. Note that if mesh_pps is set to 0 then mesh interpolation is
|
||||
disabled and the probed matrix will be sampled directly.
|
||||
|
||||
@@ -370,21 +369,146 @@ are identified in green.
|
||||
|
||||

|
||||
|
||||
### Adaptive Meshes
|
||||
|
||||
Adaptive bed meshing is a way to speed up the bed mesh generation by only probing
|
||||
the area of the bed used by the objects being printed. When used, the method will
|
||||
automatically adjust the mesh parameters based on the area occupied by the defined
|
||||
print objects.
|
||||
|
||||
The adapted mesh area will be computed from the area defined by the boundaries of all
|
||||
the defined print objects so it covers every object, including any margins defined in
|
||||
the configuration. After the area is computed, the number of probe points will be
|
||||
scaled down based on the ratio of the default mesh area and the adapted mesh area. To
|
||||
illustrate this consider the following example:
|
||||
|
||||
For a 150mmx150mm bed with `mesh_min` set to `25,25` and `mesh_max` set to `125,125`,
|
||||
the default mesh area is a 100mmx100mm square. An adapted mesh area of `50,50`
|
||||
means a ratio of `0.5x0.5` between the adapted area and default mesh area.
|
||||
|
||||
If the `bed_mesh` configuration specified `probe_count` as `7x7`, the adapted bed
|
||||
mesh will use 4x4 probe points (7 * 0.5 rounded up).
|
||||
|
||||

|
||||
|
||||
```
|
||||
[bed_mesh]
|
||||
speed: 120
|
||||
horizontal_move_z: 5
|
||||
mesh_min: 35, 6
|
||||
mesh_max: 240, 198
|
||||
probe_count: 5, 3
|
||||
adaptive_margin: 5
|
||||
```
|
||||
|
||||
- `adaptive_margin` \
|
||||
_Default Value: 0_ \
|
||||
Margin (in mm) to add around the area of the bed used by the defined objects. The diagram
|
||||
below shows the adapted bed mesh area with an `adaptive_margin` of 5mm. The adapted mesh
|
||||
area (area in green) is computed as the used bed area (area in blue) plus the defined margin.
|
||||
|
||||

|
||||
|
||||
By nature, adaptive bed meshes use the objects defined by the Gcode file being printed.
|
||||
Therefore, it is expected that each Gcode file will generate a mesh that probes a different
|
||||
area of the print bed. Therefore, adapted bed meshes should not be re-used. The expectation
|
||||
is that a new mesh will be generated for each print if adaptive meshing is used.
|
||||
|
||||
It is also important to consider that adaptive bed meshing is best used on machines that can
|
||||
normally probe the entire bed and achieve a maximum variance less than or equal to 1 layer
|
||||
height. Machines with mechanical issues that a full bed mesh normally compensates for may
|
||||
have undesirable results when attempting print moves **outside** of the probed area. If a
|
||||
full bed mesh has a variance greater than 1 layer height, caution must be taken when using
|
||||
adaptive bed meshes and attempting print moves outside of the meshed area.
|
||||
|
||||
## Surface Scans
|
||||
|
||||
Some probes, such as the [Eddy Current Probe](./Eddy_Probe.md), are capable of
|
||||
"scanning" the surface of the bed. That is, these probes can sample a mesh
|
||||
without lifting the tool between samples. To activate scanning mode, the
|
||||
`METHOD=scan` or `METHOD=rapid_scan` probe parameter should be passed in the
|
||||
`BED_MESH_CALIBRATE` gcode command.
|
||||
|
||||
### Scan Height
|
||||
|
||||
The scan height is set by the `horizontal_move_z` option in `[bed_mesh]`. In
|
||||
addition it can be supplied with the `BED_MESH_CALIBRATE` gcode command via the
|
||||
`HORIZONTAL_MOVE_Z` parameter.
|
||||
|
||||
The scan height must be sufficiently low to avoid scanning errors. Typically
|
||||
a height of 2mm (ie: `HORIZONTAL_MOVE_Z=2`) should work well, presuming that the
|
||||
probe is mounted correctly.
|
||||
|
||||
It should be noted that if the probe is more than 4mm above the surface then the
|
||||
results will be invalid. Thus, scanning is not possible on beds with severe
|
||||
surface deviation or beds with extreme tilt that hasn't been corrected.
|
||||
|
||||
### Rapid (Continuous) Scanning
|
||||
|
||||
When performing a `rapid_scan` one should keep in mind that the results will
|
||||
have some amount of error. This error should be low enough to be useful on
|
||||
large print areas with reasonably thick layer heights. Some probes may be
|
||||
more prone to error than others.
|
||||
|
||||
It is not recommended that rapid mode be used to scan a "dense" mesh. Some of
|
||||
the error introduced during a rapid scan may be gaussian noise from the sensor,
|
||||
and a dense mesh will reflect this noise (ie: there will be peaks and valleys).
|
||||
|
||||
Bed Mesh will attempt to optimize the travel path to provide the best possible
|
||||
result based on the configuration. This includes avoiding faulty regions
|
||||
when collecting samples and "overshooting" the mesh when changing direction.
|
||||
This overshoot improves sampling at the edges of a mesh, however it requires
|
||||
that the mesh be configured in a way that allows the tool to travel outside
|
||||
of the mesh.
|
||||
|
||||
```
|
||||
[bed_mesh]
|
||||
speed: 120
|
||||
horizontal_move_z: 5
|
||||
mesh_min: 35, 6
|
||||
mesh_max: 240, 198
|
||||
probe_count: 5
|
||||
scan_overshoot: 8
|
||||
```
|
||||
|
||||
- `scan_overshoot`
|
||||
_Default Value: 0 (disabled)_\
|
||||
The maximum amount of travel (in mm) available outside of the mesh.
|
||||
For rectangular beds this applies to travel on the X axis, and for round beds
|
||||
it applies to the entire radius. The tool must be able to travel the amount
|
||||
specified outside of the mesh. This value is used to optimize the travel
|
||||
path when performing a "rapid scan". The minimum value that may be specified
|
||||
is 1. The default is no overshoot.
|
||||
|
||||
If no scan overshoot is configured then travel path optimization will not
|
||||
be applied to changes in direction.
|
||||
|
||||
## Bed Mesh Gcodes
|
||||
|
||||
### Calibration
|
||||
|
||||
`BED_MESH_CALIBRATE PROFILE=<name> METHOD=[manual | automatic] [<probe_parameter>=<value>]
|
||||
[<mesh_parameter>=<value>]`\
|
||||
`BED_MESH_CALIBRATE PROFILE=<name> METHOD=[manual | automatic | scan | rapid_scan] \
|
||||
[<probe_parameter>=<value>] [<mesh_parameter>=<value>] [ADAPTIVE=[0|1] \
|
||||
[ADAPTIVE_MARGIN=<value>]`\
|
||||
_Default Profile: default_\
|
||||
_Default Method: automatic if a probe is detected, otherwise manual_
|
||||
_Default Method: automatic if a probe is detected, otherwise manual_ \
|
||||
_Default Adaptive: 0_ \
|
||||
_Default Adaptive Margin: 0_
|
||||
|
||||
Initiates the probing procedure for Bed Mesh Calibration.
|
||||
|
||||
The mesh will be saved into a profile specified by the `PROFILE` parameter,
|
||||
or `default` if unspecified. If `METHOD=manual` is selected then manual probing
|
||||
will occur. When switching between automatic and manual probing the generated
|
||||
mesh points will automatically be adjusted.
|
||||
or `default` if unspecified. The `METHOD` parameter takes one of the following
|
||||
values:
|
||||
|
||||
- `METHOD=manual`: enables manual probing using the nozzle and the paper test
|
||||
- `METHOD=automatic`: Automatic (standard) probing. This is the default.
|
||||
- `METHOD=scan`: Enables surface scanning. The tool will pause over each position
|
||||
to collect a sample.
|
||||
- `METHOD=rapid_scan`: Enables continuous surface scanning.
|
||||
|
||||
XY positions are automatically adjusted to include the X and/or Y offsets
|
||||
when a probing method other than `manual` is selected.
|
||||
|
||||
It is possible to specify mesh parameters to modify the probed area. The
|
||||
following parameters are available:
|
||||
@@ -398,7 +522,10 @@ following parameters are available:
|
||||
- `MESH_ORIGIN`
|
||||
- `ROUND_PROBE_COUNT`
|
||||
- All beds:
|
||||
- `MESH_PPS`
|
||||
- `ALGORITHM`
|
||||
- `ADAPTIVE`
|
||||
- `ADAPTIVE_MARGIN`
|
||||
|
||||
See the configuration documentation above for details on how each parameter
|
||||
applies to the mesh.
|
||||
@@ -486,11 +613,207 @@ This gcode may be used to clear the internal mesh state.
|
||||
|
||||
### Apply X/Y offsets
|
||||
|
||||
`BED_MESH_OFFSET [X=<value>] [Y=<value>]`
|
||||
`BED_MESH_OFFSET [X=<value>] [Y=<value>] [ZFADE=<value>]`
|
||||
|
||||
This is useful for printers with multiple independent extruders, as an offset
|
||||
is necessary to produce correct Z adjustment after a tool change. Offsets
|
||||
should be specified relative to the primary extruder. That is, a positive
|
||||
X offset should be specified if the secondary extruder is mounted to the
|
||||
right of the primary extruder, and a positive Y offset should be specified
|
||||
if the secondary extruder is mounted "behind" the primary extruder.
|
||||
right of the primary extruder, a positive Y offset should be specified
|
||||
if the secondary extruder is mounted "behind" the primary extruder, and
|
||||
a positive ZFADE offset should be specified if the secondary extruder's
|
||||
nozzle is above the primary extruder's.
|
||||
|
||||
Note that a ZFADE offset does *NOT* directly apply additional adjustment. It
|
||||
is intended to compensate for a `gcode offset` when [mesh fade](#mesh-fade)
|
||||
is enabled. For example, if a secondary extruder is higher than the primary
|
||||
and needs a negative gcode offset, ie: `SET_GCODE_OFFSET Z=-.2`, it can be
|
||||
accounted for in `bed_mesh` with `BED_MESH_OFFSET ZFADE=.2`.
|
||||
|
||||
## Bed Mesh Webhooks APIs
|
||||
|
||||
### Dumping mesh data
|
||||
|
||||
`{"id": 123, "method": "bed_mesh/dump_mesh"}`
|
||||
|
||||
Dumps the configuration and state for the current mesh and all
|
||||
saved profiles.
|
||||
|
||||
The `dump_mesh` endpoint takes one optional parameter, `mesh_args`.
|
||||
This parameter must be an object, where the keys and values are
|
||||
parameters available to [BED_MESH_CALIBRATE](#bed_mesh_calibrate).
|
||||
This will update the mesh configuration and probe points using the
|
||||
supplied parameters prior to returning the result. It is recommended
|
||||
to omit mesh parameters unless it is desired to visualize the probe points
|
||||
and/or travel path before performing `BED_MESH_CALIBRATE`.
|
||||
|
||||
## Visualization and analysis
|
||||
|
||||
Most users will likely find that the visualizers included with
|
||||
applications such as Mainsail, Fluidd, and Octoprint are sufficient
|
||||
for basic analysis. However, Klipper's `scripts` folder contains the
|
||||
`graph_mesh.py` script that may be used to perform additional
|
||||
visualizations and more detailed analysis, particularly useful
|
||||
for debugging hardware or the results produced by `bed_mesh`:
|
||||
|
||||
```
|
||||
usage: graph_mesh.py [-h] {list,plot,analyze,dump} ...
|
||||
|
||||
Graph Bed Mesh Data
|
||||
|
||||
positional arguments:
|
||||
{list,plot,analyze,dump}
|
||||
list List available plot types
|
||||
plot Plot a specified type
|
||||
analyze Perform analysis on mesh data
|
||||
dump Dump API response to json file
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
```
|
||||
|
||||
### Pre-requisites
|
||||
|
||||
Like most graphing tools provided by Klipper, `graph_mesh.py` requires
|
||||
the `matplotlib` and `numpy` python dependencies. In addition, connecting
|
||||
to Klipper via Moonraker's websocket requires the `websockets` python
|
||||
dependency. While all visualizations can be output to an `svg` file, most of
|
||||
the visualizations offered by `graph_mesh.py` are better viewed in live
|
||||
preview mode on a desktop class PC. For example, the 3D visualizations may be
|
||||
rotated and zoomed in preview mode, and the path visualizations can optionally
|
||||
be animated in preview mode.
|
||||
|
||||
### Plotting Mesh data
|
||||
|
||||
The `graph_mesh.py` tool can plot several types of visualizations.
|
||||
Available types can be shown by running `graph_mesh.py list`:
|
||||
|
||||
```
|
||||
graph_mesh.py list
|
||||
points Plot original generated points
|
||||
path Plot probe travel path
|
||||
rapid Plot rapid scan travel path
|
||||
probedz Plot probed Z values
|
||||
meshz Plot mesh Z values
|
||||
overlay Plots the current probed mesh overlaid with a profile
|
||||
delta Plots the delta between current probed mesh and a profile
|
||||
```
|
||||
|
||||
Several options are available when plotting visualizations:
|
||||
|
||||
```
|
||||
usage: graph_mesh.py plot [-h] [-a] [-s] [-p PROFILE_NAME] [-o OUTPUT] <plot type> <input>
|
||||
|
||||
positional arguments:
|
||||
<plot type> Type of data to graph
|
||||
<input> Path/url to Klipper Socket or path to json file
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
-a, --animate Animate paths in live preview
|
||||
-s, --scale-plot Use axis limits reported by Klipper to scale plot X/Y
|
||||
-p PROFILE_NAME, --profile-name PROFILE_NAME
|
||||
Optional name of a profile to plot for 'probedz'
|
||||
-o OUTPUT, --output OUTPUT
|
||||
Output file path
|
||||
```
|
||||
|
||||
Below is a description of each argument:
|
||||
|
||||
- `plot type`: A required positional argument designating the type of
|
||||
visualization to generate. Must be one of the types output by the
|
||||
`graph_mesh.py list` command.
|
||||
- `input`: A required positional argument containing a path or url
|
||||
to the input source. This must be one of the following:
|
||||
- A path to Klipper's Unix Domain Socket
|
||||
- A url to an instance of Moonraker
|
||||
- A path to a json file produced by `graph_mesh.py dump <input>`
|
||||
- `-a`: Optional animation for the `path` and `rapid` visualization types.
|
||||
Animations only apply to a live preview.
|
||||
- `-s`: Optionally scales a plot using the `axis_minimum` and `axis_maximum`
|
||||
values reported by Klipper's `toolhead` object when the dump file was
|
||||
generated.
|
||||
- `-p`: A profile name that may be specified when generating the
|
||||
`probedz` 3D mesh visualization. When generating an `overlay` or
|
||||
`delta` visualization this argument must be provided.
|
||||
- `-o`: An optional file path indicating that the script should save the
|
||||
visualization to this location rather than run in preview mode. Images
|
||||
are saved in `svg` format.
|
||||
|
||||
For example, to plot an animated rapid path, connecting via Klipper's unix
|
||||
socket:
|
||||
|
||||
```
|
||||
graph_mesh.py plot -a rapid ~/printer_data/comms/klippy.sock
|
||||
```
|
||||
|
||||
Or to plot a 3d visualization of the mesh, connecting via Moonraker:
|
||||
|
||||
```
|
||||
graph_mesh.py plot meshz http://my-printer.local
|
||||
```
|
||||
|
||||
### Bed Mesh Analysis
|
||||
|
||||
The `graph_mesh.py` tool may also be used to perform an analysis on the
|
||||
data provided by the [bed_mesh/dump_mesh](#dumping-mesh-data) API:
|
||||
|
||||
```
|
||||
graph_mesh.py analyze <input>
|
||||
```
|
||||
|
||||
As with the `plot` command, the `<input>` must be a path to Klipper's
|
||||
unix socket, a URL to an instance of Moonraker, or a path to a json file
|
||||
generated by the dump command.
|
||||
|
||||
To begin, the analysis will perform various checks on the points and
|
||||
probe paths generated by `bed_mesh` at the time of the dump. This
|
||||
includes the following:
|
||||
|
||||
- The number of probe points generated, without any additions
|
||||
- The number of probe points generated including any points generated
|
||||
as the result faulty regions and/or a configured zero reference position.
|
||||
- The number of probe points generated when performing a rapid scan.
|
||||
- The total number of moves generated for a rapid scan.
|
||||
- A validation that the probe points generated for a rapid scan are
|
||||
identical to the probe points generated for a standard probing procedure.
|
||||
- A "backtracking" check for both the standard probe path and a rapid scan
|
||||
path. Backtracking can be defined as moving to the same position more than
|
||||
once during the probing procedure. Backtracking should never occur during a
|
||||
standard probe. Faulty regions *can* result in backtracking during a rapid
|
||||
scan in an attempt to avoid entering a faulty region when approaching or
|
||||
leaving a probe location, however should never occur otherwise.
|
||||
|
||||
Next each probed mesh present in the dump will by analyzed, beginning with
|
||||
the mesh loaded at the time of the dump (if present) and followed by any
|
||||
saved profiles. The following data is extracted:
|
||||
|
||||
- Mesh shape (Min X,Y, Max X,Y Probe Count)
|
||||
- Mesh Z range, (Minimum Z, Maximum Z)
|
||||
- Mean Z value in the mesh
|
||||
- Standard Deviation of the Z values in the Mesh
|
||||
|
||||
In addition to the above, a delta analysis is performed between meshes
|
||||
with the same shape, reporting the following:
|
||||
- The range of the delta between to meshes (Minimum and Maximum)
|
||||
- The mean delta
|
||||
- Standard Deviation of the delta
|
||||
- The absolute maximum difference
|
||||
- The absolute mean
|
||||
|
||||
### Save mesh data to a file
|
||||
|
||||
The `dump` command may be used to save the response to a file which
|
||||
can be shared for analysis when troubleshooting:
|
||||
|
||||
```
|
||||
graph_mesh.py dump -o <output file name> <input>
|
||||
```
|
||||
|
||||
The `<input>` should be a path to Klipper's unix socket or
|
||||
a URL to an instance of Moonraker. The `-o` option may be used to
|
||||
specify the path to the output file. If omitted, the file will be
|
||||
saved in the working directory, with a file name in the following
|
||||
format:
|
||||
|
||||
`klipper-bedmesh-{year}{month}{day}{hour}{minute}{second}.json`
|
||||
|
||||
@@ -31,7 +31,7 @@ adapter. This is typically done by creating a new file named
|
||||
allow-hotplug can0
|
||||
iface can0 can static
|
||||
bitrate 1000000
|
||||
up ifconfig $IFACE txqueuelen 128
|
||||
up ip link set $IFACE txqueuelen 128
|
||||
```
|
||||
|
||||
## Terminating Resistors
|
||||
@@ -113,7 +113,7 @@ Some important notes when using this mode:
|
||||
allow-hotplug can0
|
||||
iface can0 can static
|
||||
bitrate 1000000
|
||||
up ifconfig $IFACE txqueuelen 128
|
||||
up ip link set $IFACE txqueuelen 128
|
||||
```
|
||||
|
||||
* The "bridge mcu" is not actually on the CAN bus. Messages to and
|
||||
|
||||
@@ -52,6 +52,56 @@ Reordered messages is a severe problem that must be fixed. It will
|
||||
result in unstable behavior and can lead to confusing errors at any
|
||||
part of a print.
|
||||
|
||||
## Use an appropriate txqueuelen setting
|
||||
|
||||
The Klipper code uses the Linux kernel to manage CAN bus traffic. By
|
||||
default, the kernel will only queue 10 CAN transmit packets. It is
|
||||
recommended to [configure the can0 device](CANBUS.md#host-hardware)
|
||||
with a `txqueuelen 128` to increase that size.
|
||||
|
||||
If Klipper transmits a packet and Linux has filled all of its transmit
|
||||
queue space then Linux will drop that packet and messages like the
|
||||
following will appear in the Klipper log:
|
||||
```
|
||||
Got error -1 in can write: (105)No buffer space available
|
||||
```
|
||||
Klipper will automatically retransmit the lost messages as part of its
|
||||
normal application level message retransmit system. Thus, this log
|
||||
message is a warning and it does not indicate an unrecoverable error.
|
||||
|
||||
If a complete CAN bus failure occurs (such as a CAN wire break) then
|
||||
Linux will not be able to transmit any messages on the CAN bus and it
|
||||
is common to find the above message in the Klipper log. In this case,
|
||||
the log message is a symptom of a larger problem (the inability to
|
||||
transmit any messages) and is not directly related to Linux
|
||||
`txqueuelen`.
|
||||
|
||||
One may check the current queue size by running the Linux command `ip
|
||||
link show can0`. It should report a bunch of text including the
|
||||
snippet `qlen 128`. If one sees something like `qlen 10` then it
|
||||
indicates the CAN device has not been properly configured.
|
||||
|
||||
It is not recommended to use a `txqueuelen` significantly larger
|
||||
than 128. A CAN bus running at a frequency of 1000000 will typically
|
||||
take around 120us to transmit a CAN packet. Thus a queue of 128
|
||||
packets is likely to take around 15-20ms to drain. A substantially
|
||||
larger queue could cause excessive spikes in message round-trip-time
|
||||
which could lead to unrecoverable errors. Said another way, Klipper's
|
||||
application retransmit system is more robust if it does not have to
|
||||
wait for Linux to drain an excessively large queue of possibly stale
|
||||
data. This is analogous to the problem of
|
||||
[bufferbloat](https://en.wikipedia.org/wiki/Bufferbloat) on internet
|
||||
routers.
|
||||
|
||||
Under normal circumstances Klipper may utilize ~25 queue slots per
|
||||
MCU - typically only utilizing more slots during retransmits.
|
||||
(Specifically, the Klipper host may transmit up to 192 bytes to each
|
||||
Klipper MCU before receiving an acknowledgment from that MCU.) If a
|
||||
single CAN bus has 5 or more Klipper MCUs on it, then it might be
|
||||
necessary to increase the `txqueuelen` above the recommended value
|
||||
of 128. However, as above, care should be taken when selecting a new
|
||||
value to avoid excessive round-trip-time latency.
|
||||
|
||||
## Obtaining candump logs
|
||||
|
||||
The CAN bus messages sent to and from the micro-controller are handled
|
||||
|
||||
@@ -136,8 +136,9 @@ provides further information on the mechanics of moves.
|
||||
|
||||
* The ToolHead class (in toolhead.py) handles "look-ahead" and tracks
|
||||
the timing of printing actions. The main codepath for a move is:
|
||||
`ToolHead.move() -> MoveQueue.add_move() -> MoveQueue.flush() ->
|
||||
Move.set_junction() -> ToolHead._process_moves()`.
|
||||
`ToolHead.move() -> LookAheadQueue.add_move() ->
|
||||
LookAheadQueue.flush() -> Move.set_junction() ->
|
||||
ToolHead._process_moves()`.
|
||||
* ToolHead.move() creates a Move() object with the parameters of the
|
||||
move (in cartesian space and in units of seconds and millimeters).
|
||||
* The kinematics class is given the opportunity to audit each move
|
||||
@@ -146,10 +147,10 @@ provides further information on the mechanics of moves.
|
||||
may raise an error if the move is not valid. If check_move()
|
||||
completes successfully then the underlying kinematics must be able
|
||||
to handle the move.
|
||||
* MoveQueue.add_move() places the move object on the "look-ahead"
|
||||
queue.
|
||||
* MoveQueue.flush() determines the start and end velocities of each
|
||||
move.
|
||||
* LookAheadQueue.add_move() places the move object on the
|
||||
"look-ahead" queue.
|
||||
* LookAheadQueue.flush() determines the start and end velocities of
|
||||
each move.
|
||||
* Move.set_junction() implements the "trapezoid generator" on a
|
||||
move. The "trapezoid generator" breaks every move into three parts:
|
||||
a constant acceleration phase, followed by a constant velocity
|
||||
@@ -170,17 +171,18 @@ provides further information on the mechanics of moves.
|
||||
placed on a "trapezoid motion queue": `ToolHead._process_moves() ->
|
||||
trapq_append()` (in klippy/chelper/trapq.c). The step times are then
|
||||
generated: `ToolHead._process_moves() ->
|
||||
ToolHead._update_move_time() -> MCU_Stepper.generate_steps() ->
|
||||
itersolve_generate_steps() -> itersolve_gen_steps_range()` (in
|
||||
klippy/chelper/itersolve.c). The goal of the iterative solver is to
|
||||
find step times given a function that calculates a stepper position
|
||||
from a time. This is done by repeatedly "guessing" various times
|
||||
until the stepper position formula returns the desired position of
|
||||
the next step on the stepper. The feedback produced from each guess
|
||||
is used to improve future guesses so that the process rapidly
|
||||
converges to the desired time. The kinematic stepper position
|
||||
formulas are located in the klippy/chelper/ directory (eg,
|
||||
kin_cart.c, kin_corexy.c, kin_delta.c, kin_extruder.c).
|
||||
ToolHead._advance_move_time() -> ToolHead._advance_flush_time() ->
|
||||
MCU_Stepper.generate_steps() -> itersolve_generate_steps() ->
|
||||
itersolve_gen_steps_range()` (in klippy/chelper/itersolve.c). The
|
||||
goal of the iterative solver is to find step times given a function
|
||||
that calculates a stepper position from a time. This is done by
|
||||
repeatedly "guessing" various times until the stepper position
|
||||
formula returns the desired position of the next step on the
|
||||
stepper. The feedback produced from each guess is used to improve
|
||||
future guesses so that the process rapidly converges to the desired
|
||||
time. The kinematic stepper position formulas are located in the
|
||||
klippy/chelper/ directory (eg, kin_cart.c, kin_corexy.c,
|
||||
kin_delta.c, kin_extruder.c).
|
||||
|
||||
* Note that the extruder is handled in its own kinematic class:
|
||||
`ToolHead._process_moves() -> PrinterExtruder.move()`. Since
|
||||
|
||||
@@ -8,6 +8,53 @@ All dates in this document are approximate.
|
||||
|
||||
## Changes
|
||||
|
||||
20240415: The `on_error_gcode` parameter in the `[virtual_sdcard]`
|
||||
config section now has a default. If this parameter is not specified
|
||||
it now defaults to `TURN_OFF_HEATERS`. If the previous behavior is
|
||||
desired (take no default action on an error during a virtual_sdcard
|
||||
print) then define `on_error_gcode` with an empty value.
|
||||
|
||||
20240313: The `max_accel_to_decel` parameter in the `[printer]` config
|
||||
section has been deprecated. The `ACCEL_TO_DECEL` parameter of the
|
||||
`SET_VELOCITY_LIMIT` command has been deprecated. The
|
||||
`printer.toolhead.max_accel_to_decel` status has been removed. Use the
|
||||
[minimum_cruise_ratio parameter](./Config_Reference.md#printer)
|
||||
instead. The deprecated features will be removed in the near future,
|
||||
and using them in the interim may result in subtly different behavior.
|
||||
|
||||
20240215: Several deprecated features have been removed. Using "NTC
|
||||
100K beta 3950" as a thermistor name has been removed (deprecated on
|
||||
20211110). The `SYNC_STEPPER_TO_EXTRUDER` and
|
||||
`SET_EXTRUDER_STEP_DISTANCE` commands have been removed, and the
|
||||
extruder `shared_heater` config option has been removed (deprecated on
|
||||
20220210). The bed_mesh `relative_reference_index` option has been
|
||||
removed (deprecated on 20230619).
|
||||
|
||||
20240123: The output_pin SET_PIN CYCLE_TIME parameter has been
|
||||
removed. Use the new
|
||||
[pwm_cycle_time](Config_Reference.md#pwm_cycle_time) module if it is
|
||||
necessary to dynamically change a pwm pin's cycle time.
|
||||
|
||||
20240123: The output_pin `maximum_mcu_duration` parameter is
|
||||
deprecated. Use a [pwm_tool config section](Config_Reference.md#pwm_tool)
|
||||
instead. The option will be removed in the near future.
|
||||
|
||||
20240123: The output_pin `static_value` parameter is deprecated.
|
||||
Replace with `value` and `shutdown_value` parameters. The option will
|
||||
be removed in the near future.
|
||||
|
||||
20231216: The `[hall_filament_width_sensor]` is changed to trigger filament runout
|
||||
when the thickness of the filament exceeds `max_diameter`. The maximum diameter
|
||||
defaults to `default_nominal_filament_diameter + max_difference`. See
|
||||
[[hall_filament_width_sensor] configuration
|
||||
reference](./Config_Reference.md#hall_filament_width_sensor) for more details.
|
||||
|
||||
20231207: Several undocumented config parameters in the `[printer]`
|
||||
config section have been removed (the buffer_time_low,
|
||||
buffer_time_high, buffer_time_start, and move_flush_time parameters).
|
||||
|
||||
20231110: Klipper v0.12.0 released.
|
||||
|
||||
20230826: If `safe_distance` is set or calculated to be 0 in `[dual_carriage]`,
|
||||
the carriages proximity checks will be disabled as per documentation. A user
|
||||
may wish to configure `safe_distance` explicitly to prevent accidental crashes
|
||||
|
||||
@@ -88,16 +88,31 @@ kinematics:
|
||||
# deltesian, polar, winch, or none. This parameter must be specified.
|
||||
max_velocity:
|
||||
# Maximum velocity (in mm/s) of the toolhead (relative to the
|
||||
# print). This parameter must be specified.
|
||||
# print). This value may be changed at runtime using the
|
||||
# SET_VELOCITY_LIMIT command. This parameter must be specified.
|
||||
max_accel:
|
||||
# Maximum acceleration (in mm/s^2) of the toolhead (relative to the
|
||||
# print). This parameter must be specified.
|
||||
#max_accel_to_decel:
|
||||
# A pseudo acceleration (in mm/s^2) controlling how fast the
|
||||
# toolhead may go from acceleration to deceleration. It is used to
|
||||
# reduce the top speed of short zig-zag moves (and thus reduce
|
||||
# printer vibration from these moves). The default is half of
|
||||
# max_accel.
|
||||
# print). Although this parameter is described as a "maximum"
|
||||
# acceleration, in practice most moves that accelerate or decelerate
|
||||
# will do so at the rate specified here. The value specified here
|
||||
# may be changed at runtime using the SET_VELOCITY_LIMIT command.
|
||||
# This parameter must be specified.
|
||||
#minimum_cruise_ratio: 0.5
|
||||
# Most moves will accelerate to a cruising speed, travel at that
|
||||
# cruising speed, and then decelerate. However, some moves that
|
||||
# travel a short distance could nominally accelerate and then
|
||||
# immediately decelerate. This option reduces the top speed of these
|
||||
# moves to ensure there is always a minimum distance traveled at a
|
||||
# cruising speed. That is, it enforces a minimum distance traveled
|
||||
# at cruising speed relative to the total distance traveled. It is
|
||||
# intended to reduce the top speed of short zigzag moves (and thus
|
||||
# reduce printer vibration from these moves). For example, a
|
||||
# minimum_cruise_ratio of 0.5 would ensure that a standalone 1.5mm
|
||||
# move would have a minimum cruising distance of 0.75mm. Specify a
|
||||
# ratio of 0.0 to disable this feature (there would be no minimum
|
||||
# cruising distance enforced between acceleration and deceleration).
|
||||
# The value specified here may be changed at runtime using the
|
||||
# SET_VELOCITY_LIMIT command. The default is 0.5.
|
||||
#square_corner_velocity: 5.0
|
||||
# The maximum velocity (in mm/s) that the toolhead may travel a 90
|
||||
# degree corner at. A non-zero value can reduce changes in extruder
|
||||
@@ -107,7 +122,11 @@ max_accel:
|
||||
# larger than 90 degrees will have a higher cornering velocity while
|
||||
# corners with angles less than 90 degrees will have a lower
|
||||
# cornering velocity. If this is set to zero then the toolhead will
|
||||
# decelerate to zero at each corner. The default is 5mm/s.
|
||||
# decelerate to zero at each corner. The value specified here may be
|
||||
# changed at runtime using the SET_VELOCITY_LIMIT command. The
|
||||
# default is 5mm/s.
|
||||
#max_accel_to_decel:
|
||||
# This parameter is deprecated and should no longer be used.
|
||||
```
|
||||
|
||||
### [stepper]
|
||||
@@ -971,18 +990,21 @@ Visual Examples:
|
||||
# where Z = 0. When this option is specified the mesh will be offset
|
||||
# so that zero Z adjustment occurs at this location. The default is
|
||||
# no zero reference.
|
||||
#relative_reference_index:
|
||||
# **DEPRECATED, use the "zero_reference_position" option**
|
||||
# The legacy option superceded by the "zero reference position".
|
||||
# Rather than a coordinate this option takes an integer "index" that
|
||||
# refers to the location of one of the generated points. It is recommended
|
||||
# to use the "zero_reference_position" instead of this option for new
|
||||
# configurations. The default is no relative reference index.
|
||||
#faulty_region_1_min:
|
||||
#faulty_region_1_max:
|
||||
# Optional points that define a faulty region. See docs/Bed_Mesh.md
|
||||
# for details on faulty regions. Up to 99 faulty regions may be added.
|
||||
# By default no faulty regions are set.
|
||||
#adaptive_margin:
|
||||
# An optional margin (in mm) to be added around the bed area used by
|
||||
# the defined print objects when generating an adaptive mesh.
|
||||
#scan_overshoot:
|
||||
# The maximum amount of travel (in mm) available outside of the mesh.
|
||||
# For rectangular beds this applies to travel on the X axis, and for round beds
|
||||
# it applies to the entire radius. The tool must be able to travel the amount
|
||||
# specified outside of the mesh. This value is used to optimize the travel
|
||||
# path when performing a "rapid scan". The minimum value that may be specified
|
||||
# is 1. The default is no overshoot.
|
||||
```
|
||||
|
||||
### [bed_tilt]
|
||||
@@ -1457,7 +1479,8 @@ path:
|
||||
# be provided.
|
||||
#on_error_gcode:
|
||||
# A list of G-Code commands to execute when an error is reported.
|
||||
|
||||
# See docs/Command_Templates.md for G-Code format. The default is to
|
||||
# run TURN_OFF_HEATERS.
|
||||
```
|
||||
|
||||
### [sdcard_loop]
|
||||
@@ -1980,6 +2003,43 @@ z_offset:
|
||||
# See the "probe" section for more information on the parameters above.
|
||||
```
|
||||
|
||||
### [probe_eddy_current]
|
||||
|
||||
Support for eddy current inductive probes. One may define this section
|
||||
(instead of a probe section) to enable this probe. See the
|
||||
[command reference](G-Codes.md#probe_eddy_current) for further information.
|
||||
|
||||
```
|
||||
[probe_eddy_current my_eddy_probe]
|
||||
sensor_type: ldc1612
|
||||
# The sensor chip used to perform eddy current measurements. This
|
||||
# parameter must be provided and must be set to ldc1612.
|
||||
#intb_pin:
|
||||
# MCU gpio pin connected to the ldc1612 sensor's INTB pin (if
|
||||
# available). The default is to not use the INTB pin.
|
||||
#z_offset:
|
||||
# The nominal distance (in mm) between the nozzle and bed that a
|
||||
# probing attempt should stop at. This parameter must be provided.
|
||||
#i2c_address:
|
||||
#i2c_mcu:
|
||||
#i2c_bus:
|
||||
#i2c_software_scl_pin:
|
||||
#i2c_software_sda_pin:
|
||||
#i2c_speed:
|
||||
# The i2c settings for the sensor chip. See the "common I2C
|
||||
# settings" section for a description of the above parameters.
|
||||
#x_offset:
|
||||
#y_offset:
|
||||
#speed:
|
||||
#lift_speed:
|
||||
#samples:
|
||||
#sample_retract_dist:
|
||||
#samples_result:
|
||||
#samples_tolerance:
|
||||
#samples_tolerance_retries:
|
||||
# See the "probe" section for information on these parameters.
|
||||
```
|
||||
|
||||
### [axis_twist_compensation]
|
||||
|
||||
A tool to compensate for inaccurate probe readings due to twist in X gantry. See
|
||||
@@ -2341,6 +2401,65 @@ temperature sensors that are reported via the M105 command.
|
||||
# parameter.
|
||||
```
|
||||
|
||||
### [temperature_probe]
|
||||
|
||||
Reports probe coil temperature. Includes optional thermal drift
|
||||
calibration for eddy current based probes. A `[temperature_probe]`
|
||||
section may be linked to a `[probe_eddy_current]` by using the same
|
||||
postfix for both sections.
|
||||
|
||||
```
|
||||
[temperature_probe my_probe]
|
||||
#sensor_type:
|
||||
#sensor_pin:
|
||||
#min_temp:
|
||||
#max_temp:
|
||||
# Temperature sensor configuration.
|
||||
# See the "extruder" section for the definition of the above
|
||||
# parameters.
|
||||
#smooth_time:
|
||||
# A time value (in seconds) over which temperature measurements will
|
||||
# be smoothed to reduce the impact of measurement noise. The default
|
||||
# is 2.0 seconds.
|
||||
#gcode_id:
|
||||
# See the "heater_generic" section for the definition of this
|
||||
# parameter.
|
||||
#speed:
|
||||
# The travel speed [mm/s] for xy moves during calibration. Default
|
||||
# is the speed defined by the probe.
|
||||
#horizontal_move_z:
|
||||
# The z distance [mm] from the bed at which xy moves will occur
|
||||
# during calibration. Default is 2mm.
|
||||
#resting_z:
|
||||
# The z distance [mm] from the bed at which the tool will rest
|
||||
# to heat the probe coil during calibration. Default is .4mm
|
||||
#calibration_position:
|
||||
# The X, Y, Z position where the tool should be moved when
|
||||
# probe drift calibration initializes. This is the location
|
||||
# where the first manual probe will occur. If omitted, the
|
||||
# default behavior is not to move the tool prior to the first
|
||||
# manual probe.
|
||||
#calibration_bed_temp:
|
||||
# The maximum safe bed temperature (in C) used to heat the probe
|
||||
# during probe drift calibration. When set, the calibration
|
||||
# procedure will turn on the bed after the first sample is
|
||||
# taken. When the calibration procedure is complete the bed
|
||||
# temperature will be set to zero. When omitted the default
|
||||
# behavior is not to set the bed temperature.
|
||||
#calibration_extruder_temp:
|
||||
# The extruder temperature (in C) set probe during drift calibration.
|
||||
# When this option is supplied the procedure will wait for until the
|
||||
# specified temperature is reached before requesting the first manual
|
||||
# probe. When the calibration procedure is complete the extruder
|
||||
# temperature will be set to 0. When omitted the default behavior is
|
||||
# not to set the extruder temperature.
|
||||
#extruder_heating_z: 50.
|
||||
# The Z location where extruder heating will occur if the
|
||||
# "calibration_extruder_temp" option is set. Its recommended to heat
|
||||
# the extruder some distance from the bed to minimize its impact on
|
||||
# the probe coil temperature. The default is 50.
|
||||
```
|
||||
|
||||
## Temperature sensors
|
||||
|
||||
Klipper includes definitions for many types of temperature sensors.
|
||||
@@ -2440,9 +2559,9 @@ sensor_pin:
|
||||
# name in the above list.
|
||||
```
|
||||
|
||||
### BMP280/BME280/BME680 temperature sensor
|
||||
### BMP180/BMP280/BME280/BMP388/BME680 temperature sensor
|
||||
|
||||
BMP280/BME280/BME680 two wire interface (I2C) environmental sensors.
|
||||
BMP180/BMP280/BME280/BMP388/BME680 two wire interface (I2C) environmental sensors.
|
||||
Note that these sensors are not intended for use with extruders and
|
||||
heater beds, but rather for monitoring ambient temperature (C),
|
||||
pressure (hPa), relative humidity and in case of the BME680 gas level.
|
||||
@@ -2453,8 +2572,8 @@ temperature.
|
||||
```
|
||||
sensor_type: BME280
|
||||
#i2c_address:
|
||||
# Default is 118 (0x76). Some BME280 sensors have an address of 119
|
||||
# (0x77).
|
||||
# Default is 118 (0x76). The BMP180, BMP388 and some BME280 sensors
|
||||
# have an address of 119 (0x77).
|
||||
#i2c_mcu:
|
||||
#i2c_bus:
|
||||
#i2c_software_scl_pin:
|
||||
@@ -2525,6 +2644,25 @@ sensor_type:
|
||||
# Interval in seconds between readings. Default is 30
|
||||
```
|
||||
|
||||
### SHT3X sensor
|
||||
|
||||
SHT3X family two wire interface (I2C) environmental sensor. These sensors
|
||||
have a range of -55~125 C, so are usable for e.g. chamber temperature
|
||||
monitoring. They can also function as simple fan/heater controllers.
|
||||
|
||||
```
|
||||
sensor_type: SHT3X
|
||||
#i2c_address:
|
||||
# Default is 68 (0x44).
|
||||
#i2c_mcu:
|
||||
#i2c_bus:
|
||||
#i2c_software_scl_pin:
|
||||
#i2c_software_sda_pin:
|
||||
#i2c_speed:
|
||||
# See the "common I2C settings" section for a description of the
|
||||
# above parameters.
|
||||
```
|
||||
|
||||
### LM75 temperature sensor
|
||||
|
||||
LM75/LM75A two wire (I2C) connected temperature sensors. These sensors
|
||||
@@ -2551,7 +2689,7 @@ sensor_type: LM75
|
||||
|
||||
### Builtin micro-controller temperature sensor
|
||||
|
||||
The atsam, atsamd, and stm32 micro-controllers contain an internal
|
||||
The atsam, atsamd, stm32 and rp2040 micro-controllers contain an internal
|
||||
temperature sensor. One can use the "temperature_mcu" sensor to
|
||||
monitor these temperatures.
|
||||
|
||||
@@ -3088,24 +3226,12 @@ pin:
|
||||
# If this is true, the value fields should be between 0 and 1; if it
|
||||
# is false the value fields should be either 0 or 1. The default is
|
||||
# False.
|
||||
#static_value:
|
||||
# If this is set, then the pin is assigned to this value at startup
|
||||
# and the pin can not be changed during runtime. A static pin uses
|
||||
# slightly less ram in the micro-controller. The default is to use
|
||||
# runtime configuration of pins.
|
||||
#value:
|
||||
# The value to initially set the pin to during MCU configuration.
|
||||
# The default is 0 (for low voltage).
|
||||
#shutdown_value:
|
||||
# The value to set the pin to on an MCU shutdown event. The default
|
||||
# is 0 (for low voltage).
|
||||
#maximum_mcu_duration:
|
||||
# The maximum duration a non-shutdown value may be driven by the MCU
|
||||
# without an acknowledge from the host.
|
||||
# If host can not keep up with an update, the MCU will shutdown
|
||||
# and set all pins to their respective shutdown values.
|
||||
# Default: 0 (disabled)
|
||||
# Usual values are around 5 seconds.
|
||||
#cycle_time: 0.100
|
||||
# The amount of time (in seconds) per PWM cycle. It is recommended
|
||||
# this be 10 milliseconds or greater when using software based PWM.
|
||||
@@ -3125,6 +3251,54 @@ pin:
|
||||
# then the 'value' parameter can be specified using the desired
|
||||
# amperage for the stepper. The default is to not scale the 'value'
|
||||
# parameter.
|
||||
#maximum_mcu_duration:
|
||||
#static_value:
|
||||
# These options are deprecated and should no longer be specified.
|
||||
```
|
||||
|
||||
### [pwm_tool]
|
||||
|
||||
Pulse width modulation digital output pins capable of high speed
|
||||
updates (one may define any number of sections with an "output_pin"
|
||||
prefix). Pins configured here will be setup as output pins and one may
|
||||
modify them at run-time using "SET_PIN PIN=my_pin VALUE=.1" type
|
||||
extended [g-code commands](G-Codes.md#output_pin).
|
||||
|
||||
```
|
||||
[pwm_tool my_tool]
|
||||
pin:
|
||||
# The pin to configure as an output. This parameter must be provided.
|
||||
#maximum_mcu_duration:
|
||||
# The maximum duration a non-shutdown value may be driven by the MCU
|
||||
# without an acknowledge from the host.
|
||||
# If host can not keep up with an update, the MCU will shutdown
|
||||
# and set all pins to their respective shutdown values.
|
||||
# Default: 0 (disabled)
|
||||
# Usual values are around 5 seconds.
|
||||
#value:
|
||||
#shutdown_value:
|
||||
#cycle_time: 0.100
|
||||
#hardware_pwm: False
|
||||
#scale:
|
||||
# See the "output_pin" section for the definition of these parameters.
|
||||
```
|
||||
|
||||
### [pwm_cycle_time]
|
||||
|
||||
Run-time configurable output pins with dynamic pwm cycle timing (one
|
||||
may define any number of sections with an "pwm_cycle_time" prefix).
|
||||
Pins configured here will be setup as output pins and one may modify
|
||||
them at run-time using "SET_PIN PIN=my_pin VALUE=.1 CYCLE_TIME=0.100"
|
||||
type extended [g-code commands](G-Codes.md#pwm_cycle_time).
|
||||
|
||||
```
|
||||
[pwm_cycle_time my_pin]
|
||||
pin:
|
||||
#value:
|
||||
#shutdown_value:
|
||||
#cycle_time: 0.100
|
||||
#scale:
|
||||
# See the "output_pin" section for information on these parameters.
|
||||
```
|
||||
|
||||
### [static_digital_output]
|
||||
@@ -3212,6 +3386,18 @@ run_current:
|
||||
# set, "stealthChop" mode will be enabled if the stepper motor
|
||||
# velocity is below this value. The default is 0, which disables
|
||||
# "stealthChop" mode.
|
||||
#coolstep_threshold:
|
||||
# The velocity (in mm/s) to set the TMC driver internal "CoolStep"
|
||||
# threshold to. If set, the coolstep feature will be enabled when
|
||||
# the stepper motor velocity is near or above this value. Important
|
||||
# - if coolstep_threshold is set and "sensorless homing" is used,
|
||||
# then one must ensure that the homing speed is above the coolstep
|
||||
# threshold! The default is to not enable the coolstep feature.
|
||||
#high_velocity_threshold:
|
||||
# The velocity (in mm/s) to set the TMC driver internal "high
|
||||
# velocity" threshold (THIGH) to. This is typically used to disable
|
||||
# the "CoolStep" feature at high speeds. The default is to not set a
|
||||
# TMC "high velocity" threshold.
|
||||
#driver_MSLUT0: 2863314260
|
||||
#driver_MSLUT1: 1251300522
|
||||
#driver_MSLUT2: 608774441
|
||||
@@ -3242,11 +3428,19 @@ run_current:
|
||||
#driver_TOFF: 4
|
||||
#driver_HEND: 7
|
||||
#driver_HSTRT: 0
|
||||
#driver_VHIGHFS: 0
|
||||
#driver_VHIGHCHM: 0
|
||||
#driver_PWM_AUTOSCALE: True
|
||||
#driver_PWM_FREQ: 1
|
||||
#driver_PWM_GRAD: 4
|
||||
#driver_PWM_AMPL: 128
|
||||
#driver_SGT: 0
|
||||
#driver_SEMIN: 0
|
||||
#driver_SEUP: 0
|
||||
#driver_SEMAX: 0
|
||||
#driver_SEDN: 0
|
||||
#driver_SEIMIN: 0
|
||||
#driver_SFILT: 0
|
||||
# Set the given register during the configuration of the TMC2130
|
||||
# chip. This may be used to set custom motor parameters. The
|
||||
# defaults for each parameter are next to the parameter name in the
|
||||
@@ -3343,6 +3537,13 @@ run_current:
|
||||
#sense_resistor: 0.110
|
||||
#stealthchop_threshold: 0
|
||||
# See the "tmc2208" section for the definition of these parameters.
|
||||
#coolstep_threshold:
|
||||
# The velocity (in mm/s) to set the TMC driver internal "CoolStep"
|
||||
# threshold to. If set, the coolstep feature will be enabled when
|
||||
# the stepper motor velocity is near or above this value. Important
|
||||
# - if coolstep_threshold is set and "sensorless homing" is used,
|
||||
# then one must ensure that the homing speed is above the coolstep
|
||||
# threshold! The default is to not enable the coolstep feature.
|
||||
#uart_address:
|
||||
# The address of the TMC2209 chip for UART messages (an integer
|
||||
# between 0 and 3). This is typically used when multiple TMC2209
|
||||
@@ -3362,6 +3563,11 @@ run_current:
|
||||
#driver_PWM_GRAD: 14
|
||||
#driver_PWM_OFS: 36
|
||||
#driver_SGTHRS: 0
|
||||
#driver_SEMIN: 0
|
||||
#driver_SEUP: 0
|
||||
#driver_SEMAX: 0
|
||||
#driver_SEDN: 0
|
||||
#driver_SEIMIN: 0
|
||||
# Set the given register during the configuration of the TMC2209
|
||||
# chip. This may be used to set custom motor parameters. The
|
||||
# defaults for each parameter are next to the parameter name in the
|
||||
@@ -3496,6 +3702,18 @@ run_current:
|
||||
# set, "stealthChop" mode will be enabled if the stepper motor
|
||||
# velocity is below this value. The default is 0, which disables
|
||||
# "stealthChop" mode.
|
||||
#coolstep_threshold:
|
||||
# The velocity (in mm/s) to set the TMC driver internal "CoolStep"
|
||||
# threshold to. If set, the coolstep feature will be enabled when
|
||||
# the stepper motor velocity is near or above this value. Important
|
||||
# - if coolstep_threshold is set and "sensorless homing" is used,
|
||||
# then one must ensure that the homing speed is above the coolstep
|
||||
# threshold! The default is to not enable the coolstep feature.
|
||||
#high_velocity_threshold:
|
||||
# The velocity (in mm/s) to set the TMC driver internal "high
|
||||
# velocity" threshold (THIGH) to. This is typically used to disable
|
||||
# the "CoolStep" feature at high speeds. The default is to not set a
|
||||
# TMC "high velocity" threshold.
|
||||
#driver_MSLUT0: 2863314260
|
||||
#driver_MSLUT1: 1251300522
|
||||
#driver_MSLUT2: 608774441
|
||||
@@ -3617,6 +3835,18 @@ run_current:
|
||||
# set, "stealthChop" mode will be enabled if the stepper motor
|
||||
# velocity is below this value. The default is 0, which disables
|
||||
# "stealthChop" mode.
|
||||
#coolstep_threshold:
|
||||
# The velocity (in mm/s) to set the TMC driver internal "CoolStep"
|
||||
# threshold to. If set, the coolstep feature will be enabled when
|
||||
# the stepper motor velocity is near or above this value. Important
|
||||
# - if coolstep_threshold is set and "sensorless homing" is used,
|
||||
# then one must ensure that the homing speed is above the coolstep
|
||||
# threshold! The default is to not enable the coolstep feature.
|
||||
#high_velocity_threshold:
|
||||
# The velocity (in mm/s) to set the TMC driver internal "high
|
||||
# velocity" threshold (THIGH) to. This is typically used to disable
|
||||
# the "CoolStep" feature at high speeds. The default is to not set a
|
||||
# TMC "high velocity" threshold.
|
||||
#driver_MSLUT0: 2863314260
|
||||
#driver_MSLUT1: 1251300522
|
||||
#driver_MSLUT2: 608774441
|
||||
@@ -4400,6 +4630,9 @@ adc2:
|
||||
# command.
|
||||
#min_diameter: 1.0
|
||||
# Minimal diameter for trigger virtual filament_switch_sensor.
|
||||
#max_diameter:
|
||||
# Maximum diameter for triggering virtual filament_switch_sensor.
|
||||
# The default is default_nominal_filament_diameter + max_difference.
|
||||
#use_current_dia_while_delay: False
|
||||
# Use the current diameter instead of the nominal diameter while
|
||||
# the measurement delay has not run through.
|
||||
@@ -4412,6 +4645,95 @@ adc2:
|
||||
# above parameters.
|
||||
```
|
||||
|
||||
## Load Cells
|
||||
|
||||
### [load_cell]
|
||||
Load Cell. Uses an ADC sensor attached to a load cell to create a digital
|
||||
scale.
|
||||
|
||||
```
|
||||
[load_cell]
|
||||
sensor_type:
|
||||
# This must be one of the supported sensor types, see below.
|
||||
```
|
||||
|
||||
#### XH711
|
||||
This is a 24 bit low sample rate chip using "bit-bang" communications. It is
|
||||
suitable for filament scales.
|
||||
```
|
||||
[load_cell]
|
||||
sensor_type: hx711
|
||||
sclk_pin:
|
||||
# The pin connected to the HX711 clock line. This parameter must be provided.
|
||||
dout_pin:
|
||||
# The pin connected to the HX711 data output line. This parameter must be
|
||||
# provided.
|
||||
#gain: A-128
|
||||
# Valid values for gain are: A-128, A-64, B-32. The default is A-128.
|
||||
# 'A' denotes the input channel and the number denotes the gain. Only the 3
|
||||
# listed combinations are supported by the chip. Note that changing the gain
|
||||
# setting also selects the channel being read.
|
||||
#sample_rate: 80
|
||||
# Valid values for sample_rate are 80 or 10. The default value is 80.
|
||||
# This must match the wiring of the chip. The sample rate cannot be changed
|
||||
# in software.
|
||||
```
|
||||
|
||||
#### HX717
|
||||
This is the 4x higher sample rate version of the HX711, suitable for probing.
|
||||
```
|
||||
[load_cell]
|
||||
sensor_type: hx717
|
||||
sclk_pin:
|
||||
# The pin connected to the HX717 clock line. This parameter must be provided.
|
||||
dout_pin:
|
||||
# The pin connected to the HX717 data output line. This parameter must be
|
||||
# provided.
|
||||
#gain: A-128
|
||||
# Valid values for gain are A-128, B-64, A-64, B-8.
|
||||
# 'A' denotes the input channel and the number denotes the gain setting.
|
||||
# Only the 4 listed combinations are supported by the chip. Note that
|
||||
# changing the gain setting also selects the channel being read.
|
||||
#sample_rate: 320
|
||||
# Valid values for sample_rate are: 10, 20, 80, 320. The default is 320.
|
||||
# This must match the wiring of the chip. The sample rate cannot be changed
|
||||
# in software.
|
||||
```
|
||||
|
||||
#### ADS1220
|
||||
The ADS1220 is a 24 bit ADC supporting up to a 2Khz sample rate configurable in
|
||||
software.
|
||||
```
|
||||
[load_cell]
|
||||
sensor_type: ads1220
|
||||
cs_pin:
|
||||
# The pin connected to the ADS1220 chip select line. This parameter must
|
||||
# be provided.
|
||||
#spi_speed: 512000
|
||||
# This chip supports 2 speeds: 256000 or 512000. The faster speed is only
|
||||
# enabled when one of the Turbo sample rates is used. The correct spi_speed
|
||||
# is selected based on the sample rate.
|
||||
#spi_bus:
|
||||
#spi_software_sclk_pin:
|
||||
#spi_software_mosi_pin:
|
||||
#spi_software_miso_pin:
|
||||
# See the "common SPI settings" section for a description of the
|
||||
# above parameters.
|
||||
data_ready_pin:
|
||||
# Pin connected to the ADS1220 data ready line. This parameter must be
|
||||
# provided.
|
||||
#gain: 128
|
||||
# Valid gain values are 128, 64, 32, 16, 8, 4, 2, 1
|
||||
# The default is 128
|
||||
#sample_rate: 660
|
||||
# This chip supports two ranges of sample rates, Normal and Turbo. In turbo
|
||||
# mode the chips c internal clock runs twice as fast and the SPI communication
|
||||
# speed is also doubled.
|
||||
# Normal sample rates: 20, 45, 90, 175, 330, 600, 1000
|
||||
# Turbo sample rates: 40, 90, 180, 350, 660, 1200, 2000
|
||||
# The default is 660
|
||||
```
|
||||
|
||||
## Board specific hardware support
|
||||
|
||||
### [sx1509]
|
||||
|
||||
144
docs/Eddy_Probe.md
Normal file
144
docs/Eddy_Probe.md
Normal file
@@ -0,0 +1,144 @@
|
||||
# Eddy Current Inductive probe
|
||||
|
||||
This document describes how to use an
|
||||
[eddy current](https://en.wikipedia.org/wiki/Eddy_current) inductive
|
||||
probe in Klipper.
|
||||
|
||||
Currently, an eddy current probe can not be used for Z homing. The
|
||||
sensor can only be used for Z probing.
|
||||
|
||||
Start by declaring a
|
||||
[probe_eddy_current config section](Config_Reference.md#probe_eddy_current)
|
||||
in the printer.cfg file. It is recommended to set the `z_offset` to
|
||||
0.5mm. It is typical for the sensor to require an `x_offset` and
|
||||
`y_offset`. If these values are not known, one should estimate the
|
||||
values during initial calibration.
|
||||
|
||||
The first step in calibration is to determine the appropriate
|
||||
DRIVE_CURRENT for the sensor. Home the printer and navigate the
|
||||
toolhead so that the sensor is near the center of the bed and is about
|
||||
20mm above the bed. Then issue an `LDC_CALIBRATE_DRIVE_CURRENT
|
||||
CHIP=<config_name>` command. For example, if the config section was
|
||||
named `[probe_eddy_current my_eddy_probe]` then one would run
|
||||
`LDC_CALIBRATE_DRIVE_CURRENT CHIP=my_eddy_probe`. This command should
|
||||
complete in a few seconds. After it completes, issue a `SAVE_CONFIG`
|
||||
command to save the results to the printer.cfg and restart.
|
||||
|
||||
The second step in calibration is to correlate the sensor readings to
|
||||
the corresponding Z heights. Home the printer and navigate the
|
||||
toolhead so that the nozzle is near the center of the bed. Then run an
|
||||
`PROBE_EDDY_CURRENT_CALIBRATE CHIP=my_eddy_probe` command. Once the
|
||||
tool starts, follow the steps described at
|
||||
["the paper test"](Bed_Level.md#the-paper-test) to determine the
|
||||
actual distance between the nozzle and bed at the given location. Once
|
||||
those steps are complete one can `ACCEPT` the position. The tool will
|
||||
then move the the toolhead so that the sensor is above the point where
|
||||
the nozzle used to be and run a series of movements to correlate the
|
||||
sensor to Z positions. This will take a couple of minutes. After the
|
||||
tool completes, issue a `SAVE_CONFIG` command to save the results to
|
||||
the printer.cfg and restart.
|
||||
|
||||
After initial calibration it is a good idea to verify that the
|
||||
`x_offset` and `y_offset` are accurate. Follow the steps to
|
||||
[calibrate probe x and y offsets](Probe_Calibrate.md#calibrating-probe-x-and-y-offsets).
|
||||
If either the `x_offset` or `y_offset` is modified then be sure to run
|
||||
the `PROBE_EDDY_CURRENT_CALIBRATE` command (as described above) after
|
||||
making the change.
|
||||
|
||||
Once calibration is complete, one may use all the standard Klipper
|
||||
tools that use a Z probe.
|
||||
|
||||
Note that eddy current sensors (and inductive probes in general) are
|
||||
susceptible to "thermal drift". That is, changes in temperature can
|
||||
result in changes in reported Z height. Changes in either the bed
|
||||
surface temperature or sensor hardware temperature can skew the
|
||||
results. It is important that calibration and probing is only done
|
||||
when the printer is at a stable temperature.
|
||||
|
||||
## Thermal Drift Calibration
|
||||
|
||||
As with all inductive probes, eddy current probes are subject to
|
||||
significant thermal drift. If the eddy probe has a temperature
|
||||
sensor on the coil it is possible to configure a `[temperature_probe]`
|
||||
to report coil temperature and enable software drift compensation. To
|
||||
link a temperature probe to an eddy current probe the
|
||||
`[temperature_probe]` section must share a name with the
|
||||
`[probe_eddy_current]` section. For example:
|
||||
|
||||
```
|
||||
[probe_eddy_current my_probe]
|
||||
# eddy probe configuration...
|
||||
|
||||
[temperature_probe my_probe]
|
||||
# temperature probe configuration...
|
||||
```
|
||||
|
||||
See the [configuration reference](Config_Reference.md#temperature_probe)
|
||||
for further details on how to configure a `temperature_probe`. It is
|
||||
advised to configure the `calibration_position`,
|
||||
`calibration_extruder_temp`, `extruder_heating_z`, and
|
||||
`calibration_bed_temp` options, as doing so will automate some of the
|
||||
steps outlined below.
|
||||
|
||||
Eddy probe manufacturers may offer a stock drift calibration that can be
|
||||
manually added to `drift_calibration` option of the `[probe_eddy_current]`
|
||||
section. If they do not, or if the stock calibration does not perform well on
|
||||
your system, the `temperature_probe` module offers a manual calibration
|
||||
procedure via the `TEMPERATURE_PROBE_CALIBRATE` gcode command.
|
||||
|
||||
Prior to performing calibration the user should have an idea of what the
|
||||
maximum attainable temperature probe coil temperature is. This temperature
|
||||
should be used to set the `TARGET` parameter of the
|
||||
`TEMPERATURE_PROBE_CALIBRATE` command. The goal is to calibrate across the
|
||||
widest temperature range possible, thus its desirable to start with the printer
|
||||
cold and finish with the coil at the maximum temperature it can reach.
|
||||
|
||||
Once a `[temperature_probe]` is configured, the following steps may be taken
|
||||
to perform thermal drift calibration:
|
||||
|
||||
- The probe must be calibrated using `PROBE_EDDY_CURRENT_CALIBRATE`
|
||||
when a `[temperature_probe]` is configured and linked. This captures
|
||||
the temperature during calibration which is necessary to perform
|
||||
thermal drift compensation.
|
||||
- Make sure the nozzle is free of debris and filament.
|
||||
- The bed, nozzle, and probe coil should be cold prior to calibration.
|
||||
- The following steps are required if the `calibration_position`,
|
||||
`calibration_extruder_temp`, and `extruder_heating_z` options in
|
||||
`[temperature_probe]` are **NOT** configured:
|
||||
- Move the tool to the center of the bed. Z should be 30mm+ above the bed.
|
||||
- Heat the extruder to a temperature above the maximum safe bed temperature.
|
||||
150-170C should be sufficient for most configurations. The purpose of
|
||||
heating the extruder is to avoid nozzle expansion during calibration.
|
||||
- When the extruder temperature has settled, move the Z axis down to about 1mm
|
||||
above the bed.
|
||||
- Start drift calibration. If the probe's name is `my_probe` and the maximum
|
||||
probe temperature we can achieve is 80C, the appropriate gcode command is
|
||||
`TEMPERATURE_PROBE_CALIBRATE PROBE=my_probe TARGET=80`. If configured, the
|
||||
tool will move to the X,Y coordinate specified by the `calibration_position`
|
||||
and the Z value specified by `extruder_heating_z`. After heating the extruder
|
||||
to the specified temperature the tool will move to the Z value specified
|
||||
by the`calibration_position`.
|
||||
- The procedure will request a manual probe. Perform the manual probe with
|
||||
the paper test and `ACCEPT`. The calibration procedure will take the first
|
||||
set of samples with the probe then park the probe in the heating position.
|
||||
- If the `calibration_bed_temp` is **NOT** configured turn on the bed heat
|
||||
to the maximum safe temperature. Otherwise this step will be performed
|
||||
automatically.
|
||||
- By default the calibration procedure will request a manual probe every
|
||||
2C between samples until the `TARGET` is reached. The temperature delta
|
||||
between samples can be customized by setting the `STEP` parameter in
|
||||
`TEMPERATURE_PROBE_CALIBRATE`. Care should be taken when setting a custom
|
||||
`STEP` value, a value too high may request too few samples resulting in
|
||||
a poor calibration.
|
||||
- The following additional gcode commands are available during drift
|
||||
calibration:
|
||||
- `TEMPERATURE_PROBE_NEXT` may be used to force a new sample before the step
|
||||
delta has been reached.
|
||||
- `TEMPERATURE_PROBE_COMPLETE` may be used to complete calibration before the
|
||||
`TARGET` has been reached.
|
||||
- `ABORT` may be used to end calibration and discard results.
|
||||
- When calibration is finished use `SAVE_CONFIG` to store the drift
|
||||
calibration.
|
||||
|
||||
As one may conclude, the calibration process outlined above is more challenging
|
||||
and time consuming than most other procedures. It may require practice and several attempts to achieve an optimal calibration.
|
||||
152
docs/G-Codes.md
152
docs/G-Codes.md
@@ -139,6 +139,17 @@ Writes raw "value" into register "register". Both "value" and
|
||||
and refer to sensor data sheet for the reference. This is only
|
||||
available for tle5012b chips.
|
||||
|
||||
### [axis_twist_compensation]
|
||||
|
||||
The following commands are available when the
|
||||
[axis_twist_compensation config
|
||||
section](Config_Reference.md#axis_twist_compensation) is enabled.
|
||||
|
||||
#### AXIS_TWIST_COMPENSATION_CALIBRATE
|
||||
`AXIS_TWIST_COMPENSATION_CALIBRATE [SAMPLE_COUNT=<value>]`: Initiates the X
|
||||
twist calibration wizard. `SAMPLE_COUNT` specifies the number of points along
|
||||
the X axis to calibrate at and defaults to 3.
|
||||
|
||||
### [bed_mesh]
|
||||
|
||||
The following commands are available when the
|
||||
@@ -146,15 +157,21 @@ The following commands are available when the
|
||||
(also see the [bed mesh guide](Bed_Mesh.md)).
|
||||
|
||||
#### BED_MESH_CALIBRATE
|
||||
`BED_MESH_CALIBRATE [METHOD=manual] [HORIZONTAL_MOVE_Z=<value>]
|
||||
[<probe_parameter>=<value>] [<mesh_parameter>=<value>]`: This command probes
|
||||
the bed using generated points specified by the parameters in the config. After
|
||||
probing, a mesh is generated and z-movement is adjusted according to the mesh.
|
||||
`BED_MESH_CALIBRATE [PROFILE=<name>] [METHOD=manual] [HORIZONTAL_MOVE_Z=<value>]
|
||||
[<probe_parameter>=<value>] [<mesh_parameter>=<value>] [ADAPTIVE=1]
|
||||
[ADAPTIVE_MARGIN=<value>]`: This command probes the bed using generated points
|
||||
specified by the parameters in the config. After probing, a mesh is generated
|
||||
and z-movement is adjusted according to the mesh.
|
||||
The mesh will be saved into a profile specified by the `PROFILE` parameter,
|
||||
or `default` if unspecified.
|
||||
See the PROBE command for details on the optional probe parameters. If
|
||||
METHOD=manual is specified then the manual probing tool is activated - see the
|
||||
MANUAL_PROBE command above for details on the additional commands available
|
||||
while this tool is active. The optional `HORIZONTAL_MOVE_Z` value overrides the
|
||||
`horizontal_move_z` option specified in the config file.
|
||||
`horizontal_move_z` option specified in the config file. If ADAPTIVE=1 is
|
||||
specified then the objects defined by the Gcode file being printed will be used
|
||||
to define the probed area. The optional `ADAPTIVE_MARGIN` value overrides the
|
||||
`adaptive_margin` option specified in the config file.
|
||||
|
||||
#### BED_MESH_OUTPUT
|
||||
`BED_MESH_OUTPUT PGP=[<0:1>]`: This command outputs the current probed
|
||||
@@ -184,10 +201,12 @@ SAVE_CONFIG gcode must be run to make the changes to persistent memory
|
||||
permanent.
|
||||
|
||||
#### BED_MESH_OFFSET
|
||||
`BED_MESH_OFFSET [X=<value>] [Y=<value>]`: Applies X and/or Y offsets
|
||||
to the mesh lookup. This is useful for printers with independent
|
||||
extruders, as an offset is necessary to produce correct Z adjustment
|
||||
after a tool change.
|
||||
`BED_MESH_OFFSET [X=<value>] [Y=<value>] [ZFADE=<value]`: Applies X, Y,
|
||||
and/or ZFADE offsets to the mesh lookup. This is useful for printers with
|
||||
independent extruders, as an offset is necessary to produce correct Z
|
||||
adjustment after a tool change. Note that a ZFADE offset does not apply
|
||||
additional z-adjustment directly, it is used to correct the `fade`
|
||||
calculation when a `gcode offset` has been applied to the Z axis.
|
||||
|
||||
### [bed_screws]
|
||||
|
||||
@@ -447,12 +466,6 @@ MOTION_QUEUE (as defined in an [extruder](Config_Reference.md#extruder)
|
||||
config section). If MOTION_QUEUE is an empty string then the stepper
|
||||
will be desynchronized from all extruder movement.
|
||||
|
||||
#### SET_EXTRUDER_STEP_DISTANCE
|
||||
This command is deprecated and will be removed in the near future.
|
||||
|
||||
#### SYNC_STEPPER_TO_EXTRUDER
|
||||
This command is deprecated and will be removed in the near future.
|
||||
|
||||
### [fan_generic]
|
||||
|
||||
The following command is available when a
|
||||
@@ -834,21 +847,15 @@ commands to manage the LED's color settings).
|
||||
### [output_pin]
|
||||
|
||||
The following command is available when an
|
||||
[output_pin config section](Config_Reference.md#output_pin) is
|
||||
[output_pin config section](Config_Reference.md#output_pin) or
|
||||
[pwm_tool config section](Config_Reference.md#pwm_tool) is
|
||||
enabled.
|
||||
|
||||
#### SET_PIN
|
||||
`SET_PIN PIN=config_name VALUE=<value> [CYCLE_TIME=<cycle_time>]`: Set
|
||||
the pin to the given output `VALUE`. VALUE should be 0 or 1 for
|
||||
"digital" output pins. For PWM pins, set to a value between 0.0 and
|
||||
1.0, or between 0.0 and `scale` if a scale is configured in the
|
||||
output_pin config section.
|
||||
|
||||
Some pins (currently only "soft PWM" pins) support setting an explicit
|
||||
cycle time using the CYCLE_TIME parameter (specified in seconds). Note
|
||||
that the CYCLE_TIME parameter is not stored between SET_PIN commands
|
||||
(any SET_PIN command without an explicit CYCLE_TIME parameter will use
|
||||
the `cycle_time` specified in the output_pin config section).
|
||||
`SET_PIN PIN=config_name VALUE=<value>`: Set the pin to the given
|
||||
output `VALUE`. VALUE should be 0 or 1 for "digital" output pins. For
|
||||
PWM pins, set to a value between 0.0 and 1.0, or between 0.0 and
|
||||
`scale` if a scale is configured in the output_pin config section.
|
||||
|
||||
### [palette2]
|
||||
|
||||
@@ -977,6 +984,43 @@ babystepping), and subtract if from the probe's z_offset. This acts
|
||||
to take a frequently used babystepping value, and "make it permanent".
|
||||
Requires a `SAVE_CONFIG` to take effect.
|
||||
|
||||
### [probe_eddy_current]
|
||||
|
||||
The following commands are available when a
|
||||
[probe_eddy_current config section](Config_Reference.md#probe_eddy_current)
|
||||
is enabled.
|
||||
|
||||
#### PROBE_EDDY_CURRENT_CALIBRATE
|
||||
`PROBE_EDDY_CURRENT_CALIBRATE CHIP=<config_name>`: This starts a tool
|
||||
that calibrates the sensor resonance frequencies to corresponding Z
|
||||
heights. The tool will take a couple of minutes to complete. After
|
||||
completion, use the SAVE_CONFIG command to store the results in the
|
||||
printer.cfg file.
|
||||
|
||||
#### LDC_CALIBRATE_DRIVE_CURRENT
|
||||
`LDC_CALIBRATE_DRIVE_CURRENT CHIP=<config_name>` This tool will
|
||||
calibrate the ldc1612 DRIVE_CURRENT0 register. Prior to using this
|
||||
tool, move the sensor so that it is near the center of the bed and
|
||||
about 20mm above the bed surface. Run this command to determine an
|
||||
appropriate DRIVE_CURRENT for the sensor. After running this command
|
||||
use the SAVE_CONFIG command to store that new setting in the
|
||||
printer.cfg config file.
|
||||
|
||||
### [pwm_cycle_time]
|
||||
|
||||
The following command is available when a
|
||||
[pwm_cycle_time config section](Config_Reference.md#pwm_cycle_time)
|
||||
is enabled.
|
||||
|
||||
#### SET_PIN
|
||||
`SET_PIN PIN=config_name VALUE=<value> [CYCLE_TIME=<cycle_time>]`:
|
||||
This command works similarly to [output_pin](#output_pin) SET_PIN
|
||||
commands. The command here supports setting an explicit cycle time
|
||||
using the CYCLE_TIME parameter (specified in seconds). Note that the
|
||||
CYCLE_TIME parameter is not stored between SET_PIN commands (any
|
||||
SET_PIN command without an explicit CYCLE_TIME parameter will use the
|
||||
`cycle_time` specified in the pwm_cycle_time config section).
|
||||
|
||||
### [query_adc]
|
||||
|
||||
The query_adc module is automatically loaded.
|
||||
@@ -1280,8 +1324,11 @@ The toolhead module is automatically loaded.
|
||||
|
||||
#### SET_VELOCITY_LIMIT
|
||||
`SET_VELOCITY_LIMIT [VELOCITY=<value>] [ACCEL=<value>]
|
||||
[ACCEL_TO_DECEL=<value>] [SQUARE_CORNER_VELOCITY=<value>]`: Modify the
|
||||
printer's velocity limits.
|
||||
[MINIMUM_CRUISE_RATIO=<value>] [SQUARE_CORNER_VELOCITY=<value>]`: This
|
||||
command can alter the velocity limits that were specified in the
|
||||
printer config file. See the
|
||||
[printer config section](Config_Reference.md#printer) for a
|
||||
description of each parameter.
|
||||
|
||||
### [tuning_tower]
|
||||
|
||||
@@ -1339,17 +1386,6 @@ print.
|
||||
#### SDCARD_RESET_FILE
|
||||
`SDCARD_RESET_FILE`: Unload file and clear SD state.
|
||||
|
||||
### [axis_twist_compensation]
|
||||
|
||||
The following commands are available when the
|
||||
[axis_twist_compensation config
|
||||
section](Config_Reference.md#axis_twist_compensation) is enabled.
|
||||
|
||||
#### AXIS_TWIST_COMPENSATION_CALIBRATE
|
||||
`AXIS_TWIST_COMPENSATION_CALIBRATE [SAMPLE_COUNT=<value>]`: Initiates the X
|
||||
twist calibration wizard. `SAMPLE_COUNT` specifies the number of points along
|
||||
the X axis to calibrate at and defaults to 3.
|
||||
|
||||
### [z_thermal_adjust]
|
||||
|
||||
The following commands are available when the
|
||||
@@ -1379,3 +1415,39 @@ command will probe the points specified in the config and then make independent
|
||||
adjustments to each Z stepper to compensate for tilt. See the PROBE command for
|
||||
details on the optional probe parameters. The optional `HORIZONTAL_MOVE_Z`
|
||||
value overrides the `horizontal_move_z` option specified in the config file.
|
||||
|
||||
### [temperature_probe]
|
||||
|
||||
The following commands are available when a
|
||||
[temperature_probe config section](Config_Reference.md#temperature_probe)
|
||||
is enabled.
|
||||
|
||||
#### TEMPERATURE_PROBE_CALIBRATE
|
||||
`TEMPERATURE_PROBE_CALIBRATE [PROBE=<probe name>] [TARGET=<value>] [STEP=<value>]`:
|
||||
Initiates probe drift calibration for eddy current based probes. The `TARGET`
|
||||
is a target temperature for the last sample. When the temperature recorded
|
||||
during a sample exceeds the `TARGET` calibration will complete. The `STEP`
|
||||
parameter sets temperature delta (in C) between samples. After a sample has
|
||||
been taken, this delta is used to schedule a call to `TEMPERATURE_PROBE_NEXT`.
|
||||
The default `STEP` is 2.
|
||||
|
||||
#### TEMPERATURE_PROBE_NEXT
|
||||
`TEMPERATURE_PROBE_NEXT`: After calibration has started this command is run to
|
||||
take the next sample. It is automatically scheduled to run when the delta
|
||||
specified by `STEP` has been reached, however its also possible to manually run
|
||||
this command to force a new sample. This command is only available during
|
||||
calibration.
|
||||
|
||||
#### TEMPERATURE_PROBE_COMPLETE:
|
||||
`TEMPERATURE_PROBE_COMPLETE`: Can be used to end calibration and save the
|
||||
current result before the `TARGET` temperature is reached. This command
|
||||
is only available during calibration.
|
||||
|
||||
#### ABORT
|
||||
`ABORT`: Aborts the calibration process, discarding the current results.
|
||||
This command is only available during drift calibration.
|
||||
|
||||
### TEMPERATURE_PROBE_ENABLE
|
||||
`TEMPERATURE_PROBE_ENABLE ENABLE=[0|1]`: Sets temperature drift
|
||||
compensation on or off. If ENABLE is set to 0, drift compensation
|
||||
will be disabled, if set to 1 it is enabled.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
These instructions assume the software will run on a Raspberry Pi
|
||||
computer in conjunction with OctoPrint. It is recommended that a
|
||||
Raspberry Pi 2, 3, or 4 computer be used as the host machine (see the
|
||||
Raspberry Pi 2 (or later) be used as the host machine (see the
|
||||
[FAQ](FAQ.md#can-i-run-klipper-on-something-other-than-a-raspberry-pi-3)
|
||||
for other machines).
|
||||
|
||||
@@ -50,7 +50,7 @@ using a Linux or MacOS desktop, then the "ssh" software should already
|
||||
be installed on the desktop. There are free ssh clients available for
|
||||
other desktops (eg,
|
||||
[PuTTY](https://www.chiark.greenend.org.uk/~sgtatham/putty/)). Use the
|
||||
ssh utility to connect to the Raspberry Pi (ssh pi@octopi -- password
|
||||
ssh utility to connect to the Raspberry Pi (`ssh pi@octopi` -- password
|
||||
is "raspberry") and run the following commands:
|
||||
|
||||
```
|
||||
@@ -135,18 +135,18 @@ web page and then configure the following items:
|
||||
|
||||
Navigate to the Settings tab (the wrench icon at the top of the
|
||||
page). Under "Serial Connection" in "Additional serial ports" add
|
||||
"/tmp/printer". Then click "Save".
|
||||
`/tmp/printer`. Then click "Save".
|
||||
|
||||
Enter the Settings tab again and under "Serial Connection" change the
|
||||
"Serial Port" setting to "/tmp/printer".
|
||||
"Serial Port" setting to `/tmp/printer`.
|
||||
|
||||
In the Settings tab, navigate to the "Behavior" sub-tab and select the
|
||||
"Cancel any ongoing prints but stay connected to the printer"
|
||||
option. Click "Save".
|
||||
|
||||
From the main page, under the "Connection" section (at the top left of
|
||||
the page) make sure the "Serial Port" is set to "/tmp/printer" and
|
||||
click "Connect". (If "/tmp/printer" is not an available selection then
|
||||
the page) make sure the "Serial Port" is set to `/tmp/printer` and
|
||||
click "Connect". (If `/tmp/printer` is not an available selection then
|
||||
try reloading the page.)
|
||||
|
||||
Once connected, navigate to the "Terminal" tab and type "status"
|
||||
@@ -165,8 +165,8 @@ Arguably the easiest way to set the Klipper configuration file is to
|
||||
use a desktop editor that supports editing files over the "scp" and/or
|
||||
"sftp" protocols. There are freely available tools that support this
|
||||
(eg, Notepad++, WinSCP, and Cyberduck). Load the printer config file
|
||||
in the editor and then save it as a file named "printer.cfg" in the
|
||||
home directory of the pi user (ie, /home/pi/printer.cfg).
|
||||
in the editor and then save it as a file named `printer.cfg` in the
|
||||
home directory of the pi user (ie, `/home/pi/printer.cfg`).
|
||||
|
||||
Alternatively, one can also copy and edit the file directly on the
|
||||
Raspberry Pi via ssh. That may look something like the following (be
|
||||
|
||||
@@ -96,7 +96,7 @@ Key formula for look-ahead:
|
||||
end_velocity^2 = start_velocity^2 + 2*accel*move_distance
|
||||
```
|
||||
|
||||
### Smoothed look-ahead
|
||||
### Minimum cruise ratio
|
||||
|
||||
Klipper also implements a mechanism for smoothing out the motions of
|
||||
short "zigzag" moves. Consider the following moves:
|
||||
@@ -105,21 +105,27 @@ short "zigzag" moves. Consider the following moves:
|
||||
|
||||
In the above, the frequent changes from acceleration to deceleration
|
||||
can cause the machine to vibrate which causes stress on the machine
|
||||
and increases the noise. To reduce this, Klipper tracks both regular
|
||||
move acceleration as well as a virtual "acceleration to deceleration"
|
||||
rate. Using this system, the top speed of these short "zigzag" moves
|
||||
are limited to smooth out the printer motion:
|
||||
and increases the noise. Klipper implements a mechanism to ensure
|
||||
there is always some movement at a cruising speed between acceleration
|
||||
and deceleration. This is done by reducing the top speed of some moves
|
||||
(or sequence of moves) to ensure there is a minimum distance traveled
|
||||
at cruising speed relative to the distance traveled during
|
||||
acceleration and deceleration.
|
||||
|
||||
Klipper implements this feature by tracking both a regular move
|
||||
acceleration as well as a virtual "acceleration to deceleration" rate:
|
||||
|
||||

|
||||
|
||||
Specifically, the code calculates what the velocity of each move would
|
||||
be if it were limited to this virtual "acceleration to deceleration"
|
||||
rate (half the normal acceleration rate by default). In the above
|
||||
picture the dashed gray lines represent this virtual acceleration rate
|
||||
for the first move. If a move can not reach its full cruising speed
|
||||
using this virtual acceleration rate then its top speed is reduced to
|
||||
the maximum speed it could obtain at this virtual acceleration
|
||||
rate. For most moves the limit will be at or above the move's existing
|
||||
rate. In the above picture the dashed gray lines represent this
|
||||
virtual acceleration rate for the first move. If a move can not reach
|
||||
its full cruising speed using this virtual acceleration rate then its
|
||||
top speed is reduced to the maximum speed it could obtain at this
|
||||
virtual acceleration rate.
|
||||
|
||||
For most moves the limit will be at or above the move's existing
|
||||
limits and no change in behavior is induced. For short zigzag moves,
|
||||
however, this limit reduces the top speed. Note that it does not
|
||||
change the actual acceleration within the move - the move continues to
|
||||
|
||||
@@ -207,7 +207,7 @@ software dependencies not installed by default. First, run on your Raspberry Pi
|
||||
the following commands:
|
||||
```
|
||||
sudo apt update
|
||||
sudo apt install python3-numpy python3-matplotlib libatlas-base-dev
|
||||
sudo apt install python3-numpy python3-matplotlib libatlas-base-dev libopenblas-dev
|
||||
```
|
||||
|
||||
Next, in order to install NumPy in the Klipper environment, run the command:
|
||||
@@ -450,7 +450,11 @@ TEST_RESONANCES AXIS=Y
|
||||
```
|
||||
This will generate 2 CSV files (`/tmp/resonances_x_*.csv` and
|
||||
`/tmp/resonances_y_*.csv`). These files can be processed with the stand-alone
|
||||
script on a Raspberry Pi. To do that, run the following commands:
|
||||
script on a Raspberry Pi. This script is intended to be run with a single CSV
|
||||
file for each axis measured, although it can be used with multiple CSV files
|
||||
if you desire to average the results. Averaging results can be useful, for
|
||||
example, if resonance tests were done at multiple test points. Delete the extra
|
||||
CSV files if you do not desire to average them.
|
||||
```
|
||||
~/klipper/scripts/calibrate_shaper.py /tmp/resonances_x_*.csv -o /tmp/shaper_calibrate_x.png
|
||||
~/klipper/scripts/calibrate_shaper.py /tmp/resonances_y_*.csv -o /tmp/shaper_calibrate_y.png
|
||||
@@ -662,6 +666,19 @@ The same notice applies to the input shaper
|
||||
`max_accel` value after the auto-calibration, and the suggested acceleration
|
||||
limits will not be applied automatically.
|
||||
|
||||
Keep in mind that the maximum acceleration without too much smoothing depends
|
||||
on the `square_corner_velocity`. The general recommendation is not to change
|
||||
it from its default value 5.0, and this is the value used by default by the
|
||||
`calibrate_shaper.py` script. If you did change it though, you should inform
|
||||
the script about it by passing `--square_corner_velocity=...` parameter, e.g.
|
||||
```
|
||||
~/klipper/scripts/calibrate_shaper.py /tmp/resonances_x_*.csv -o /tmp/shaper_calibrate_x.png --square_corner_velocity=10.0
|
||||
```
|
||||
so that it can calculate the maximum acceleration recommendations correctly.
|
||||
Note that the `SHAPER_CALIBRATE` command already takes the configured
|
||||
`square_corner_velocity` parameter into account, and there is no need
|
||||
to specify it explicitly.
|
||||
|
||||
If you are doing a shaper re-calibration and the reported smoothing for the
|
||||
suggested shaper configuration is almost the same as what you got during the
|
||||
previous calibration, this step can be skipped.
|
||||
|
||||
@@ -31,9 +31,15 @@ overshoot and account for it in its calculations. However, it is
|
||||
important that the hardware design is capable of handling overshoot
|
||||
without causing damage to the machine.
|
||||
|
||||
Should Klipper detect a communication issue between micro-controllers
|
||||
during multi-mcu homing then it will raise a "Communication timeout
|
||||
during homing" error.
|
||||
In order to use this "multi-mcu homing" capability the hardware must
|
||||
have predictably low latency between the host computer and all of the
|
||||
micro-controllers. Typically the round-trip time must be consistently
|
||||
less than 10ms. High latency (even for short periods) is likely to
|
||||
result in homing failures.
|
||||
|
||||
Should high latency result in a failure (or if some other
|
||||
communication issue is detected) then Klipper will raise a
|
||||
"Communication timeout during homing" error.
|
||||
|
||||
Note that an axis with multiple steppers (eg, `stepper_z` and
|
||||
`stepper_z1`) need to be on the same micro-controller in order to use
|
||||
|
||||
@@ -99,3 +99,4 @@ communication with the Klipper developers.
|
||||
troubleshooting CAN bus.
|
||||
- [TSL1401CL filament width sensor](TSL1401CL_Filament_Width_Sensor.md)
|
||||
- [Hall filament width sensor](Hall_Filament_Width_Sensor.md)
|
||||
- [Eddy Current Inductive probe](Eddy_Probe.md)
|
||||
|
||||
@@ -64,7 +64,7 @@ automatic probe point, then `ABORT` the manual probe tool and perform
|
||||
the XY probe offset calibration described above.
|
||||
|
||||
Once the manual probe tool starts, follow the steps described at
|
||||
["the paper test"](Bed_Level.md#the-paper-test)) to determine the
|
||||
["the paper test"](Bed_Level.md#the-paper-test) to determine the
|
||||
actual distance between the nozzle and bed at the given location. Once
|
||||
those steps are complete one can `ACCEPT` the position and save the
|
||||
results to the config file with:
|
||||
|
||||
@@ -48,8 +48,8 @@ First, measure the **ringing frequency**.
|
||||
to 5.0. It is not advised to increase it when using input shaper
|
||||
because it can cause more smoothing in parts - it is better to use
|
||||
higher acceleration value instead.
|
||||
2. Increase `max_accel_to_decel` by issuing the following command:
|
||||
`SET_VELOCITY_LIMIT ACCEL_TO_DECEL=7000`
|
||||
2. Disable the `minimum_cruise_ratio` feature by issuing the following
|
||||
command: `SET_VELOCITY_LIMIT MINIMUM_CRUISE_RATIO=0`
|
||||
3. Disable Pressure Advance: `SET_PRESSURE_ADVANCE ADVANCE=0`
|
||||
4. If you have already added `[input_shaper]` section to the printer.cfg,
|
||||
execute `SET_INPUT_SHAPER SHAPER_FREQ_X=0 SHAPER_FREQ_Y=0` command. If you
|
||||
@@ -149,7 +149,7 @@ a few other related parameters.
|
||||
Print the ringing test model as follows:
|
||||
|
||||
1. Restart the firmware: `RESTART`
|
||||
2. Prepare for test: `SET_VELOCITY_LIMIT ACCEL_TO_DECEL=7000`
|
||||
2. Prepare for test: `SET_VELOCITY_LIMIT MINIMUM_CRUISE_RATIO=0`
|
||||
3. Disable Pressure Advance: `SET_PRESSURE_ADVANCE ADVANCE=0`
|
||||
4. Execute: `SET_INPUT_SHAPER SHAPER_TYPE=MZV`
|
||||
5. Execute the command:
|
||||
@@ -270,7 +270,7 @@ frequencies after enabling [input_shaper], this section will not help with that.
|
||||
Assuming that you have sliced the ringing model with suggested
|
||||
parameters, complete the following steps for each of the axes X and Y:
|
||||
|
||||
1. Prepare for test: `SET_VELOCITY_LIMIT ACCEL_TO_DECEL=7000`
|
||||
1. Prepare for test: `SET_VELOCITY_LIMIT MINIMUM_CRUISE_RATIO=0`
|
||||
2. Make sure Pressure Advance is disabled: `SET_PRESSURE_ADVANCE ADVANCE=0`
|
||||
3. Execute: `SET_INPUT_SHAPER SHAPER_TYPE=ZV`
|
||||
4. From the existing ringing test model with your chosen input shaper select
|
||||
@@ -331,7 +331,7 @@ with suggested parameters, print the test model 3 times as
|
||||
follows. First time, prior to printing, run
|
||||
|
||||
1. `RESTART`
|
||||
2. `SET_VELOCITY_LIMIT ACCEL_TO_DECEL=7000`
|
||||
2. `SET_VELOCITY_LIMIT MINIMUM_CRUISE_RATIO=0`
|
||||
3. `SET_PRESSURE_ADVANCE ADVANCE=0`
|
||||
4. `SET_INPUT_SHAPER SHAPER_TYPE=2HUMP_EI SHAPER_FREQ_X=60 SHAPER_FREQ_Y=60`
|
||||
5. `TUNING_TOWER COMMAND=SET_VELOCITY_LIMIT PARAMETER=ACCEL START=1500 STEP_DELTA=500 STEP_HEIGHT=5`
|
||||
|
||||
@@ -21,7 +21,7 @@ or by issuing a `SET_SKEW CLEAR=1` gcode.
|
||||
|
||||
## Take your measurements
|
||||
|
||||
The `[skew_correcton]` module requires 3 measurements for each plane you want
|
||||
The `[skew_correction]` module requires 3 measurements for each plane you want
|
||||
to correct; the length from Corner A to Corner C, the length from Corner B
|
||||
to Corner D, and the length from Corner A to Corner D. When measuring length
|
||||
AD do not include the flats on the corners that some test objects provide.
|
||||
|
||||
@@ -168,6 +168,12 @@ The following information is available in the
|
||||
module. These settings may differ from the config file if a
|
||||
`SET_RETRACTION` command alters them.
|
||||
|
||||
## gcode
|
||||
|
||||
The following information is available in the `gcode` object:
|
||||
- `commands`: Returns a list of all currently available commands. For each
|
||||
command, if a help string is defined it will also be provided.
|
||||
|
||||
## gcode_button
|
||||
|
||||
The following information is available in
|
||||
@@ -250,6 +256,11 @@ object is available if any heater is defined):
|
||||
e.g. `["tmc2240 stepper_x"]`. While a temperature sensor is always
|
||||
available to read, a temperature monitor may not be available and
|
||||
will return null in such case.
|
||||
- `temperature_wait`: Indicates if G-Code processing is stalled
|
||||
waiting for a requested temperature (typically via
|
||||
`TEMPERATURE_WAIT`, `M109`, or `M190` commands). The value will
|
||||
contain the name of the sensor that is causing the stall or `None`
|
||||
if no wait is in progress.
|
||||
|
||||
## idle_timeout
|
||||
|
||||
@@ -318,7 +329,8 @@ is defined):
|
||||
## output_pin
|
||||
|
||||
The following information is available in
|
||||
[output_pin some_name](Config_Reference.md#output_pin) objects:
|
||||
[output_pin some_name](Config_Reference.md#output_pin) and
|
||||
[pwm_tool some_name](Config_Reference.md#pwm_tool) objects:
|
||||
- `value`: The "value" of the pin, as set by a `SET_PIN` command.
|
||||
|
||||
## palette2
|
||||
@@ -367,6 +379,13 @@ is defined):
|
||||
template expansion, the PROBE (or similar) command must be run prior
|
||||
to the macro containing this reference.
|
||||
|
||||
## pwm_cycle_time
|
||||
|
||||
The following information is available in
|
||||
[pwm_cycle_time some_name](Config_Reference.md#pwm_cycle_time)
|
||||
objects:
|
||||
- `value`: The "value" of the pin, as set by a `SET_PIN` command.
|
||||
|
||||
## quad_gantry_level
|
||||
|
||||
The following information is available in the `quad_gantry_level` object
|
||||
@@ -431,6 +450,7 @@ The following information is available in
|
||||
|
||||
[bme280 config_section_name](Config_Reference.md#bmp280bme280bme680-temperature-sensor),
|
||||
[htu21d config_section_name](Config_Reference.md#htu21d-sensor),
|
||||
[sht3x config_section_name](Config_Reference.md#sht31-sensor),
|
||||
[lm75 config_section_name](Config_Reference.md#lm75-temperature-sensor),
|
||||
[temperature_host config_section_name](Config_Reference.md#host-temperature-sensor)
|
||||
and
|
||||
@@ -438,7 +458,7 @@ and
|
||||
objects:
|
||||
- `temperature`: The last read temperature from the sensor.
|
||||
- `humidity`, `pressure`, `gas`: The last read values from the sensor
|
||||
(only on bme280, htu21d, and lm75 sensors).
|
||||
(only on bme280, htu21d, sht3x and lm75 sensors).
|
||||
|
||||
## temperature_fan
|
||||
|
||||
@@ -497,7 +517,7 @@ The following information is available in the `toolhead` object
|
||||
limit value (eg, `axis_minimum.x`, `axis_maximum.z`).
|
||||
- For Delta printers the `cone_start_z` is the max z height at
|
||||
maximum radius (`printer.toolhead.cone_start_z`).
|
||||
- `max_velocity`, `max_accel`, `max_accel_to_decel`,
|
||||
- `max_velocity`, `max_accel`, `minimum_cruise_ratio`,
|
||||
`square_corner_velocity`: The current printing limits that are in
|
||||
effect. This may differ from the config file settings if a
|
||||
`SET_VELOCITY_LIMIT` (or `M204`) command alters them at run-time.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Using PWM tools
|
||||
|
||||
This document describes how to setup a PWM-controlled laser or spindle
|
||||
using `output_pin` and some macros.
|
||||
using `pwm_tool` and some macros.
|
||||
|
||||
## How does it work?
|
||||
|
||||
@@ -26,14 +26,6 @@ so that when your host or MCU encounters an error, the tool will stop.
|
||||
|
||||
For an example configuration, see [config/sample-pwm-tool.cfg](/config/sample-pwm-tool.cfg).
|
||||
|
||||
## Current Limitations
|
||||
|
||||
There is a limitation of how frequent PWM updates may occur.
|
||||
While being very precise, a PWM update may only occur every 0.1 seconds,
|
||||
rendering it almost useless for raster engraving.
|
||||
However, there exists an [experimental branch](https://github.com/Cirromulus/klipper/tree/laser_tool) with its own tradeoffs.
|
||||
In long term, it is planned to add this functionality to main-line klipper.
|
||||
|
||||
## Commands
|
||||
|
||||
`M3/M4 S<value>` : Set PWM duty-cycle. Values between 0 and 255.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Python virtualenv module requirements for mkdocs
|
||||
jinja2==3.0.3
|
||||
mkdocs==1.2.3
|
||||
jinja2==3.1.4
|
||||
mkdocs==1.2.4
|
||||
mkdocs-material==8.1.3
|
||||
mkdocs-simple-hooks==0.1.3
|
||||
mkdocs-exclude==1.0.2
|
||||
|
||||
@@ -71,7 +71,7 @@ extra:
|
||||
# https://squidfunk.github.io/mkdocs-material/setup/setting-up-site-analytics/#site-search-tracking
|
||||
analytics:
|
||||
provider: google
|
||||
property: UA-138371409-1
|
||||
property: G-VEN1PGNQL4
|
||||
# Language Selection
|
||||
alternate:
|
||||
- name: English
|
||||
@@ -138,4 +138,5 @@ nav:
|
||||
- CANBUS_Troubleshooting.md
|
||||
- TSL1401CL_Filament_Width_Sensor.md
|
||||
- Hall_Filament_Width_Sensor.md
|
||||
- Eddy_Probe.md
|
||||
- Sponsors.md
|
||||
|
||||
4
docs/img/adaptive_bed_mesh.svg
Normal file
4
docs/img/adaptive_bed_mesh.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 36 KiB |
4
docs/img/adaptive_bed_mesh_margin.svg
Normal file
4
docs/img/adaptive_bed_mesh_margin.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 20 KiB |
@@ -49,6 +49,8 @@ defs_stepcompress = """
|
||||
, uint64_t clock);
|
||||
int stepcompress_queue_msg(struct stepcompress *sc
|
||||
, uint32_t *data, int len);
|
||||
int stepcompress_queue_mq_msg(struct stepcompress *sc, uint64_t req_clock
|
||||
, uint32_t *data, int len);
|
||||
int stepcompress_extract_old(struct stepcompress *sc
|
||||
, struct pull_history_steps *p, int max
|
||||
, uint64_t start_clock, uint64_t end_clock);
|
||||
@@ -58,7 +60,8 @@ defs_stepcompress = """
|
||||
void steppersync_free(struct steppersync *ss);
|
||||
void steppersync_set_time(struct steppersync *ss
|
||||
, double time_offset, double mcu_freq);
|
||||
int steppersync_flush(struct steppersync *ss, uint64_t move_clock);
|
||||
int steppersync_flush(struct steppersync *ss, uint64_t move_clock
|
||||
, uint64_t clear_history_clock);
|
||||
"""
|
||||
|
||||
defs_itersolve = """
|
||||
@@ -92,7 +95,8 @@ defs_trapq = """
|
||||
, double start_pos_x, double start_pos_y, double start_pos_z
|
||||
, double axes_r_x, double axes_r_y, double axes_r_z
|
||||
, double start_v, double cruise_v, double accel);
|
||||
void trapq_finalize_moves(struct trapq *tq, double print_time);
|
||||
void trapq_finalize_moves(struct trapq *tq, double print_time
|
||||
, double clear_history_time);
|
||||
void trapq_set_position(struct trapq *tq, double print_time
|
||||
, double pos_x, double pos_y, double pos_z);
|
||||
int trapq_extract_old(struct trapq *tq, struct pull_move *p, int max
|
||||
@@ -138,8 +142,9 @@ defs_kin_winch = """
|
||||
|
||||
defs_kin_extruder = """
|
||||
struct stepper_kinematics *extruder_stepper_alloc(void);
|
||||
void extruder_stepper_free(struct stepper_kinematics *sk);
|
||||
void extruder_set_pressure_advance(struct stepper_kinematics *sk
|
||||
, double pressure_advance, double smooth_time);
|
||||
, double print_time, double pressure_advance, double smooth_time);
|
||||
"""
|
||||
|
||||
defs_kin_shaper = """
|
||||
|
||||
@@ -9,9 +9,15 @@
|
||||
#include <string.h> // memset
|
||||
#include "compiler.h" // __visible
|
||||
#include "itersolve.h" // struct stepper_kinematics
|
||||
#include "list.h" // list_node
|
||||
#include "pyhelper.h" // errorf
|
||||
#include "trapq.h" // move_get_distance
|
||||
|
||||
struct pa_params {
|
||||
double pressure_advance, active_print_time;
|
||||
struct list_node node;
|
||||
};
|
||||
|
||||
// Without pressure advance, the extruder stepper position is:
|
||||
// extruder_position(t) = nominal_position(t)
|
||||
// When pressure advance is enabled, additional filament is pushed
|
||||
@@ -52,17 +58,25 @@ extruder_integrate_time(double base, double start_v, double half_accel
|
||||
|
||||
// Calculate the definitive integral of extruder for a given move
|
||||
static double
|
||||
pa_move_integrate(struct move *m, double pressure_advance
|
||||
pa_move_integrate(struct move *m, struct list_head *pa_list
|
||||
, double base, double start, double end, double time_offset)
|
||||
{
|
||||
if (start < 0.)
|
||||
start = 0.;
|
||||
if (end > m->move_t)
|
||||
end = m->move_t;
|
||||
// Calculate base position and velocity with pressure advance
|
||||
// Determine pressure_advance value
|
||||
int can_pressure_advance = m->axes_r.y != 0.;
|
||||
if (!can_pressure_advance)
|
||||
pressure_advance = 0.;
|
||||
double pressure_advance = 0.;
|
||||
if (can_pressure_advance) {
|
||||
struct pa_params *pa = list_last_entry(pa_list, struct pa_params, node);
|
||||
while (unlikely(pa->active_print_time > m->print_time) &&
|
||||
!list_is_first(&pa->node, pa_list)) {
|
||||
pa = list_prev_entry(pa, node);
|
||||
}
|
||||
pressure_advance = pa->pressure_advance;
|
||||
}
|
||||
// Calculate base position and velocity with pressure advance
|
||||
base += pressure_advance * m->start_v;
|
||||
double start_v = m->start_v + pressure_advance * 2. * m->half_accel;
|
||||
// Calculate definitive integral
|
||||
@@ -75,20 +89,20 @@ pa_move_integrate(struct move *m, double pressure_advance
|
||||
// Calculate the definitive integral of the extruder over a range of moves
|
||||
static double
|
||||
pa_range_integrate(struct move *m, double move_time
|
||||
, double pressure_advance, double hst)
|
||||
, struct list_head *pa_list, double hst)
|
||||
{
|
||||
// Calculate integral for the current move
|
||||
double res = 0., start = move_time - hst, end = move_time + hst;
|
||||
double start_base = m->start_pos.x;
|
||||
res += pa_move_integrate(m, pressure_advance, 0., start, move_time, start);
|
||||
res -= pa_move_integrate(m, pressure_advance, 0., move_time, end, end);
|
||||
res += pa_move_integrate(m, pa_list, 0., start, move_time, start);
|
||||
res -= pa_move_integrate(m, pa_list, 0., move_time, end, end);
|
||||
// Integrate over previous moves
|
||||
struct move *prev = m;
|
||||
while (unlikely(start < 0.)) {
|
||||
prev = list_prev_entry(prev, node);
|
||||
start += prev->move_t;
|
||||
double base = prev->start_pos.x - start_base;
|
||||
res += pa_move_integrate(prev, pressure_advance, base, start
|
||||
res += pa_move_integrate(prev, pa_list, base, start
|
||||
, prev->move_t, start);
|
||||
}
|
||||
// Integrate over future moves
|
||||
@@ -96,14 +110,15 @@ pa_range_integrate(struct move *m, double move_time
|
||||
end -= m->move_t;
|
||||
m = list_next_entry(m, node);
|
||||
double base = m->start_pos.x - start_base;
|
||||
res -= pa_move_integrate(m, pressure_advance, base, 0., end, end);
|
||||
res -= pa_move_integrate(m, pa_list, base, 0., end, end);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
struct extruder_stepper {
|
||||
struct stepper_kinematics sk;
|
||||
double pressure_advance, half_smooth_time, inv_half_smooth_time2;
|
||||
struct list_head pa_list;
|
||||
double half_smooth_time, inv_half_smooth_time2;
|
||||
};
|
||||
|
||||
static double
|
||||
@@ -116,22 +131,45 @@ extruder_calc_position(struct stepper_kinematics *sk, struct move *m
|
||||
// Pressure advance not enabled
|
||||
return m->start_pos.x + move_get_distance(m, move_time);
|
||||
// Apply pressure advance and average over smooth_time
|
||||
double area = pa_range_integrate(m, move_time, es->pressure_advance, hst);
|
||||
double area = pa_range_integrate(m, move_time, &es->pa_list, hst);
|
||||
return m->start_pos.x + area * es->inv_half_smooth_time2;
|
||||
}
|
||||
|
||||
void __visible
|
||||
extruder_set_pressure_advance(struct stepper_kinematics *sk
|
||||
extruder_set_pressure_advance(struct stepper_kinematics *sk, double print_time
|
||||
, double pressure_advance, double smooth_time)
|
||||
{
|
||||
struct extruder_stepper *es = container_of(sk, struct extruder_stepper, sk);
|
||||
double hst = smooth_time * .5;
|
||||
double hst = smooth_time * .5, old_hst = es->half_smooth_time;
|
||||
es->half_smooth_time = hst;
|
||||
es->sk.gen_steps_pre_active = es->sk.gen_steps_post_active = hst;
|
||||
|
||||
// Cleanup old pressure advance parameters
|
||||
double cleanup_time = sk->last_flush_time - (old_hst > hst ? old_hst : hst);
|
||||
struct pa_params *first_pa = list_first_entry(
|
||||
&es->pa_list, struct pa_params, node);
|
||||
while (!list_is_last(&first_pa->node, &es->pa_list)) {
|
||||
struct pa_params *next_pa = list_next_entry(first_pa, node);
|
||||
if (next_pa->active_print_time >= cleanup_time) break;
|
||||
list_del(&first_pa->node);
|
||||
first_pa = next_pa;
|
||||
}
|
||||
|
||||
if (! hst)
|
||||
return;
|
||||
es->inv_half_smooth_time2 = 1. / (hst * hst);
|
||||
es->pressure_advance = pressure_advance;
|
||||
|
||||
if (list_last_entry(&es->pa_list, struct pa_params, node)->pressure_advance
|
||||
== pressure_advance) {
|
||||
// Retain old pa_params
|
||||
return;
|
||||
}
|
||||
// Add new pressure advance parameters
|
||||
struct pa_params *pa = malloc(sizeof(*pa));
|
||||
memset(pa, 0, sizeof(*pa));
|
||||
pa->pressure_advance = pressure_advance;
|
||||
pa->active_print_time = print_time;
|
||||
list_add_tail(&pa->node, &es->pa_list);
|
||||
}
|
||||
|
||||
struct stepper_kinematics * __visible
|
||||
@@ -141,5 +179,22 @@ extruder_stepper_alloc(void)
|
||||
memset(es, 0, sizeof(*es));
|
||||
es->sk.calc_position_cb = extruder_calc_position;
|
||||
es->sk.active_flags = AF_X;
|
||||
list_init(&es->pa_list);
|
||||
struct pa_params *pa = malloc(sizeof(*pa));
|
||||
memset(pa, 0, sizeof(*pa));
|
||||
list_add_tail(&pa->node, &es->pa_list);
|
||||
return &es->sk;
|
||||
}
|
||||
|
||||
void __visible
|
||||
extruder_stepper_free(struct stepper_kinematics *sk)
|
||||
{
|
||||
struct extruder_stepper *es = container_of(sk, struct extruder_stepper, sk);
|
||||
while (!list_empty(&es->pa_list)) {
|
||||
struct pa_params *pa = list_first_entry(
|
||||
&es->pa_list, struct pa_params, node);
|
||||
list_del(&pa->node);
|
||||
free(pa);
|
||||
}
|
||||
free(sk);
|
||||
}
|
||||
|
||||
@@ -222,12 +222,11 @@ handle_message(struct serialqueue *sq, double eventtime, int len)
|
||||
pthread_mutex_lock(&sq->lock);
|
||||
|
||||
// Calculate receive sequence number
|
||||
uint64_t rseq = ((sq->receive_seq & ~MESSAGE_SEQ_MASK)
|
||||
| (sq->input_buf[MESSAGE_POS_SEQ] & MESSAGE_SEQ_MASK));
|
||||
uint32_t rseq_delta = ((sq->input_buf[MESSAGE_POS_SEQ] - sq->receive_seq)
|
||||
& MESSAGE_SEQ_MASK);
|
||||
uint64_t rseq = sq->receive_seq + rseq_delta;
|
||||
if (rseq != sq->receive_seq) {
|
||||
// New sequence number
|
||||
if (rseq < sq->receive_seq)
|
||||
rseq += MESSAGE_SEQ_MASK+1;
|
||||
if (rseq > sq->send_seq && sq->receive_seq != 1) {
|
||||
// An ack for a message not sent? Out of order message?
|
||||
sq->bytes_invalid += len;
|
||||
|
||||
@@ -54,8 +54,6 @@ struct step_move {
|
||||
int16_t add;
|
||||
};
|
||||
|
||||
#define HISTORY_EXPIRE (30.0)
|
||||
|
||||
struct history_steps {
|
||||
struct list_node node;
|
||||
uint64_t first_clock, last_clock;
|
||||
@@ -292,6 +290,13 @@ free_history(struct stepcompress *sc, uint64_t end_clock)
|
||||
}
|
||||
}
|
||||
|
||||
// Expire the stepcompress history older than the given clock
|
||||
static void
|
||||
stepcompress_history_expire(struct stepcompress *sc, uint64_t end_clock)
|
||||
{
|
||||
free_history(sc, end_clock);
|
||||
}
|
||||
|
||||
// Free memory associated with a 'stepcompress' object
|
||||
void __visible
|
||||
stepcompress_free(struct stepcompress *sc)
|
||||
@@ -322,9 +327,6 @@ calc_last_step_print_time(struct stepcompress *sc)
|
||||
{
|
||||
double lsc = sc->last_step_clock;
|
||||
sc->last_step_print_time = sc->mcu_time_offset + (lsc - .5) / sc->mcu_freq;
|
||||
|
||||
if (lsc > sc->mcu_freq * HISTORY_EXPIRE)
|
||||
free_history(sc, lsc - sc->mcu_freq * HISTORY_EXPIRE);
|
||||
}
|
||||
|
||||
// Set the conversion rate of 'print_time' to mcu clock
|
||||
@@ -623,6 +625,21 @@ stepcompress_queue_msg(struct stepcompress *sc, uint32_t *data, int len)
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Queue an mcu command that will consume space in the mcu move queue
|
||||
int __visible
|
||||
stepcompress_queue_mq_msg(struct stepcompress *sc, uint64_t req_clock
|
||||
, uint32_t *data, int len)
|
||||
{
|
||||
int ret = stepcompress_flush(sc, UINT64_MAX);
|
||||
if (ret)
|
||||
return ret;
|
||||
|
||||
struct queue_message *qm = message_alloc_and_encode(data, len);
|
||||
qm->min_clock = qm->req_clock = req_clock;
|
||||
list_add_tail(&qm->node, &sc->msg_queue);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Return history of queue_step commands
|
||||
int __visible
|
||||
stepcompress_extract_old(struct stepcompress *sc, struct pull_history_steps *p
|
||||
@@ -716,6 +733,18 @@ steppersync_set_time(struct steppersync *ss, double time_offset
|
||||
}
|
||||
}
|
||||
|
||||
// Expire the stepcompress history before the given clock time
|
||||
static void
|
||||
steppersync_history_expire(struct steppersync *ss, uint64_t end_clock)
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < ss->sc_num; i++)
|
||||
{
|
||||
struct stepcompress *sc = ss->sc_list[i];
|
||||
stepcompress_history_expire(sc, end_clock);
|
||||
}
|
||||
}
|
||||
|
||||
// Implement a binary heap algorithm to track when the next available
|
||||
// 'struct move' in the mcu will be available
|
||||
static void
|
||||
@@ -743,7 +772,8 @@ heap_replace(struct steppersync *ss, uint64_t req_clock)
|
||||
|
||||
// Find and transmit any scheduled steps prior to the given 'move_clock'
|
||||
int __visible
|
||||
steppersync_flush(struct steppersync *ss, uint64_t move_clock)
|
||||
steppersync_flush(struct steppersync *ss, uint64_t move_clock
|
||||
, uint64_t clear_history_clock)
|
||||
{
|
||||
// Flush each stepcompress to the specified move_clock
|
||||
int i;
|
||||
@@ -791,5 +821,7 @@ steppersync_flush(struct steppersync *ss, uint64_t move_clock)
|
||||
// Transmit commands
|
||||
if (!list_empty(&msgs))
|
||||
serialqueue_send_batch(ss->sq, ss->cq, &msgs);
|
||||
|
||||
steppersync_history_expire(ss, clear_history_clock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ int stepcompress_set_last_position(struct stepcompress *sc, uint64_t clock
|
||||
int64_t stepcompress_find_past_position(struct stepcompress *sc
|
||||
, uint64_t clock);
|
||||
int stepcompress_queue_msg(struct stepcompress *sc, uint32_t *data, int len);
|
||||
int stepcompress_queue_mq_msg(struct stepcompress *sc, uint64_t req_clock
|
||||
, uint32_t *data, int len);
|
||||
int stepcompress_extract_old(struct stepcompress *sc
|
||||
, struct pull_history_steps *p, int max
|
||||
, uint64_t start_clock, uint64_t end_clock);
|
||||
@@ -40,6 +42,7 @@ struct steppersync *steppersync_alloc(
|
||||
void steppersync_free(struct steppersync *ss);
|
||||
void steppersync_set_time(struct steppersync *ss, double time_offset
|
||||
, double mcu_freq);
|
||||
int steppersync_flush(struct steppersync *ss, uint64_t move_clock);
|
||||
int steppersync_flush(struct steppersync *ss, uint64_t move_clock
|
||||
, uint64_t clear_history_clock);
|
||||
|
||||
#endif // stepcompress.h
|
||||
|
||||
@@ -163,11 +163,10 @@ trapq_append(struct trapq *tq, double print_time
|
||||
}
|
||||
}
|
||||
|
||||
#define HISTORY_EXPIRE (30.0)
|
||||
|
||||
// Expire any moves older than `print_time` from the trapezoid velocity queue
|
||||
void __visible
|
||||
trapq_finalize_moves(struct trapq *tq, double print_time)
|
||||
trapq_finalize_moves(struct trapq *tq, double print_time
|
||||
, double clear_history_time)
|
||||
{
|
||||
struct move *head_sentinel = list_first_entry(&tq->moves, struct move,node);
|
||||
struct move *tail_sentinel = list_last_entry(&tq->moves, struct move, node);
|
||||
@@ -190,10 +189,9 @@ trapq_finalize_moves(struct trapq *tq, double print_time)
|
||||
if (list_empty(&tq->history))
|
||||
return;
|
||||
struct move *latest = list_first_entry(&tq->history, struct move, node);
|
||||
double expire_time = latest->print_time + latest->move_t - HISTORY_EXPIRE;
|
||||
for (;;) {
|
||||
struct move *m = list_last_entry(&tq->history, struct move, node);
|
||||
if (m == latest || m->print_time + m->move_t > expire_time)
|
||||
if (m == latest || m->print_time + m->move_t > clear_history_time)
|
||||
break;
|
||||
list_del(&m->node);
|
||||
free(m);
|
||||
@@ -206,7 +204,7 @@ trapq_set_position(struct trapq *tq, double print_time
|
||||
, double pos_x, double pos_y, double pos_z)
|
||||
{
|
||||
// Flush all moves from trapq
|
||||
trapq_finalize_moves(tq, NEVER_TIME);
|
||||
trapq_finalize_moves(tq, NEVER_TIME, 0);
|
||||
|
||||
// Prune any moves in the trapq history that were interrupted
|
||||
while (!list_empty(&tq->history)) {
|
||||
|
||||
@@ -43,7 +43,8 @@ void trapq_append(struct trapq *tq, double print_time
|
||||
, double start_pos_x, double start_pos_y, double start_pos_z
|
||||
, double axes_r_x, double axes_r_y, double axes_r_z
|
||||
, double start_v, double cruise_v, double accel);
|
||||
void trapq_finalize_moves(struct trapq *tq, double print_time);
|
||||
void trapq_finalize_moves(struct trapq *tq, double print_time
|
||||
, double clear_history_time);
|
||||
void trapq_set_position(struct trapq *tq, double print_time
|
||||
, double pos_x, double pos_y, double pos_z);
|
||||
int trapq_extract_old(struct trapq *tq, struct pull_move *p, int max
|
||||
|
||||
@@ -66,10 +66,8 @@ class ClockSync:
|
||||
self.queries_pending = 0
|
||||
# Extend clock to 64bit
|
||||
last_clock = self.last_clock
|
||||
clock = (last_clock & ~0xffffffff) | params['clock']
|
||||
if clock < last_clock:
|
||||
clock += 0x100000000
|
||||
self.last_clock = clock
|
||||
clock_delta = (params['clock'] - last_clock) & 0xffffffff
|
||||
self.last_clock = clock = last_clock + clock_delta
|
||||
# Check if this is the best round-trip-time seen so far
|
||||
sent_time = params['#sent_time']
|
||||
if not sent_time:
|
||||
@@ -138,10 +136,9 @@ class ClockSync:
|
||||
# misc commands
|
||||
def clock32_to_clock64(self, clock32):
|
||||
last_clock = self.last_clock
|
||||
clock_diff = (last_clock - clock32) & 0xffffffff
|
||||
if clock_diff & 0x80000000:
|
||||
return last_clock + 0x100000000 - clock_diff
|
||||
return last_clock - clock_diff
|
||||
clock_diff = (clock32 - last_clock) & 0xffffffff
|
||||
clock_diff -= (clock_diff & 0x80000000) << 1
|
||||
return last_clock + clock_diff
|
||||
def is_active(self):
|
||||
return self.queries_pending <= 4
|
||||
def dump_debug(self):
|
||||
|
||||
@@ -69,6 +69,8 @@ class ConfigWrapper:
|
||||
return self._get_wrapper(self.fileconfig.getboolean, option, default,
|
||||
note_valid=note_valid)
|
||||
def getchoice(self, option, choices, default=sentinel, note_valid=True):
|
||||
if type(choices) == type([]):
|
||||
choices = {i: i for i in choices}
|
||||
if choices and type(list(choices.keys())[0]) == int:
|
||||
c = self.getint(option, default, note_valid=note_valid)
|
||||
else:
|
||||
@@ -143,6 +145,8 @@ class PrinterConfig:
|
||||
self.printer = printer
|
||||
self.autosave = None
|
||||
self.deprecated = {}
|
||||
self.runtime_warnings = []
|
||||
self.deprecate_warnings = []
|
||||
self.status_raw_config = {}
|
||||
self.status_save_pending = {}
|
||||
self.status_settings = {}
|
||||
@@ -172,16 +176,16 @@ class PrinterConfig:
|
||||
autosave_data = data[pos + len(AUTOSAVE_HEADER):].strip()
|
||||
# Check for errors and strip line prefixes
|
||||
if "\n#*# " in regular_data:
|
||||
logging.warn("Can't read autosave from config file"
|
||||
" - autosave state corrupted")
|
||||
logging.warning("Can't read autosave from config file"
|
||||
" - autosave state corrupted")
|
||||
return data, ""
|
||||
out = [""]
|
||||
for line in autosave_data.split('\n'):
|
||||
if ((not line.startswith("#*#")
|
||||
or (len(line) >= 4 and not line.startswith("#*# ")))
|
||||
and autosave_data):
|
||||
logging.warn("Can't read autosave from config file"
|
||||
" - modifications after header")
|
||||
logging.warning("Can't read autosave from config file"
|
||||
" - modifications after header")
|
||||
return data, ""
|
||||
out.append(line[4:])
|
||||
out.append("")
|
||||
@@ -189,7 +193,6 @@ class PrinterConfig:
|
||||
comment_r = re.compile('[#;].*$')
|
||||
value_r = re.compile('[^A-Za-z0-9_].*$')
|
||||
def _strip_duplicates(self, data, config):
|
||||
fileconfig = config.fileconfig
|
||||
# Comment out fields in 'data' that are defined in 'config'
|
||||
lines = data.split('\n')
|
||||
section = None
|
||||
@@ -217,7 +220,10 @@ class PrinterConfig:
|
||||
data = '\n'.join(buffer)
|
||||
del buffer[:]
|
||||
sbuffer = io.StringIO(data)
|
||||
fileconfig.readfp(sbuffer, filename)
|
||||
if sys.version_info.major >= 3:
|
||||
fileconfig.read_file(sbuffer, filename)
|
||||
else:
|
||||
fileconfig.readfp(sbuffer, filename)
|
||||
def _resolve_include(self, source_filename, include_spec, fileconfig,
|
||||
visited):
|
||||
dirname = os.path.dirname(source_filename)
|
||||
@@ -311,6 +317,11 @@ class PrinterConfig:
|
||||
"======================="]
|
||||
self.printer.set_rollover_info("config", "\n".join(lines))
|
||||
# Status reporting
|
||||
def runtime_warning(self, msg):
|
||||
logging.warning(msg)
|
||||
res = {'type': 'runtime_warning', 'message': msg}
|
||||
self.runtime_warnings.append(res)
|
||||
self.status_warnings = self.runtime_warnings + self.deprecate_warnings
|
||||
def deprecate(self, section, option, value=None, msg=None):
|
||||
self.deprecated[(section, option, value)] = msg
|
||||
def _build_status(self, config):
|
||||
@@ -322,7 +333,7 @@ class PrinterConfig:
|
||||
self.status_settings = {}
|
||||
for (section, option), value in config.access_tracking.items():
|
||||
self.status_settings.setdefault(section, {})[option] = value
|
||||
self.status_warnings = []
|
||||
self.deprecate_warnings = []
|
||||
for (section, option, value), msg in self.deprecated.items():
|
||||
if value is None:
|
||||
res = {'type': 'deprecated_option'}
|
||||
@@ -331,7 +342,8 @@ class PrinterConfig:
|
||||
res['message'] = msg
|
||||
res['section'] = section
|
||||
res['option'] = option
|
||||
self.status_warnings.append(res)
|
||||
self.deprecate_warnings.append(res)
|
||||
self.status_warnings = self.runtime_warnings + self.deprecate_warnings
|
||||
def get_status(self, eventtime):
|
||||
return {'config': self.status_raw_config,
|
||||
'settings': self.status_settings,
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
SAMPLE_TIME = 0.001
|
||||
SAMPLE_COUNT = 8
|
||||
REPORT_TIME = 0.300
|
||||
RANGE_CHECK_COUNT = 4
|
||||
|
||||
class MCU_scaled_adc:
|
||||
def __init__(self, main, pin_params):
|
||||
@@ -18,7 +17,7 @@ class MCU_scaled_adc:
|
||||
qname = main.name + ":" + pin_params['pin']
|
||||
query_adc.register_adc(qname, self._mcu_adc)
|
||||
self._callback = None
|
||||
self.setup_minmax = self._mcu_adc.setup_minmax
|
||||
self.setup_adc_sample = self._mcu_adc.setup_adc_sample
|
||||
self.get_mcu = self._mcu_adc.get_mcu
|
||||
def _handle_callback(self, read_time, read_value):
|
||||
max_adc = self._main.last_vref[1]
|
||||
@@ -54,8 +53,7 @@ class PrinterADCScaled:
|
||||
ppins = self.printer.lookup_object('pins')
|
||||
mcu_adc = ppins.setup_pin('adc', pin_name)
|
||||
mcu_adc.setup_adc_callback(REPORT_TIME, callback)
|
||||
mcu_adc.setup_minmax(SAMPLE_TIME, SAMPLE_COUNT, minval=0., maxval=1.,
|
||||
range_check_count=RANGE_CHECK_COUNT)
|
||||
mcu_adc.setup_adc_sample(SAMPLE_TIME, SAMPLE_COUNT)
|
||||
query_adc = config.get_printer().load_object(config, 'query_adc')
|
||||
query_adc.register_adc(self.name + ":" + name, mcu_adc)
|
||||
return mcu_adc
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Obtain temperature using linear interpolation of ADC values
|
||||
#
|
||||
# Copyright (C) 2016-2018 Kevin O'Connor <kevin@koconnor.net>
|
||||
# Copyright (C) 2016-2024 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging, bisect
|
||||
@@ -22,8 +22,8 @@ class PrinterADCtoTemperature:
|
||||
ppins = config.get_printer().lookup_object('pins')
|
||||
self.mcu_adc = ppins.setup_pin('adc', config.get('sensor_pin'))
|
||||
self.mcu_adc.setup_adc_callback(REPORT_TIME, self.adc_callback)
|
||||
query_adc = config.get_printer().load_object(config, 'query_adc')
|
||||
query_adc.register_adc(config.get_name(), self.mcu_adc)
|
||||
self.diag_helper = HelperTemperatureDiagnostics(
|
||||
config, self.mcu_adc, adc_convert.calc_temp)
|
||||
def setup_callback(self, temperature_callback):
|
||||
self.temperature_callback = temperature_callback
|
||||
def get_report_time_delta(self):
|
||||
@@ -32,10 +32,44 @@ class PrinterADCtoTemperature:
|
||||
temp = self.adc_convert.calc_temp(read_value)
|
||||
self.temperature_callback(read_time + SAMPLE_COUNT * SAMPLE_TIME, temp)
|
||||
def setup_minmax(self, min_temp, max_temp):
|
||||
adc_range = [self.adc_convert.calc_adc(t) for t in [min_temp, max_temp]]
|
||||
self.mcu_adc.setup_minmax(SAMPLE_TIME, SAMPLE_COUNT,
|
||||
minval=min(adc_range), maxval=max(adc_range),
|
||||
range_check_count=RANGE_CHECK_COUNT)
|
||||
arange = [self.adc_convert.calc_adc(t) for t in [min_temp, max_temp]]
|
||||
min_adc, max_adc = sorted(arange)
|
||||
self.mcu_adc.setup_adc_sample(SAMPLE_TIME, SAMPLE_COUNT,
|
||||
minval=min_adc, maxval=max_adc,
|
||||
range_check_count=RANGE_CHECK_COUNT)
|
||||
self.diag_helper.setup_diag_minmax(min_temp, max_temp, min_adc, max_adc)
|
||||
|
||||
# Tool to register with query_adc and report extra info on ADC range errors
|
||||
class HelperTemperatureDiagnostics:
|
||||
def __init__(self, config, mcu_adc, calc_temp_cb):
|
||||
self.printer = config.get_printer()
|
||||
self.name = config.get_name()
|
||||
self.mcu_adc = mcu_adc
|
||||
self.calc_temp_cb = calc_temp_cb
|
||||
self.min_temp = self.max_temp = self.min_adc = self.max_adc = None
|
||||
query_adc = self.printer.load_object(config, 'query_adc')
|
||||
query_adc.register_adc(self.name, self.mcu_adc)
|
||||
error_mcu = self.printer.load_object(config, 'error_mcu')
|
||||
error_mcu.add_clarify("ADC out of range", self._clarify_adc_range)
|
||||
def setup_diag_minmax(self, min_temp, max_temp, min_adc, max_adc):
|
||||
self.min_temp, self.max_temp = min_temp, max_temp
|
||||
self.min_adc, self.max_adc = min_adc, max_adc
|
||||
def _clarify_adc_range(self, msg, details):
|
||||
if self.min_temp is None:
|
||||
return None
|
||||
last_value, last_read_time = self.mcu_adc.get_last_value()
|
||||
if not last_read_time:
|
||||
return None
|
||||
if last_value >= self.min_adc and last_value <= self.max_adc:
|
||||
return None
|
||||
tempstr = "?"
|
||||
try:
|
||||
last_temp = self.calc_temp_cb(last_value)
|
||||
tempstr = "%.3f" % (last_temp,)
|
||||
except e:
|
||||
logging.exception("Error in calc_temp callback")
|
||||
return ("Sensor '%s' temperature %s not in range %.3f:%.3f"
|
||||
% (self.name, tempstr, self.min_temp, self.max_temp))
|
||||
|
||||
|
||||
######################################################################
|
||||
@@ -95,8 +129,8 @@ class LinearVoltage:
|
||||
for temp, volt in params:
|
||||
adc = (volt - voltage_offset) / adc_voltage
|
||||
if adc < 0. or adc > 1.:
|
||||
logging.warn("Ignoring adc sample %.3f/%.3f in heater %s",
|
||||
temp, volt, config.get_name())
|
||||
logging.warning("Ignoring adc sample %.3f/%.3f in heater %s",
|
||||
temp, volt, config.get_name())
|
||||
continue
|
||||
samples.append((adc, temp))
|
||||
try:
|
||||
|
||||
187
klippy/extras/ads1220.py
Normal file
187
klippy/extras/ads1220.py
Normal file
@@ -0,0 +1,187 @@
|
||||
# ADS1220 Support
|
||||
#
|
||||
# Copyright (C) 2024 Gareth Farrington <gareth@waves.ky>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
from . import bulk_sensor, bus
|
||||
|
||||
#
|
||||
# Constants
|
||||
#
|
||||
BYTES_PER_SAMPLE = 4 # samples are 4 byte wide unsigned integers
|
||||
MAX_SAMPLES_PER_MESSAGE = bulk_sensor.MAX_BULK_MSG_SIZE // BYTES_PER_SAMPLE
|
||||
UPDATE_INTERVAL = 0.10
|
||||
RESET_CMD = 0x06
|
||||
START_SYNC_CMD = 0x08
|
||||
RREG_CMD = 0x20
|
||||
WREG_CMD = 0x40
|
||||
NOOP_CMD = 0x0
|
||||
RESET_STATE = bytearray([0x0, 0x0, 0x0, 0x0])
|
||||
|
||||
# turn bytearrays into pretty hex strings: [0xff, 0x1]
|
||||
def hexify(byte_array):
|
||||
return "[%s]" % (", ".join([hex(b) for b in byte_array]))
|
||||
|
||||
|
||||
class ADS1220():
|
||||
def __init__(self, config):
|
||||
self.printer = printer = config.get_printer()
|
||||
self.name = config.get_name().split()[-1]
|
||||
self.last_error_count = 0
|
||||
self.consecutive_fails = 0
|
||||
# Chip options
|
||||
# Gain
|
||||
self.gain_options = {'1': 0x0, '2': 0x1, '4': 0x2, '8': 0x3, '16': 0x4,
|
||||
'32': 0x5, '64': 0x6, '128': 0x7}
|
||||
self.gain = config.getchoice('gain', self.gain_options, default='128')
|
||||
# Sample rate
|
||||
self.sps_normal = {'20': 20, '45': 45, '90': 90, '175': 175,
|
||||
'330': 330, '600': 600, '1000': 1000}
|
||||
self.sps_turbo = {'40': 40, '90': 90, '180': 180, '350': 350,
|
||||
'660': 660, '1200': 1200, '2000': 2000}
|
||||
self.sps_options = self.sps_normal.copy()
|
||||
self.sps_options.update(self.sps_turbo)
|
||||
self.sps = config.getchoice('sps', self.sps_options, default='660')
|
||||
self.is_turbo = str(self.sps) in self.sps_turbo
|
||||
# SPI Setup
|
||||
spi_speed = 512000 if self.is_turbo else 256000
|
||||
self.spi = bus.MCU_SPI_from_config(config, 1, default_speed=spi_speed)
|
||||
self.mcu = mcu = self.spi.get_mcu()
|
||||
self.oid = mcu.create_oid()
|
||||
# Data Ready (DRDY) Pin
|
||||
drdy_pin = config.get('data_ready_pin')
|
||||
ppins = printer.lookup_object('pins')
|
||||
drdy_ppin = ppins.lookup_pin(drdy_pin)
|
||||
self.data_ready_pin = drdy_ppin['pin']
|
||||
drdy_pin_mcu = drdy_ppin['chip']
|
||||
if drdy_pin_mcu != self.mcu:
|
||||
raise config.error("ADS1220 config error: SPI communication and"
|
||||
" data_ready_pin must be on the same MCU")
|
||||
# Bulk Sensor Setup
|
||||
self.bulk_queue = bulk_sensor.BulkDataQueue(self.mcu, oid=self.oid)
|
||||
# Clock tracking
|
||||
chip_smooth = self.sps * UPDATE_INTERVAL * 2
|
||||
# Measurement conversion
|
||||
self.ffreader = bulk_sensor.FixedFreqReader(mcu, chip_smooth, "<i")
|
||||
# Process messages in batches
|
||||
self.batch_bulk = bulk_sensor.BatchBulkHelper(
|
||||
self.printer, self._process_batch, self._start_measurements,
|
||||
self._finish_measurements, UPDATE_INTERVAL)
|
||||
# publish raw samples to the socket
|
||||
self.batch_bulk.add_mux_endpoint("ads1220/dump_ads1220", "sensor",
|
||||
self.name,
|
||||
{'header': ('time', 'counts')})
|
||||
# Command Configuration
|
||||
mcu.add_config_cmd(
|
||||
"config_ads1220 oid=%d spi_oid=%d data_ready_pin=%s"
|
||||
% (self.oid, self.spi.get_oid(), self.data_ready_pin))
|
||||
mcu.add_config_cmd("query_ads1220 oid=%d rest_ticks=0"
|
||||
% (self.oid,), on_restart=True)
|
||||
mcu.register_config_callback(self._build_config)
|
||||
self.query_ads1220_cmd = None
|
||||
|
||||
def _build_config(self):
|
||||
cmdqueue = self.spi.get_command_queue()
|
||||
self.query_ads1220_cmd = self.mcu.lookup_command(
|
||||
"query_ads1220 oid=%c rest_ticks=%u", cq=cmdqueue)
|
||||
self.ffreader.setup_query_command("query_ads1220_status oid=%c",
|
||||
oid=self.oid, cq=cmdqueue)
|
||||
|
||||
def get_mcu(self):
|
||||
return self.mcu
|
||||
|
||||
def get_samples_per_second(self):
|
||||
return self.sps
|
||||
|
||||
# returns a tuple of the minimum and maximum value of the sensor, used to
|
||||
# detect if a data value is saturated
|
||||
def get_range(self):
|
||||
return -0x800000, 0x7FFFFF
|
||||
|
||||
# add_client interface, direct pass through to bulk_sensor API
|
||||
def add_client(self, callback):
|
||||
self.batch_bulk.add_client(callback)
|
||||
|
||||
# Measurement decoding
|
||||
def _convert_samples(self, samples):
|
||||
adc_factor = 1. / (1 << 23)
|
||||
count = 0
|
||||
for ptime, val in samples:
|
||||
samples[count] = (round(ptime, 6), val, round(val * adc_factor, 9))
|
||||
count += 1
|
||||
del samples[count:]
|
||||
|
||||
# Start, stop, and process message batches
|
||||
def _start_measurements(self):
|
||||
self.last_error_count = 0
|
||||
self.consecutive_fails = 0
|
||||
# Start bulk reading
|
||||
self.reset_chip()
|
||||
self.setup_chip()
|
||||
rest_ticks = self.mcu.seconds_to_clock(1. / (10. * self.sps))
|
||||
self.query_ads1220_cmd.send([self.oid, rest_ticks])
|
||||
logging.info("ADS1220 starting '%s' measurements", self.name)
|
||||
# Initialize clock tracking
|
||||
self.ffreader.note_start()
|
||||
|
||||
def _finish_measurements(self):
|
||||
# don't use serial connection after shutdown
|
||||
if self.printer.is_shutdown():
|
||||
return
|
||||
# Halt bulk reading
|
||||
self.query_ads1220_cmd.send_wait_ack([self.oid, 0])
|
||||
self.ffreader.note_end()
|
||||
logging.info("ADS1220 finished '%s' measurements", self.name)
|
||||
|
||||
def _process_batch(self, eventtime):
|
||||
samples = self.ffreader.pull_samples()
|
||||
self._convert_samples(samples)
|
||||
return {'data': samples, 'errors': self.last_error_count,
|
||||
'overflows': self.ffreader.get_last_overflows()}
|
||||
|
||||
def reset_chip(self):
|
||||
# the reset command takes 50us to complete
|
||||
self.send_command(RESET_CMD)
|
||||
# read startup register state and validate
|
||||
val = self.read_reg(0x0, 4)
|
||||
if val != RESET_STATE:
|
||||
raise self.printer.command_error(
|
||||
"Invalid ads1220 reset state (got %s vs %s).\n"
|
||||
"This is generally indicative of connection problems\n"
|
||||
"(e.g. faulty wiring) or a faulty ADS1220 chip."
|
||||
% (hexify(val), hexify(RESET_STATE)))
|
||||
|
||||
def setup_chip(self):
|
||||
continuous = 0x1 # enable continuous conversions
|
||||
mode = 0x2 if self.is_turbo else 0x0 # turbo mode
|
||||
sps_list = self.sps_turbo if self.is_turbo else self.sps_normal
|
||||
data_rate = list(sps_list.keys()).index(str(self.sps))
|
||||
reg_values = [(self.gain << 1),
|
||||
(data_rate << 5) | (mode << 3) | (continuous << 2)]
|
||||
self.write_reg(0x0, reg_values)
|
||||
# start measurements immediately
|
||||
self.send_command(START_SYNC_CMD)
|
||||
|
||||
def read_reg(self, reg, byte_count):
|
||||
read_command = [RREG_CMD | (reg << 2) | (byte_count - 1)]
|
||||
read_command += [NOOP_CMD] * byte_count
|
||||
params = self.spi.spi_transfer(read_command)
|
||||
return bytearray(params['response'][1:])
|
||||
|
||||
def send_command(self, cmd):
|
||||
self.spi.spi_send([cmd])
|
||||
|
||||
def write_reg(self, reg, register_bytes):
|
||||
write_command = [WREG_CMD | (reg << 2) | (len(register_bytes) - 1)]
|
||||
write_command.extend(register_bytes)
|
||||
self.spi.spi_send(write_command)
|
||||
stored_val = self.read_reg(reg, len(register_bytes))
|
||||
if register_bytes != stored_val:
|
||||
raise self.printer.command_error(
|
||||
"Failed to set ADS1220 register [0x%x] to %s: got %s. "
|
||||
"This may be a connection problem (e.g. faulty wiring)" % (
|
||||
reg, hexify(register_bytes), hexify(stored_val)))
|
||||
|
||||
|
||||
ADS1220_SENSOR_TYPE = {"ads1220": ADS1220}
|
||||
@@ -1,10 +1,10 @@
|
||||
# Support for reading acceleration data from an adxl345 chip
|
||||
#
|
||||
# Copyright (C) 2020-2021 Kevin O'Connor <kevin@koconnor.net>
|
||||
# Copyright (C) 2020-2023 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging, time, collections, threading, multiprocessing, os
|
||||
from . import bus, motion_report
|
||||
import logging, time, collections, multiprocessing, os
|
||||
from . import bus, bulk_sensor
|
||||
|
||||
# ADXL345 registers
|
||||
REG_DEVID = 0x00
|
||||
@@ -32,26 +32,29 @@ Accel_Measurement = collections.namedtuple(
|
||||
|
||||
# Helper class to obtain measurements
|
||||
class AccelQueryHelper:
|
||||
def __init__(self, printer, cconn):
|
||||
def __init__(self, printer):
|
||||
self.printer = printer
|
||||
self.cconn = cconn
|
||||
self.is_finished = False
|
||||
print_time = printer.lookup_object('toolhead').get_last_move_time()
|
||||
self.request_start_time = self.request_end_time = print_time
|
||||
self.samples = self.raw_samples = []
|
||||
self.msgs = []
|
||||
self.samples = []
|
||||
def finish_measurements(self):
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
self.request_end_time = toolhead.get_last_move_time()
|
||||
toolhead.wait_moves()
|
||||
self.cconn.finalize()
|
||||
def _get_raw_samples(self):
|
||||
raw_samples = self.cconn.get_messages()
|
||||
if raw_samples:
|
||||
self.raw_samples = raw_samples
|
||||
return self.raw_samples
|
||||
self.is_finished = True
|
||||
def handle_batch(self, msg):
|
||||
if self.is_finished:
|
||||
return False
|
||||
if len(self.msgs) >= 10000:
|
||||
# Avoid filling up memory with too many samples
|
||||
return False
|
||||
self.msgs.append(msg)
|
||||
return True
|
||||
def has_valid_samples(self):
|
||||
raw_samples = self._get_raw_samples()
|
||||
for msg in raw_samples:
|
||||
data = msg['params']['data']
|
||||
for msg in self.msgs:
|
||||
data = msg['data']
|
||||
first_sample_time = data[0][0]
|
||||
last_sample_time = data[-1][0]
|
||||
if (first_sample_time > self.request_end_time
|
||||
@@ -60,21 +63,20 @@ class AccelQueryHelper:
|
||||
# The time intervals [first_sample_time, last_sample_time]
|
||||
# and [request_start_time, request_end_time] have non-zero
|
||||
# intersection. It is still theoretically possible that none
|
||||
# of the samples from raw_samples fall into the time interval
|
||||
# of the samples from msgs fall into the time interval
|
||||
# [request_start_time, request_end_time] if it is too narrow
|
||||
# or on very heavy data losses. In practice, that interval
|
||||
# is at least 1 second, so this possibility is negligible.
|
||||
return True
|
||||
return False
|
||||
def get_samples(self):
|
||||
raw_samples = self._get_raw_samples()
|
||||
if not raw_samples:
|
||||
if not self.msgs:
|
||||
return self.samples
|
||||
total = sum([len(m['params']['data']) for m in raw_samples])
|
||||
total = sum([len(m['data']) for m in self.msgs])
|
||||
count = 0
|
||||
self.samples = samples = [None] * total
|
||||
for msg in raw_samples:
|
||||
for samp_time, x, y, z in msg['params']['data']:
|
||||
for msg in self.msgs:
|
||||
for samp_time, x, y, z in msg['data']:
|
||||
if samp_time < self.request_start_time:
|
||||
continue
|
||||
if samp_time > self.request_end_time:
|
||||
@@ -173,112 +175,54 @@ class AccelCommandHelper:
|
||||
val = gcmd.get("VAL", minval=0, maxval=255, parser=lambda x: int(x, 0))
|
||||
self.chip.set_reg(reg, val)
|
||||
|
||||
# Helper class for chip clock synchronization via linear regression
|
||||
class ClockSyncRegression:
|
||||
def __init__(self, mcu, chip_clock_smooth, decay = 1. / 20.):
|
||||
self.mcu = mcu
|
||||
self.chip_clock_smooth = chip_clock_smooth
|
||||
self.decay = decay
|
||||
self.last_chip_clock = self.last_exp_mcu_clock = 0.
|
||||
self.mcu_clock_avg = self.mcu_clock_variance = 0.
|
||||
self.chip_clock_avg = self.chip_clock_covariance = 0.
|
||||
def reset(self, mcu_clock, chip_clock):
|
||||
self.mcu_clock_avg = self.last_mcu_clock = mcu_clock
|
||||
self.chip_clock_avg = chip_clock
|
||||
self.mcu_clock_variance = self.chip_clock_covariance = 0.
|
||||
self.last_chip_clock = self.last_exp_mcu_clock = 0.
|
||||
def update(self, mcu_clock, chip_clock):
|
||||
# Update linear regression
|
||||
decay = self.decay
|
||||
diff_mcu_clock = mcu_clock - self.mcu_clock_avg
|
||||
self.mcu_clock_avg += decay * diff_mcu_clock
|
||||
self.mcu_clock_variance = (1. - decay) * (
|
||||
self.mcu_clock_variance + diff_mcu_clock**2 * decay)
|
||||
diff_chip_clock = chip_clock - self.chip_clock_avg
|
||||
self.chip_clock_avg += decay * diff_chip_clock
|
||||
self.chip_clock_covariance = (1. - decay) * (
|
||||
self.chip_clock_covariance + diff_mcu_clock*diff_chip_clock*decay)
|
||||
def set_last_chip_clock(self, chip_clock):
|
||||
base_mcu, base_chip, inv_cfreq = self.get_clock_translation()
|
||||
self.last_chip_clock = chip_clock
|
||||
self.last_exp_mcu_clock = base_mcu + (chip_clock-base_chip) * inv_cfreq
|
||||
def get_clock_translation(self):
|
||||
inv_chip_freq = self.mcu_clock_variance / self.chip_clock_covariance
|
||||
if not self.last_chip_clock:
|
||||
return self.mcu_clock_avg, self.chip_clock_avg, inv_chip_freq
|
||||
# Find mcu clock associated with future chip_clock
|
||||
s_chip_clock = self.last_chip_clock + self.chip_clock_smooth
|
||||
scdiff = s_chip_clock - self.chip_clock_avg
|
||||
s_mcu_clock = self.mcu_clock_avg + scdiff * inv_chip_freq
|
||||
# Calculate frequency to converge at future point
|
||||
mdiff = s_mcu_clock - self.last_exp_mcu_clock
|
||||
s_inv_chip_freq = mdiff / self.chip_clock_smooth
|
||||
return self.last_exp_mcu_clock, self.last_chip_clock, s_inv_chip_freq
|
||||
def get_time_translation(self):
|
||||
base_mcu, base_chip, inv_cfreq = self.get_clock_translation()
|
||||
clock_to_print_time = self.mcu.clock_to_print_time
|
||||
base_time = clock_to_print_time(base_mcu)
|
||||
inv_freq = clock_to_print_time(base_mcu + inv_cfreq) - base_time
|
||||
return base_time, base_chip, inv_freq
|
||||
# Helper to read the axes_map parameter from the config
|
||||
def read_axes_map(config, scale_x, scale_y, scale_z):
|
||||
am = {'x': (0, scale_x), 'y': (1, scale_y), 'z': (2, scale_z),
|
||||
'-x': (0, -scale_x), '-y': (1, -scale_y), '-z': (2, -scale_z)}
|
||||
axes_map = config.getlist('axes_map', ('x','y','z'), count=3)
|
||||
if any([a not in am for a in axes_map]):
|
||||
raise config.error("Invalid axes_map parameter")
|
||||
return [am[a.strip()] for a in axes_map]
|
||||
|
||||
MIN_MSG_TIME = 0.100
|
||||
|
||||
BYTES_PER_SAMPLE = 5
|
||||
SAMPLES_PER_BLOCK = 10
|
||||
BATCH_UPDATES = 0.100
|
||||
|
||||
# Printer class that controls ADXL345 chip
|
||||
class ADXL345:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
AccelCommandHelper(config, self)
|
||||
self.query_rate = 0
|
||||
am = {'x': (0, SCALE_XY), 'y': (1, SCALE_XY), 'z': (2, SCALE_Z),
|
||||
'-x': (0, -SCALE_XY), '-y': (1, -SCALE_XY), '-z': (2, -SCALE_Z)}
|
||||
axes_map = config.getlist('axes_map', ('x','y','z'), count=3)
|
||||
if any([a not in am for a in axes_map]):
|
||||
raise config.error("Invalid adxl345 axes_map parameter")
|
||||
self.axes_map = [am[a.strip()] for a in axes_map]
|
||||
self.axes_map = read_axes_map(config, SCALE_XY, SCALE_XY, SCALE_Z)
|
||||
self.data_rate = config.getint('rate', 3200)
|
||||
if self.data_rate not in QUERY_RATES:
|
||||
raise config.error("Invalid rate parameter: %d" % (self.data_rate,))
|
||||
# Measurement storage (accessed from background thread)
|
||||
self.lock = threading.Lock()
|
||||
self.raw_samples = []
|
||||
# Setup mcu sensor_adxl345 bulk query code
|
||||
self.spi = bus.MCU_SPI_from_config(config, 3, default_speed=5000000)
|
||||
self.mcu = mcu = self.spi.get_mcu()
|
||||
self.oid = oid = mcu.create_oid()
|
||||
self.query_adxl345_cmd = self.query_adxl345_end_cmd = None
|
||||
self.query_adxl345_status_cmd = None
|
||||
self.query_adxl345_cmd = None
|
||||
mcu.add_config_cmd("config_adxl345 oid=%d spi_oid=%d"
|
||||
% (oid, self.spi.get_oid()))
|
||||
mcu.add_config_cmd("query_adxl345 oid=%d clock=0 rest_ticks=0"
|
||||
mcu.add_config_cmd("query_adxl345 oid=%d rest_ticks=0"
|
||||
% (oid,), on_restart=True)
|
||||
mcu.register_config_callback(self._build_config)
|
||||
mcu.register_response(self._handle_adxl345_data, "adxl345_data", oid)
|
||||
# Clock tracking
|
||||
self.last_sequence = self.max_query_duration = 0
|
||||
self.last_limit_count = self.last_error_count = 0
|
||||
self.clock_sync = ClockSyncRegression(self.mcu, 640)
|
||||
# API server endpoints
|
||||
self.api_dump = motion_report.APIDumpHelper(
|
||||
self.printer, self._api_update, self._api_startstop, 0.100)
|
||||
# Bulk sample message reading
|
||||
chip_smooth = self.data_rate * BATCH_UPDATES * 2
|
||||
self.ffreader = bulk_sensor.FixedFreqReader(mcu, chip_smooth, "BBBBB")
|
||||
self.last_error_count = 0
|
||||
# Process messages in batches
|
||||
self.batch_bulk = bulk_sensor.BatchBulkHelper(
|
||||
self.printer, self._process_batch,
|
||||
self._start_measurements, self._finish_measurements, BATCH_UPDATES)
|
||||
self.name = config.get_name().split()[-1]
|
||||
wh = self.printer.lookup_object('webhooks')
|
||||
wh.register_mux_endpoint("adxl345/dump_adxl345", "sensor", self.name,
|
||||
self._handle_dump_adxl345)
|
||||
hdr = ('time', 'x_acceleration', 'y_acceleration', 'z_acceleration')
|
||||
self.batch_bulk.add_mux_endpoint("adxl345/dump_adxl345", "sensor",
|
||||
self.name, {'header': hdr})
|
||||
def _build_config(self):
|
||||
cmdqueue = self.spi.get_command_queue()
|
||||
self.query_adxl345_cmd = self.mcu.lookup_command(
|
||||
"query_adxl345 oid=%c clock=%u rest_ticks=%u", cq=cmdqueue)
|
||||
self.query_adxl345_end_cmd = self.mcu.lookup_query_command(
|
||||
"query_adxl345 oid=%c clock=%u rest_ticks=%u",
|
||||
"adxl345_status oid=%c clock=%u query_ticks=%u next_sequence=%hu"
|
||||
" buffered=%c fifo=%c limit_count=%hu", oid=self.oid, cq=cmdqueue)
|
||||
self.query_adxl345_status_cmd = self.mcu.lookup_query_command(
|
||||
"query_adxl345_status oid=%c",
|
||||
"adxl345_status oid=%c clock=%u query_ticks=%u next_sequence=%hu"
|
||||
" buffered=%c fifo=%c limit_count=%hu", oid=self.oid, cq=cmdqueue)
|
||||
"query_adxl345 oid=%c rest_ticks=%u", cq=cmdqueue)
|
||||
self.ffreader.setup_query_command("query_adxl345_status oid=%c",
|
||||
oid=self.oid, cq=cmdqueue)
|
||||
def read_reg(self, reg):
|
||||
params = self.spi.spi_transfer([reg | REG_MOD_READ, 0x00])
|
||||
response = bytearray(params['response'])
|
||||
@@ -292,83 +236,31 @@ class ADXL345:
|
||||
"This is generally indicative of connection problems "
|
||||
"(e.g. faulty wiring) or a faulty adxl345 chip." % (
|
||||
reg, val, stored_val))
|
||||
# Measurement collection
|
||||
def is_measuring(self):
|
||||
return self.query_rate > 0
|
||||
def _handle_adxl345_data(self, params):
|
||||
with self.lock:
|
||||
self.raw_samples.append(params)
|
||||
def _extract_samples(self, raw_samples):
|
||||
# Load variables to optimize inner loop below
|
||||
def start_internal_client(self):
|
||||
aqh = AccelQueryHelper(self.printer)
|
||||
self.batch_bulk.add_client(aqh.handle_batch)
|
||||
return aqh
|
||||
# Measurement decoding
|
||||
def _convert_samples(self, samples):
|
||||
(x_pos, x_scale), (y_pos, y_scale), (z_pos, z_scale) = self.axes_map
|
||||
last_sequence = self.last_sequence
|
||||
time_base, chip_base, inv_freq = self.clock_sync.get_time_translation()
|
||||
# Process every message in raw_samples
|
||||
count = seq = 0
|
||||
samples = [None] * (len(raw_samples) * SAMPLES_PER_BLOCK)
|
||||
for params in raw_samples:
|
||||
seq_diff = (last_sequence - params['sequence']) & 0xffff
|
||||
seq_diff -= (seq_diff & 0x8000) << 1
|
||||
seq = last_sequence - seq_diff
|
||||
d = bytearray(params['data'])
|
||||
msg_cdiff = seq * SAMPLES_PER_BLOCK - chip_base
|
||||
for i in range(len(d) // BYTES_PER_SAMPLE):
|
||||
d_xyz = d[i*BYTES_PER_SAMPLE:(i+1)*BYTES_PER_SAMPLE]
|
||||
xlow, ylow, zlow, xzhigh, yzhigh = d_xyz
|
||||
if yzhigh & 0x80:
|
||||
self.last_error_count += 1
|
||||
continue
|
||||
rx = (xlow | ((xzhigh & 0x1f) << 8)) - ((xzhigh & 0x10) << 9)
|
||||
ry = (ylow | ((yzhigh & 0x1f) << 8)) - ((yzhigh & 0x10) << 9)
|
||||
rz = ((zlow | ((xzhigh & 0xe0) << 3) | ((yzhigh & 0xe0) << 6))
|
||||
- ((yzhigh & 0x40) << 7))
|
||||
raw_xyz = (rx, ry, rz)
|
||||
x = round(raw_xyz[x_pos] * x_scale, 6)
|
||||
y = round(raw_xyz[y_pos] * y_scale, 6)
|
||||
z = round(raw_xyz[z_pos] * z_scale, 6)
|
||||
ptime = round(time_base + (msg_cdiff + i) * inv_freq, 6)
|
||||
samples[count] = (ptime, x, y, z)
|
||||
count += 1
|
||||
self.clock_sync.set_last_chip_clock(seq * SAMPLES_PER_BLOCK + i)
|
||||
count = 0
|
||||
for ptime, xlow, ylow, zlow, xzhigh, yzhigh in samples:
|
||||
if yzhigh & 0x80:
|
||||
self.last_error_count += 1
|
||||
continue
|
||||
rx = (xlow | ((xzhigh & 0x1f) << 8)) - ((xzhigh & 0x10) << 9)
|
||||
ry = (ylow | ((yzhigh & 0x1f) << 8)) - ((yzhigh & 0x10) << 9)
|
||||
rz = ((zlow | ((xzhigh & 0xe0) << 3) | ((yzhigh & 0xe0) << 6))
|
||||
- ((yzhigh & 0x40) << 7))
|
||||
raw_xyz = (rx, ry, rz)
|
||||
x = round(raw_xyz[x_pos] * x_scale, 6)
|
||||
y = round(raw_xyz[y_pos] * y_scale, 6)
|
||||
z = round(raw_xyz[z_pos] * z_scale, 6)
|
||||
samples[count] = (round(ptime, 6), x, y, z)
|
||||
count += 1
|
||||
del samples[count:]
|
||||
return samples
|
||||
def _update_clock(self, minclock=0):
|
||||
# Query current state
|
||||
for retry in range(5):
|
||||
params = self.query_adxl345_status_cmd.send([self.oid],
|
||||
minclock=minclock)
|
||||
fifo = params['fifo'] & 0x7f
|
||||
if fifo <= 32:
|
||||
break
|
||||
else:
|
||||
raise self.printer.command_error("Unable to query adxl345 fifo")
|
||||
mcu_clock = self.mcu.clock32_to_clock64(params['clock'])
|
||||
sequence = (self.last_sequence & ~0xffff) | params['next_sequence']
|
||||
if sequence < self.last_sequence:
|
||||
sequence += 0x10000
|
||||
self.last_sequence = sequence
|
||||
buffered = params['buffered']
|
||||
limit_count = (self.last_limit_count & ~0xffff) | params['limit_count']
|
||||
if limit_count < self.last_limit_count:
|
||||
limit_count += 0x10000
|
||||
self.last_limit_count = limit_count
|
||||
duration = params['query_ticks']
|
||||
if duration > self.max_query_duration:
|
||||
# Skip measurement as a high query time could skew clock tracking
|
||||
self.max_query_duration = max(2 * self.max_query_duration,
|
||||
self.mcu.seconds_to_clock(.000005))
|
||||
return
|
||||
self.max_query_duration = 2 * duration
|
||||
msg_count = (sequence * SAMPLES_PER_BLOCK
|
||||
+ buffered // BYTES_PER_SAMPLE + fifo)
|
||||
# The "chip clock" is the message counter plus .5 for average
|
||||
# inaccuracy of query responses and plus .5 for assumed offset
|
||||
# of adxl345 hw processing time.
|
||||
chip_clock = msg_count + 1
|
||||
self.clock_sync.update(mcu_clock + duration // 2, chip_clock)
|
||||
# Start, stop, and process message batches
|
||||
def _start_measurements(self):
|
||||
if self.is_measuring():
|
||||
return
|
||||
# In case of miswiring, testing ADXL345 device ID prevents treating
|
||||
# noise or wrong signal as a correctly initialized device
|
||||
dev_id = self.read_reg(REG_DEVID)
|
||||
@@ -384,59 +276,27 @@ class ADXL345:
|
||||
self.set_reg(REG_FIFO_CTL, 0x00)
|
||||
self.set_reg(REG_BW_RATE, QUERY_RATES[self.data_rate])
|
||||
self.set_reg(REG_FIFO_CTL, SET_FIFO_CTL)
|
||||
# Setup samples
|
||||
with self.lock:
|
||||
self.raw_samples = []
|
||||
# Start bulk reading
|
||||
systime = self.printer.get_reactor().monotonic()
|
||||
print_time = self.mcu.estimated_print_time(systime) + MIN_MSG_TIME
|
||||
reqclock = self.mcu.print_time_to_clock(print_time)
|
||||
rest_ticks = self.mcu.seconds_to_clock(4. / self.data_rate)
|
||||
self.query_rate = self.data_rate
|
||||
self.query_adxl345_cmd.send([self.oid, reqclock, rest_ticks],
|
||||
reqclock=reqclock)
|
||||
self.query_adxl345_cmd.send([self.oid, rest_ticks])
|
||||
self.set_reg(REG_POWER_CTL, 0x08)
|
||||
logging.info("ADXL345 starting '%s' measurements", self.name)
|
||||
# Initialize clock tracking
|
||||
self.last_sequence = 0
|
||||
self.last_limit_count = self.last_error_count = 0
|
||||
self.clock_sync.reset(reqclock, 0)
|
||||
self.max_query_duration = 1 << 31
|
||||
self._update_clock(minclock=reqclock)
|
||||
self.max_query_duration = 1 << 31
|
||||
self.ffreader.note_start()
|
||||
self.last_error_count = 0
|
||||
def _finish_measurements(self):
|
||||
if not self.is_measuring():
|
||||
return
|
||||
# Halt bulk reading
|
||||
params = self.query_adxl345_end_cmd.send([self.oid, 0, 0])
|
||||
self.query_rate = 0
|
||||
with self.lock:
|
||||
self.raw_samples = []
|
||||
self.set_reg(REG_POWER_CTL, 0x00)
|
||||
self.query_adxl345_cmd.send_wait_ack([self.oid, 0])
|
||||
self.ffreader.note_end()
|
||||
logging.info("ADXL345 finished '%s' measurements", self.name)
|
||||
# API interface
|
||||
def _api_update(self, eventtime):
|
||||
self._update_clock()
|
||||
with self.lock:
|
||||
raw_samples = self.raw_samples
|
||||
self.raw_samples = []
|
||||
if not raw_samples:
|
||||
return {}
|
||||
samples = self._extract_samples(raw_samples)
|
||||
def _process_batch(self, eventtime):
|
||||
samples = self.ffreader.pull_samples()
|
||||
self._convert_samples(samples)
|
||||
if not samples:
|
||||
return {}
|
||||
return {'data': samples, 'errors': self.last_error_count,
|
||||
'overflows': self.last_limit_count}
|
||||
def _api_startstop(self, is_start):
|
||||
if is_start:
|
||||
self._start_measurements()
|
||||
else:
|
||||
self._finish_measurements()
|
||||
def _handle_dump_adxl345(self, web_request):
|
||||
self.api_dump.add_client(web_request)
|
||||
hdr = ('time', 'x_acceleration', 'y_acceleration', 'z_acceleration')
|
||||
web_request.send({'header': hdr})
|
||||
def start_internal_client(self):
|
||||
cconn = self.api_dump.add_internal_client()
|
||||
return AccelQueryHelper(self.printer, cconn)
|
||||
'overflows': self.ffreader.get_last_overflows()}
|
||||
|
||||
def load_config(config):
|
||||
return ADXL345(config)
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
# Copyright (C) 2021,2022 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging, math, threading
|
||||
from . import bus, motion_report
|
||||
import logging, math
|
||||
from . import bus, bulk_sensor
|
||||
|
||||
MIN_MSG_TIME = 0.100
|
||||
TCODE_ERROR = 0xff
|
||||
@@ -85,9 +85,9 @@ class AngleCalibration:
|
||||
cal2 = calibration[bucket + 1]
|
||||
adj = (angle & interp_mask) * (cal2 - cal1)
|
||||
adj = cal1 + ((adj + interp_round) >> interp_bits)
|
||||
angle_diff = (angle - adj) & 0xffff
|
||||
angle_diff = (adj - angle) & 0xffff
|
||||
angle_diff -= (angle_diff & 0x8000) << 1
|
||||
new_angle = angle - angle_diff
|
||||
new_angle = angle + angle_diff
|
||||
if calibration_reversed:
|
||||
new_angle = -new_angle
|
||||
samples[i] = (samp_time, new_angle)
|
||||
@@ -157,8 +157,14 @@ class AngleCalibration:
|
||||
def do_calibration_moves(self):
|
||||
move = self.printer.lookup_object('force_move').manual_move
|
||||
# Start data collection
|
||||
angle_sensor = self.printer.lookup_object(self.name)
|
||||
cconn = angle_sensor.start_internal_client()
|
||||
msgs = []
|
||||
is_finished = False
|
||||
def handle_batch(msg):
|
||||
if is_finished:
|
||||
return False
|
||||
msgs.append(msg)
|
||||
return True
|
||||
self.printer.lookup_object(self.name).add_client(handle_batch)
|
||||
# Move stepper several turns (to allow internal sensor calibration)
|
||||
microsteps, full_steps = self.get_microsteps()
|
||||
mcu_stepper = self.mcu_stepper
|
||||
@@ -190,13 +196,12 @@ class AngleCalibration:
|
||||
move(mcu_stepper, .5*rotation_dist + align_dist, move_speed)
|
||||
toolhead.wait_moves()
|
||||
# Finish data collection
|
||||
cconn.finalize()
|
||||
msgs = cconn.get_messages()
|
||||
is_finished = True
|
||||
# Correlate query responses
|
||||
cal = {}
|
||||
step = 0
|
||||
for msg in msgs:
|
||||
for query_time, pos in msg['params']['data']:
|
||||
for query_time, pos in msg['data']:
|
||||
# Add to step tracking
|
||||
while step < len(times) and query_time > times[step][1]:
|
||||
step += 1
|
||||
@@ -375,9 +380,9 @@ class HelperTLE5012B:
|
||||
mcu_clock, chip_clock = self._query_clock()
|
||||
mdiff = mcu_clock - self.last_chip_mcu_clock
|
||||
chip_mclock = self.last_chip_clock + int(mdiff * self.chip_freq + .5)
|
||||
cdiff = (chip_mclock - chip_clock) & 0xffff
|
||||
cdiff = (chip_clock - chip_mclock) & 0xffff
|
||||
cdiff -= (cdiff & 0x8000) << 1
|
||||
new_chip_clock = chip_mclock - cdiff
|
||||
new_chip_clock = chip_mclock + cdiff
|
||||
self.chip_freq = float(new_chip_clock - self.last_chip_clock) / mdiff
|
||||
self.last_chip_clock = new_chip_clock
|
||||
self.last_chip_mcu_clock = mcu_clock
|
||||
@@ -406,7 +411,11 @@ class HelperTLE5012B:
|
||||
parser=lambda x: int(x, 0))
|
||||
self._write_reg(reg, val)
|
||||
|
||||
BYTES_PER_SAMPLE = 3
|
||||
SAMPLES_PER_BLOCK = bulk_sensor.MAX_BULK_MSG_SIZE // BYTES_PER_SAMPLE
|
||||
|
||||
SAMPLE_PERIOD = 0.000400
|
||||
BATCH_UPDATES = 0.100
|
||||
|
||||
class Angle:
|
||||
def __init__(self, config):
|
||||
@@ -417,9 +426,6 @@ class Angle:
|
||||
# Measurement conversion
|
||||
self.start_clock = self.time_shift = self.sample_ticks = 0
|
||||
self.last_sequence = self.last_angle = 0
|
||||
# Measurement storage (accessed from background thread)
|
||||
self.lock = threading.Lock()
|
||||
self.raw_samples = []
|
||||
# Sensor type
|
||||
sensors = { "a1333": HelperA1333, "as5047d": HelperAS5047D,
|
||||
"tle5012b": HelperTLE5012B }
|
||||
@@ -431,7 +437,7 @@ class Angle:
|
||||
self.oid = oid = mcu.create_oid()
|
||||
self.sensor_helper = sensor_class(config, self.spi, oid)
|
||||
# Setup mcu sensor_spi_angle bulk query code
|
||||
self.query_spi_angle_cmd = self.query_spi_angle_end_cmd = None
|
||||
self.query_spi_angle_cmd = None
|
||||
mcu.add_config_cmd(
|
||||
"config_spi_angle oid=%d spi_oid=%d spi_angle_type=%s"
|
||||
% (oid, self.spi.get_oid(), sensor_type))
|
||||
@@ -439,15 +445,15 @@ class Angle:
|
||||
"query_spi_angle oid=%d clock=0 rest_ticks=0 time_shift=0"
|
||||
% (oid,), on_restart=True)
|
||||
mcu.register_config_callback(self._build_config)
|
||||
mcu.register_response(self._handle_spi_angle_data,
|
||||
"spi_angle_data", oid)
|
||||
# API server endpoints
|
||||
self.api_dump = motion_report.APIDumpHelper(
|
||||
self.printer, self._api_update, self._api_startstop, 0.100)
|
||||
self.bulk_queue = bulk_sensor.BulkDataQueue(mcu, oid=oid)
|
||||
# Process messages in batches
|
||||
self.batch_bulk = bulk_sensor.BatchBulkHelper(
|
||||
self.printer, self._process_batch,
|
||||
self._start_measurements, self._finish_measurements, BATCH_UPDATES)
|
||||
self.name = config.get_name().split()[1]
|
||||
wh = self.printer.lookup_object('webhooks')
|
||||
wh.register_mux_endpoint("angle/dump_angle", "sensor", self.name,
|
||||
self._handle_dump_angle)
|
||||
api_resp = {'header': ('time', 'angle')}
|
||||
self.batch_bulk.add_mux_endpoint("angle/dump_angle",
|
||||
"sensor", self.name, api_resp)
|
||||
def _build_config(self):
|
||||
freq = self.mcu.seconds_to_clock(1.)
|
||||
while float(TCODE_ERROR << self.time_shift) / freq < 0.002:
|
||||
@@ -456,17 +462,11 @@ class Angle:
|
||||
self.query_spi_angle_cmd = self.mcu.lookup_command(
|
||||
"query_spi_angle oid=%c clock=%u rest_ticks=%u time_shift=%c",
|
||||
cq=cmdqueue)
|
||||
self.query_spi_angle_end_cmd = self.mcu.lookup_query_command(
|
||||
"query_spi_angle oid=%c clock=%u rest_ticks=%u time_shift=%c",
|
||||
"spi_angle_end oid=%c sequence=%hu", oid=self.oid, cq=cmdqueue)
|
||||
def get_status(self, eventtime=None):
|
||||
return {'temperature': self.sensor_helper.last_temperature}
|
||||
# Measurement collection
|
||||
def is_measuring(self):
|
||||
return self.start_clock != 0
|
||||
def _handle_spi_angle_data(self, params):
|
||||
with self.lock:
|
||||
self.raw_samples.append(params)
|
||||
def add_client(self, client_cb):
|
||||
self.batch_bulk.add_client(client_cb)
|
||||
# Measurement decoding
|
||||
def _extract_samples(self, raw_samples):
|
||||
# Load variables to optimize inner loop below
|
||||
sample_ticks = self.sample_ticks
|
||||
@@ -487,23 +487,23 @@ class Angle:
|
||||
static_delay = self.sensor_helper.get_static_delay()
|
||||
# Process every message in raw_samples
|
||||
count = error_count = 0
|
||||
samples = [None] * (len(raw_samples) * 16)
|
||||
samples = [None] * (len(raw_samples) * SAMPLES_PER_BLOCK)
|
||||
for params in raw_samples:
|
||||
seq = (last_sequence & ~0xffff) | params['sequence']
|
||||
if seq < last_sequence:
|
||||
seq += 0x10000
|
||||
last_sequence = seq
|
||||
seq_diff = (params['sequence'] - last_sequence) & 0xffff
|
||||
last_sequence += seq_diff
|
||||
samp_count = last_sequence * SAMPLES_PER_BLOCK
|
||||
msg_mclock = start_clock + samp_count*sample_ticks
|
||||
d = bytearray(params['data'])
|
||||
msg_mclock = start_clock + seq*16*sample_ticks
|
||||
for i in range(len(d) // 3):
|
||||
tcode = d[i*3]
|
||||
for i in range(len(d) // BYTES_PER_SAMPLE):
|
||||
d_ta = d[i*BYTES_PER_SAMPLE:(i+1)*BYTES_PER_SAMPLE]
|
||||
tcode = d_ta[0]
|
||||
if tcode == TCODE_ERROR:
|
||||
error_count += 1
|
||||
continue
|
||||
raw_angle = d[i*3 + 1] | (d[i*3 + 2] << 8)
|
||||
angle_diff = (last_angle - raw_angle) & 0xffff
|
||||
raw_angle = d_ta[1] | (d_ta[2] << 8)
|
||||
angle_diff = (raw_angle - last_angle) & 0xffff
|
||||
angle_diff -= (angle_diff & 0x8000) << 1
|
||||
last_angle -= angle_diff
|
||||
last_angle += angle_diff
|
||||
mclock = msg_mclock + i*sample_ticks
|
||||
if is_tcode_absolute:
|
||||
# tcode is tle5012b frame counter
|
||||
@@ -522,29 +522,14 @@ class Angle:
|
||||
self.last_angle = last_angle
|
||||
del samples[count:]
|
||||
return samples, error_count
|
||||
# API interface
|
||||
def _api_update(self, eventtime):
|
||||
if self.sensor_helper.is_tcode_absolute:
|
||||
self.sensor_helper.update_clock()
|
||||
with self.lock:
|
||||
raw_samples = self.raw_samples
|
||||
self.raw_samples = []
|
||||
if not raw_samples:
|
||||
return {}
|
||||
samples, error_count = self._extract_samples(raw_samples)
|
||||
if not samples:
|
||||
return {}
|
||||
offset = self.calibration.apply_calibration(samples)
|
||||
return {'data': samples, 'errors': error_count,
|
||||
'position_offset': offset}
|
||||
# Start, stop, and process message batches
|
||||
def _is_measuring(self):
|
||||
return self.start_clock != 0
|
||||
def _start_measurements(self):
|
||||
if self.is_measuring():
|
||||
return
|
||||
logging.info("Starting angle '%s' measurements", self.name)
|
||||
self.sensor_helper.start()
|
||||
# Start bulk reading
|
||||
with self.lock:
|
||||
self.raw_samples = []
|
||||
self.bulk_queue.clear_queue()
|
||||
self.last_sequence = 0
|
||||
systime = self.printer.get_reactor().monotonic()
|
||||
print_time = self.mcu.estimated_print_time(systime) + MIN_MSG_TIME
|
||||
@@ -554,26 +539,23 @@ class Angle:
|
||||
self.query_spi_angle_cmd.send([self.oid, reqclock, rest_ticks,
|
||||
self.time_shift], reqclock=reqclock)
|
||||
def _finish_measurements(self):
|
||||
if not self.is_measuring():
|
||||
return
|
||||
# Halt bulk reading
|
||||
params = self.query_spi_angle_end_cmd.send([self.oid, 0, 0, 0])
|
||||
self.start_clock = 0
|
||||
with self.lock:
|
||||
self.raw_samples = []
|
||||
self.query_spi_angle_cmd.send_wait_ack([self.oid, 0, 0, 0])
|
||||
self.bulk_queue.clear_queue()
|
||||
self.sensor_helper.last_temperature = None
|
||||
logging.info("Stopped angle '%s' measurements", self.name)
|
||||
def _api_startstop(self, is_start):
|
||||
if is_start:
|
||||
self._start_measurements()
|
||||
else:
|
||||
self._finish_measurements()
|
||||
def _handle_dump_angle(self, web_request):
|
||||
self.api_dump.add_client(web_request)
|
||||
hdr = ('time', 'angle')
|
||||
web_request.send({'header': hdr})
|
||||
def start_internal_client(self):
|
||||
return self.api_dump.add_internal_client()
|
||||
def _process_batch(self, eventtime):
|
||||
if self.sensor_helper.is_tcode_absolute:
|
||||
self.sensor_helper.update_clock()
|
||||
raw_samples = self.bulk_queue.pull_queue()
|
||||
if not raw_samples:
|
||||
return {}
|
||||
samples, error_count = self._extract_samples(raw_samples)
|
||||
if not samples:
|
||||
return {}
|
||||
offset = self.calibration.apply_calibration(samples)
|
||||
return {'data': samples, 'errors': error_count,
|
||||
'position_offset': offset}
|
||||
|
||||
def load_config_prefix(config):
|
||||
return Angle(config)
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
import math
|
||||
from . import manual_probe as ManualProbe, bed_mesh as BedMesh
|
||||
from . import manual_probe, bed_mesh, probe
|
||||
|
||||
|
||||
DEFAULT_SAMPLE_COUNT = 3
|
||||
@@ -38,10 +38,13 @@ class AxisTwistCompensation:
|
||||
|
||||
# setup calibrater
|
||||
self.calibrater = Calibrater(self, config)
|
||||
# register events
|
||||
self.printer.register_event_handler("probe:update_results",
|
||||
self._update_z_compensation_value)
|
||||
|
||||
def get_z_compensation_value(self, pos):
|
||||
def _update_z_compensation_value(self, pos):
|
||||
if not self.z_compensations:
|
||||
return 0
|
||||
return
|
||||
|
||||
x_coord = pos[0]
|
||||
z_compensations = self.z_compensations
|
||||
@@ -50,12 +53,12 @@ class AxisTwistCompensation:
|
||||
/ (sample_count - 1))
|
||||
interpolate_t = (x_coord - self.calibrate_start_x) / spacing
|
||||
interpolate_i = int(math.floor(interpolate_t))
|
||||
interpolate_i = BedMesh.constrain(interpolate_i, 0, sample_count - 2)
|
||||
interpolate_i = bed_mesh.constrain(interpolate_i, 0, sample_count - 2)
|
||||
interpolate_t -= interpolate_i
|
||||
interpolated_z_compensation = BedMesh.lerp(
|
||||
interpolated_z_compensation = bed_mesh.lerp(
|
||||
interpolate_t, z_compensations[interpolate_i],
|
||||
z_compensations[interpolate_i + 1])
|
||||
return interpolated_z_compensation
|
||||
pos[2] += interpolated_z_compensation
|
||||
|
||||
def clear_compensations(self):
|
||||
self.z_compensations = []
|
||||
@@ -95,7 +98,7 @@ class Calibrater:
|
||||
config = self.printer.lookup_object('configfile')
|
||||
raise config.error(
|
||||
"AXIS_TWIST_COMPENSATION requires [probe] to be defined")
|
||||
self.lift_speed = self.probe.get_lift_speed()
|
||||
self.lift_speed = self.probe.get_probe_params()['lift_speed']
|
||||
self.probe_x_offset, self.probe_y_offset, _ = \
|
||||
self.probe.get_offsets()
|
||||
|
||||
@@ -134,7 +137,7 @@ class Calibrater:
|
||||
nozzle_points, self.probe_x_offset, self.probe_y_offset)
|
||||
|
||||
# verify no other manual probe is in progress
|
||||
ManualProbe.verify_no_manual_probe(self.printer)
|
||||
manual_probe.verify_no_manual_probe(self.printer)
|
||||
|
||||
# begin calibration
|
||||
self.current_point_index = 0
|
||||
@@ -186,7 +189,8 @@ class Calibrater:
|
||||
probe_points[self.current_point_index][1], None))
|
||||
|
||||
# probe the point
|
||||
self.current_measured_z = self.probe.run_probe(self.gcmd)[2]
|
||||
pos = probe.run_single_probe(self.probe, self.gcmd)
|
||||
self.current_measured_z = pos[2]
|
||||
|
||||
# horizontal_move_z (to prevent probe trigger or hitting bed)
|
||||
self._move_helper((None, None, self.horizontal_move_z))
|
||||
@@ -195,7 +199,7 @@ class Calibrater:
|
||||
self._move_helper((nozzle_points[self.current_point_index]))
|
||||
|
||||
# start the manual (nozzle) probe
|
||||
ManualProbe.ManualProbeHelper(
|
||||
manual_probe.ManualProbeHelper(
|
||||
self.printer, self.gcmd,
|
||||
self._manual_probe_callback_factory(
|
||||
probe_points, nozzle_points, interval))
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
# BLTouch support
|
||||
#
|
||||
# Copyright (C) 2018-2021 Kevin O'Connor <kevin@koconnor.net>
|
||||
# Copyright (C) 2018-2024 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
@@ -23,13 +23,9 @@ Commands = {
|
||||
}
|
||||
|
||||
# BLTouch "endstop" wrapper
|
||||
class BLTouchEndstopWrapper:
|
||||
class BLTouchProbe:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
self.printer.register_event_handler("klippy:connect",
|
||||
self.handle_connect)
|
||||
self.printer.register_event_handler('klippy:mcu_identify',
|
||||
self.handle_mcu_identify)
|
||||
self.position_endstop = config.getfloat('z_offset', minval=0.)
|
||||
self.stow_on_each_sample = config.getboolean('stow_on_each_sample',
|
||||
True)
|
||||
@@ -44,12 +40,9 @@ class BLTouchEndstopWrapper:
|
||||
self.next_cmd_time = self.action_end_time = 0.
|
||||
self.finish_home_complete = self.wait_trigger_complete = None
|
||||
# Create an "endstop" object to handle the sensor pin
|
||||
pin = config.get('sensor_pin')
|
||||
pin_params = ppins.lookup_pin(pin, can_invert=True, can_pullup=True)
|
||||
mcu = pin_params['chip']
|
||||
self.mcu_endstop = mcu.setup_pin('endstop', pin_params)
|
||||
self.mcu_endstop = ppins.setup_pin('endstop', config.get('sensor_pin'))
|
||||
# output mode
|
||||
omodes = {'5V': '5V', 'OD': 'OD', None: None}
|
||||
omodes = ['5V', 'OD', None]
|
||||
self.output_mode = config.getchoice('set_output_mode', omodes, None)
|
||||
# Setup for sensor test
|
||||
self.next_test_time = 0.
|
||||
@@ -65,19 +58,30 @@ class BLTouchEndstopWrapper:
|
||||
self.get_steppers = self.mcu_endstop.get_steppers
|
||||
self.home_wait = self.mcu_endstop.home_wait
|
||||
self.query_endstop = self.mcu_endstop.query_endstop
|
||||
# multi probes state
|
||||
self.multi = 'OFF'
|
||||
# Common probe implementation helpers
|
||||
self.cmd_helper = probe.ProbeCommandHelper(
|
||||
config, self, self.mcu_endstop.query_endstop)
|
||||
self.probe_offsets = probe.ProbeOffsetsHelper(config)
|
||||
self.probe_session = probe.ProbeSessionHelper(config, self)
|
||||
# Register BLTOUCH_DEBUG command
|
||||
self.gcode = self.printer.lookup_object('gcode')
|
||||
self.gcode.register_command("BLTOUCH_DEBUG", self.cmd_BLTOUCH_DEBUG,
|
||||
desc=self.cmd_BLTOUCH_DEBUG_help)
|
||||
self.gcode.register_command("BLTOUCH_STORE", self.cmd_BLTOUCH_STORE,
|
||||
desc=self.cmd_BLTOUCH_STORE_help)
|
||||
# multi probes state
|
||||
self.multi = 'OFF'
|
||||
def handle_mcu_identify(self):
|
||||
kin = self.printer.lookup_object('toolhead').get_kinematics()
|
||||
for stepper in kin.get_steppers():
|
||||
if stepper.is_active_axis('z'):
|
||||
self.add_stepper(stepper)
|
||||
# Register events
|
||||
self.printer.register_event_handler("klippy:connect",
|
||||
self.handle_connect)
|
||||
def get_probe_params(self, gcmd=None):
|
||||
return self.probe_session.get_probe_params(gcmd)
|
||||
def get_offsets(self):
|
||||
return self.probe_offsets.get_offsets()
|
||||
def get_status(self, eventtime):
|
||||
return self.cmd_helper.get_status(eventtime)
|
||||
def start_probe_session(self, gcmd):
|
||||
return self.probe_session.start_probe_session(gcmd)
|
||||
def handle_connect(self):
|
||||
self.sync_mcu_print_time()
|
||||
self.next_cmd_time += 0.200
|
||||
@@ -116,7 +120,11 @@ class BLTouchEndstopWrapper:
|
||||
self.mcu_endstop.home_start(self.action_end_time, ENDSTOP_SAMPLE_TIME,
|
||||
ENDSTOP_SAMPLE_COUNT, ENDSTOP_REST_TIME,
|
||||
triggered=triggered)
|
||||
trigger_time = self.mcu_endstop.home_wait(self.action_end_time + 0.100)
|
||||
try:
|
||||
trigger_time = self.mcu_endstop.home_wait(
|
||||
self.action_end_time + 0.100)
|
||||
except self.printer.command_error as e:
|
||||
return False
|
||||
return trigger_time > 0.
|
||||
def raise_probe(self):
|
||||
self.sync_mcu_print_time()
|
||||
@@ -183,6 +191,9 @@ class BLTouchEndstopWrapper:
|
||||
self.verify_raise_probe()
|
||||
self.sync_print_time()
|
||||
self.multi = 'OFF'
|
||||
def probing_move(self, pos, speed):
|
||||
phoming = self.printer.lookup_object('homing')
|
||||
return phoming.probing_move(self, pos, speed)
|
||||
def probe_prepare(self, hmove):
|
||||
if self.multi == 'OFF' or self.multi == 'FIRST':
|
||||
self.lower_probe()
|
||||
@@ -271,6 +282,6 @@ class BLTouchEndstopWrapper:
|
||||
self.sync_print_time()
|
||||
|
||||
def load_config(config):
|
||||
blt = BLTouchEndstopWrapper(config)
|
||||
config.get_printer().add_object('probe', probe.PrinterProbe(config, blt))
|
||||
blt = BLTouchProbe(config)
|
||||
config.get_printer().add_object('probe', blt)
|
||||
return blt
|
||||
|
||||
@@ -8,6 +8,7 @@ from . import bus
|
||||
|
||||
REPORT_TIME = .8
|
||||
BME280_CHIP_ADDR = 0x76
|
||||
|
||||
BME280_REGS = {
|
||||
'RESET': 0xE0, 'CTRL_HUM': 0xF2,
|
||||
'STATUS': 0xF3, 'CTRL_MEAS': 0xF4, 'CONFIG': 0xF5,
|
||||
@@ -16,6 +17,29 @@ BME280_REGS = {
|
||||
'HUM_MSB': 0xFD, 'HUM_LSB': 0xFE, 'CAL_1': 0x88, 'CAL_2': 0xE1
|
||||
}
|
||||
|
||||
BMP388_REGS = {
|
||||
"CMD": 0x7E,
|
||||
"STATUS": 0x03,
|
||||
"PWR_CTRL": 0x1B,
|
||||
"OSR": 0x1C,
|
||||
"ORD": 0x1D,
|
||||
"INT_CTRL": 0x19,
|
||||
"CAL_1": 0x31,
|
||||
"TEMP_MSB": 0x09,
|
||||
"TEMP_LSB": 0x08,
|
||||
"TEMP_XLSB": 0x07,
|
||||
"PRESS_MSB": 0x06,
|
||||
"PRESS_LSB": 0x05,
|
||||
"PRESS_XLSB": 0x04,
|
||||
}
|
||||
BMP388_REG_VAL_PRESS_EN = 0x01
|
||||
BMP388_REG_VAL_TEMP_EN = 0x02
|
||||
BMP388_REG_VAL_PRESS_OS_NO = 0b000
|
||||
BMP388_REG_VAL_TEMP_OS_NO = 0b000000
|
||||
BMP388_REG_VAL_ODR_50_HZ = 0x02
|
||||
BMP388_REG_VAL_DRDY_EN = 0b100000
|
||||
BMP388_REG_VAL_NORMAL_MODE = 0x30
|
||||
|
||||
BME680_REGS = {
|
||||
'RESET': 0xE0, 'CTRL_HUM': 0x72, 'CTRL_GAS_1': 0x71, 'CTRL_GAS_0': 0x70,
|
||||
'GAS_WAIT_0': 0x64, 'RES_HEAT_0': 0x5A, 'IDAC_HEAT_0': 0x50,
|
||||
@@ -46,6 +70,16 @@ BME680_GAS_CONSTANTS = {
|
||||
15: (1., 244.140625)
|
||||
}
|
||||
|
||||
BMP180_REGS = {
|
||||
'RESET': 0xE0,
|
||||
'CAL_1': 0xAA,
|
||||
'CTRL_MEAS': 0xF4,
|
||||
'REG_MSB': 0xF6,
|
||||
'REG_LSB': 0xF7,
|
||||
'CRV_TEMP': 0x2E,
|
||||
'CRV_PRES': 0x34
|
||||
}
|
||||
|
||||
STATUS_MEASURING = 1 << 3
|
||||
STATUS_IM_UPDATE = 1
|
||||
MODE = 1
|
||||
@@ -57,9 +91,11 @@ MEASURE_DONE = 1 << 5
|
||||
RESET_CHIP_VALUE = 0xB6
|
||||
|
||||
BME_CHIPS = {
|
||||
0x58: 'BMP280', 0x60: 'BME280', 0x61: 'BME680'
|
||||
0x58: 'BMP280', 0x60: 'BME280', 0x61: 'BME680', 0x55: 'BMP180',
|
||||
0x50: 'BMP388'
|
||||
}
|
||||
BME_CHIP_ID_REG = 0xD0
|
||||
BMP3_CHIP_ID_REG = 0x00
|
||||
|
||||
|
||||
def get_twos_complement(val, bit_size):
|
||||
@@ -81,6 +117,14 @@ def get_signed_byte(bits):
|
||||
return get_twos_complement(bits, 8)
|
||||
|
||||
|
||||
def get_unsigned_short_msb(bits):
|
||||
return bits[0] << 8 | bits[1]
|
||||
|
||||
|
||||
def get_signed_short_msb(bits):
|
||||
val = get_unsigned_short_msb(bits)
|
||||
return get_twos_complement(val, 16)
|
||||
|
||||
class BME280:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
@@ -144,6 +188,29 @@ class BME280:
|
||||
dig['P9'] = get_signed_short(calib_data_1[22:24])
|
||||
return dig
|
||||
|
||||
def read_calibration_data_bmp388(calib_data_1):
|
||||
dig = {}
|
||||
dig["T1"] = get_unsigned_short(calib_data_1[0:2]) / 0.00390625
|
||||
dig["T2"] = get_unsigned_short(calib_data_1[2:4]) / 1073741824.0
|
||||
dig["T3"] = get_signed_byte(calib_data_1[4]) / 281474976710656.0
|
||||
|
||||
dig["P1"] = get_signed_short(calib_data_1[5:7]) - 16384
|
||||
dig["P1"] /= 1048576.0
|
||||
dig["P2"] = get_signed_short(calib_data_1[7:9]) - 16384
|
||||
dig["P2"] /= 536870912.0
|
||||
dig["P3"] = get_signed_byte(calib_data_1[9]) / 4294967296.0
|
||||
dig["P4"] = get_signed_byte(calib_data_1[10]) / 137438953472.0
|
||||
dig["P5"] = get_unsigned_short(calib_data_1[11:13]) / 0.125
|
||||
dig["P6"] = get_unsigned_short(calib_data_1[13:15]) / 64.0
|
||||
dig["P7"] = get_signed_byte(calib_data_1[15]) / 256.0
|
||||
dig["P8"] = get_signed_byte(calib_data_1[16]) / 32768.0
|
||||
dig["P9"] = get_signed_short(calib_data_1[17:19])
|
||||
dig["P9"] /= 281474976710656.0
|
||||
dig["P10"] = get_signed_byte(calib_data_1[19]) / 281474976710656.0
|
||||
dig["P11"] = get_signed_byte(calib_data_1[20])
|
||||
dig["P11"] /= 36893488147419103232.0
|
||||
return dig
|
||||
|
||||
def read_calibration_data_bme280(calib_data_1, calib_data_2):
|
||||
dig = read_calibration_data_bmp280(calib_data_1)
|
||||
dig['H1'] = calib_data_1[25] & 0xFF
|
||||
@@ -188,7 +255,24 @@ class BME280:
|
||||
dig['G3'] = get_signed_byte(calib_data_2[13])
|
||||
return dig
|
||||
|
||||
chip_id = self.read_id()
|
||||
def read_calibration_data_bmp180(calib_data_1):
|
||||
dig = {}
|
||||
dig['AC1'] = get_signed_short_msb(calib_data_1[0:2])
|
||||
dig['AC2'] = get_signed_short_msb(calib_data_1[2:4])
|
||||
dig['AC3'] = get_signed_short_msb(calib_data_1[4:6])
|
||||
dig['AC4'] = get_unsigned_short_msb(calib_data_1[6:8])
|
||||
dig['AC5'] = get_unsigned_short_msb(calib_data_1[8:10])
|
||||
dig['AC6'] = get_unsigned_short_msb(calib_data_1[10:12])
|
||||
|
||||
dig['B1'] = get_signed_short_msb(calib_data_1[12:14])
|
||||
dig['B2'] = get_signed_short_msb(calib_data_1[14:16])
|
||||
|
||||
dig['MB'] = get_signed_short_msb(calib_data_1[16:18])
|
||||
dig['MC'] = get_signed_short_msb(calib_data_1[18:20])
|
||||
dig['MD'] = get_signed_short_msb(calib_data_1[20:22])
|
||||
return dig
|
||||
|
||||
chip_id = self.read_id() or self.read_bmp3_id()
|
||||
if chip_id not in BME_CHIPS.keys():
|
||||
logging.info("bme280: Unknown Chip ID received %#x" % chip_id)
|
||||
else:
|
||||
@@ -201,15 +285,39 @@ class BME280:
|
||||
self.reactor.pause(self.reactor.monotonic() + .5)
|
||||
|
||||
# Make sure non-volatile memory has been copied to registers
|
||||
status = self.read_register('STATUS', 1)[0]
|
||||
while status & STATUS_IM_UPDATE:
|
||||
self.reactor.pause(self.reactor.monotonic() + .01)
|
||||
if self.chip_type != 'BMP180':
|
||||
# BMP180 has no status register available
|
||||
status = self.read_register('STATUS', 1)[0]
|
||||
while status & STATUS_IM_UPDATE:
|
||||
self.reactor.pause(self.reactor.monotonic() + .01)
|
||||
status = self.read_register('STATUS', 1)[0]
|
||||
|
||||
if self.chip_type == 'BME680':
|
||||
self.max_sample_time = 0.5
|
||||
self.sample_timer = self.reactor.register_timer(self._sample_bme680)
|
||||
self.chip_registers = BME680_REGS
|
||||
elif self.chip_type == 'BMP180':
|
||||
self.max_sample_time = (1.25 + ((2.3 * self.os_pres) + .575)) / 1000
|
||||
self.sample_timer = self.reactor.register_timer(self._sample_bmp180)
|
||||
self.chip_registers = BMP180_REGS
|
||||
elif self.chip_type == 'BMP388':
|
||||
self.max_sample_time = 0.5
|
||||
self.chip_registers = BMP388_REGS
|
||||
self.write_register(
|
||||
"PWR_CTRL",
|
||||
[
|
||||
BMP388_REG_VAL_PRESS_EN
|
||||
| BMP388_REG_VAL_TEMP_EN
|
||||
| BMP388_REG_VAL_NORMAL_MODE
|
||||
],
|
||||
)
|
||||
self.write_register(
|
||||
"OSR", [BMP388_REG_VAL_PRESS_OS_NO | BMP388_REG_VAL_TEMP_OS_NO]
|
||||
)
|
||||
self.write_register("ORD", [BMP388_REG_VAL_ODR_50_HZ])
|
||||
self.write_register("INT_CTRL", [BMP388_REG_VAL_DRDY_EN])
|
||||
|
||||
self.sample_timer = self.reactor.register_timer(self._sample_bmp388)
|
||||
else:
|
||||
self.max_sample_time = \
|
||||
(1.25 + (2.3 * self.os_temp) + ((2.3 * self.os_pres) + .575)
|
||||
@@ -221,14 +329,23 @@ class BME280:
|
||||
self.write_register('CONFIG', (self.iir_filter & 0x07) << 2)
|
||||
|
||||
# Read out and calculate the trimming parameters
|
||||
cal_1 = self.read_register('CAL_1', 26)
|
||||
cal_2 = self.read_register('CAL_2', 16)
|
||||
if self.chip_type == 'BMP180':
|
||||
cal_1 = self.read_register('CAL_1', 22)
|
||||
elif self.chip_type == 'BMP388':
|
||||
cal_1 = self.read_register('CAL_1', 21)
|
||||
else:
|
||||
cal_1 = self.read_register('CAL_1', 26)
|
||||
cal_2 = self.read_register('CAL_2', 16)
|
||||
if self.chip_type == 'BME280':
|
||||
self.dig = read_calibration_data_bme280(cal_1, cal_2)
|
||||
elif self.chip_type == 'BMP280':
|
||||
self.dig = read_calibration_data_bmp280(cal_1)
|
||||
elif self.chip_type == 'BME680':
|
||||
self.dig = read_calibration_data_bme680(cal_1, cal_2)
|
||||
elif self.chip_type == 'BMP180':
|
||||
self.dig = read_calibration_data_bmp180(cal_1)
|
||||
elif self.chip_type == 'BMP388':
|
||||
self.dig = read_calibration_data_bmp388(cal_1)
|
||||
|
||||
def _sample_bme280(self, eventtime):
|
||||
# Enter forced mode
|
||||
@@ -271,6 +388,79 @@ class BME280:
|
||||
self._callback(self.mcu.estimated_print_time(measured_time), self.temp)
|
||||
return measured_time + REPORT_TIME
|
||||
|
||||
def _sample_bmp388(self, eventtime):
|
||||
status = self.read_register("STATUS", 1)
|
||||
if status[0] & 0b100000:
|
||||
self.temp = self._sample_bmp388_temp()
|
||||
if self.temp < self.min_temp or self.temp > self.max_temp:
|
||||
self.printer.invoke_shutdown(
|
||||
"BME280 temperature %0.1f outside range of %0.1f:%.01f"
|
||||
% (self.temp, self.min_temp, self.max_temp)
|
||||
)
|
||||
|
||||
if status[0] & 0b010000:
|
||||
self.pressure = self._sample_bmp388_press() / 100.0
|
||||
|
||||
measured_time = self.reactor.monotonic()
|
||||
self._callback(self.mcu.estimated_print_time(measured_time), self.temp)
|
||||
return measured_time + REPORT_TIME
|
||||
|
||||
def _sample_bmp388_temp(self):
|
||||
xlsb = self.read_register("TEMP_XLSB", 1)
|
||||
lsb = self.read_register("TEMP_LSB", 1)
|
||||
msb = self.read_register("TEMP_MSB", 1)
|
||||
adc_T = (msb[0] << 16) + (lsb[0] << 8) + (xlsb[0])
|
||||
|
||||
partial_data1 = adc_T - self.dig["T1"]
|
||||
partial_data2 = self.dig["T2"] * partial_data1
|
||||
|
||||
self.t_fine = partial_data2
|
||||
self.t_fine += (partial_data1 * partial_data1) * self.dig["T3"]
|
||||
|
||||
if self.t_fine < -40.0:
|
||||
self.t_fine = -40.0
|
||||
|
||||
if self.t_fine > 85.0:
|
||||
self.t_fine = 85.0
|
||||
|
||||
return self.t_fine
|
||||
|
||||
def _sample_bmp388_press(self):
|
||||
xlsb = self.read_register("PRESS_XLSB", 1)
|
||||
lsb = self.read_register("PRESS_LSB", 1)
|
||||
msb = self.read_register("PRESS_MSB", 1)
|
||||
adc_P = (msb[0] << 16) + (lsb[0] << 8) + (xlsb[0])
|
||||
|
||||
partial_data1 = self.dig["P6"] * self.t_fine
|
||||
partial_data2 = self.dig["P7"] * (self.t_fine * self.t_fine)
|
||||
partial_data3 = self.dig["P8"]
|
||||
partial_data3 *= self.t_fine * self.t_fine * self.t_fine
|
||||
partial_out1 = self.dig["P5"]
|
||||
partial_out1 += partial_data1 + partial_data2 + partial_data3
|
||||
|
||||
partial_data1 = self.dig["P2"] * self.t_fine
|
||||
partial_data2 = self.dig["P3"] * (self.t_fine * self.t_fine)
|
||||
partial_data3 = self.dig["P4"]
|
||||
partial_data3 *= (self.t_fine * self.t_fine * self.t_fine)
|
||||
partial_out2 = adc_P * (
|
||||
self.dig["P1"] + partial_data1 + partial_data2 + partial_data3
|
||||
)
|
||||
|
||||
partial_data1 = adc_P * adc_P
|
||||
partial_data2 = self.dig["P9"] + (self.dig["P10"] * self.t_fine)
|
||||
partial_data3 = partial_data1 * partial_data2
|
||||
partial_data4 = partial_data3 + adc_P * adc_P * adc_P * self.dig["P11"]
|
||||
|
||||
comp_press = partial_out1 + partial_out2 + partial_data4
|
||||
|
||||
if comp_press < 30000:
|
||||
comp_press = 30000
|
||||
|
||||
if comp_press > 125000:
|
||||
comp_press = 125000
|
||||
|
||||
return comp_press
|
||||
|
||||
def _sample_bme680(self, eventtime):
|
||||
self.write_register('CTRL_HUM', self.os_hum & 0x07)
|
||||
meas = self.os_temp << 5 | self.os_pres << 2
|
||||
@@ -334,6 +524,43 @@ class BME280:
|
||||
self._callback(self.mcu.estimated_print_time(measured_time), self.temp)
|
||||
return measured_time + REPORT_TIME
|
||||
|
||||
def _sample_bmp180(self, eventtime):
|
||||
meas = self.chip_registers['CRV_TEMP']
|
||||
self.write_register('CTRL_MEAS', meas)
|
||||
|
||||
try:
|
||||
self.reactor.pause(self.reactor.monotonic() + .01)
|
||||
data = self.read_register('REG_MSB', 2)
|
||||
temp_raw = (data[0] << 8) | data[1]
|
||||
except Exception:
|
||||
logging.exception("BMP180: Error reading temperature")
|
||||
self.temp = self.pressure = .0
|
||||
return self.reactor.NEVER
|
||||
|
||||
meas = self.chip_registers['CRV_PRES'] | (self.os_pres << 6)
|
||||
self.write_register('CTRL_MEAS', meas)
|
||||
|
||||
try:
|
||||
self.reactor.pause(self.reactor.monotonic() + .01)
|
||||
data = self.read_register('REG_MSB', 3)
|
||||
pressure_raw = \
|
||||
((data[0] << 16)|(data[1] << 8)|data[2]) >> (8 - self.os_pres)
|
||||
except Exception:
|
||||
logging.exception("BMP180: Error reading pressure")
|
||||
self.temp = self.pressure = .0
|
||||
return self.reactor.NEVER
|
||||
|
||||
self.temp = self._compensate_temp_bmp180(temp_raw)
|
||||
self.pressure = self._compensate_pressure_bmp180(pressure_raw) / 100.
|
||||
if self.temp < self.min_temp or self.temp > self.max_temp:
|
||||
self.printer.invoke_shutdown(
|
||||
"BMP180 temperature %0.1f outside range of %0.1f:%.01f"
|
||||
% (self.temp, self.min_temp, self.max_temp))
|
||||
measured_time = self.reactor.monotonic()
|
||||
self._callback(self.mcu.estimated_print_time(measured_time), self.temp)
|
||||
return measured_time + REPORT_TIME
|
||||
|
||||
|
||||
def _compensate_temp(self, raw_temp):
|
||||
dig = self.dig
|
||||
var1 = ((raw_temp / 16384. - (dig['T1'] / 1024.)) * dig['T2'])
|
||||
@@ -443,12 +670,49 @@ class BME280:
|
||||
|
||||
return duration_reg
|
||||
|
||||
def _compensate_temp_bmp180(self, raw_temp):
|
||||
dig = self.dig
|
||||
x1 = (raw_temp - dig['AC6']) * dig['AC5'] / 32768.
|
||||
x2 = dig['MC'] * 2048 / (x1 + dig['MD'])
|
||||
b5 = x1 + x2
|
||||
self.t_fine = b5
|
||||
return (b5 + 8)/16./10.
|
||||
|
||||
def _compensate_pressure_bmp180(self, raw_pressure):
|
||||
dig = self.dig
|
||||
b5 = self.t_fine
|
||||
b6 = b5 - 4000
|
||||
x1 = (dig['B2'] * (b6 * b6 / 4096)) / 2048
|
||||
x2 = dig['AC2'] * b6 / 2048
|
||||
x3 = x1 + x2
|
||||
b3 = ((int(dig['AC1'] * 4 + x3) << self.os_pres) + 2) / 4
|
||||
x1 = dig['AC3'] * b6 / 8192
|
||||
x2 = (dig['B1'] * (b6 * b6 / 4096)) / 65536
|
||||
x3 = ((x1 + x2) + 2) / 4
|
||||
b4 = dig['AC4'] * (x3 + 32768) / 32768
|
||||
b7 = (raw_pressure - b3) * (50000 >> self.os_pres)
|
||||
if (b7 < 0x80000000):
|
||||
p = (b7 * 2) / b4
|
||||
else:
|
||||
p = (b7 / b4) * 2
|
||||
x1 = (p / 256) * (p / 256)
|
||||
x1 = (x1 * 3038) / 65536
|
||||
x2 = (-7357 * p) / 65536
|
||||
p = p + (x1 + x2 + 3791) / 16.
|
||||
return p
|
||||
|
||||
def read_id(self):
|
||||
# read chip id register
|
||||
regs = [BME_CHIP_ID_REG]
|
||||
params = self.i2c.i2c_read(regs, 1)
|
||||
return bytearray(params['response'])[0]
|
||||
|
||||
def read_bmp3_id(self):
|
||||
# read chip id register
|
||||
regs = [BMP3_CHIP_ID_REG]
|
||||
params = self.i2c.i2c_read(regs, 1)
|
||||
return bytearray(params['response'])[0]
|
||||
|
||||
def read_register(self, reg_name, read_len):
|
||||
# read a single register
|
||||
regs = [self.chip_registers[reg_name]]
|
||||
|
||||
297
klippy/extras/bulk_sensor.py
Normal file
297
klippy/extras/bulk_sensor.py
Normal file
@@ -0,0 +1,297 @@
|
||||
# Tools for reading bulk sensor data from the mcu
|
||||
#
|
||||
# Copyright (C) 2020-2023 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging, threading, struct
|
||||
|
||||
# This "bulk sensor" module facilitates the processing of sensor chip
|
||||
# measurements that do not require the host to respond with low
|
||||
# latency. This module helps collect these measurements into batches
|
||||
# that are then processed periodically by the host code (as specified
|
||||
# by BatchBulkHelper.batch_interval). It supports the collection of
|
||||
# thousands of sensor measurements per second.
|
||||
#
|
||||
# Processing measurements in batches reduces load on the mcu, reduces
|
||||
# bandwidth to/from the mcu, and reduces load on the host. It also
|
||||
# makes it easier to export the raw measurements via the webhooks
|
||||
# system (aka API Server).
|
||||
|
||||
BATCH_INTERVAL = 0.500
|
||||
|
||||
# Helper to process accumulated messages in periodic batches
|
||||
class BatchBulkHelper:
|
||||
def __init__(self, printer, batch_cb, start_cb=None, stop_cb=None,
|
||||
batch_interval=BATCH_INTERVAL):
|
||||
self.printer = printer
|
||||
self.batch_cb = batch_cb
|
||||
if start_cb is None:
|
||||
start_cb = (lambda: None)
|
||||
self.start_cb = start_cb
|
||||
if stop_cb is None:
|
||||
stop_cb = (lambda: None)
|
||||
self.stop_cb = stop_cb
|
||||
self.is_started = False
|
||||
self.batch_interval = batch_interval
|
||||
self.batch_timer = None
|
||||
self.client_cbs = []
|
||||
self.webhooks_start_resp = {}
|
||||
# Periodic batch processing
|
||||
def _start(self):
|
||||
if self.is_started:
|
||||
return
|
||||
self.is_started = True
|
||||
try:
|
||||
self.start_cb()
|
||||
except self.printer.command_error as e:
|
||||
logging.exception("BatchBulkHelper start callback error")
|
||||
self.is_started = False
|
||||
del self.client_cbs[:]
|
||||
raise
|
||||
reactor = self.printer.get_reactor()
|
||||
systime = reactor.monotonic()
|
||||
waketime = systime + self.batch_interval
|
||||
self.batch_timer = reactor.register_timer(self._proc_batch, waketime)
|
||||
def _stop(self):
|
||||
del self.client_cbs[:]
|
||||
self.printer.get_reactor().unregister_timer(self.batch_timer)
|
||||
self.batch_timer = None
|
||||
if not self.is_started:
|
||||
return
|
||||
try:
|
||||
self.stop_cb()
|
||||
except self.printer.command_error as e:
|
||||
logging.exception("BatchBulkHelper stop callback error")
|
||||
del self.client_cbs[:]
|
||||
self.is_started = False
|
||||
if self.client_cbs:
|
||||
# New client started while in process of stopping
|
||||
self._start()
|
||||
def _proc_batch(self, eventtime):
|
||||
try:
|
||||
msg = self.batch_cb(eventtime)
|
||||
except self.printer.command_error as e:
|
||||
logging.exception("BatchBulkHelper batch callback error")
|
||||
self._stop()
|
||||
return self.printer.get_reactor().NEVER
|
||||
if not msg:
|
||||
return eventtime + self.batch_interval
|
||||
for client_cb in list(self.client_cbs):
|
||||
res = client_cb(msg)
|
||||
if not res:
|
||||
# This client no longer needs updates - unregister it
|
||||
self.client_cbs.remove(client_cb)
|
||||
if not self.client_cbs:
|
||||
self._stop()
|
||||
return self.printer.get_reactor().NEVER
|
||||
return eventtime + self.batch_interval
|
||||
# Client registration
|
||||
def add_client(self, client_cb):
|
||||
self.client_cbs.append(client_cb)
|
||||
self._start()
|
||||
# Webhooks registration
|
||||
def _add_api_client(self, web_request):
|
||||
whbatch = BatchWebhooksClient(web_request)
|
||||
self.add_client(whbatch.handle_batch)
|
||||
web_request.send(self.webhooks_start_resp)
|
||||
def add_mux_endpoint(self, path, key, value, webhooks_start_resp):
|
||||
self.webhooks_start_resp = webhooks_start_resp
|
||||
wh = self.printer.lookup_object('webhooks')
|
||||
wh.register_mux_endpoint(path, key, value, self._add_api_client)
|
||||
|
||||
# A webhooks wrapper for use by BatchBulkHelper
|
||||
class BatchWebhooksClient:
|
||||
def __init__(self, web_request):
|
||||
self.cconn = web_request.get_client_connection()
|
||||
self.template = web_request.get_dict('response_template', {})
|
||||
def handle_batch(self, msg):
|
||||
if self.cconn.is_closed():
|
||||
return False
|
||||
tmp = dict(self.template)
|
||||
tmp['params'] = msg
|
||||
self.cconn.send(tmp)
|
||||
return True
|
||||
|
||||
# Helper class to store incoming messages in a queue
|
||||
class BulkDataQueue:
|
||||
def __init__(self, mcu, msg_name="sensor_bulk_data", oid=None):
|
||||
# Measurement storage (accessed from background thread)
|
||||
self.lock = threading.Lock()
|
||||
self.raw_samples = []
|
||||
# Register callback with mcu
|
||||
mcu.register_response(self._handle_data, msg_name, oid)
|
||||
def _handle_data(self, params):
|
||||
with self.lock:
|
||||
self.raw_samples.append(params)
|
||||
def pull_queue(self):
|
||||
with self.lock:
|
||||
raw_samples = self.raw_samples
|
||||
self.raw_samples = []
|
||||
return raw_samples
|
||||
def clear_queue(self):
|
||||
self.pull_queue()
|
||||
|
||||
|
||||
######################################################################
|
||||
# Clock synchronization
|
||||
######################################################################
|
||||
|
||||
# It is common for sensors to produce measurements at a fixed
|
||||
# frequency. If the mcu can reliably obtain all of these
|
||||
# measurements, then the code here can calculate a precision timestamp
|
||||
# for them. That is, it can determine the actual sensor measurement
|
||||
# frequency, the time of the first measurement, and thus a precise
|
||||
# time for all measurements.
|
||||
#
|
||||
# This system works by having the mcu periodically report a precision
|
||||
# timestamp along with the total number of measurements the sensor has
|
||||
# taken as of that time. In brief, knowing the total number of
|
||||
# measurements taken over an extended period provides an accurate
|
||||
# estimate of measurement frequency, which can then also be utilized
|
||||
# to determine the time of the first measurement.
|
||||
|
||||
# Helper class for chip clock synchronization via linear regression
|
||||
class ClockSyncRegression:
|
||||
def __init__(self, mcu, chip_clock_smooth, decay = 1. / 20.):
|
||||
self.mcu = mcu
|
||||
self.chip_clock_smooth = chip_clock_smooth
|
||||
self.decay = decay
|
||||
self.last_chip_clock = self.last_exp_mcu_clock = 0.
|
||||
self.mcu_clock_avg = self.mcu_clock_variance = 0.
|
||||
self.chip_clock_avg = self.chip_clock_covariance = 0.
|
||||
def reset(self, mcu_clock, chip_clock):
|
||||
self.mcu_clock_avg = self.last_mcu_clock = mcu_clock
|
||||
self.chip_clock_avg = chip_clock
|
||||
self.mcu_clock_variance = self.chip_clock_covariance = 0.
|
||||
self.last_chip_clock = self.last_exp_mcu_clock = 0.
|
||||
def update(self, mcu_clock, chip_clock):
|
||||
# Update linear regression
|
||||
decay = self.decay
|
||||
diff_mcu_clock = mcu_clock - self.mcu_clock_avg
|
||||
self.mcu_clock_avg += decay * diff_mcu_clock
|
||||
self.mcu_clock_variance = (1. - decay) * (
|
||||
self.mcu_clock_variance + diff_mcu_clock**2 * decay)
|
||||
diff_chip_clock = chip_clock - self.chip_clock_avg
|
||||
self.chip_clock_avg += decay * diff_chip_clock
|
||||
self.chip_clock_covariance = (1. - decay) * (
|
||||
self.chip_clock_covariance + diff_mcu_clock*diff_chip_clock*decay)
|
||||
def set_last_chip_clock(self, chip_clock):
|
||||
base_mcu, base_chip, inv_cfreq = self.get_clock_translation()
|
||||
self.last_chip_clock = chip_clock
|
||||
self.last_exp_mcu_clock = base_mcu + (chip_clock-base_chip) * inv_cfreq
|
||||
def get_clock_translation(self):
|
||||
inv_chip_freq = self.mcu_clock_variance / self.chip_clock_covariance
|
||||
if not self.last_chip_clock:
|
||||
return self.mcu_clock_avg, self.chip_clock_avg, inv_chip_freq
|
||||
# Find mcu clock associated with future chip_clock
|
||||
s_chip_clock = self.last_chip_clock + self.chip_clock_smooth
|
||||
scdiff = s_chip_clock - self.chip_clock_avg
|
||||
s_mcu_clock = self.mcu_clock_avg + scdiff * inv_chip_freq
|
||||
# Calculate frequency to converge at future point
|
||||
mdiff = s_mcu_clock - self.last_exp_mcu_clock
|
||||
s_inv_chip_freq = mdiff / self.chip_clock_smooth
|
||||
return self.last_exp_mcu_clock, self.last_chip_clock, s_inv_chip_freq
|
||||
def get_time_translation(self):
|
||||
base_mcu, base_chip, inv_cfreq = self.get_clock_translation()
|
||||
clock_to_print_time = self.mcu.clock_to_print_time
|
||||
base_time = clock_to_print_time(base_mcu)
|
||||
inv_freq = clock_to_print_time(base_mcu + inv_cfreq) - base_time
|
||||
return base_time, base_chip, inv_freq
|
||||
|
||||
MAX_BULK_MSG_SIZE = 51
|
||||
|
||||
# Read sensor_bulk_data and calculate timestamps for devices that take
|
||||
# samples at a fixed frequency (and produce fixed data size samples).
|
||||
class FixedFreqReader:
|
||||
def __init__(self, mcu, chip_clock_smooth, unpack_fmt):
|
||||
self.mcu = mcu
|
||||
self.clock_sync = ClockSyncRegression(mcu, chip_clock_smooth)
|
||||
unpack = struct.Struct(unpack_fmt)
|
||||
self.unpack_from = unpack.unpack_from
|
||||
self.bytes_per_sample = unpack.size
|
||||
self.samples_per_block = MAX_BULK_MSG_SIZE // self.bytes_per_sample
|
||||
self.last_sequence = self.max_query_duration = 0
|
||||
self.last_overflows = 0
|
||||
self.bulk_queue = self.oid = self.query_status_cmd = None
|
||||
def setup_query_command(self, msgformat, oid, cq):
|
||||
# Lookup sensor query command (that responds with sensor_bulk_status)
|
||||
self.oid = oid
|
||||
self.query_status_cmd = self.mcu.lookup_query_command(
|
||||
msgformat, "sensor_bulk_status oid=%c clock=%u query_ticks=%u"
|
||||
" next_sequence=%hu buffered=%u possible_overflows=%hu",
|
||||
oid=oid, cq=cq)
|
||||
# Read sensor_bulk_data messages and store in a queue
|
||||
self.bulk_queue = BulkDataQueue(self.mcu, oid=oid)
|
||||
def get_last_overflows(self):
|
||||
return self.last_overflows
|
||||
def _clear_duration_filter(self):
|
||||
self.max_query_duration = 1 << 31
|
||||
def note_start(self):
|
||||
self.last_sequence = 0
|
||||
self.last_overflows = 0
|
||||
# Clear local queue (clear any stale samples from previous session)
|
||||
self.bulk_queue.clear_queue()
|
||||
# Set initial clock
|
||||
self._clear_duration_filter()
|
||||
self._update_clock(is_reset=True)
|
||||
self._clear_duration_filter()
|
||||
def note_end(self):
|
||||
# Clear local queue (free no longer needed memory)
|
||||
self.bulk_queue.clear_queue()
|
||||
def _update_clock(self, is_reset=False):
|
||||
params = self.query_status_cmd.send([self.oid])
|
||||
mcu_clock = self.mcu.clock32_to_clock64(params['clock'])
|
||||
seq_diff = (params['next_sequence'] - self.last_sequence) & 0xffff
|
||||
self.last_sequence += seq_diff
|
||||
buffered = params['buffered']
|
||||
po_diff = (params['possible_overflows'] - self.last_overflows) & 0xffff
|
||||
self.last_overflows += po_diff
|
||||
duration = params['query_ticks']
|
||||
if duration > self.max_query_duration:
|
||||
# Skip measurement as a high query time could skew clock tracking
|
||||
self.max_query_duration = max(2 * self.max_query_duration,
|
||||
self.mcu.seconds_to_clock(.000005))
|
||||
return
|
||||
self.max_query_duration = 2 * duration
|
||||
msg_count = (self.last_sequence * self.samples_per_block
|
||||
+ buffered // self.bytes_per_sample)
|
||||
# The "chip clock" is the message counter plus .5 for average
|
||||
# inaccuracy of query responses and plus .5 for assumed offset
|
||||
# of hardware processing time.
|
||||
chip_clock = msg_count + 1
|
||||
avg_mcu_clock = mcu_clock + duration // 2
|
||||
if is_reset:
|
||||
self.clock_sync.reset(avg_mcu_clock, chip_clock)
|
||||
else:
|
||||
self.clock_sync.update(avg_mcu_clock, chip_clock)
|
||||
# Convert sensor_bulk_data responses into list of samples
|
||||
def pull_samples(self):
|
||||
# Query MCU for sample timing and update clock synchronization
|
||||
self._update_clock()
|
||||
# Pull sensor_bulk_data messages from local queue
|
||||
raw_samples = self.bulk_queue.pull_queue()
|
||||
if not raw_samples:
|
||||
return []
|
||||
# Load variables to optimize inner loop below
|
||||
last_sequence = self.last_sequence
|
||||
time_base, chip_base, inv_freq = self.clock_sync.get_time_translation()
|
||||
unpack_from = self.unpack_from
|
||||
bytes_per_sample = self.bytes_per_sample
|
||||
samples_per_block = self.samples_per_block
|
||||
# Process every message in raw_samples
|
||||
count = seq = 0
|
||||
samples = [None] * (len(raw_samples) * samples_per_block)
|
||||
for params in raw_samples:
|
||||
seq_diff = (params['sequence'] - last_sequence) & 0xffff
|
||||
seq_diff -= (seq_diff & 0x8000) << 1
|
||||
seq = last_sequence + seq_diff
|
||||
msg_cdiff = seq * samples_per_block - chip_base
|
||||
data = params['data']
|
||||
for i in range(len(data) // bytes_per_sample):
|
||||
ptime = time_base + (msg_cdiff + i) * inv_freq
|
||||
udata = unpack_from(data, i * bytes_per_sample)
|
||||
samples[count] = (ptime,) + udata
|
||||
count += 1
|
||||
self.clock_sync.set_last_chip_clock(seq * samples_per_block + i)
|
||||
del samples[count:]
|
||||
return samples
|
||||
@@ -192,6 +192,9 @@ class MCU_I2C:
|
||||
return
|
||||
self.i2c_write_cmd.send([self.oid, data],
|
||||
minclock=minclock, reqclock=reqclock)
|
||||
def i2c_write_wait_ack(self, data, minclock=0, reqclock=0):
|
||||
self.i2c_write_cmd.send_wait_ack([self.oid, data],
|
||||
minclock=minclock, reqclock=reqclock)
|
||||
def i2c_read(self, write, read_len):
|
||||
return self.i2c_read_cmd.send([self.oid, write, read_len])
|
||||
def i2c_modify_bits(self, reg, clear_bits, set_bits,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Support for button detection and callbacks
|
||||
#
|
||||
# Copyright (C) 2018 Kevin O'Connor <kevin@koconnor.net>
|
||||
# Copyright (C) 2018-2023 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
@@ -57,10 +57,9 @@ class MCU_buttons:
|
||||
def handle_buttons_state(self, params):
|
||||
# Expand the message ack_count from 8-bit
|
||||
ack_count = self.ack_count
|
||||
ack_diff = (ack_count - params['ack_count']) & 0xff
|
||||
if ack_diff & 0x80:
|
||||
ack_diff -= 0x100
|
||||
msg_ack_count = ack_count - ack_diff
|
||||
ack_diff = (params['ack_count'] - ack_count) & 0xff
|
||||
ack_diff -= (ack_diff & 0x80) << 1
|
||||
msg_ack_count = ack_count + ack_diff
|
||||
# Determine new buttons
|
||||
buttons = bytearray(params['state'])
|
||||
new_count = msg_ack_count + len(buttons) - self.ack_count
|
||||
@@ -70,17 +69,17 @@ class MCU_buttons:
|
||||
# Send ack to MCU
|
||||
self.ack_cmd.send([self.oid, new_count])
|
||||
self.ack_count += new_count
|
||||
# Call self.handle_button() with this event in main thread
|
||||
for nb in new_buttons:
|
||||
self.reactor.register_async_callback(
|
||||
(lambda e, s=self, b=nb: s.handle_button(e, b)))
|
||||
def handle_button(self, eventtime, button):
|
||||
button ^= self.invert
|
||||
changed = button ^ self.last_button
|
||||
for mask, shift, callback in self.callbacks:
|
||||
if changed & mask:
|
||||
callback(eventtime, (button & mask) >> shift)
|
||||
self.last_button = button
|
||||
# Invoke callbacks with this event in main thread
|
||||
btime = params['#receive_time']
|
||||
for button in new_buttons:
|
||||
button ^= self.invert
|
||||
changed = button ^ self.last_button
|
||||
self.last_button = button
|
||||
for mask, shift, callback in self.callbacks:
|
||||
if changed & mask:
|
||||
state = (button & mask) >> shift
|
||||
self.reactor.register_async_callback(
|
||||
(lambda et, c=callback, bt=btime, s=state: c(bt, s)))
|
||||
|
||||
|
||||
######################################################################
|
||||
@@ -105,7 +104,7 @@ class MCU_ADC_buttons:
|
||||
self.max_value = 0.
|
||||
ppins = printer.lookup_object('pins')
|
||||
self.mcu_adc = ppins.setup_pin('adc', self.pin)
|
||||
self.mcu_adc.setup_minmax(ADC_SAMPLE_TIME, ADC_SAMPLE_COUNT)
|
||||
self.mcu_adc.setup_adc_sample(ADC_SAMPLE_TIME, ADC_SAMPLE_COUNT)
|
||||
self.mcu_adc.setup_adc_callback(ADC_REPORT_TIME, self.adc_callback)
|
||||
query_adc = printer.lookup_object('query_adc')
|
||||
query_adc.register_adc('adc_button:' + pin.strip(), self.mcu_adc)
|
||||
|
||||
@@ -8,7 +8,7 @@ import logging
|
||||
|
||||
BACKGROUND_PRIORITY_CLOCK = 0x7fffffff00000000
|
||||
LINE_LENGTH_DEFAULT=20
|
||||
LINE_LENGTH_OPTIONS={16:16, 20:20}
|
||||
LINE_LENGTH_OPTIONS=[16, 20]
|
||||
|
||||
TextGlyphs = { 'right_arrow': b'\x7e' }
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import logging
|
||||
from .. import bus
|
||||
|
||||
LINE_LENGTH_DEFAULT=20
|
||||
LINE_LENGTH_OPTIONS={16:16, 20:20}
|
||||
LINE_LENGTH_OPTIONS=[16, 20]
|
||||
|
||||
TextGlyphs = { 'right_arrow': b'\x7e' }
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ class MenuKeys:
|
||||
# Register rotary encoder
|
||||
encoder_pins = config.get('encoder_pins', None)
|
||||
encoder_steps_per_detent = config.getchoice('encoder_steps_per_detent',
|
||||
{2: 2, 4: 4}, 4)
|
||||
[2, 4], 4)
|
||||
if encoder_pins is not None:
|
||||
try:
|
||||
pin1, pin2 = encoder_pins.split(',')
|
||||
|
||||
@@ -10,7 +10,6 @@ BACKGROUND_PRIORITY_CLOCK = 0x7fffffff00000000
|
||||
class PrinterDotstar:
|
||||
def __init__(self, config):
|
||||
self.printer = printer = config.get_printer()
|
||||
name = config.get_name().split()[1]
|
||||
# Configure a software spi bus
|
||||
ppins = printer.lookup_object('pins')
|
||||
data_pin_params = ppins.lookup_pin(config.get('data_pin'))
|
||||
|
||||
@@ -191,7 +191,6 @@ class EndstopPhases:
|
||||
def generate_stats(self, stepper_name, phase_calc):
|
||||
phase_history = phase_calc.phase_history
|
||||
wph = phase_history + phase_history
|
||||
count = sum(phase_history)
|
||||
phases = len(phase_history)
|
||||
half_phases = phases // 2
|
||||
res = []
|
||||
|
||||
133
klippy/extras/error_mcu.py
Normal file
133
klippy/extras/error_mcu.py
Normal file
@@ -0,0 +1,133 @@
|
||||
# More verbose information on micro-controller errors
|
||||
#
|
||||
# Copyright (C) 2024 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
|
||||
message_shutdown = """
|
||||
Once the underlying issue is corrected, use the
|
||||
"FIRMWARE_RESTART" command to reset the firmware, reload the
|
||||
config, and restart the host software.
|
||||
Printer is shutdown
|
||||
"""
|
||||
|
||||
message_protocol_error1 = """
|
||||
This is frequently caused by running an older version of the
|
||||
firmware on the MCU(s). Fix by recompiling and flashing the
|
||||
firmware.
|
||||
"""
|
||||
|
||||
message_protocol_error2 = """
|
||||
Once the underlying issue is corrected, use the "RESTART"
|
||||
command to reload the config and restart the host software.
|
||||
"""
|
||||
|
||||
message_mcu_connect_error = """
|
||||
Once the underlying issue is corrected, use the
|
||||
"FIRMWARE_RESTART" command to reset the firmware, reload the
|
||||
config, and restart the host software.
|
||||
Error configuring printer
|
||||
"""
|
||||
|
||||
Common_MCU_errors = {
|
||||
("Timer too close",): """
|
||||
This often indicates the host computer is overloaded. Check
|
||||
for other processes consuming excessive CPU time, high swap
|
||||
usage, disk errors, overheating, unstable voltage, or
|
||||
similar system problems on the host computer.""",
|
||||
("Missed scheduling of next ",): """
|
||||
This is generally indicative of an intermittent
|
||||
communication failure between micro-controller and host.""",
|
||||
("ADC out of range",): """
|
||||
This generally occurs when a heater temperature exceeds
|
||||
its configured min_temp or max_temp.""",
|
||||
("Rescheduled timer in the past", "Stepper too far in past"): """
|
||||
This generally occurs when the micro-controller has been
|
||||
requested to step at a rate higher than it is capable of
|
||||
obtaining.""",
|
||||
("Command request",): """
|
||||
This generally occurs in response to an M112 G-Code command
|
||||
or in response to an internal error in the host software.""",
|
||||
}
|
||||
|
||||
def error_hint(msg):
|
||||
for prefixes, help_msg in Common_MCU_errors.items():
|
||||
for prefix in prefixes:
|
||||
if msg.startswith(prefix):
|
||||
return help_msg
|
||||
return ""
|
||||
|
||||
class PrinterMCUError:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
self.clarify_callbacks = {}
|
||||
self.printer.register_event_handler("klippy:notify_mcu_shutdown",
|
||||
self._handle_notify_mcu_shutdown)
|
||||
self.printer.register_event_handler("klippy:notify_mcu_error",
|
||||
self._handle_notify_mcu_error)
|
||||
def add_clarify(self, msg, callback):
|
||||
self.clarify_callbacks.setdefault(msg, []).append(callback)
|
||||
def _check_mcu_shutdown(self, msg, details):
|
||||
mcu_name = details['mcu']
|
||||
mcu_msg = details['reason']
|
||||
event_type = details['event_type']
|
||||
prefix = "MCU '%s' shutdown: " % (mcu_name,)
|
||||
if event_type == 'is_shutdown':
|
||||
prefix = "Previous MCU '%s' shutdown: " % (mcu_name,)
|
||||
# Lookup generic hint
|
||||
hint = error_hint(mcu_msg)
|
||||
# Add per instance help
|
||||
clarify = [cb(msg, details)
|
||||
for cb in self.clarify_callbacks.get(mcu_msg, [])]
|
||||
clarify = [cm for cm in clarify if cm is not None]
|
||||
clarify_msg = ""
|
||||
if clarify:
|
||||
clarify_msg = "\n".join(["", ""] + clarify + [""])
|
||||
# Update error message
|
||||
newmsg = "%s%s%s%s%s" % (prefix, mcu_msg, clarify_msg,
|
||||
hint, message_shutdown)
|
||||
self.printer.update_error_msg(msg, newmsg)
|
||||
def _handle_notify_mcu_shutdown(self, msg, details):
|
||||
if msg == "MCU shutdown":
|
||||
self._check_mcu_shutdown(msg, details)
|
||||
else:
|
||||
self.printer.update_error_msg(msg, "%s%s" % (msg, message_shutdown))
|
||||
def _check_protocol_error(self, msg, details):
|
||||
host_version = self.printer.start_args['software_version']
|
||||
msg_update = []
|
||||
msg_updated = []
|
||||
for mcu_name, mcu in self.printer.lookup_objects('mcu'):
|
||||
try:
|
||||
mcu_version = mcu.get_status()['mcu_version']
|
||||
except:
|
||||
logging.exception("Unable to retrieve mcu_version from mcu")
|
||||
continue
|
||||
if mcu_version != host_version:
|
||||
msg_update.append("%s: Current version %s"
|
||||
% (mcu_name.split()[-1], mcu_version))
|
||||
else:
|
||||
msg_updated.append("%s: Current version %s"
|
||||
% (mcu_name.split()[-1], mcu_version))
|
||||
if not msg_update:
|
||||
msg_update.append("<none>")
|
||||
if not msg_updated:
|
||||
msg_updated.append("<none>")
|
||||
newmsg = ["MCU Protocol error",
|
||||
message_protocol_error1,
|
||||
"Your Klipper version is: %s" % (host_version,),
|
||||
"MCU(s) which should be updated:"]
|
||||
newmsg += msg_update + ["Up-to-date MCU(s):"] + msg_updated
|
||||
newmsg += [message_protocol_error2, details['error']]
|
||||
self.printer.update_error_msg(msg, "\n".join(newmsg))
|
||||
def _check_mcu_connect_error(self, msg, details):
|
||||
newmsg = "%s%s" % (details['error'], message_mcu_connect_error)
|
||||
self.printer.update_error_msg(msg, newmsg)
|
||||
def _handle_notify_mcu_error(self, msg, details):
|
||||
if msg == "Protocol error":
|
||||
self._check_protocol_error(msg, details)
|
||||
elif msg == "MCU error during connect":
|
||||
self._check_mcu_connect_error(msg, details)
|
||||
|
||||
def load_config(config):
|
||||
return PrinterMCUError(config)
|
||||
@@ -234,7 +234,7 @@ class ExcludeObject:
|
||||
|
||||
elif current:
|
||||
if not self.current_object:
|
||||
gcmd.respond_error('There is no current object to cancel')
|
||||
raise self.gcode.error('There is no current object to cancel')
|
||||
|
||||
else:
|
||||
self._exclude_object(self.current_object)
|
||||
|
||||
@@ -86,11 +86,13 @@ class ForceMove:
|
||||
0., 0., 0., axis_r, 0., 0., 0., cruise_v, accel)
|
||||
print_time = print_time + accel_t + cruise_t + accel_t
|
||||
stepper.generate_steps(print_time)
|
||||
self.trapq_finalize_moves(self.trapq, print_time + 99999.9)
|
||||
self.trapq_finalize_moves(self.trapq, print_time + 99999.9,
|
||||
print_time + 99999.9)
|
||||
stepper.set_trapq(prev_trapq)
|
||||
stepper.set_stepper_kinematics(prev_sk)
|
||||
toolhead.note_kinematic_activity(print_time)
|
||||
toolhead.note_mcu_movequeue_activity(print_time)
|
||||
toolhead.dwell(accel_t + cruise_t + accel_t)
|
||||
toolhead.flush_step_generation()
|
||||
def _lookup_stepper(self, gcmd):
|
||||
name = gcmd.get('STEPPER')
|
||||
if name not in self.steppers:
|
||||
|
||||
@@ -30,7 +30,8 @@ class HallFilamentWidthSensor:
|
||||
- self.measurement_max_difference)
|
||||
self.diameter =self.nominal_filament_dia
|
||||
self.is_active =config.getboolean('enable', False)
|
||||
self.runout_dia=config.getfloat('min_diameter', 1.0)
|
||||
self.runout_dia_min=config.getfloat('min_diameter', 1.0)
|
||||
self.runout_dia_max=config.getfloat('max_diameter', self.max_diameter)
|
||||
self.is_log =config.getboolean('logging', False)
|
||||
# Use the current diameter instead of nominal while the first
|
||||
# measurement isn't in place
|
||||
@@ -48,10 +49,10 @@ class HallFilamentWidthSensor:
|
||||
# Start adc
|
||||
self.ppins = self.printer.lookup_object('pins')
|
||||
self.mcu_adc = self.ppins.setup_pin('adc', self.pin1)
|
||||
self.mcu_adc.setup_minmax(ADC_SAMPLE_TIME, ADC_SAMPLE_COUNT)
|
||||
self.mcu_adc.setup_adc_sample(ADC_SAMPLE_TIME, ADC_SAMPLE_COUNT)
|
||||
self.mcu_adc.setup_adc_callback(ADC_REPORT_TIME, self.adc_callback)
|
||||
self.mcu_adc2 = self.ppins.setup_pin('adc', self.pin2)
|
||||
self.mcu_adc2.setup_minmax(ADC_SAMPLE_TIME, ADC_SAMPLE_COUNT)
|
||||
self.mcu_adc2.setup_adc_sample(ADC_SAMPLE_TIME, ADC_SAMPLE_COUNT)
|
||||
self.mcu_adc2.setup_adc_callback(ADC_REPORT_TIME, self.adc2_callback)
|
||||
# extrude factor updating
|
||||
self.extrude_factor_update_timer = self.reactor.register_timer(
|
||||
@@ -125,7 +126,7 @@ class HallFilamentWidthSensor:
|
||||
self.update_filament_array(last_epos)
|
||||
# Check runout
|
||||
self.runout_helper.note_filament_present(
|
||||
self.diameter > self.runout_dia)
|
||||
self.runout_dia_min <= self.diameter <= self.runout_dia_max)
|
||||
# Does filament exists
|
||||
if self.diameter > 0.5:
|
||||
if len(self.filament_array) > 0:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Tracking of PWM controlled heaters and their temperature control
|
||||
#
|
||||
# Copyright (C) 2016-2020 Kevin O'Connor <kevin@koconnor.net>
|
||||
# Copyright (C) 2016-2024 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import os, logging, threading
|
||||
@@ -18,7 +18,8 @@ PID_PARAM_BASE = 255.
|
||||
class Heater:
|
||||
def __init__(self, config, sensor):
|
||||
self.printer = config.get_printer()
|
||||
self.name = config.get_name().split()[-1]
|
||||
self.name = config.get_name()
|
||||
self.short_name = short_name = self.name.split()[-1]
|
||||
# Setup sensor
|
||||
self.sensor = sensor
|
||||
self.min_temp = config.getfloat('min_temp', minval=KELVIN_TO_CELSIUS)
|
||||
@@ -36,6 +37,8 @@ class Heater:
|
||||
self.max_power = config.getfloat('max_power', 1., above=0., maxval=1.)
|
||||
self.smooth_time = config.getfloat('smooth_time', 1., above=0.)
|
||||
self.inv_smooth_time = 1. / self.smooth_time
|
||||
self.is_shutdown = False
|
||||
self.set_temp_count = 0
|
||||
self.lock = threading.Lock()
|
||||
self.last_temp = self.smoothed_temp = self.target_temp = 0.
|
||||
self.last_temp_time = 0.
|
||||
@@ -55,14 +58,19 @@ class Heater:
|
||||
self.mcu_pwm.setup_cycle_time(pwm_cycle_time)
|
||||
self.mcu_pwm.setup_max_duration(MAX_HEAT_TIME)
|
||||
# Load additional modules
|
||||
self.printer.load_object(config, "verify_heater %s" % (self.name,))
|
||||
self.printer.load_object(config, "verify_heater %s" % (short_name,))
|
||||
self.printer.load_object(config, "pid_calibrate")
|
||||
gcode = self.printer.lookup_object("gcode")
|
||||
gcode.register_mux_command("SET_HEATER_TEMPERATURE", "HEATER",
|
||||
self.name, self.cmd_SET_HEATER_TEMPERATURE,
|
||||
short_name, self.cmd_SET_HEATER_TEMPERATURE,
|
||||
desc=self.cmd_SET_HEATER_TEMPERATURE_help)
|
||||
wh = self.printer.lookup_object('webhooks')
|
||||
wh.register_mux_endpoint("heaters/set_target_temperature", "heater",
|
||||
self.name, self._api_set_target_temperature)
|
||||
self.printer.register_event_handler("klippy:shutdown",
|
||||
self._handle_shutdown)
|
||||
def set_pwm(self, read_time, value):
|
||||
if self.target_temp <= 0.:
|
||||
if self.target_temp <= 0. or self.is_shutdown:
|
||||
value = 0.
|
||||
if ((read_time < self.next_pwm_time or not self.last_pwm_value)
|
||||
and abs(value - self.last_pwm_value) < 0.05):
|
||||
@@ -86,7 +94,11 @@ class Heater:
|
||||
self.smoothed_temp += temp_diff * adj_time
|
||||
self.can_extrude = (self.smoothed_temp >= self.min_extrude_temp)
|
||||
#logging.debug("temp: %.3f %f = %f", read_time, temp)
|
||||
def _handle_shutdown(self):
|
||||
self.is_shutdown = True
|
||||
# External commands
|
||||
def get_name(self):
|
||||
return self.name
|
||||
def get_pwm_delay(self):
|
||||
return self.pwm_delay
|
||||
def get_max_power(self):
|
||||
@@ -98,6 +110,7 @@ class Heater:
|
||||
raise self.printer.command_error(
|
||||
"Requested temperature (%.1f) out of range (%.1f:%.1f)"
|
||||
% (degrees, self.min_temp, self.max_temp))
|
||||
self.set_temp_count += 1
|
||||
with self.lock:
|
||||
self.target_temp = degrees
|
||||
def get_temp(self, eventtime):
|
||||
@@ -127,7 +140,7 @@ class Heater:
|
||||
last_pwm_value = self.last_pwm_value
|
||||
is_active = target_temp or last_temp > 50.
|
||||
return is_active, '%s: target=%.0f temp=%.1f pwm=%.3f' % (
|
||||
self.name, target_temp, last_temp, last_pwm_value)
|
||||
self.short_name, target_temp, last_temp, last_pwm_value)
|
||||
def get_status(self, eventtime):
|
||||
with self.lock:
|
||||
target_temp = self.target_temp
|
||||
@@ -135,11 +148,17 @@ class Heater:
|
||||
last_pwm_value = self.last_pwm_value
|
||||
return {'temperature': round(smoothed_temp, 2), 'target': target_temp,
|
||||
'power': last_pwm_value}
|
||||
def get_set_temp_count(self):
|
||||
return self.set_temp_count
|
||||
cmd_SET_HEATER_TEMPERATURE_help = "Sets a heater temperature"
|
||||
def cmd_SET_HEATER_TEMPERATURE(self, gcmd):
|
||||
temp = gcmd.get_float('TARGET', 0.)
|
||||
pheaters = self.printer.lookup_object('heaters')
|
||||
pheaters.set_temperature(self, temp)
|
||||
def _api_set_target_temperature(self, web_request):
|
||||
temp = web_request.get_float('target')
|
||||
pheaters = self.printer.lookup_object('heaters')
|
||||
pheaters.set_temperature(self, temp)
|
||||
|
||||
|
||||
######################################################################
|
||||
@@ -231,6 +250,7 @@ class PrinterHeaters:
|
||||
self.available_heaters = []
|
||||
self.available_sensors = []
|
||||
self.available_monitors = []
|
||||
self.in_temperature_wait = None
|
||||
self.has_started = self.have_load_sensors = False
|
||||
self.printer.register_event_handler("klippy:ready", self._handle_ready)
|
||||
self.printer.register_event_handler("gcode:request_restart",
|
||||
@@ -281,8 +301,6 @@ class PrinterHeaters:
|
||||
if sensor_type not in self.sensor_factories:
|
||||
raise self.printer.config_error(
|
||||
"Unknown temperature sensor '%s'" % (sensor_type,))
|
||||
if sensor_type == 'NTC 100K beta 3950':
|
||||
config.deprecate('sensor_type', 'NTC 100K beta 3950')
|
||||
return self.sensor_factories[sensor_type](config)
|
||||
def register_sensor(self, config, psensor, gcode_id=None):
|
||||
self.available_sensors.append(config.get_name())
|
||||
@@ -299,7 +317,8 @@ class PrinterHeaters:
|
||||
def get_status(self, eventtime):
|
||||
return {'available_heaters': self.available_heaters,
|
||||
'available_sensors': self.available_sensors,
|
||||
'available_monitors': self.available_monitors}
|
||||
'available_monitors': self.available_monitors,
|
||||
'temperature_wait': self.in_temperature_wait}
|
||||
def turn_off_all_heaters(self, print_time=0.):
|
||||
for heater in self.heaters.values():
|
||||
heater.set_temp(0.)
|
||||
@@ -330,14 +349,23 @@ class PrinterHeaters:
|
||||
# Helper to wait on heater.check_busy() and report M105 temperatures
|
||||
if self.printer.get_start_args().get('debugoutput') is not None:
|
||||
return
|
||||
full_name = heater.get_name()
|
||||
set_temp_count = heater.get_set_temp_count()
|
||||
toolhead = self.printer.lookup_object("toolhead")
|
||||
gcode = self.printer.lookup_object("gcode")
|
||||
reactor = self.printer.get_reactor()
|
||||
eventtime = reactor.monotonic()
|
||||
while not self.printer.is_shutdown() and heater.check_busy(eventtime):
|
||||
self.in_temperature_wait = full_name
|
||||
print_time = toolhead.get_last_move_time()
|
||||
gcode.respond_raw(self._get_temp(eventtime))
|
||||
eventtime = reactor.pause(eventtime + 1.)
|
||||
if heater.get_set_temp_count() != set_temp_count:
|
||||
self.in_temperature_wait = None
|
||||
raise self.printer.command_error(
|
||||
"Heater '%s' target temperature changed during wait"
|
||||
% (full_name,))
|
||||
self.in_temperature_wait = None
|
||||
def set_temperature(self, heater, temp, wait=False):
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
toolhead.register_lookahead_callback((lambda pt: None))
|
||||
@@ -356,8 +384,12 @@ class PrinterHeaters:
|
||||
"Error on 'TEMPERATURE_WAIT': missing MINIMUM or MAXIMUM.")
|
||||
if self.printer.get_start_args().get('debugoutput') is not None:
|
||||
return
|
||||
full_name = sensor_name
|
||||
set_temp_count = None
|
||||
if sensor_name in self.heaters:
|
||||
sensor = self.heaters[sensor_name]
|
||||
full_name = sensor.get_name()
|
||||
set_temp_count = sensor.get_set_temp_count()
|
||||
else:
|
||||
sensor = self.printer.lookup_object(sensor_name)
|
||||
toolhead = self.printer.lookup_object("toolhead")
|
||||
@@ -366,10 +398,18 @@ class PrinterHeaters:
|
||||
while not self.printer.is_shutdown():
|
||||
temp, target = sensor.get_temp(eventtime)
|
||||
if temp >= min_temp and temp <= max_temp:
|
||||
return
|
||||
break
|
||||
self.in_temperature_wait = full_name
|
||||
print_time = toolhead.get_last_move_time()
|
||||
gcmd.respond_raw(self._get_temp(eventtime))
|
||||
eventtime = reactor.pause(eventtime + 1.)
|
||||
if (set_temp_count is not None
|
||||
and sensor.get_set_temp_count() != set_temp_count):
|
||||
self.in_temperature_wait = None
|
||||
raise self.printer.command_error(
|
||||
"Heater '%s' target temperature changed during wait"
|
||||
% (full_name,))
|
||||
self.in_temperature_wait = None
|
||||
|
||||
def load_config(config):
|
||||
return PrinterHeaters(config)
|
||||
|
||||
@@ -98,11 +98,14 @@ class HomingMove:
|
||||
trigger_times = {}
|
||||
move_end_print_time = self.toolhead.get_last_move_time()
|
||||
for mcu_endstop, name in self.endstops:
|
||||
trigger_time = mcu_endstop.home_wait(move_end_print_time)
|
||||
try:
|
||||
trigger_time = mcu_endstop.home_wait(move_end_print_time)
|
||||
except self.printer.command_error as e:
|
||||
if error is None:
|
||||
error = "Error during homing %s: %s" % (name, str(e))
|
||||
continue
|
||||
if trigger_time > 0.:
|
||||
trigger_times[name] = trigger_time
|
||||
elif trigger_time < 0. and error is None:
|
||||
error = "Communication timeout during homing %s" % (name,)
|
||||
elif check_triggered and error is None:
|
||||
error = "No trigger on %s after full movement" % (name,)
|
||||
# Determine stepper halt positions
|
||||
|
||||
@@ -55,6 +55,7 @@ class HomingOverride:
|
||||
# Perform homing
|
||||
context = self.template.create_template_context()
|
||||
context['params'] = gcmd.get_command_parameters()
|
||||
context['rawparams'] = gcmd.get_raw_command_parameters()
|
||||
try:
|
||||
self.in_script = True
|
||||
self.template.run_gcode_from_command(context)
|
||||
|
||||
@@ -126,7 +126,7 @@ class HTU21D:
|
||||
rdevId |= response[1]
|
||||
checksum = response[2]
|
||||
if self._chekCRC8(rdevId) != checksum:
|
||||
logging.warn("htu21d: Reading deviceId !Checksum error!")
|
||||
logging.warning("htu21d: Reading deviceId !Checksum error!")
|
||||
rdevId = rdevId >> 8
|
||||
deviceId_list = list(
|
||||
filter(
|
||||
@@ -135,10 +135,10 @@ class HTU21D:
|
||||
if len(deviceId_list) != 0:
|
||||
logging.info("htu21d: Found Device Type %s" % deviceId_list[0])
|
||||
else:
|
||||
logging.warn("htu21d: Unknown Device ID %#x " % rdevId)
|
||||
logging.warning("htu21d: Unknown Device ID %#x " % rdevId)
|
||||
|
||||
if(self.deviceId != deviceId_list[0]):
|
||||
logging.warn(
|
||||
if self.deviceId != deviceId_list[0]:
|
||||
logging.warning(
|
||||
"htu21d: Found device %s. Forcing to type %s as config.",
|
||||
deviceId_list[0],self.deviceId)
|
||||
|
||||
@@ -169,7 +169,9 @@ class HTU21D:
|
||||
rtemp = response[0] << 8
|
||||
rtemp |= response[1]
|
||||
if self._chekCRC8(rtemp) != response[2]:
|
||||
logging.warn("htu21d: Checksum error on Temperature reading!")
|
||||
logging.warning(
|
||||
"htu21d: Checksum error on Temperature reading!"
|
||||
)
|
||||
else:
|
||||
self.temp = (0.002681 * float(rtemp) - 46.85)
|
||||
logging.debug("htu21d: Temperature %.2f " % self.temp)
|
||||
@@ -190,7 +192,7 @@ class HTU21D:
|
||||
rhumid = response[0] << 8
|
||||
rhumid|= response[1]
|
||||
if self._chekCRC8(rhumid) != response[2]:
|
||||
logging.warn("htu21d: Checksum error on Humidity reading!")
|
||||
logging.warning("htu21d: Checksum error on Humidity reading!")
|
||||
else:
|
||||
#clear status bits,
|
||||
# humidity always returns xxxxxx10 in the LSB field
|
||||
|
||||
170
klippy/extras/hx71x.py
Normal file
170
klippy/extras/hx71x.py
Normal file
@@ -0,0 +1,170 @@
|
||||
# HX711/HX717 Support
|
||||
#
|
||||
# Copyright (C) 2024 Gareth Farrington <gareth@waves.ky>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
from . import bulk_sensor
|
||||
|
||||
#
|
||||
# Constants
|
||||
#
|
||||
UPDATE_INTERVAL = 0.10
|
||||
SAMPLE_ERROR_DESYNC = -0x80000000
|
||||
SAMPLE_ERROR_LONG_READ = 0x40000000
|
||||
|
||||
# Implementation of HX711 and HX717
|
||||
class HX71xBase():
|
||||
def __init__(self, config, sensor_type,
|
||||
sample_rate_options, default_sample_rate,
|
||||
gain_options, default_gain):
|
||||
self.printer = printer = config.get_printer()
|
||||
self.name = config.get_name().split()[-1]
|
||||
self.last_error_count = 0
|
||||
self.consecutive_fails = 0
|
||||
self.sensor_type = sensor_type
|
||||
# Chip options
|
||||
dout_pin_name = config.get('dout_pin')
|
||||
sclk_pin_name = config.get('sclk_pin')
|
||||
ppins = printer.lookup_object('pins')
|
||||
dout_ppin = ppins.lookup_pin(dout_pin_name)
|
||||
sclk_ppin = ppins.lookup_pin(sclk_pin_name)
|
||||
self.mcu = mcu = dout_ppin['chip']
|
||||
self.oid = mcu.create_oid()
|
||||
if sclk_ppin['chip'] is not mcu:
|
||||
raise config.error("%s config error: All pins must be "
|
||||
"connected to the same MCU" % (self.name,))
|
||||
self.dout_pin = dout_ppin['pin']
|
||||
self.sclk_pin = sclk_ppin['pin']
|
||||
# Samples per second choices
|
||||
self.sps = config.getchoice('sample_rate', sample_rate_options,
|
||||
default=default_sample_rate)
|
||||
# gain/channel choices
|
||||
self.gain_channel = int(config.getchoice('gain', gain_options,
|
||||
default=default_gain))
|
||||
## Bulk Sensor Setup
|
||||
self.bulk_queue = bulk_sensor.BulkDataQueue(mcu, oid=self.oid)
|
||||
# Clock tracking
|
||||
chip_smooth = self.sps * UPDATE_INTERVAL * 2
|
||||
self.ffreader = bulk_sensor.FixedFreqReader(mcu, chip_smooth, "<i")
|
||||
# Process messages in batches
|
||||
self.batch_bulk = bulk_sensor.BatchBulkHelper(
|
||||
self.printer, self._process_batch, self._start_measurements,
|
||||
self._finish_measurements, UPDATE_INTERVAL)
|
||||
# publish raw samples to the socket
|
||||
dump_path = "%s/dump_%s" % (sensor_type, sensor_type)
|
||||
self.batch_bulk.add_mux_endpoint(dump_path, "sensor", self.name,
|
||||
{'header': ('time', 'counts')})
|
||||
# Command Configuration
|
||||
self.query_hx71x_cmd = None
|
||||
mcu.add_config_cmd(
|
||||
"config_hx71x oid=%d gain_channel=%d dout_pin=%s sclk_pin=%s"
|
||||
% (self.oid, self.gain_channel, self.dout_pin, self.sclk_pin))
|
||||
mcu.add_config_cmd("query_hx71x oid=%d rest_ticks=0"
|
||||
% (self.oid,), on_restart=True)
|
||||
|
||||
mcu.register_config_callback(self._build_config)
|
||||
|
||||
def _build_config(self):
|
||||
self.query_hx71x_cmd = self.mcu.lookup_command(
|
||||
"query_hx71x oid=%c rest_ticks=%u")
|
||||
self.ffreader.setup_query_command("query_hx71x_status oid=%c",
|
||||
oid=self.oid,
|
||||
cq=self.mcu.alloc_command_queue())
|
||||
|
||||
def get_mcu(self):
|
||||
return self.mcu
|
||||
|
||||
def get_samples_per_second(self):
|
||||
return self.sps
|
||||
|
||||
# returns a tuple of the minimum and maximum value of the sensor, used to
|
||||
# detect if a data value is saturated
|
||||
def get_range(self):
|
||||
return -0x800000, 0x7FFFFF
|
||||
|
||||
# add_client interface, direct pass through to bulk_sensor API
|
||||
def add_client(self, callback):
|
||||
self.batch_bulk.add_client(callback)
|
||||
|
||||
# Measurement decoding
|
||||
def _convert_samples(self, samples):
|
||||
adc_factor = 1. / (1 << 23)
|
||||
count = 0
|
||||
for ptime, val in samples:
|
||||
if val == SAMPLE_ERROR_DESYNC or val == SAMPLE_ERROR_LONG_READ:
|
||||
self.last_error_count += 1
|
||||
break # additional errors are duplicates
|
||||
samples[count] = (round(ptime, 6), val, round(val * adc_factor, 9))
|
||||
count += 1
|
||||
del samples[count:]
|
||||
|
||||
# Start, stop, and process message batches
|
||||
def _start_measurements(self):
|
||||
self.consecutive_fails = 0
|
||||
self.last_error_count = 0
|
||||
# Start bulk reading
|
||||
rest_ticks = self.mcu.seconds_to_clock(1. / (10. * self.sps))
|
||||
self.query_hx71x_cmd.send([self.oid, rest_ticks])
|
||||
logging.info("%s starting '%s' measurements",
|
||||
self.sensor_type, self.name)
|
||||
# Initialize clock tracking
|
||||
self.ffreader.note_start()
|
||||
|
||||
def _finish_measurements(self):
|
||||
# don't use serial connection after shutdown
|
||||
if self.printer.is_shutdown():
|
||||
return
|
||||
# Halt bulk reading
|
||||
self.query_hx71x_cmd.send_wait_ack([self.oid, 0])
|
||||
self.ffreader.note_end()
|
||||
logging.info("%s finished '%s' measurements",
|
||||
self.sensor_type, self.name)
|
||||
|
||||
def _process_batch(self, eventtime):
|
||||
prev_overflows = self.ffreader.get_last_overflows()
|
||||
prev_error_count = self.last_error_count
|
||||
samples = self.ffreader.pull_samples()
|
||||
self._convert_samples(samples)
|
||||
overflows = self.ffreader.get_last_overflows() - prev_overflows
|
||||
errors = self.last_error_count - prev_error_count
|
||||
if errors > 0:
|
||||
logging.error("%s: Forced sensor restart due to error", self.name)
|
||||
self._finish_measurements()
|
||||
self._start_measurements()
|
||||
elif overflows > 0:
|
||||
self.consecutive_fails += 1
|
||||
if self.consecutive_fails > 4:
|
||||
logging.error("%s: Forced sensor restart due to overflows",
|
||||
self.name)
|
||||
self._finish_measurements()
|
||||
self._start_measurements()
|
||||
else:
|
||||
self.consecutive_fails = 0
|
||||
return {'data': samples, 'errors': self.last_error_count,
|
||||
'overflows': self.ffreader.get_last_overflows()}
|
||||
|
||||
|
||||
class HX711(HX71xBase):
|
||||
def __init__(self, config):
|
||||
super(HX711, self).__init__(config, "hx711",
|
||||
# HX711 sps options
|
||||
{80: 80, 10: 10}, 80,
|
||||
# HX711 gain/channel options
|
||||
{'A-128': 1, 'B-32': 2, 'A-64': 3}, 'A-128')
|
||||
|
||||
|
||||
class HX717(HX71xBase):
|
||||
def __init__(self, config):
|
||||
super(HX717, self).__init__(config, "hx717",
|
||||
# HX717 sps options
|
||||
{320: 320, 80: 80, 20: 20, 10: 10}, 320,
|
||||
# HX717 gain/channel options
|
||||
{'A-128': 1, 'B-64': 2, 'A-64': 3,
|
||||
'B-8': 4}, 'A-128')
|
||||
|
||||
|
||||
HX71X_SENSOR_TYPES = {
|
||||
"hx711": HX711,
|
||||
"hx717": HX717
|
||||
}
|
||||
@@ -45,7 +45,7 @@ class IdleTimeout:
|
||||
self.state = "Printing"
|
||||
try:
|
||||
script = self.idle_gcode.render()
|
||||
res = self.gcode.run_script(script)
|
||||
self.gcode.run_script(script)
|
||||
except:
|
||||
logging.exception("idle timeout gcode execution")
|
||||
self.state = "Ready"
|
||||
|
||||
@@ -59,7 +59,6 @@ class AxisInputShaper:
|
||||
return self.n, self.A, self.T
|
||||
def update(self, gcmd):
|
||||
self.params.update(gcmd)
|
||||
old_n, old_A, old_T = self.n, self.A, self.T
|
||||
self.n, self.A, self.T = self.params.get_shaper()
|
||||
def set_shaper_kinematics(self, sk):
|
||||
ffi_main, ffi_lib = chelper.get_ffi()
|
||||
|
||||
206
klippy/extras/ldc1612.py
Normal file
206
klippy/extras/ldc1612.py
Normal file
@@ -0,0 +1,206 @@
|
||||
# Support for reading frequency samples from ldc1612
|
||||
#
|
||||
# Copyright (C) 2020-2024 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
from . import bus, bulk_sensor
|
||||
|
||||
MIN_MSG_TIME = 0.100
|
||||
|
||||
BATCH_UPDATES = 0.100
|
||||
|
||||
LDC1612_ADDR = 0x2a
|
||||
|
||||
LDC1612_FREQ = 12000000
|
||||
SETTLETIME = 0.005
|
||||
DRIVECUR = 15
|
||||
DEGLITCH = 0x05 # 10 Mhz
|
||||
|
||||
LDC1612_MANUF_ID = 0x5449
|
||||
LDC1612_DEV_ID = 0x3055
|
||||
|
||||
REG_RCOUNT0 = 0x08
|
||||
REG_OFFSET0 = 0x0c
|
||||
REG_SETTLECOUNT0 = 0x10
|
||||
REG_CLOCK_DIVIDERS0 = 0x14
|
||||
REG_ERROR_CONFIG = 0x19
|
||||
REG_CONFIG = 0x1a
|
||||
REG_MUX_CONFIG = 0x1b
|
||||
REG_DRIVE_CURRENT0 = 0x1e
|
||||
REG_MANUFACTURER_ID = 0x7e
|
||||
REG_DEVICE_ID = 0x7f
|
||||
|
||||
# Tool for determining appropriate DRIVE_CURRENT register
|
||||
class DriveCurrentCalibrate:
|
||||
def __init__(self, config, sensor):
|
||||
self.printer = config.get_printer()
|
||||
self.sensor = sensor
|
||||
self.drive_cur = config.getint("reg_drive_current", DRIVECUR,
|
||||
minval=0, maxval=31)
|
||||
self.name = config.get_name()
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
gcode.register_mux_command("LDC_CALIBRATE_DRIVE_CURRENT",
|
||||
"CHIP", self.name.split()[-1],
|
||||
self.cmd_LDC_CALIBRATE,
|
||||
desc=self.cmd_LDC_CALIBRATE_help)
|
||||
def get_drive_current(self):
|
||||
return self.drive_cur
|
||||
cmd_LDC_CALIBRATE_help = "Calibrate LDC1612 DRIVE_CURRENT register"
|
||||
def cmd_LDC_CALIBRATE(self, gcmd):
|
||||
is_in_progress = True
|
||||
def handle_batch(msg):
|
||||
return is_in_progress
|
||||
self.sensor.add_client(handle_batch)
|
||||
toolhead = self.printer.lookup_object("toolhead")
|
||||
toolhead.dwell(0.100)
|
||||
toolhead.wait_moves()
|
||||
old_config = self.sensor.read_reg(REG_CONFIG)
|
||||
self.sensor.set_reg(REG_CONFIG, 0x001 | (1<<9))
|
||||
toolhead.wait_moves()
|
||||
toolhead.dwell(0.100)
|
||||
toolhead.wait_moves()
|
||||
reg_drive_current0 = self.sensor.read_reg(REG_DRIVE_CURRENT0)
|
||||
self.sensor.set_reg(REG_CONFIG, old_config)
|
||||
is_in_progress = False
|
||||
# Report found value to user
|
||||
drive_cur = (reg_drive_current0 >> 6) & 0x1f
|
||||
gcmd.respond_info(
|
||||
"%s: reg_drive_current: %d\n"
|
||||
"The SAVE_CONFIG command will update the printer config file\n"
|
||||
"with the above and restart the printer." % (self.name, drive_cur))
|
||||
configfile = self.printer.lookup_object('configfile')
|
||||
configfile.set(self.name, 'reg_drive_current', "%d" % (drive_cur,))
|
||||
|
||||
# Interface class to LDC1612 mcu support
|
||||
class LDC1612:
|
||||
def __init__(self, config, calibration=None):
|
||||
self.printer = config.get_printer()
|
||||
self.calibration = calibration
|
||||
self.dccal = DriveCurrentCalibrate(config, self)
|
||||
self.data_rate = 250
|
||||
# Setup mcu sensor_ldc1612 bulk query code
|
||||
self.i2c = bus.MCU_I2C_from_config(config,
|
||||
default_addr=LDC1612_ADDR,
|
||||
default_speed=400000)
|
||||
self.mcu = mcu = self.i2c.get_mcu()
|
||||
self.oid = oid = mcu.create_oid()
|
||||
self.query_ldc1612_cmd = None
|
||||
self.ldc1612_setup_home_cmd = self.query_ldc1612_home_state_cmd = None
|
||||
if config.get('intb_pin', None) is not None:
|
||||
ppins = config.get_printer().lookup_object("pins")
|
||||
pin_params = ppins.lookup_pin(config.get('intb_pin'))
|
||||
if pin_params['chip'] != mcu:
|
||||
raise config.error("ldc1612 intb_pin must be on same mcu")
|
||||
mcu.add_config_cmd(
|
||||
"config_ldc1612_with_intb oid=%d i2c_oid=%d intb_pin=%s"
|
||||
% (oid, self.i2c.get_oid(), pin_params['pin']))
|
||||
else:
|
||||
mcu.add_config_cmd("config_ldc1612 oid=%d i2c_oid=%d"
|
||||
% (oid, self.i2c.get_oid()))
|
||||
mcu.add_config_cmd("query_ldc1612 oid=%d rest_ticks=0"
|
||||
% (oid,), on_restart=True)
|
||||
mcu.register_config_callback(self._build_config)
|
||||
# Bulk sample message reading
|
||||
chip_smooth = self.data_rate * BATCH_UPDATES * 2
|
||||
self.ffreader = bulk_sensor.FixedFreqReader(mcu, chip_smooth, ">I")
|
||||
self.last_error_count = 0
|
||||
# Process messages in batches
|
||||
self.batch_bulk = bulk_sensor.BatchBulkHelper(
|
||||
self.printer, self._process_batch,
|
||||
self._start_measurements, self._finish_measurements, BATCH_UPDATES)
|
||||
self.name = config.get_name().split()[-1]
|
||||
hdr = ('time', 'frequency', 'z')
|
||||
self.batch_bulk.add_mux_endpoint("ldc1612/dump_ldc1612", "sensor",
|
||||
self.name, {'header': hdr})
|
||||
def _build_config(self):
|
||||
cmdqueue = self.i2c.get_command_queue()
|
||||
self.query_ldc1612_cmd = self.mcu.lookup_command(
|
||||
"query_ldc1612 oid=%c rest_ticks=%u", cq=cmdqueue)
|
||||
self.ffreader.setup_query_command("query_status_ldc1612 oid=%c",
|
||||
oid=self.oid, cq=cmdqueue)
|
||||
self.ldc1612_setup_home_cmd = self.mcu.lookup_command(
|
||||
"ldc1612_setup_home oid=%c clock=%u threshold=%u"
|
||||
" trsync_oid=%c trigger_reason=%c error_reason=%c", cq=cmdqueue)
|
||||
self.query_ldc1612_home_state_cmd = self.mcu.lookup_query_command(
|
||||
"query_ldc1612_home_state oid=%c",
|
||||
"ldc1612_home_state oid=%c homing=%c trigger_clock=%u",
|
||||
oid=self.oid, cq=cmdqueue)
|
||||
def get_mcu(self):
|
||||
return self.i2c.get_mcu()
|
||||
def read_reg(self, reg):
|
||||
params = self.i2c.i2c_read([reg], 2)
|
||||
response = bytearray(params['response'])
|
||||
return (response[0] << 8) | response[1]
|
||||
def set_reg(self, reg, val, minclock=0):
|
||||
self.i2c.i2c_write([reg, (val >> 8) & 0xff, val & 0xff],
|
||||
minclock=minclock)
|
||||
def add_client(self, cb):
|
||||
self.batch_bulk.add_client(cb)
|
||||
# Homing
|
||||
def setup_home(self, print_time, trigger_freq,
|
||||
trsync_oid, hit_reason, err_reason):
|
||||
clock = self.mcu.print_time_to_clock(print_time)
|
||||
tfreq = int(trigger_freq * (1<<28) / float(LDC1612_FREQ) + 0.5)
|
||||
self.ldc1612_setup_home_cmd.send(
|
||||
[self.oid, clock, tfreq, trsync_oid, hit_reason, err_reason])
|
||||
def clear_home(self):
|
||||
self.ldc1612_setup_home_cmd.send([self.oid, 0, 0, 0, 0, 0])
|
||||
if self.mcu.is_fileoutput():
|
||||
return 0.
|
||||
params = self.query_ldc1612_home_state_cmd.send([self.oid])
|
||||
tclock = self.mcu.clock32_to_clock64(params['trigger_clock'])
|
||||
return self.mcu.clock_to_print_time(tclock)
|
||||
# Measurement decoding
|
||||
def _convert_samples(self, samples):
|
||||
freq_conv = float(LDC1612_FREQ) / (1<<28)
|
||||
count = 0
|
||||
for ptime, val in samples:
|
||||
mv = val & 0x0fffffff
|
||||
if mv != val:
|
||||
self.last_error_count += 1
|
||||
samples[count] = (round(ptime, 6), round(freq_conv * mv, 3), 999.9)
|
||||
count += 1
|
||||
# Start, stop, and process message batches
|
||||
def _start_measurements(self):
|
||||
# In case of miswiring, testing LDC1612 device ID prevents treating
|
||||
# noise or wrong signal as a correctly initialized device
|
||||
manuf_id = self.read_reg(REG_MANUFACTURER_ID)
|
||||
dev_id = self.read_reg(REG_DEVICE_ID)
|
||||
if manuf_id != LDC1612_MANUF_ID or dev_id != LDC1612_DEV_ID:
|
||||
raise self.printer.command_error(
|
||||
"Invalid ldc1612 id (got %x,%x vs %x,%x).\n"
|
||||
"This is generally indicative of connection problems\n"
|
||||
"(e.g. faulty wiring) or a faulty ldc1612 chip."
|
||||
% (manuf_id, dev_id, LDC1612_MANUF_ID, LDC1612_DEV_ID))
|
||||
# Setup chip in requested query rate
|
||||
rcount0 = LDC1612_FREQ / (16. * (self.data_rate - 4))
|
||||
self.set_reg(REG_RCOUNT0, int(rcount0 + 0.5))
|
||||
self.set_reg(REG_OFFSET0, 0)
|
||||
self.set_reg(REG_SETTLECOUNT0, int(SETTLETIME*LDC1612_FREQ/16. + .5))
|
||||
self.set_reg(REG_CLOCK_DIVIDERS0, (1 << 12) | 1)
|
||||
self.set_reg(REG_ERROR_CONFIG, (0x1f << 11) | 1)
|
||||
self.set_reg(REG_MUX_CONFIG, 0x0208 | DEGLITCH)
|
||||
self.set_reg(REG_CONFIG, 0x001 | (1<<12) | (1<<10) | (1<<9))
|
||||
self.set_reg(REG_DRIVE_CURRENT0, self.dccal.get_drive_current() << 11)
|
||||
# Start bulk reading
|
||||
rest_ticks = self.mcu.seconds_to_clock(0.5 / self.data_rate)
|
||||
self.query_ldc1612_cmd.send([self.oid, rest_ticks])
|
||||
logging.info("LDC1612 starting '%s' measurements", self.name)
|
||||
# Initialize clock tracking
|
||||
self.ffreader.note_start()
|
||||
self.last_error_count = 0
|
||||
def _finish_measurements(self):
|
||||
# Halt bulk reading
|
||||
self.query_ldc1612_cmd.send_wait_ack([self.oid, 0])
|
||||
self.ffreader.note_end()
|
||||
logging.info("LDC1612 finished '%s' measurements", self.name)
|
||||
def _process_batch(self, eventtime):
|
||||
samples = self.ffreader.pull_samples()
|
||||
self._convert_samples(samples)
|
||||
if not samples:
|
||||
return {}
|
||||
if self.calibration is not None:
|
||||
self.calibration.apply_calibration(samples)
|
||||
return {'data': samples, 'errors': self.last_error_count,
|
||||
'overflows': self.ffreader.get_last_overflows()}
|
||||
@@ -1,11 +1,11 @@
|
||||
# Support for reading acceleration data from an LIS2DW chip
|
||||
#
|
||||
# Copyright (C) 2023 Zhou.XianMing <zhouxm@biqu3d.com>
|
||||
# Copyright (C) 2020-2021 Kevin O'Connor <kevin@koconnor.net>
|
||||
# Copyright (C) 2020-2023 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging, time, collections, threading, multiprocessing, os
|
||||
from . import bus, motion_report, adxl345
|
||||
import logging
|
||||
from . import bus, adxl345, bulk_sensor
|
||||
|
||||
# LIS2DW registers
|
||||
REG_LIS2DW_WHO_AM_I_ADDR = 0x0F
|
||||
@@ -30,66 +30,44 @@ LIS2DW_DEV_ID = 0x44
|
||||
FREEFALL_ACCEL = 9.80665
|
||||
SCALE = FREEFALL_ACCEL * 1.952 / 4
|
||||
|
||||
Accel_Measurement = collections.namedtuple(
|
||||
'Accel_Measurement', ('time', 'accel_x', 'accel_y', 'accel_z'))
|
||||
|
||||
MIN_MSG_TIME = 0.100
|
||||
|
||||
BYTES_PER_SAMPLE = 6
|
||||
SAMPLES_PER_BLOCK = 8
|
||||
BATCH_UPDATES = 0.100
|
||||
|
||||
# Printer class that controls LIS2DW chip
|
||||
class LIS2DW:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
adxl345.AccelCommandHelper(config, self)
|
||||
self.query_rate = 0
|
||||
am = {'x': (0, SCALE), 'y': (1, SCALE), 'z': (2, SCALE),
|
||||
'-x': (0, -SCALE), '-y': (1, -SCALE), '-z': (2, -SCALE)}
|
||||
axes_map = config.getlist('axes_map', ('x','y','z'), count=3)
|
||||
if any([a not in am for a in axes_map]):
|
||||
raise config.error("Invalid lis2dw axes_map parameter")
|
||||
self.axes_map = [am[a.strip()] for a in axes_map]
|
||||
self.axes_map = adxl345.read_axes_map(config, SCALE, SCALE, SCALE)
|
||||
self.data_rate = 1600
|
||||
# Measurement storage (accessed from background thread)
|
||||
self.lock = threading.Lock()
|
||||
self.raw_samples = []
|
||||
# Setup mcu sensor_lis2dw bulk query code
|
||||
self.spi = bus.MCU_SPI_from_config(config, 3, default_speed=5000000)
|
||||
self.mcu = mcu = self.spi.get_mcu()
|
||||
self.oid = oid = mcu.create_oid()
|
||||
self.query_lis2dw_cmd = self.query_lis2dw_end_cmd = None
|
||||
self.query_lis2dw_status_cmd = None
|
||||
self.query_lis2dw_cmd = None
|
||||
mcu.add_config_cmd("config_lis2dw oid=%d spi_oid=%d"
|
||||
% (oid, self.spi.get_oid()))
|
||||
mcu.add_config_cmd("query_lis2dw oid=%d clock=0 rest_ticks=0"
|
||||
mcu.add_config_cmd("query_lis2dw oid=%d rest_ticks=0"
|
||||
% (oid,), on_restart=True)
|
||||
mcu.register_config_callback(self._build_config)
|
||||
mcu.register_response(self._handle_lis2dw_data, "lis2dw_data", oid)
|
||||
# Clock tracking
|
||||
self.last_sequence = self.max_query_duration = 0
|
||||
self.last_limit_count = self.last_error_count = 0
|
||||
self.clock_sync = adxl345.ClockSyncRegression(self.mcu, 640)
|
||||
# API server endpoints
|
||||
self.api_dump = motion_report.APIDumpHelper(
|
||||
self.printer, self._api_update, self._api_startstop, 0.100)
|
||||
# Bulk sample message reading
|
||||
chip_smooth = self.data_rate * BATCH_UPDATES * 2
|
||||
self.ffreader = bulk_sensor.FixedFreqReader(mcu, chip_smooth, "<hhh")
|
||||
self.last_error_count = 0
|
||||
# Process messages in batches
|
||||
self.batch_bulk = bulk_sensor.BatchBulkHelper(
|
||||
self.printer, self._process_batch,
|
||||
self._start_measurements, self._finish_measurements, BATCH_UPDATES)
|
||||
self.name = config.get_name().split()[-1]
|
||||
wh = self.printer.lookup_object('webhooks')
|
||||
wh.register_mux_endpoint("lis2dw/dump_lis2dw", "sensor", self.name,
|
||||
self._handle_dump_lis2dw)
|
||||
hdr = ('time', 'x_acceleration', 'y_acceleration', 'z_acceleration')
|
||||
self.batch_bulk.add_mux_endpoint("lis2dw/dump_lis2dw", "sensor",
|
||||
self.name, {'header': hdr})
|
||||
|
||||
def _build_config(self):
|
||||
cmdqueue = self.spi.get_command_queue()
|
||||
self.query_lis2dw_cmd = self.mcu.lookup_command(
|
||||
"query_lis2dw oid=%c clock=%u rest_ticks=%u", cq=cmdqueue)
|
||||
self.query_lis2dw_end_cmd = self.mcu.lookup_query_command(
|
||||
"query_lis2dw oid=%c clock=%u rest_ticks=%u",
|
||||
"lis2dw_status oid=%c clock=%u query_ticks=%u next_sequence=%hu"
|
||||
" buffered=%c fifo=%c limit_count=%hu", oid=self.oid, cq=cmdqueue)
|
||||
self.query_lis2dw_status_cmd = self.mcu.lookup_query_command(
|
||||
"query_lis2dw_status oid=%c",
|
||||
"lis2dw_status oid=%c clock=%u query_ticks=%u next_sequence=%hu"
|
||||
" buffered=%c fifo=%c limit_count=%hu", oid=self.oid, cq=cmdqueue)
|
||||
"query_lis2dw oid=%c rest_ticks=%u", cq=cmdqueue)
|
||||
self.ffreader.setup_query_command("query_lis2dw_status oid=%c",
|
||||
oid=self.oid, cq=cmdqueue)
|
||||
def read_reg(self, reg):
|
||||
params = self.spi.spi_transfer([reg | REG_MOD_READ, 0x00])
|
||||
response = bytearray(params['response'])
|
||||
@@ -103,85 +81,23 @@ class LIS2DW:
|
||||
"This is generally indicative of connection problems "
|
||||
"(e.g. faulty wiring) or a faulty lis2dw chip." % (
|
||||
reg, val, stored_val))
|
||||
# Measurement collection
|
||||
def is_measuring(self):
|
||||
return self.query_rate > 0
|
||||
def _handle_lis2dw_data(self, params):
|
||||
with self.lock:
|
||||
self.raw_samples.append(params)
|
||||
def _extract_samples(self, raw_samples):
|
||||
# Load variables to optimize inner loop below
|
||||
def start_internal_client(self):
|
||||
aqh = adxl345.AccelQueryHelper(self.printer)
|
||||
self.batch_bulk.add_client(aqh.handle_batch)
|
||||
return aqh
|
||||
# Measurement decoding
|
||||
def _convert_samples(self, samples):
|
||||
(x_pos, x_scale), (y_pos, y_scale), (z_pos, z_scale) = self.axes_map
|
||||
last_sequence = self.last_sequence
|
||||
time_base, chip_base, inv_freq = self.clock_sync.get_time_translation()
|
||||
# Process every message in raw_samples
|
||||
count = seq = 0
|
||||
samples = [None] * (len(raw_samples) * SAMPLES_PER_BLOCK)
|
||||
for params in raw_samples:
|
||||
seq_diff = (last_sequence - params['sequence']) & 0xffff
|
||||
seq_diff -= (seq_diff & 0x8000) << 1
|
||||
seq = last_sequence - seq_diff
|
||||
d = bytearray(params['data'])
|
||||
msg_cdiff = seq * SAMPLES_PER_BLOCK - chip_base
|
||||
|
||||
for i in range(len(d) // BYTES_PER_SAMPLE):
|
||||
d_xyz = d[i*BYTES_PER_SAMPLE:(i+1)*BYTES_PER_SAMPLE]
|
||||
xlow, xhigh, ylow, yhigh, zlow, zhigh = d_xyz
|
||||
# Merge and perform twos-complement
|
||||
|
||||
rx = (((xhigh << 8) | xlow)) - ((xhigh & 0x80) << 9)
|
||||
ry = (((yhigh << 8) | ylow)) - ((yhigh & 0x80) << 9)
|
||||
rz = (((zhigh << 8) | zlow)) - ((zhigh & 0x80) << 9)
|
||||
|
||||
raw_xyz = (rx, ry, rz)
|
||||
|
||||
x = round(raw_xyz[x_pos] * x_scale, 6)
|
||||
y = round(raw_xyz[y_pos] * y_scale, 6)
|
||||
z = round(raw_xyz[z_pos] * z_scale, 6)
|
||||
|
||||
ptime = round(time_base + (msg_cdiff + i) * inv_freq, 6)
|
||||
samples[count] = (ptime, x, y, z)
|
||||
count += 1
|
||||
self.clock_sync.set_last_chip_clock(seq * SAMPLES_PER_BLOCK + i)
|
||||
del samples[count:]
|
||||
return samples
|
||||
def _update_clock(self, minclock=0):
|
||||
# Query current state
|
||||
for retry in range(5):
|
||||
params = self.query_lis2dw_status_cmd.send([self.oid],
|
||||
minclock=minclock)
|
||||
fifo = params['fifo'] & 0x1f
|
||||
if fifo <= 32:
|
||||
break
|
||||
else:
|
||||
raise self.printer.command_error("Unable to query lis2dw fifo")
|
||||
mcu_clock = self.mcu.clock32_to_clock64(params['clock'])
|
||||
sequence = (self.last_sequence & ~0xffff) | params['next_sequence']
|
||||
if sequence < self.last_sequence:
|
||||
sequence += 0x10000
|
||||
self.last_sequence = sequence
|
||||
buffered = params['buffered']
|
||||
limit_count = (self.last_limit_count & ~0xffff) | params['limit_count']
|
||||
if limit_count < self.last_limit_count:
|
||||
limit_count += 0x10000
|
||||
self.last_limit_count = limit_count
|
||||
duration = params['query_ticks']
|
||||
if duration > self.max_query_duration:
|
||||
# Skip measurement as a high query time could skew clock tracking
|
||||
self.max_query_duration = max(2 * self.max_query_duration,
|
||||
self.mcu.seconds_to_clock(.000005))
|
||||
return
|
||||
self.max_query_duration = 2 * duration
|
||||
msg_count = (sequence * SAMPLES_PER_BLOCK
|
||||
+ buffered // BYTES_PER_SAMPLE + fifo)
|
||||
# The "chip clock" is the message counter plus .5 for average
|
||||
# inaccuracy of query responses and plus .5 for assumed offset
|
||||
# of lis2dw hw processing time.
|
||||
chip_clock = msg_count + 1
|
||||
self.clock_sync.update(mcu_clock + duration // 2, chip_clock)
|
||||
count = 0
|
||||
for ptime, rx, ry, rz in samples:
|
||||
raw_xyz = (rx, ry, rz)
|
||||
x = round(raw_xyz[x_pos] * x_scale, 6)
|
||||
y = round(raw_xyz[y_pos] * y_scale, 6)
|
||||
z = round(raw_xyz[z_pos] * z_scale, 6)
|
||||
samples[count] = (round(ptime, 6), x, y, z)
|
||||
count += 1
|
||||
# Start, stop, and process message batches
|
||||
def _start_measurements(self):
|
||||
if self.is_measuring():
|
||||
return
|
||||
# In case of miswiring, testing LIS2DW device ID prevents treating
|
||||
# noise or wrong signal as a correctly initialized device
|
||||
dev_id = self.read_reg(REG_LIS2DW_WHO_AM_I_ADDR)
|
||||
@@ -202,61 +118,28 @@ class LIS2DW:
|
||||
# High-Performance Mode (14-bit resolution)
|
||||
self.set_reg(REG_LIS2DW_CTRL_REG1_ADDR, 0x94)
|
||||
|
||||
# Setup samples
|
||||
with self.lock:
|
||||
self.raw_samples = []
|
||||
# Start bulk reading
|
||||
systime = self.printer.get_reactor().monotonic()
|
||||
print_time = self.mcu.estimated_print_time(systime) + MIN_MSG_TIME
|
||||
reqclock = self.mcu.print_time_to_clock(print_time)
|
||||
rest_ticks = self.mcu.seconds_to_clock(4. / self.data_rate)
|
||||
self.query_rate = self.data_rate
|
||||
self.query_lis2dw_cmd.send([self.oid, reqclock, rest_ticks],
|
||||
reqclock=reqclock)
|
||||
self.query_lis2dw_cmd.send([self.oid, rest_ticks])
|
||||
self.set_reg(REG_LIS2DW_FIFO_CTRL, 0xC0)
|
||||
logging.info("LIS2DW starting '%s' measurements", self.name)
|
||||
# Initialize clock tracking
|
||||
self.last_sequence = 0
|
||||
self.last_limit_count = self.last_error_count = 0
|
||||
self.clock_sync.reset(reqclock, 0)
|
||||
self.max_query_duration = 1 << 31
|
||||
self._update_clock(minclock=reqclock)
|
||||
self.max_query_duration = 1 << 31
|
||||
self.ffreader.note_start()
|
||||
self.last_error_count = 0
|
||||
def _finish_measurements(self):
|
||||
if not self.is_measuring():
|
||||
return
|
||||
# Halt bulk reading
|
||||
params = self.query_lis2dw_end_cmd.send([self.oid, 0, 0])
|
||||
self.query_rate = 0
|
||||
with self.lock:
|
||||
self.raw_samples = []
|
||||
self.set_reg(REG_LIS2DW_FIFO_CTRL, 0x00)
|
||||
self.query_lis2dw_cmd.send_wait_ack([self.oid, 0])
|
||||
self.ffreader.note_end()
|
||||
logging.info("LIS2DW finished '%s' measurements", self.name)
|
||||
self.set_reg(REG_LIS2DW_FIFO_CTRL, 0x00)
|
||||
# API interface
|
||||
def _api_update(self, eventtime):
|
||||
self._update_clock()
|
||||
with self.lock:
|
||||
raw_samples = self.raw_samples
|
||||
self.raw_samples = []
|
||||
if not raw_samples:
|
||||
return {}
|
||||
samples = self._extract_samples(raw_samples)
|
||||
def _process_batch(self, eventtime):
|
||||
samples = self.ffreader.pull_samples()
|
||||
self._convert_samples(samples)
|
||||
if not samples:
|
||||
return {}
|
||||
return {'data': samples, 'errors': self.last_error_count,
|
||||
'overflows': self.last_limit_count}
|
||||
def _api_startstop(self, is_start):
|
||||
if is_start:
|
||||
self._start_measurements()
|
||||
else:
|
||||
self._finish_measurements()
|
||||
def _handle_dump_lis2dw(self, web_request):
|
||||
self.api_dump.add_client(web_request)
|
||||
hdr = ('time', 'x_acceleration', 'y_acceleration', 'z_acceleration')
|
||||
web_request.send({'header': hdr})
|
||||
def start_internal_client(self):
|
||||
cconn = self.api_dump.add_internal_client()
|
||||
return adxl345.AccelQueryHelper(self.printer, cconn)
|
||||
|
||||
'overflows': self.ffreader.get_last_overflows()}
|
||||
|
||||
def load_config(config):
|
||||
return LIS2DW(config)
|
||||
|
||||
30
klippy/extras/load_cell.py
Normal file
30
klippy/extras/load_cell.py
Normal file
@@ -0,0 +1,30 @@
|
||||
# Load Cell Implementation
|
||||
#
|
||||
# Copyright (C) 2024 Gareth Farrington <gareth@waves.ky>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
from . import hx71x
|
||||
from . import ads1220
|
||||
|
||||
# Printer class that controls a load cell
|
||||
class LoadCell:
|
||||
def __init__(self, config, sensor):
|
||||
self.printer = printer = config.get_printer()
|
||||
self.sensor = sensor # must implement BulkAdcSensor
|
||||
|
||||
def _on_sample(self, msg):
|
||||
return True
|
||||
|
||||
def get_sensor(self):
|
||||
return self.sensor
|
||||
|
||||
def load_config(config):
|
||||
# Sensor types
|
||||
sensors = {}
|
||||
sensors.update(hx71x.HX71X_SENSOR_TYPES)
|
||||
sensors.update(ads1220.ADS1220_SENSOR_TYPE)
|
||||
sensor_class = config.getchoice('sensor_type', sensors)
|
||||
return LoadCell(config, sensor_class(config))
|
||||
|
||||
def load_config_prefix(config):
|
||||
return load_config(config)
|
||||
@@ -67,9 +67,10 @@ class ManualStepper:
|
||||
0., cruise_v, accel)
|
||||
self.next_cmd_time = self.next_cmd_time + accel_t + cruise_t + accel_t
|
||||
self.rail.generate_steps(self.next_cmd_time)
|
||||
self.trapq_finalize_moves(self.trapq, self.next_cmd_time + 99999.9)
|
||||
self.trapq_finalize_moves(self.trapq, self.next_cmd_time + 99999.9,
|
||||
self.next_cmd_time + 99999.9)
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
toolhead.note_kinematic_activity(self.next_cmd_time)
|
||||
toolhead.note_mcu_movequeue_activity(self.next_cmd_time)
|
||||
if sync:
|
||||
self.sync_print_time()
|
||||
def do_homing_move(self, movepos, speed, accel, triggered, check_trigger):
|
||||
|
||||
@@ -5,110 +5,19 @@
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
import chelper
|
||||
|
||||
API_UPDATE_INTERVAL = 0.500
|
||||
|
||||
# Helper to periodically transmit data to a set of API clients
|
||||
class APIDumpHelper:
|
||||
def __init__(self, printer, data_cb, startstop_cb=None,
|
||||
update_interval=API_UPDATE_INTERVAL):
|
||||
self.printer = printer
|
||||
self.data_cb = data_cb
|
||||
if startstop_cb is None:
|
||||
startstop_cb = (lambda is_start: None)
|
||||
self.startstop_cb = startstop_cb
|
||||
self.is_started = False
|
||||
self.update_interval = update_interval
|
||||
self.update_timer = None
|
||||
self.clients = {}
|
||||
def _stop(self):
|
||||
self.clients.clear()
|
||||
reactor = self.printer.get_reactor()
|
||||
reactor.unregister_timer(self.update_timer)
|
||||
self.update_timer = None
|
||||
if not self.is_started:
|
||||
return reactor.NEVER
|
||||
try:
|
||||
self.startstop_cb(False)
|
||||
except self.printer.command_error as e:
|
||||
logging.exception("API Dump Helper stop callback error")
|
||||
self.clients.clear()
|
||||
self.is_started = False
|
||||
if self.clients:
|
||||
# New client started while in process of stopping
|
||||
self._start()
|
||||
return reactor.NEVER
|
||||
def _start(self):
|
||||
if self.is_started:
|
||||
return
|
||||
self.is_started = True
|
||||
try:
|
||||
self.startstop_cb(True)
|
||||
except self.printer.command_error as e:
|
||||
logging.exception("API Dump Helper start callback error")
|
||||
self.is_started = False
|
||||
self.clients.clear()
|
||||
raise
|
||||
reactor = self.printer.get_reactor()
|
||||
systime = reactor.monotonic()
|
||||
waketime = systime + self.update_interval
|
||||
self.update_timer = reactor.register_timer(self._update, waketime)
|
||||
def add_client(self, web_request):
|
||||
cconn = web_request.get_client_connection()
|
||||
template = web_request.get_dict('response_template', {})
|
||||
self.clients[cconn] = template
|
||||
self._start()
|
||||
def add_internal_client(self):
|
||||
cconn = InternalDumpClient()
|
||||
self.clients[cconn] = {}
|
||||
self._start()
|
||||
return cconn
|
||||
def _update(self, eventtime):
|
||||
try:
|
||||
msg = self.data_cb(eventtime)
|
||||
except self.printer.command_error as e:
|
||||
logging.exception("API Dump Helper data callback error")
|
||||
return self._stop()
|
||||
if not msg:
|
||||
return eventtime + self.update_interval
|
||||
for cconn, template in list(self.clients.items()):
|
||||
if cconn.is_closed():
|
||||
del self.clients[cconn]
|
||||
if not self.clients:
|
||||
return self._stop()
|
||||
continue
|
||||
tmp = dict(template)
|
||||
tmp['params'] = msg
|
||||
cconn.send(tmp)
|
||||
return eventtime + self.update_interval
|
||||
|
||||
# An "internal webhooks" wrapper for using APIDumpHelper internally
|
||||
class InternalDumpClient:
|
||||
def __init__(self):
|
||||
self.msgs = []
|
||||
self.is_done = False
|
||||
def get_messages(self):
|
||||
return self.msgs
|
||||
def finalize(self):
|
||||
self.is_done = True
|
||||
def is_closed(self):
|
||||
return self.is_done
|
||||
def send(self, msg):
|
||||
self.msgs.append(msg)
|
||||
if len(self.msgs) >= 10000:
|
||||
# Avoid filling up memory with too many samples
|
||||
self.finalize()
|
||||
from . import bulk_sensor
|
||||
|
||||
# Extract stepper queue_step messages
|
||||
class DumpStepper:
|
||||
def __init__(self, printer, mcu_stepper):
|
||||
self.printer = printer
|
||||
self.mcu_stepper = mcu_stepper
|
||||
self.last_api_clock = 0
|
||||
self.api_dump = APIDumpHelper(printer, self._api_update)
|
||||
wh = self.printer.lookup_object('webhooks')
|
||||
wh.register_mux_endpoint("motion_report/dump_stepper", "name",
|
||||
mcu_stepper.get_name(), self._add_api_client)
|
||||
self.last_batch_clock = 0
|
||||
self.batch_bulk = bulk_sensor.BatchBulkHelper(printer,
|
||||
self._process_batch)
|
||||
api_resp = {'header': ('interval', 'count', 'add')}
|
||||
self.batch_bulk.add_mux_endpoint("motion_report/dump_stepper", "name",
|
||||
mcu_stepper.get_name(), api_resp)
|
||||
def get_step_queue(self, start_clock, end_clock):
|
||||
mcu_stepper = self.mcu_stepper
|
||||
res = []
|
||||
@@ -134,30 +43,24 @@ class DumpStepper:
|
||||
% (i, s.first_clock, s.start_position, s.interval,
|
||||
s.step_count, s.add))
|
||||
logging.info('\n'.join(out))
|
||||
def _api_update(self, eventtime):
|
||||
data, cdata = self.get_step_queue(self.last_api_clock, 1<<63)
|
||||
def _process_batch(self, eventtime):
|
||||
data, cdata = self.get_step_queue(self.last_batch_clock, 1<<63)
|
||||
if not data:
|
||||
return {}
|
||||
clock_to_print_time = self.mcu_stepper.get_mcu().clock_to_print_time
|
||||
first = data[0]
|
||||
first_clock = first.first_clock
|
||||
first_time = clock_to_print_time(first_clock)
|
||||
self.last_api_clock = last_clock = data[-1].last_clock
|
||||
self.last_batch_clock = last_clock = data[-1].last_clock
|
||||
last_time = clock_to_print_time(last_clock)
|
||||
mcu_pos = first.start_position
|
||||
start_position = self.mcu_stepper.mcu_to_commanded_position(mcu_pos)
|
||||
step_dist = self.mcu_stepper.get_step_dist()
|
||||
if self.mcu_stepper.get_dir_inverted()[0]:
|
||||
step_dist = -step_dist
|
||||
d = [(s.interval, s.step_count, s.add) for s in data]
|
||||
return {"data": d, "start_position": start_position,
|
||||
"start_mcu_position": mcu_pos, "step_distance": step_dist,
|
||||
"first_clock": first_clock, "first_step_time": first_time,
|
||||
"last_clock": last_clock, "last_step_time": last_time}
|
||||
def _add_api_client(self, web_request):
|
||||
self.api_dump.add_client(web_request)
|
||||
hdr = ('interval', 'count', 'add')
|
||||
web_request.send({'header': hdr})
|
||||
|
||||
NEVER_TIME = 9999999999999999.
|
||||
|
||||
@@ -167,11 +70,13 @@ class DumpTrapQ:
|
||||
self.printer = printer
|
||||
self.name = name
|
||||
self.trapq = trapq
|
||||
self.last_api_msg = (0., 0.)
|
||||
self.api_dump = APIDumpHelper(printer, self._api_update)
|
||||
wh = self.printer.lookup_object('webhooks')
|
||||
wh.register_mux_endpoint("motion_report/dump_trapq", "name", name,
|
||||
self._add_api_client)
|
||||
self.last_batch_msg = (0., 0.)
|
||||
self.batch_bulk = bulk_sensor.BatchBulkHelper(printer,
|
||||
self._process_batch)
|
||||
api_resp = {'header': ('time', 'duration', 'start_velocity',
|
||||
'acceleration', 'start_position', 'direction')}
|
||||
self.batch_bulk.add_mux_endpoint("motion_report/dump_trapq",
|
||||
"name", name, api_resp)
|
||||
def extract_trapq(self, start_time, end_time):
|
||||
ffi_main, ffi_lib = chelper.get_ffi()
|
||||
res = []
|
||||
@@ -210,23 +115,18 @@ class DumpTrapQ:
|
||||
move.start_z + move.z_r * dist)
|
||||
velocity = move.start_v + move.accel * move_time
|
||||
return pos, velocity
|
||||
def _api_update(self, eventtime):
|
||||
qtime = self.last_api_msg[0] + min(self.last_api_msg[1], 0.100)
|
||||
def _process_batch(self, eventtime):
|
||||
qtime = self.last_batch_msg[0] + min(self.last_batch_msg[1], 0.100)
|
||||
data, cdata = self.extract_trapq(qtime, NEVER_TIME)
|
||||
d = [(m.print_time, m.move_t, m.start_v, m.accel,
|
||||
(m.start_x, m.start_y, m.start_z), (m.x_r, m.y_r, m.z_r))
|
||||
for m in data]
|
||||
if d and d[0] == self.last_api_msg:
|
||||
if d and d[0] == self.last_batch_msg:
|
||||
d.pop(0)
|
||||
if not d:
|
||||
return {}
|
||||
self.last_api_msg = d[-1]
|
||||
self.last_batch_msg = d[-1]
|
||||
return {"data": d}
|
||||
def _add_api_client(self, web_request):
|
||||
self.api_dump.add_client(web_request)
|
||||
hdr = ('time', 'duration', 'start_velocity', 'acceleration',
|
||||
'start_position', 'direction')
|
||||
web_request.send({'header': hdr})
|
||||
|
||||
STATUS_REFRESH_TIME = 0.250
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
# Copyright (C) 2020-2021 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging, time, collections, threading, multiprocessing, os
|
||||
from . import bus, motion_report, adxl345
|
||||
import logging
|
||||
from . import bus, adxl345, bulk_sensor
|
||||
|
||||
MPU9250_ADDR = 0x68
|
||||
|
||||
@@ -30,6 +30,7 @@ REG_ACCEL_CONFIG2 = 0x1D
|
||||
REG_USER_CTRL = 0x6A
|
||||
REG_PWR_MGMT_1 = 0x6B
|
||||
REG_PWR_MGMT_2 = 0x6C
|
||||
REG_INT_STATUS = 0x3A
|
||||
|
||||
SAMPLE_RATE_DIVS = { 4000:0x00 }
|
||||
|
||||
@@ -40,6 +41,10 @@ SET_PWR_MGMT_1_WAKE = 0x00
|
||||
SET_PWR_MGMT_1_SLEEP= 0x40
|
||||
SET_PWR_MGMT_2_ACCEL_ON = 0x07
|
||||
SET_PWR_MGMT_2_OFF = 0x3F
|
||||
SET_USER_FIFO_RESET = 0x04
|
||||
SET_USER_FIFO_EN = 0x40
|
||||
SET_ENABLE_FIFO = 0x08
|
||||
SET_DISABLE_FIFO = 0x00
|
||||
|
||||
FREEFALL_ACCEL = 9.80665 * 1000.
|
||||
# SCALE = 1/4096 g/LSB @8g scale * Earth gravity in mm/s**2
|
||||
@@ -47,153 +52,69 @@ SCALE = 0.000244140625 * FREEFALL_ACCEL
|
||||
|
||||
FIFO_SIZE = 512
|
||||
|
||||
Accel_Measurement = collections.namedtuple(
|
||||
'Accel_Measurement', ('time', 'accel_x', 'accel_y', 'accel_z'))
|
||||
|
||||
MIN_MSG_TIME = 0.100
|
||||
|
||||
BYTES_PER_SAMPLE = 6
|
||||
SAMPLES_PER_BLOCK = 8
|
||||
BATCH_UPDATES = 0.100
|
||||
|
||||
# Printer class that controls MPU9250 chip
|
||||
class MPU9250:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
adxl345.AccelCommandHelper(config, self)
|
||||
self.query_rate = 0
|
||||
am = {'x': (0, SCALE), 'y': (1, SCALE), 'z': (2, SCALE),
|
||||
'-x': (0, -SCALE), '-y': (1, -SCALE), '-z': (2, -SCALE)}
|
||||
axes_map = config.getlist('axes_map', ('x','y','z'), count=3)
|
||||
if any([a not in am for a in axes_map]):
|
||||
raise config.error("Invalid mpu9250 axes_map parameter")
|
||||
self.axes_map = [am[a.strip()] for a in axes_map]
|
||||
self.axes_map = adxl345.read_axes_map(config, SCALE, SCALE, SCALE)
|
||||
self.data_rate = config.getint('rate', 4000)
|
||||
if self.data_rate not in SAMPLE_RATE_DIVS:
|
||||
raise config.error("Invalid rate parameter: %d" % (self.data_rate,))
|
||||
# Measurement storage (accessed from background thread)
|
||||
self.lock = threading.Lock()
|
||||
self.raw_samples = []
|
||||
# Setup mcu sensor_mpu9250 bulk query code
|
||||
self.i2c = bus.MCU_I2C_from_config(config,
|
||||
default_addr=MPU9250_ADDR,
|
||||
default_speed=400000)
|
||||
self.mcu = mcu = self.i2c.get_mcu()
|
||||
self.oid = oid = mcu.create_oid()
|
||||
self.query_mpu9250_cmd = self.query_mpu9250_end_cmd = None
|
||||
self.query_mpu9250_status_cmd = None
|
||||
self.query_mpu9250_cmd = None
|
||||
mcu.register_config_callback(self._build_config)
|
||||
mcu.register_response(self._handle_mpu9250_data, "mpu9250_data", oid)
|
||||
# Clock tracking
|
||||
self.last_sequence = self.max_query_duration = 0
|
||||
self.last_limit_count = self.last_error_count = 0
|
||||
self.clock_sync = adxl345.ClockSyncRegression(self.mcu, 640)
|
||||
# API server endpoints
|
||||
self.api_dump = motion_report.APIDumpHelper(
|
||||
self.printer, self._api_update, self._api_startstop, 0.100)
|
||||
# Bulk sample message reading
|
||||
chip_smooth = self.data_rate * BATCH_UPDATES * 2
|
||||
self.ffreader = bulk_sensor.FixedFreqReader(mcu, chip_smooth, ">hhh")
|
||||
self.last_error_count = 0
|
||||
# Process messages in batches
|
||||
self.batch_bulk = bulk_sensor.BatchBulkHelper(
|
||||
self.printer, self._process_batch,
|
||||
self._start_measurements, self._finish_measurements, BATCH_UPDATES)
|
||||
self.name = config.get_name().split()[-1]
|
||||
wh = self.printer.lookup_object('webhooks')
|
||||
wh.register_mux_endpoint("mpu9250/dump_mpu9250", "sensor", self.name,
|
||||
self._handle_dump_mpu9250)
|
||||
hdr = ('time', 'x_acceleration', 'y_acceleration', 'z_acceleration')
|
||||
self.batch_bulk.add_mux_endpoint("mpu9250/dump_mpu9250", "sensor",
|
||||
self.name, {'header': hdr})
|
||||
def _build_config(self):
|
||||
cmdqueue = self.i2c.get_command_queue()
|
||||
self.mcu.add_config_cmd("config_mpu9250 oid=%d i2c_oid=%d"
|
||||
% (self.oid, self.i2c.get_oid()))
|
||||
self.mcu.add_config_cmd("query_mpu9250 oid=%d clock=0 rest_ticks=0"
|
||||
self.mcu.add_config_cmd("query_mpu9250 oid=%d rest_ticks=0"
|
||||
% (self.oid,), on_restart=True)
|
||||
self.query_mpu9250_cmd = self.mcu.lookup_command(
|
||||
"query_mpu9250 oid=%c clock=%u rest_ticks=%u", cq=cmdqueue)
|
||||
self.query_mpu9250_end_cmd = self.mcu.lookup_query_command(
|
||||
"query_mpu9250 oid=%c clock=%u rest_ticks=%u",
|
||||
"mpu9250_status oid=%c clock=%u query_ticks=%u next_sequence=%hu"
|
||||
" buffered=%c fifo=%u limit_count=%hu", oid=self.oid, cq=cmdqueue)
|
||||
self.query_mpu9250_status_cmd = self.mcu.lookup_query_command(
|
||||
"query_mpu9250_status oid=%c",
|
||||
"mpu9250_status oid=%c clock=%u query_ticks=%u next_sequence=%hu"
|
||||
" buffered=%c fifo=%u limit_count=%hu", oid=self.oid, cq=cmdqueue)
|
||||
"query_mpu9250 oid=%c rest_ticks=%u", cq=cmdqueue)
|
||||
self.ffreader.setup_query_command("query_mpu9250_status oid=%c",
|
||||
oid=self.oid, cq=cmdqueue)
|
||||
def read_reg(self, reg):
|
||||
params = self.i2c.i2c_read([reg], 1)
|
||||
return bytearray(params['response'])[0]
|
||||
|
||||
def set_reg(self, reg, val, minclock=0):
|
||||
self.i2c.i2c_write([reg, val & 0xFF], minclock=minclock)
|
||||
|
||||
# Measurement collection
|
||||
def is_measuring(self):
|
||||
return self.query_rate > 0
|
||||
def _handle_mpu9250_data(self, params):
|
||||
with self.lock:
|
||||
self.raw_samples.append(params)
|
||||
def _extract_samples(self, raw_samples):
|
||||
# Load variables to optimize inner loop below
|
||||
def start_internal_client(self):
|
||||
aqh = adxl345.AccelQueryHelper(self.printer)
|
||||
self.batch_bulk.add_client(aqh.handle_batch)
|
||||
return aqh
|
||||
# Measurement decoding
|
||||
def _convert_samples(self, samples):
|
||||
(x_pos, x_scale), (y_pos, y_scale), (z_pos, z_scale) = self.axes_map
|
||||
last_sequence = self.last_sequence
|
||||
time_base, chip_base, inv_freq = self.clock_sync.get_time_translation()
|
||||
# Process every message in raw_samples
|
||||
count = seq = 0
|
||||
samples = [None] * (len(raw_samples) * SAMPLES_PER_BLOCK)
|
||||
for params in raw_samples:
|
||||
seq_diff = (last_sequence - params['sequence']) & 0xffff
|
||||
seq_diff -= (seq_diff & 0x8000) << 1
|
||||
seq = last_sequence - seq_diff
|
||||
d = bytearray(params['data'])
|
||||
msg_cdiff = seq * SAMPLES_PER_BLOCK - chip_base
|
||||
|
||||
for i in range(len(d) // BYTES_PER_SAMPLE):
|
||||
d_xyz = d[i*BYTES_PER_SAMPLE:(i+1)*BYTES_PER_SAMPLE]
|
||||
xhigh, xlow, yhigh, ylow, zhigh, zlow = d_xyz
|
||||
# Merge and perform twos-complement
|
||||
rx = ((xhigh << 8) | xlow) - ((xhigh & 0x80) << 9)
|
||||
ry = ((yhigh << 8) | ylow) - ((yhigh & 0x80) << 9)
|
||||
rz = ((zhigh << 8) | zlow) - ((zhigh & 0x80) << 9)
|
||||
|
||||
raw_xyz = (rx, ry, rz)
|
||||
x = round(raw_xyz[x_pos] * x_scale, 6)
|
||||
y = round(raw_xyz[y_pos] * y_scale, 6)
|
||||
z = round(raw_xyz[z_pos] * z_scale, 6)
|
||||
ptime = round(time_base + (msg_cdiff + i) * inv_freq, 6)
|
||||
samples[count] = (ptime, x, y, z)
|
||||
count += 1
|
||||
self.clock_sync.set_last_chip_clock(seq * SAMPLES_PER_BLOCK + i)
|
||||
del samples[count:]
|
||||
return samples
|
||||
|
||||
def _update_clock(self, minclock=0):
|
||||
# Query current state
|
||||
for retry in range(5):
|
||||
params = self.query_mpu9250_status_cmd.send([self.oid],
|
||||
minclock=minclock)
|
||||
fifo = params['fifo'] & 0x1fff
|
||||
if fifo <= FIFO_SIZE:
|
||||
break
|
||||
else:
|
||||
raise self.printer.command_error("Unable to query mpu9250 fifo")
|
||||
mcu_clock = self.mcu.clock32_to_clock64(params['clock'])
|
||||
sequence = (self.last_sequence & ~0xffff) | params['next_sequence']
|
||||
if sequence < self.last_sequence:
|
||||
sequence += 0x10000
|
||||
self.last_sequence = sequence
|
||||
buffered = params['buffered']
|
||||
limit_count = (self.last_limit_count & ~0xffff) | params['limit_count']
|
||||
if limit_count < self.last_limit_count:
|
||||
limit_count += 0x10000
|
||||
self.last_limit_count = limit_count
|
||||
duration = params['query_ticks']
|
||||
if duration > self.max_query_duration:
|
||||
# Skip measurement as a high query time could skew clock tracking
|
||||
self.max_query_duration = max(2 * self.max_query_duration,
|
||||
self.mcu.seconds_to_clock(.000005))
|
||||
return
|
||||
self.max_query_duration = 2 * duration
|
||||
msg_count = (sequence * SAMPLES_PER_BLOCK
|
||||
+ buffered // BYTES_PER_SAMPLE + fifo)
|
||||
# The "chip clock" is the message counter plus .5 for average
|
||||
# inaccuracy of query responses and plus .5 for assumed offset
|
||||
# of mpu9250 hw processing time.
|
||||
chip_clock = msg_count + 1
|
||||
self.clock_sync.update(mcu_clock + duration // 2, chip_clock)
|
||||
count = 0
|
||||
for ptime, rx, ry, rz in samples:
|
||||
raw_xyz = (rx, ry, rz)
|
||||
x = round(raw_xyz[x_pos] * x_scale, 6)
|
||||
y = round(raw_xyz[y_pos] * y_scale, 6)
|
||||
z = round(raw_xyz[z_pos] * z_scale, 6)
|
||||
samples[count] = (round(ptime, 6), x, y, z)
|
||||
count += 1
|
||||
# Start, stop, and process message batches
|
||||
def _start_measurements(self):
|
||||
if self.is_measuring():
|
||||
return
|
||||
# In case of miswiring, testing MPU9250 device ID prevents treating
|
||||
# noise or wrong signal as a correctly initialized device
|
||||
dev_id = self.read_reg(REG_DEVID)
|
||||
@@ -208,68 +129,44 @@ class MPU9250:
|
||||
# Setup chip in requested query rate
|
||||
self.set_reg(REG_PWR_MGMT_1, SET_PWR_MGMT_1_WAKE)
|
||||
self.set_reg(REG_PWR_MGMT_2, SET_PWR_MGMT_2_ACCEL_ON)
|
||||
time.sleep(20. / 1000) # wait for accelerometer chip wake up
|
||||
self.set_reg(REG_SMPLRT_DIV, SAMPLE_RATE_DIVS[self.data_rate])
|
||||
# Add 20ms pause for accelerometer chip wake up
|
||||
self.read_reg(REG_DEVID) # Dummy read to ensure queues flushed
|
||||
systime = self.printer.get_reactor().monotonic()
|
||||
next_time = self.mcu.estimated_print_time(systime) + 0.020
|
||||
self.set_reg(REG_SMPLRT_DIV, SAMPLE_RATE_DIVS[self.data_rate],
|
||||
minclock=self.mcu.print_time_to_clock(next_time))
|
||||
self.set_reg(REG_CONFIG, SET_CONFIG)
|
||||
self.set_reg(REG_ACCEL_CONFIG, SET_ACCEL_CONFIG)
|
||||
self.set_reg(REG_ACCEL_CONFIG2, SET_ACCEL_CONFIG2)
|
||||
# Reset fifo
|
||||
self.set_reg(REG_FIFO_EN, SET_DISABLE_FIFO)
|
||||
self.set_reg(REG_USER_CTRL, SET_USER_FIFO_RESET)
|
||||
self.set_reg(REG_USER_CTRL, SET_USER_FIFO_EN)
|
||||
self.read_reg(REG_INT_STATUS) # clear FIFO overflow flag
|
||||
|
||||
# Setup samples
|
||||
with self.lock:
|
||||
self.raw_samples = []
|
||||
# Start bulk reading
|
||||
systime = self.printer.get_reactor().monotonic()
|
||||
print_time = self.mcu.estimated_print_time(systime) + MIN_MSG_TIME
|
||||
reqclock = self.mcu.print_time_to_clock(print_time)
|
||||
rest_ticks = self.mcu.seconds_to_clock(4. / self.data_rate)
|
||||
self.query_rate = self.data_rate
|
||||
self.query_mpu9250_cmd.send([self.oid, reqclock, rest_ticks],
|
||||
reqclock=reqclock)
|
||||
self.query_mpu9250_cmd.send([self.oid, rest_ticks])
|
||||
self.set_reg(REG_FIFO_EN, SET_ENABLE_FIFO)
|
||||
logging.info("MPU9250 starting '%s' measurements", self.name)
|
||||
# Initialize clock tracking
|
||||
self.last_sequence = 0
|
||||
self.last_limit_count = self.last_error_count = 0
|
||||
self.clock_sync.reset(reqclock, 0)
|
||||
self.max_query_duration = 1 << 31
|
||||
self._update_clock(minclock=reqclock)
|
||||
self.max_query_duration = 1 << 31
|
||||
self.ffreader.note_start()
|
||||
self.last_error_count = 0
|
||||
def _finish_measurements(self):
|
||||
if not self.is_measuring():
|
||||
return
|
||||
# Halt bulk reading
|
||||
params = self.query_mpu9250_end_cmd.send([self.oid, 0, 0])
|
||||
self.query_rate = 0
|
||||
with self.lock:
|
||||
self.raw_samples = []
|
||||
self.set_reg(REG_FIFO_EN, SET_DISABLE_FIFO)
|
||||
self.query_mpu9250_cmd.send_wait_ack([self.oid, 0])
|
||||
self.ffreader.note_end()
|
||||
logging.info("MPU9250 finished '%s' measurements", self.name)
|
||||
self.set_reg(REG_PWR_MGMT_1, SET_PWR_MGMT_1_SLEEP)
|
||||
self.set_reg(REG_PWR_MGMT_2, SET_PWR_MGMT_2_OFF)
|
||||
|
||||
# API interface
|
||||
def _api_update(self, eventtime):
|
||||
self._update_clock()
|
||||
with self.lock:
|
||||
raw_samples = self.raw_samples
|
||||
self.raw_samples = []
|
||||
if not raw_samples:
|
||||
return {}
|
||||
samples = self._extract_samples(raw_samples)
|
||||
def _process_batch(self, eventtime):
|
||||
samples = self.ffreader.pull_samples()
|
||||
self._convert_samples(samples)
|
||||
if not samples:
|
||||
return {}
|
||||
return {'data': samples, 'errors': self.last_error_count,
|
||||
'overflows': self.last_limit_count}
|
||||
def _api_startstop(self, is_start):
|
||||
if is_start:
|
||||
self._start_measurements()
|
||||
else:
|
||||
self._finish_measurements()
|
||||
def _handle_dump_mpu9250(self, web_request):
|
||||
self.api_dump.add_client(web_request)
|
||||
hdr = ('time', 'x_acceleration', 'y_acceleration', 'z_acceleration')
|
||||
web_request.send({'header': hdr})
|
||||
def start_internal_client(self):
|
||||
cconn = self.api_dump.add_internal_client()
|
||||
return adxl345.AccelQueryHelper(self.printer, cconn)
|
||||
'overflows': self.ffreader.get_last_overflows()}
|
||||
|
||||
def load_config(config):
|
||||
return MPU9250(config)
|
||||
|
||||
@@ -46,9 +46,9 @@ class PrinterMultiPin:
|
||||
def set_digital(self, print_time, value):
|
||||
for mcu_pin in self.mcu_pins:
|
||||
mcu_pin.set_digital(print_time, value)
|
||||
def set_pwm(self, print_time, value, cycle_time=None):
|
||||
def set_pwm(self, print_time, value):
|
||||
for mcu_pin in self.mcu_pins:
|
||||
mcu_pin.set_pwm(print_time, value, cycle_time)
|
||||
mcu_pin.set_pwm(print_time, value)
|
||||
|
||||
def load_config_prefix(config):
|
||||
return PrinterMultiPin(config)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Code to configure miscellaneous chips
|
||||
# PWM and digital output pin handling
|
||||
#
|
||||
# Copyright (C) 2017-2021 Kevin O'Connor <kevin@koconnor.net>
|
||||
# Copyright (C) 2017-2024 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
@@ -12,6 +12,7 @@ class PrinterOutputPin:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
ppins = self.printer.lookup_object('pins')
|
||||
# Determine pin type
|
||||
self.is_pwm = config.getboolean('pwm', False)
|
||||
if self.is_pwm:
|
||||
self.mcu_pin = ppins.setup_pin('pwm', config.get('pin'))
|
||||
@@ -20,68 +21,65 @@ class PrinterOutputPin:
|
||||
hardware_pwm = config.getboolean('hardware_pwm', False)
|
||||
self.mcu_pin.setup_cycle_time(cycle_time, hardware_pwm)
|
||||
self.scale = config.getfloat('scale', 1., above=0.)
|
||||
self.last_cycle_time = self.default_cycle_time = cycle_time
|
||||
else:
|
||||
self.mcu_pin = ppins.setup_pin('digital_out', config.get('pin'))
|
||||
self.scale = 1.
|
||||
self.last_cycle_time = self.default_cycle_time = 0.
|
||||
self.last_print_time = 0.
|
||||
static_value = config.getfloat('static_value', None,
|
||||
minval=0., maxval=self.scale)
|
||||
# Support mcu checking for maximum duration
|
||||
self.reactor = self.printer.get_reactor()
|
||||
self.resend_timer = None
|
||||
self.resend_interval = 0.
|
||||
max_mcu_duration = config.getfloat('maximum_mcu_duration', 0.,
|
||||
minval=0.500,
|
||||
maxval=MAX_SCHEDULE_TIME)
|
||||
self.mcu_pin.setup_max_duration(max_mcu_duration)
|
||||
if max_mcu_duration:
|
||||
config.deprecate('maximum_mcu_duration')
|
||||
self.resend_interval = max_mcu_duration - RESEND_HOST_TIME
|
||||
# Determine start and shutdown values
|
||||
static_value = config.getfloat('static_value', None,
|
||||
minval=0., maxval=self.scale)
|
||||
if static_value is not None:
|
||||
self.mcu_pin.setup_max_duration(0.)
|
||||
self.last_value = static_value / self.scale
|
||||
self.mcu_pin.setup_start_value(
|
||||
self.last_value, self.last_value, True)
|
||||
config.deprecate('static_value')
|
||||
self.last_value = self.shutdown_value = static_value / self.scale
|
||||
else:
|
||||
max_mcu_duration = config.getfloat('maximum_mcu_duration', 0.,
|
||||
minval=0.500,
|
||||
maxval=MAX_SCHEDULE_TIME)
|
||||
self.mcu_pin.setup_max_duration(max_mcu_duration)
|
||||
if max_mcu_duration:
|
||||
self.resend_interval = max_mcu_duration - RESEND_HOST_TIME
|
||||
|
||||
self.last_value = config.getfloat(
|
||||
'value', 0., minval=0., maxval=self.scale) / self.scale
|
||||
self.shutdown_value = config.getfloat(
|
||||
'shutdown_value', 0., minval=0., maxval=self.scale) / self.scale
|
||||
self.mcu_pin.setup_start_value(self.last_value, self.shutdown_value)
|
||||
pin_name = config.get_name().split()[1]
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
gcode.register_mux_command("SET_PIN", "PIN", pin_name,
|
||||
self.cmd_SET_PIN,
|
||||
desc=self.cmd_SET_PIN_help)
|
||||
self.mcu_pin.setup_start_value(self.last_value, self.shutdown_value)
|
||||
# Register commands
|
||||
pin_name = config.get_name().split()[1]
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
gcode.register_mux_command("SET_PIN", "PIN", pin_name,
|
||||
self.cmd_SET_PIN,
|
||||
desc=self.cmd_SET_PIN_help)
|
||||
def get_status(self, eventtime):
|
||||
return {'value': self.last_value}
|
||||
def _set_pin(self, print_time, value, cycle_time, is_resend=False):
|
||||
if value == self.last_value and cycle_time == self.last_cycle_time:
|
||||
if not is_resend:
|
||||
return
|
||||
def _set_pin(self, print_time, value, is_resend=False):
|
||||
if value == self.last_value and not is_resend:
|
||||
return
|
||||
print_time = max(print_time, self.last_print_time + PIN_MIN_TIME)
|
||||
if self.is_pwm:
|
||||
self.mcu_pin.set_pwm(print_time, value, cycle_time)
|
||||
self.mcu_pin.set_pwm(print_time, value)
|
||||
else:
|
||||
self.mcu_pin.set_digital(print_time, value)
|
||||
self.last_value = value
|
||||
self.last_cycle_time = cycle_time
|
||||
self.last_print_time = print_time
|
||||
if self.resend_interval and self.resend_timer is None:
|
||||
self.resend_timer = self.reactor.register_timer(
|
||||
self._resend_current_val, self.reactor.NOW)
|
||||
cmd_SET_PIN_help = "Set the value of an output pin"
|
||||
def cmd_SET_PIN(self, gcmd):
|
||||
# Read requested value
|
||||
value = gcmd.get_float('VALUE', minval=0., maxval=self.scale)
|
||||
value /= self.scale
|
||||
cycle_time = gcmd.get_float('CYCLE_TIME', self.default_cycle_time,
|
||||
above=0., maxval=MAX_SCHEDULE_TIME)
|
||||
if not self.is_pwm and value not in [0., 1.]:
|
||||
raise gcmd.error("Invalid pin value")
|
||||
# Obtain print_time and apply requested settings
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
toolhead.register_lookahead_callback(
|
||||
lambda print_time: self._set_pin(print_time, value, cycle_time))
|
||||
lambda print_time: self._set_pin(print_time, value))
|
||||
|
||||
def _resend_current_val(self, eventtime):
|
||||
if self.last_value == self.shutdown_value:
|
||||
@@ -95,8 +93,7 @@ class PrinterOutputPin:
|
||||
if time_diff > 0.:
|
||||
# Reschedule for resend time
|
||||
return systime + time_diff
|
||||
self._set_pin(print_time + PIN_MIN_TIME,
|
||||
self.last_value, self.last_cycle_time, True)
|
||||
self._set_pin(print_time + PIN_MIN_TIME, self.last_value, True)
|
||||
return systime + self.resend_interval
|
||||
|
||||
def load_config_prefix(config):
|
||||
|
||||
@@ -43,11 +43,12 @@ class PIDCalibrate:
|
||||
"The SAVE_CONFIG command will update the printer config file\n"
|
||||
"with these parameters and restart the printer." % (Kp, Ki, Kd))
|
||||
# Store results for SAVE_CONFIG
|
||||
cfgname = heater.get_name()
|
||||
configfile = self.printer.lookup_object('configfile')
|
||||
configfile.set(heater_name, 'control', 'pid')
|
||||
configfile.set(heater_name, 'pid_Kp', "%.3f" % (Kp,))
|
||||
configfile.set(heater_name, 'pid_Ki', "%.3f" % (Ki,))
|
||||
configfile.set(heater_name, 'pid_Kd', "%.3f" % (Kd,))
|
||||
configfile.set(cfgname, 'control', 'pid')
|
||||
configfile.set(cfgname, 'pid_Kp', "%.3f" % (Kp,))
|
||||
configfile.set(cfgname, 'pid_Ki', "%.3f" % (Ki,))
|
||||
configfile.set(cfgname, 'pid_Kd', "%.3f" % (Kd,))
|
||||
|
||||
TUNE_PID_DELTA = 5.0
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Z-Probe support
|
||||
#
|
||||
# Copyright (C) 2017-2021 Kevin O'Connor <kevin@koconnor.net>
|
||||
# Copyright (C) 2017-2024 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
@@ -13,232 +13,138 @@ consider reducing the Z axis minimum position so the probe
|
||||
can travel further (the Z minimum position can be negative).
|
||||
"""
|
||||
|
||||
class PrinterProbe:
|
||||
def __init__(self, config, mcu_probe):
|
||||
self.printer = config.get_printer()
|
||||
self.name = config.get_name()
|
||||
self.mcu_probe = mcu_probe
|
||||
self.speed = config.getfloat('speed', 5.0, above=0.)
|
||||
self.lift_speed = config.getfloat('lift_speed', self.speed, above=0.)
|
||||
self.x_offset = config.getfloat('x_offset', 0.)
|
||||
self.y_offset = config.getfloat('y_offset', 0.)
|
||||
self.z_offset = config.getfloat('z_offset')
|
||||
self.probe_calibrate_z = 0.
|
||||
self.multi_probe_pending = False
|
||||
self.last_state = False
|
||||
self.last_z_result = 0.
|
||||
self.gcode_move = self.printer.load_object(config, "gcode_move")
|
||||
# Infer Z position to move to during a probe
|
||||
if config.has_section('stepper_z'):
|
||||
zconfig = config.getsection('stepper_z')
|
||||
self.z_position = zconfig.getfloat('position_min', 0.,
|
||||
note_valid=False)
|
||||
else:
|
||||
pconfig = config.getsection('printer')
|
||||
self.z_position = pconfig.getfloat('minimum_z_position', 0.,
|
||||
note_valid=False)
|
||||
# Multi-sample support (for improved accuracy)
|
||||
self.sample_count = config.getint('samples', 1, minval=1)
|
||||
self.sample_retract_dist = config.getfloat('sample_retract_dist', 2.,
|
||||
above=0.)
|
||||
atypes = {'median': 'median', 'average': 'average'}
|
||||
self.samples_result = config.getchoice('samples_result', atypes,
|
||||
'average')
|
||||
self.samples_tolerance = config.getfloat('samples_tolerance', 0.100,
|
||||
minval=0.)
|
||||
self.samples_retries = config.getint('samples_tolerance_retries', 0,
|
||||
minval=0)
|
||||
# Register z_virtual_endstop pin
|
||||
self.printer.lookup_object('pins').register_chip('probe', self)
|
||||
# Register homing event handlers
|
||||
self.printer.register_event_handler("homing:homing_move_begin",
|
||||
self._handle_homing_move_begin)
|
||||
self.printer.register_event_handler("homing:homing_move_end",
|
||||
self._handle_homing_move_end)
|
||||
self.printer.register_event_handler("homing:home_rails_begin",
|
||||
self._handle_home_rails_begin)
|
||||
self.printer.register_event_handler("homing:home_rails_end",
|
||||
self._handle_home_rails_end)
|
||||
self.printer.register_event_handler("gcode:command_error",
|
||||
self._handle_command_error)
|
||||
# Register PROBE/QUERY_PROBE commands
|
||||
self.gcode = self.printer.lookup_object('gcode')
|
||||
self.gcode.register_command('PROBE', self.cmd_PROBE,
|
||||
desc=self.cmd_PROBE_help)
|
||||
self.gcode.register_command('QUERY_PROBE', self.cmd_QUERY_PROBE,
|
||||
desc=self.cmd_QUERY_PROBE_help)
|
||||
self.gcode.register_command('PROBE_CALIBRATE', self.cmd_PROBE_CALIBRATE,
|
||||
desc=self.cmd_PROBE_CALIBRATE_help)
|
||||
self.gcode.register_command('PROBE_ACCURACY', self.cmd_PROBE_ACCURACY,
|
||||
desc=self.cmd_PROBE_ACCURACY_help)
|
||||
self.gcode.register_command('Z_OFFSET_APPLY_PROBE',
|
||||
self.cmd_Z_OFFSET_APPLY_PROBE,
|
||||
desc=self.cmd_Z_OFFSET_APPLY_PROBE_help)
|
||||
def _handle_homing_move_begin(self, hmove):
|
||||
if self.mcu_probe in hmove.get_mcu_endstops():
|
||||
self.mcu_probe.probe_prepare(hmove)
|
||||
def _handle_homing_move_end(self, hmove):
|
||||
if self.mcu_probe in hmove.get_mcu_endstops():
|
||||
self.mcu_probe.probe_finish(hmove)
|
||||
def _handle_home_rails_begin(self, homing_state, rails):
|
||||
endstops = [es for rail in rails for es, name in rail.get_endstops()]
|
||||
if self.mcu_probe in endstops:
|
||||
self.multi_probe_begin()
|
||||
def _handle_home_rails_end(self, homing_state, rails):
|
||||
endstops = [es for rail in rails for es, name in rail.get_endstops()]
|
||||
if self.mcu_probe in endstops:
|
||||
self.multi_probe_end()
|
||||
def _handle_command_error(self):
|
||||
try:
|
||||
self.multi_probe_end()
|
||||
except:
|
||||
logging.exception("Multi-probe end")
|
||||
def multi_probe_begin(self):
|
||||
self.mcu_probe.multi_probe_begin()
|
||||
self.multi_probe_pending = True
|
||||
def multi_probe_end(self):
|
||||
if self.multi_probe_pending:
|
||||
self.multi_probe_pending = False
|
||||
self.mcu_probe.multi_probe_end()
|
||||
def setup_pin(self, pin_type, pin_params):
|
||||
if pin_type != 'endstop' or pin_params['pin'] != 'z_virtual_endstop':
|
||||
raise pins.error("Probe virtual endstop only useful as endstop pin")
|
||||
if pin_params['invert'] or pin_params['pullup']:
|
||||
raise pins.error("Can not pullup/invert probe virtual endstop")
|
||||
return self.mcu_probe
|
||||
def get_lift_speed(self, gcmd=None):
|
||||
if gcmd is not None:
|
||||
return gcmd.get_float("LIFT_SPEED", self.lift_speed, above=0.)
|
||||
return self.lift_speed
|
||||
def get_offsets(self):
|
||||
return self.x_offset, self.y_offset, self.z_offset
|
||||
def _probe(self, speed):
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
curtime = self.printer.get_reactor().monotonic()
|
||||
if 'z' not in toolhead.get_status(curtime)['homed_axes']:
|
||||
raise self.printer.command_error("Must home before probe")
|
||||
phoming = self.printer.lookup_object('homing')
|
||||
pos = toolhead.get_position()
|
||||
pos[2] = self.z_position
|
||||
try:
|
||||
epos = phoming.probing_move(self.mcu_probe, pos, speed)
|
||||
except self.printer.command_error as e:
|
||||
reason = str(e)
|
||||
if "Timeout during endstop homing" in reason:
|
||||
reason += HINT_TIMEOUT
|
||||
raise self.printer.command_error(reason)
|
||||
# get z compensation from axis_twist_compensation
|
||||
axis_twist_compensation = self.printer.lookup_object(
|
||||
'axis_twist_compensation', None)
|
||||
z_compensation = 0
|
||||
if axis_twist_compensation is not None:
|
||||
z_compensation = (
|
||||
axis_twist_compensation.get_z_compensation_value(pos))
|
||||
# add z compensation to probe position
|
||||
epos[2] += z_compensation
|
||||
self.gcode.respond_info("probe at %.3f,%.3f is z=%.6f"
|
||||
% (epos[0], epos[1], epos[2]))
|
||||
return epos[:3]
|
||||
def _move(self, coord, speed):
|
||||
self.printer.lookup_object('toolhead').manual_move(coord, speed)
|
||||
def _calc_mean(self, positions):
|
||||
# Calculate the average Z from a set of positions
|
||||
def calc_probe_z_average(positions, method='average'):
|
||||
if method != 'median':
|
||||
# Use mean average
|
||||
count = float(len(positions))
|
||||
return [sum([pos[i] for pos in positions]) / count
|
||||
for i in range(3)]
|
||||
def _calc_median(self, positions):
|
||||
z_sorted = sorted(positions, key=(lambda p: p[2]))
|
||||
middle = len(positions) // 2
|
||||
if (len(positions) & 1) == 1:
|
||||
# odd number of samples
|
||||
return z_sorted[middle]
|
||||
# even number of samples
|
||||
return self._calc_mean(z_sorted[middle-1:middle+1])
|
||||
def run_probe(self, gcmd):
|
||||
speed = gcmd.get_float("PROBE_SPEED", self.speed, above=0.)
|
||||
lift_speed = self.get_lift_speed(gcmd)
|
||||
sample_count = gcmd.get_int("SAMPLES", self.sample_count, minval=1)
|
||||
sample_retract_dist = gcmd.get_float("SAMPLE_RETRACT_DIST",
|
||||
self.sample_retract_dist, above=0.)
|
||||
samples_tolerance = gcmd.get_float("SAMPLES_TOLERANCE",
|
||||
self.samples_tolerance, minval=0.)
|
||||
samples_retries = gcmd.get_int("SAMPLES_TOLERANCE_RETRIES",
|
||||
self.samples_retries, minval=0)
|
||||
samples_result = gcmd.get("SAMPLES_RESULT", self.samples_result)
|
||||
must_notify_multi_probe = not self.multi_probe_pending
|
||||
if must_notify_multi_probe:
|
||||
self.multi_probe_begin()
|
||||
probexy = self.printer.lookup_object('toolhead').get_position()[:2]
|
||||
retries = 0
|
||||
positions = []
|
||||
while len(positions) < sample_count:
|
||||
# Probe position
|
||||
pos = self._probe(speed)
|
||||
positions.append(pos)
|
||||
# Check samples tolerance
|
||||
z_positions = [p[2] for p in positions]
|
||||
if max(z_positions) - min(z_positions) > samples_tolerance:
|
||||
if retries >= samples_retries:
|
||||
raise gcmd.error("Probe samples exceed samples_tolerance")
|
||||
gcmd.respond_info("Probe samples exceed tolerance. Retrying...")
|
||||
retries += 1
|
||||
positions = []
|
||||
# Retract
|
||||
if len(positions) < sample_count:
|
||||
self._move(probexy + [pos[2] + sample_retract_dist], lift_speed)
|
||||
if must_notify_multi_probe:
|
||||
self.multi_probe_end()
|
||||
# Calculate and return result
|
||||
if samples_result == 'median':
|
||||
return self._calc_median(positions)
|
||||
return self._calc_mean(positions)
|
||||
cmd_PROBE_help = "Probe Z-height at current XY position"
|
||||
def cmd_PROBE(self, gcmd):
|
||||
pos = self.run_probe(gcmd)
|
||||
gcmd.respond_info("Result is z=%.6f" % (pos[2],))
|
||||
self.last_z_result = pos[2]
|
||||
cmd_QUERY_PROBE_help = "Return the status of the z-probe"
|
||||
def cmd_QUERY_PROBE(self, gcmd):
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
print_time = toolhead.get_last_move_time()
|
||||
res = self.mcu_probe.query_endstop(print_time)
|
||||
self.last_state = res
|
||||
gcmd.respond_info("probe: %s" % (["open", "TRIGGERED"][not not res],))
|
||||
# Use median
|
||||
z_sorted = sorted(positions, key=(lambda p: p[2]))
|
||||
middle = len(positions) // 2
|
||||
if (len(positions) & 1) == 1:
|
||||
# odd number of samples
|
||||
return z_sorted[middle]
|
||||
# even number of samples
|
||||
return calc_probe_z_average(z_sorted[middle-1:middle+1], 'average')
|
||||
|
||||
|
||||
######################################################################
|
||||
# Probe device implementation helpers
|
||||
######################################################################
|
||||
|
||||
# Helper to implement common probing commands
|
||||
class ProbeCommandHelper:
|
||||
def __init__(self, config, probe, query_endstop=None):
|
||||
self.printer = config.get_printer()
|
||||
self.probe = probe
|
||||
self.query_endstop = query_endstop
|
||||
self.name = config.get_name()
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
# QUERY_PROBE command
|
||||
self.last_state = False
|
||||
gcode.register_command('QUERY_PROBE', self.cmd_QUERY_PROBE,
|
||||
desc=self.cmd_QUERY_PROBE_help)
|
||||
# PROBE command
|
||||
self.last_z_result = 0.
|
||||
gcode.register_command('PROBE', self.cmd_PROBE,
|
||||
desc=self.cmd_PROBE_help)
|
||||
# PROBE_CALIBRATE command
|
||||
self.probe_calibrate_z = 0.
|
||||
gcode.register_command('PROBE_CALIBRATE', self.cmd_PROBE_CALIBRATE,
|
||||
desc=self.cmd_PROBE_CALIBRATE_help)
|
||||
# Other commands
|
||||
gcode.register_command('PROBE_ACCURACY', self.cmd_PROBE_ACCURACY,
|
||||
desc=self.cmd_PROBE_ACCURACY_help)
|
||||
gcode.register_command('Z_OFFSET_APPLY_PROBE',
|
||||
self.cmd_Z_OFFSET_APPLY_PROBE,
|
||||
desc=self.cmd_Z_OFFSET_APPLY_PROBE_help)
|
||||
def _move(self, coord, speed):
|
||||
self.printer.lookup_object('toolhead').manual_move(coord, speed)
|
||||
def get_status(self, eventtime):
|
||||
return {'name': self.name,
|
||||
'last_query': self.last_state,
|
||||
'last_z_result': self.last_z_result}
|
||||
cmd_QUERY_PROBE_help = "Return the status of the z-probe"
|
||||
def cmd_QUERY_PROBE(self, gcmd):
|
||||
if self.query_endstop is None:
|
||||
raise gcmd.error("Probe does not support QUERY_PROBE")
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
print_time = toolhead.get_last_move_time()
|
||||
res = self.query_endstop(print_time)
|
||||
self.last_state = res
|
||||
gcmd.respond_info("probe: %s" % (["open", "TRIGGERED"][not not res],))
|
||||
cmd_PROBE_help = "Probe Z-height at current XY position"
|
||||
def cmd_PROBE(self, gcmd):
|
||||
pos = run_single_probe(self.probe, gcmd)
|
||||
gcmd.respond_info("Result is z=%.6f" % (pos[2],))
|
||||
self.last_z_result = pos[2]
|
||||
def probe_calibrate_finalize(self, kin_pos):
|
||||
if kin_pos is None:
|
||||
return
|
||||
z_offset = self.probe_calibrate_z - kin_pos[2]
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
gcode.respond_info(
|
||||
"%s: z_offset: %.3f\n"
|
||||
"The SAVE_CONFIG command will update the printer config file\n"
|
||||
"with the above and restart the printer." % (self.name, z_offset))
|
||||
configfile = self.printer.lookup_object('configfile')
|
||||
configfile.set(self.name, 'z_offset', "%.3f" % (z_offset,))
|
||||
cmd_PROBE_CALIBRATE_help = "Calibrate the probe's z_offset"
|
||||
def cmd_PROBE_CALIBRATE(self, gcmd):
|
||||
manual_probe.verify_no_manual_probe(self.printer)
|
||||
params = self.probe.get_probe_params(gcmd)
|
||||
# Perform initial probe
|
||||
curpos = run_single_probe(self.probe, gcmd)
|
||||
# Move away from the bed
|
||||
self.probe_calibrate_z = curpos[2]
|
||||
curpos[2] += 5.
|
||||
self._move(curpos, params['lift_speed'])
|
||||
# Move the nozzle over the probe point
|
||||
x_offset, y_offset, z_offset = self.probe.get_offsets()
|
||||
curpos[0] += x_offset
|
||||
curpos[1] += y_offset
|
||||
self._move(curpos, params['probe_speed'])
|
||||
# Start manual probe
|
||||
manual_probe.ManualProbeHelper(self.printer, gcmd,
|
||||
self.probe_calibrate_finalize)
|
||||
cmd_PROBE_ACCURACY_help = "Probe Z-height accuracy at current XY position"
|
||||
def cmd_PROBE_ACCURACY(self, gcmd):
|
||||
speed = gcmd.get_float("PROBE_SPEED", self.speed, above=0.)
|
||||
lift_speed = self.get_lift_speed(gcmd)
|
||||
params = self.probe.get_probe_params(gcmd)
|
||||
sample_count = gcmd.get_int("SAMPLES", 10, minval=1)
|
||||
sample_retract_dist = gcmd.get_float("SAMPLE_RETRACT_DIST",
|
||||
self.sample_retract_dist, above=0.)
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
pos = toolhead.get_position()
|
||||
gcmd.respond_info("PROBE_ACCURACY at X:%.3f Y:%.3f Z:%.3f"
|
||||
" (samples=%d retract=%.3f"
|
||||
" speed=%.1f lift_speed=%.1f)\n"
|
||||
% (pos[0], pos[1], pos[2],
|
||||
sample_count, sample_retract_dist,
|
||||
speed, lift_speed))
|
||||
sample_count, params['sample_retract_dist'],
|
||||
params['probe_speed'], params['lift_speed']))
|
||||
# Create dummy gcmd with SAMPLES=1
|
||||
fo_params = dict(gcmd.get_command_parameters())
|
||||
fo_params['SAMPLES'] = '1'
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
fo_gcmd = gcode.create_gcode_command("", "", fo_params)
|
||||
# Probe bed sample_count times
|
||||
self.multi_probe_begin()
|
||||
positions = []
|
||||
while len(positions) < sample_count:
|
||||
probe_session = self.probe.start_probe_session(fo_gcmd)
|
||||
probe_num = 0
|
||||
while probe_num < sample_count:
|
||||
# Probe position
|
||||
pos = self._probe(speed)
|
||||
positions.append(pos)
|
||||
probe_session.run_probe(fo_gcmd)
|
||||
probe_num += 1
|
||||
# Retract
|
||||
liftpos = [None, None, pos[2] + sample_retract_dist]
|
||||
self._move(liftpos, lift_speed)
|
||||
self.multi_probe_end()
|
||||
pos = toolhead.get_position()
|
||||
liftpos = [None, None, pos[2] + params['sample_retract_dist']]
|
||||
self._move(liftpos, params['lift_speed'])
|
||||
positions = probe_session.pull_probed_results()
|
||||
probe_session.end_probe_session()
|
||||
# Calculate maximum, minimum and average values
|
||||
max_value = max([p[2] for p in positions])
|
||||
min_value = min([p[2] for p in positions])
|
||||
range_value = max_value - min_value
|
||||
avg_value = self._calc_mean(positions)[2]
|
||||
median = self._calc_median(positions)[2]
|
||||
avg_value = calc_probe_z_average(positions, 'average')[2]
|
||||
median = calc_probe_z_average(positions, 'median')[2]
|
||||
# calculate the standard deviation
|
||||
deviation_sum = 0
|
||||
for i in range(len(positions)):
|
||||
@@ -249,115 +155,226 @@ class PrinterProbe:
|
||||
"probe accuracy results: maximum %.6f, minimum %.6f, range %.6f, "
|
||||
"average %.6f, median %.6f, standard deviation %.6f" % (
|
||||
max_value, min_value, range_value, avg_value, median, sigma))
|
||||
def probe_calibrate_finalize(self, kin_pos):
|
||||
if kin_pos is None:
|
||||
cmd_Z_OFFSET_APPLY_PROBE_help = "Adjust the probe's z_offset"
|
||||
def cmd_Z_OFFSET_APPLY_PROBE(self, gcmd):
|
||||
gcode_move = self.printer.lookup_object("gcode_move")
|
||||
offset = gcode_move.get_status()['homing_origin'].z
|
||||
if offset == 0:
|
||||
gcmd.respond_info("Nothing to do: Z Offset is 0")
|
||||
return
|
||||
z_offset = self.probe_calibrate_z - kin_pos[2]
|
||||
self.gcode.respond_info(
|
||||
z_offset = self.probe.get_offsets()[2]
|
||||
new_calibrate = z_offset - offset
|
||||
gcmd.respond_info(
|
||||
"%s: z_offset: %.3f\n"
|
||||
"The SAVE_CONFIG command will update the printer config file\n"
|
||||
"with the above and restart the printer." % (self.name, z_offset))
|
||||
"with the above and restart the printer."
|
||||
% (self.name, new_calibrate))
|
||||
configfile = self.printer.lookup_object('configfile')
|
||||
configfile.set(self.name, 'z_offset', "%.3f" % (z_offset,))
|
||||
cmd_PROBE_CALIBRATE_help = "Calibrate the probe's z_offset"
|
||||
def cmd_PROBE_CALIBRATE(self, gcmd):
|
||||
manual_probe.verify_no_manual_probe(self.printer)
|
||||
# Perform initial probe
|
||||
lift_speed = self.get_lift_speed(gcmd)
|
||||
curpos = self.run_probe(gcmd)
|
||||
# Move away from the bed
|
||||
self.probe_calibrate_z = curpos[2]
|
||||
curpos[2] += 5.
|
||||
self._move(curpos, lift_speed)
|
||||
# Move the nozzle over the probe point
|
||||
curpos[0] += self.x_offset
|
||||
curpos[1] += self.y_offset
|
||||
self._move(curpos, self.speed)
|
||||
# Start manual probe
|
||||
manual_probe.ManualProbeHelper(self.printer, gcmd,
|
||||
self.probe_calibrate_finalize)
|
||||
def cmd_Z_OFFSET_APPLY_PROBE(self,gcmd):
|
||||
offset = self.gcode_move.get_status()['homing_origin'].z
|
||||
configfile = self.printer.lookup_object('configfile')
|
||||
if offset == 0:
|
||||
self.gcode.respond_info("Nothing to do: Z Offset is 0")
|
||||
else:
|
||||
new_calibrate = self.z_offset - offset
|
||||
self.gcode.respond_info(
|
||||
"%s: z_offset: %.3f\n"
|
||||
"The SAVE_CONFIG command will update the printer config file\n"
|
||||
"with the above and restart the printer."
|
||||
% (self.name, new_calibrate))
|
||||
configfile.set(self.name, 'z_offset', "%.3f" % (new_calibrate,))
|
||||
cmd_Z_OFFSET_APPLY_PROBE_help = "Adjust the probe's z_offset"
|
||||
configfile.set(self.name, 'z_offset', "%.3f" % (new_calibrate,))
|
||||
|
||||
# Endstop wrapper that enables probe specific features
|
||||
class ProbeEndstopWrapper:
|
||||
def __init__(self, config):
|
||||
# Homing via probe:z_virtual_endstop
|
||||
class HomingViaProbeHelper:
|
||||
def __init__(self, config, mcu_probe):
|
||||
self.printer = config.get_printer()
|
||||
self.position_endstop = config.getfloat('z_offset')
|
||||
self.stow_on_each_sample = config.getboolean(
|
||||
'deactivate_on_each_sample', True)
|
||||
gcode_macro = self.printer.load_object(config, 'gcode_macro')
|
||||
self.activate_gcode = gcode_macro.load_template(
|
||||
config, 'activate_gcode', '')
|
||||
self.deactivate_gcode = gcode_macro.load_template(
|
||||
config, 'deactivate_gcode', '')
|
||||
# Create an "endstop" object to handle the probe pin
|
||||
ppins = self.printer.lookup_object('pins')
|
||||
pin = config.get('pin')
|
||||
pin_params = ppins.lookup_pin(pin, can_invert=True, can_pullup=True)
|
||||
mcu = pin_params['chip']
|
||||
self.mcu_endstop = mcu.setup_pin('endstop', pin_params)
|
||||
self.mcu_probe = mcu_probe
|
||||
self.multi_probe_pending = False
|
||||
# Register z_virtual_endstop pin
|
||||
self.printer.lookup_object('pins').register_chip('probe', self)
|
||||
# Register event handlers
|
||||
self.printer.register_event_handler('klippy:mcu_identify',
|
||||
self._handle_mcu_identify)
|
||||
# Wrappers
|
||||
self.get_mcu = self.mcu_endstop.get_mcu
|
||||
self.add_stepper = self.mcu_endstop.add_stepper
|
||||
self.get_steppers = self.mcu_endstop.get_steppers
|
||||
self.home_start = self.mcu_endstop.home_start
|
||||
self.home_wait = self.mcu_endstop.home_wait
|
||||
self.query_endstop = self.mcu_endstop.query_endstop
|
||||
# multi probes state
|
||||
self.multi = 'OFF'
|
||||
self.printer.register_event_handler("homing:homing_move_begin",
|
||||
self._handle_homing_move_begin)
|
||||
self.printer.register_event_handler("homing:homing_move_end",
|
||||
self._handle_homing_move_end)
|
||||
self.printer.register_event_handler("homing:home_rails_begin",
|
||||
self._handle_home_rails_begin)
|
||||
self.printer.register_event_handler("homing:home_rails_end",
|
||||
self._handle_home_rails_end)
|
||||
self.printer.register_event_handler("gcode:command_error",
|
||||
self._handle_command_error)
|
||||
def _handle_mcu_identify(self):
|
||||
kin = self.printer.lookup_object('toolhead').get_kinematics()
|
||||
for stepper in kin.get_steppers():
|
||||
if stepper.is_active_axis('z'):
|
||||
self.add_stepper(stepper)
|
||||
def raise_probe(self):
|
||||
self.mcu_probe.add_stepper(stepper)
|
||||
def _handle_homing_move_begin(self, hmove):
|
||||
if self.mcu_probe in hmove.get_mcu_endstops():
|
||||
self.mcu_probe.probe_prepare(hmove)
|
||||
def _handle_homing_move_end(self, hmove):
|
||||
if self.mcu_probe in hmove.get_mcu_endstops():
|
||||
self.mcu_probe.probe_finish(hmove)
|
||||
def _handle_home_rails_begin(self, homing_state, rails):
|
||||
endstops = [es for rail in rails for es, name in rail.get_endstops()]
|
||||
if self.mcu_probe in endstops:
|
||||
self.mcu_probe.multi_probe_begin()
|
||||
self.multi_probe_pending = True
|
||||
def _handle_home_rails_end(self, homing_state, rails):
|
||||
endstops = [es for rail in rails for es, name in rail.get_endstops()]
|
||||
if self.multi_probe_pending and self.mcu_probe in endstops:
|
||||
self.multi_probe_pending = False
|
||||
self.mcu_probe.multi_probe_end()
|
||||
def _handle_command_error(self):
|
||||
if self.multi_probe_pending:
|
||||
self.multi_probe_pending = False
|
||||
try:
|
||||
self.mcu_probe.multi_probe_end()
|
||||
except:
|
||||
logging.exception("Homing multi-probe end")
|
||||
def setup_pin(self, pin_type, pin_params):
|
||||
if pin_type != 'endstop' or pin_params['pin'] != 'z_virtual_endstop':
|
||||
raise pins.error("Probe virtual endstop only useful as endstop pin")
|
||||
if pin_params['invert'] or pin_params['pullup']:
|
||||
raise pins.error("Can not pullup/invert probe virtual endstop")
|
||||
return self.mcu_probe
|
||||
|
||||
# Helper to track multiple probe attempts in a single command
|
||||
class ProbeSessionHelper:
|
||||
def __init__(self, config, mcu_probe):
|
||||
self.printer = config.get_printer()
|
||||
self.mcu_probe = mcu_probe
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
self.dummy_gcode_cmd = gcode.create_gcode_command("", "", {})
|
||||
# Infer Z position to move to during a probe
|
||||
if config.has_section('stepper_z'):
|
||||
zconfig = config.getsection('stepper_z')
|
||||
self.z_position = zconfig.getfloat('position_min', 0.,
|
||||
note_valid=False)
|
||||
else:
|
||||
pconfig = config.getsection('printer')
|
||||
self.z_position = pconfig.getfloat('minimum_z_position', 0.,
|
||||
note_valid=False)
|
||||
self.homing_helper = HomingViaProbeHelper(config, mcu_probe)
|
||||
# Configurable probing speeds
|
||||
self.speed = config.getfloat('speed', 5.0, above=0.)
|
||||
self.lift_speed = config.getfloat('lift_speed', self.speed, above=0.)
|
||||
# Multi-sample support (for improved accuracy)
|
||||
self.sample_count = config.getint('samples', 1, minval=1)
|
||||
self.sample_retract_dist = config.getfloat('sample_retract_dist', 2.,
|
||||
above=0.)
|
||||
atypes = ['median', 'average']
|
||||
self.samples_result = config.getchoice('samples_result', atypes,
|
||||
'average')
|
||||
self.samples_tolerance = config.getfloat('samples_tolerance', 0.100,
|
||||
minval=0.)
|
||||
self.samples_retries = config.getint('samples_tolerance_retries', 0,
|
||||
minval=0)
|
||||
# Session state
|
||||
self.multi_probe_pending = False
|
||||
self.results = []
|
||||
# Register event handlers
|
||||
self.printer.register_event_handler("gcode:command_error",
|
||||
self._handle_command_error)
|
||||
def _handle_command_error(self):
|
||||
if self.multi_probe_pending:
|
||||
try:
|
||||
self.end_probe_session()
|
||||
except:
|
||||
logging.exception("Multi-probe end")
|
||||
def _probe_state_error(self):
|
||||
raise self.printer.command_error(
|
||||
"Internal probe error - start/end probe session mismatch")
|
||||
def start_probe_session(self, gcmd):
|
||||
if self.multi_probe_pending:
|
||||
self._probe_state_error()
|
||||
self.mcu_probe.multi_probe_begin()
|
||||
self.multi_probe_pending = True
|
||||
self.results = []
|
||||
return self
|
||||
def end_probe_session(self):
|
||||
if not self.multi_probe_pending:
|
||||
self._probe_state_error()
|
||||
self.results = []
|
||||
self.multi_probe_pending = False
|
||||
self.mcu_probe.multi_probe_end()
|
||||
def get_probe_params(self, gcmd=None):
|
||||
if gcmd is None:
|
||||
gcmd = self.dummy_gcode_cmd
|
||||
probe_speed = gcmd.get_float("PROBE_SPEED", self.speed, above=0.)
|
||||
lift_speed = gcmd.get_float("LIFT_SPEED", self.lift_speed, above=0.)
|
||||
samples = gcmd.get_int("SAMPLES", self.sample_count, minval=1)
|
||||
sample_retract_dist = gcmd.get_float("SAMPLE_RETRACT_DIST",
|
||||
self.sample_retract_dist, above=0.)
|
||||
samples_tolerance = gcmd.get_float("SAMPLES_TOLERANCE",
|
||||
self.samples_tolerance, minval=0.)
|
||||
samples_retries = gcmd.get_int("SAMPLES_TOLERANCE_RETRIES",
|
||||
self.samples_retries, minval=0)
|
||||
samples_result = gcmd.get("SAMPLES_RESULT", self.samples_result)
|
||||
return {'probe_speed': probe_speed,
|
||||
'lift_speed': lift_speed,
|
||||
'samples': samples,
|
||||
'sample_retract_dist': sample_retract_dist,
|
||||
'samples_tolerance': samples_tolerance,
|
||||
'samples_tolerance_retries': samples_retries,
|
||||
'samples_result': samples_result}
|
||||
def _probe(self, speed):
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
start_pos = toolhead.get_position()
|
||||
self.deactivate_gcode.run_gcode_from_command()
|
||||
if toolhead.get_position()[:3] != start_pos[:3]:
|
||||
raise self.printer.command_error(
|
||||
"Toolhead moved during probe activate_gcode script")
|
||||
def lower_probe(self):
|
||||
curtime = self.printer.get_reactor().monotonic()
|
||||
if 'z' not in toolhead.get_status(curtime)['homed_axes']:
|
||||
raise self.printer.command_error("Must home before probe")
|
||||
pos = toolhead.get_position()
|
||||
pos[2] = self.z_position
|
||||
try:
|
||||
epos = self.mcu_probe.probing_move(pos, speed)
|
||||
except self.printer.command_error as e:
|
||||
reason = str(e)
|
||||
if "Timeout during endstop homing" in reason:
|
||||
reason += HINT_TIMEOUT
|
||||
raise self.printer.command_error(reason)
|
||||
# Allow axis_twist_compensation to update results
|
||||
self.printer.send_event("probe:update_results", epos)
|
||||
# Report results
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
gcode.respond_info("probe at %.3f,%.3f is z=%.6f"
|
||||
% (epos[0], epos[1], epos[2]))
|
||||
return epos[:3]
|
||||
def run_probe(self, gcmd):
|
||||
if not self.multi_probe_pending:
|
||||
self._probe_state_error()
|
||||
params = self.get_probe_params(gcmd)
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
start_pos = toolhead.get_position()
|
||||
self.activate_gcode.run_gcode_from_command()
|
||||
if toolhead.get_position()[:3] != start_pos[:3]:
|
||||
raise self.printer.command_error(
|
||||
"Toolhead moved during probe deactivate_gcode script")
|
||||
def multi_probe_begin(self):
|
||||
if self.stow_on_each_sample:
|
||||
return
|
||||
self.multi = 'FIRST'
|
||||
def multi_probe_end(self):
|
||||
if self.stow_on_each_sample:
|
||||
return
|
||||
self.raise_probe()
|
||||
self.multi = 'OFF'
|
||||
def probe_prepare(self, hmove):
|
||||
if self.multi == 'OFF' or self.multi == 'FIRST':
|
||||
self.lower_probe()
|
||||
if self.multi == 'FIRST':
|
||||
self.multi = 'ON'
|
||||
def probe_finish(self, hmove):
|
||||
if self.multi == 'OFF':
|
||||
self.raise_probe()
|
||||
def get_position_endstop(self):
|
||||
return self.position_endstop
|
||||
probexy = toolhead.get_position()[:2]
|
||||
retries = 0
|
||||
positions = []
|
||||
sample_count = params['samples']
|
||||
while len(positions) < sample_count:
|
||||
# Probe position
|
||||
pos = self._probe(params['probe_speed'])
|
||||
positions.append(pos)
|
||||
# Check samples tolerance
|
||||
z_positions = [p[2] for p in positions]
|
||||
if max(z_positions)-min(z_positions) > params['samples_tolerance']:
|
||||
if retries >= params['samples_tolerance_retries']:
|
||||
raise gcmd.error("Probe samples exceed samples_tolerance")
|
||||
gcmd.respond_info("Probe samples exceed tolerance. Retrying...")
|
||||
retries += 1
|
||||
positions = []
|
||||
# Retract
|
||||
if len(positions) < sample_count:
|
||||
toolhead.manual_move(
|
||||
probexy + [pos[2] + params['sample_retract_dist']],
|
||||
params['lift_speed'])
|
||||
# Calculate result
|
||||
epos = calc_probe_z_average(positions, params['samples_result'])
|
||||
self.results.append(epos)
|
||||
def pull_probed_results(self):
|
||||
res = self.results
|
||||
self.results = []
|
||||
return res
|
||||
|
||||
# Helper to read the xyz probe offsets from the config
|
||||
class ProbeOffsetsHelper:
|
||||
def __init__(self, config):
|
||||
self.x_offset = config.getfloat('x_offset', 0.)
|
||||
self.y_offset = config.getfloat('y_offset', 0.)
|
||||
self.z_offset = config.getfloat('z_offset')
|
||||
def get_offsets(self):
|
||||
return self.x_offset, self.y_offset, self.z_offset
|
||||
|
||||
|
||||
######################################################################
|
||||
# Tools for utilizing the probe
|
||||
######################################################################
|
||||
|
||||
# Helper code that can probe a series of points and report the
|
||||
# position at each point.
|
||||
@@ -379,7 +396,7 @@ class ProbePointsHelper:
|
||||
# Internal probing state
|
||||
self.lift_speed = self.speed
|
||||
self.probe_offsets = (0., 0., 0.)
|
||||
self.results = []
|
||||
self.manual_results = []
|
||||
def minimum_points(self,n):
|
||||
if len(self.probe_points) < n:
|
||||
raise self.printer.config_error(
|
||||
@@ -391,68 +408,173 @@ class ProbePointsHelper:
|
||||
self.use_offsets = use_offsets
|
||||
def get_lift_speed(self):
|
||||
return self.lift_speed
|
||||
def _move_next(self):
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
# Lift toolhead
|
||||
def _move(self, coord, speed):
|
||||
self.printer.lookup_object('toolhead').manual_move(coord, speed)
|
||||
def _raise_tool(self, is_first=False):
|
||||
speed = self.lift_speed
|
||||
if not self.results:
|
||||
if is_first:
|
||||
# Use full speed to first probe position
|
||||
speed = self.speed
|
||||
toolhead.manual_move([None, None, self.horizontal_move_z], speed)
|
||||
# Check if done probing
|
||||
if len(self.results) >= len(self.probe_points):
|
||||
toolhead.get_last_move_time()
|
||||
res = self.finalize_callback(self.probe_offsets, self.results)
|
||||
if res != "retry":
|
||||
return True
|
||||
self.results = []
|
||||
self._move([None, None, self.horizontal_move_z], speed)
|
||||
def _invoke_callback(self, results):
|
||||
# Flush lookahead queue
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
toolhead.get_last_move_time()
|
||||
# Invoke callback
|
||||
res = self.finalize_callback(self.probe_offsets, results)
|
||||
return res != "retry"
|
||||
def _move_next(self, probe_num):
|
||||
# Move to next XY probe point
|
||||
nextpos = list(self.probe_points[len(self.results)])
|
||||
nextpos = list(self.probe_points[probe_num])
|
||||
if self.use_offsets:
|
||||
nextpos[0] -= self.probe_offsets[0]
|
||||
nextpos[1] -= self.probe_offsets[1]
|
||||
toolhead.manual_move(nextpos, self.speed)
|
||||
return False
|
||||
self._move(nextpos, self.speed)
|
||||
def start_probe(self, gcmd):
|
||||
manual_probe.verify_no_manual_probe(self.printer)
|
||||
# Lookup objects
|
||||
probe = self.printer.lookup_object('probe', None)
|
||||
method = gcmd.get('METHOD', 'automatic').lower()
|
||||
self.results = []
|
||||
def_move_z = self.default_horizontal_move_z
|
||||
self.horizontal_move_z = gcmd.get_float('HORIZONTAL_MOVE_Z',
|
||||
def_move_z)
|
||||
if probe is None or method != 'automatic':
|
||||
if probe is None or method == 'manual':
|
||||
# Manual probe
|
||||
self.lift_speed = self.speed
|
||||
self.probe_offsets = (0., 0., 0.)
|
||||
self.manual_results = []
|
||||
self._manual_probe_start()
|
||||
return
|
||||
# Perform automatic probing
|
||||
self.lift_speed = probe.get_lift_speed(gcmd)
|
||||
self.lift_speed = probe.get_probe_params(gcmd)['lift_speed']
|
||||
self.probe_offsets = probe.get_offsets()
|
||||
if self.horizontal_move_z < self.probe_offsets[2]:
|
||||
raise gcmd.error("horizontal_move_z can't be less than"
|
||||
" probe's z_offset")
|
||||
probe.multi_probe_begin()
|
||||
probe_session = probe.start_probe_session(gcmd)
|
||||
probe_num = 0
|
||||
while 1:
|
||||
done = self._move_next()
|
||||
if done:
|
||||
break
|
||||
pos = probe.run_probe(gcmd)
|
||||
self.results.append(pos)
|
||||
probe.multi_probe_end()
|
||||
self._raise_tool(not probe_num)
|
||||
if probe_num >= len(self.probe_points):
|
||||
results = probe_session.pull_probed_results()
|
||||
done = self._invoke_callback(results)
|
||||
if done:
|
||||
break
|
||||
# Caller wants a "retry" - restart probing
|
||||
probe_num = 0
|
||||
self._move_next(probe_num)
|
||||
probe_session.run_probe(gcmd)
|
||||
probe_num += 1
|
||||
probe_session.end_probe_session()
|
||||
def _manual_probe_start(self):
|
||||
done = self._move_next()
|
||||
if not done:
|
||||
gcmd = self.gcode.create_gcode_command("", "", {})
|
||||
manual_probe.ManualProbeHelper(self.printer, gcmd,
|
||||
self._manual_probe_finalize)
|
||||
self._raise_tool(not self.manual_results)
|
||||
if len(self.manual_results) >= len(self.probe_points):
|
||||
done = self._invoke_callback(self.manual_results)
|
||||
if done:
|
||||
return
|
||||
# Caller wants a "retry" - clear results and restart probing
|
||||
self.manual_results = []
|
||||
self._move_next(len(self.manual_results))
|
||||
gcmd = self.gcode.create_gcode_command("", "", {})
|
||||
manual_probe.ManualProbeHelper(self.printer, gcmd,
|
||||
self._manual_probe_finalize)
|
||||
def _manual_probe_finalize(self, kin_pos):
|
||||
if kin_pos is None:
|
||||
return
|
||||
self.results.append(kin_pos)
|
||||
self.manual_results.append(kin_pos)
|
||||
self._manual_probe_start()
|
||||
|
||||
# Helper to obtain a single probe measurement
|
||||
def run_single_probe(probe, gcmd):
|
||||
probe_session = probe.start_probe_session(gcmd)
|
||||
probe_session.run_probe(gcmd)
|
||||
pos = probe_session.pull_probed_results()[0]
|
||||
probe_session.end_probe_session()
|
||||
return pos
|
||||
|
||||
|
||||
######################################################################
|
||||
# Handle [probe] config
|
||||
######################################################################
|
||||
|
||||
# Endstop wrapper that enables probe specific features
|
||||
class ProbeEndstopWrapper:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
self.position_endstop = config.getfloat('z_offset')
|
||||
self.stow_on_each_sample = config.getboolean(
|
||||
'deactivate_on_each_sample', True)
|
||||
gcode_macro = self.printer.load_object(config, 'gcode_macro')
|
||||
self.activate_gcode = gcode_macro.load_template(
|
||||
config, 'activate_gcode', '')
|
||||
self.deactivate_gcode = gcode_macro.load_template(
|
||||
config, 'deactivate_gcode', '')
|
||||
# Create an "endstop" object to handle the probe pin
|
||||
ppins = self.printer.lookup_object('pins')
|
||||
self.mcu_endstop = ppins.setup_pin('endstop', config.get('pin'))
|
||||
# Wrappers
|
||||
self.get_mcu = self.mcu_endstop.get_mcu
|
||||
self.add_stepper = self.mcu_endstop.add_stepper
|
||||
self.get_steppers = self.mcu_endstop.get_steppers
|
||||
self.home_start = self.mcu_endstop.home_start
|
||||
self.home_wait = self.mcu_endstop.home_wait
|
||||
self.query_endstop = self.mcu_endstop.query_endstop
|
||||
# multi probes state
|
||||
self.multi = 'OFF'
|
||||
def _raise_probe(self):
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
start_pos = toolhead.get_position()
|
||||
self.deactivate_gcode.run_gcode_from_command()
|
||||
if toolhead.get_position()[:3] != start_pos[:3]:
|
||||
raise self.printer.command_error(
|
||||
"Toolhead moved during probe deactivate_gcode script")
|
||||
def _lower_probe(self):
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
start_pos = toolhead.get_position()
|
||||
self.activate_gcode.run_gcode_from_command()
|
||||
if toolhead.get_position()[:3] != start_pos[:3]:
|
||||
raise self.printer.command_error(
|
||||
"Toolhead moved during probe activate_gcode script")
|
||||
def multi_probe_begin(self):
|
||||
if self.stow_on_each_sample:
|
||||
return
|
||||
self.multi = 'FIRST'
|
||||
def multi_probe_end(self):
|
||||
if self.stow_on_each_sample:
|
||||
return
|
||||
self._raise_probe()
|
||||
self.multi = 'OFF'
|
||||
def probing_move(self, pos, speed):
|
||||
phoming = self.printer.lookup_object('homing')
|
||||
return phoming.probing_move(self, pos, speed)
|
||||
def probe_prepare(self, hmove):
|
||||
if self.multi == 'OFF' or self.multi == 'FIRST':
|
||||
self._lower_probe()
|
||||
if self.multi == 'FIRST':
|
||||
self.multi = 'ON'
|
||||
def probe_finish(self, hmove):
|
||||
if self.multi == 'OFF':
|
||||
self._raise_probe()
|
||||
def get_position_endstop(self):
|
||||
return self.position_endstop
|
||||
|
||||
# Main external probe interface
|
||||
class PrinterProbe:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
self.mcu_probe = ProbeEndstopWrapper(config)
|
||||
self.cmd_helper = ProbeCommandHelper(config, self,
|
||||
self.mcu_probe.query_endstop)
|
||||
self.probe_offsets = ProbeOffsetsHelper(config)
|
||||
self.probe_session = ProbeSessionHelper(config, self.mcu_probe)
|
||||
def get_probe_params(self, gcmd=None):
|
||||
return self.probe_session.get_probe_params(gcmd)
|
||||
def get_offsets(self):
|
||||
return self.probe_offsets.get_offsets()
|
||||
def get_status(self, eventtime):
|
||||
return self.cmd_helper.get_status(eventtime)
|
||||
def start_probe_session(self, gcmd):
|
||||
return self.probe_session.start_probe_session(gcmd)
|
||||
|
||||
def load_config(config):
|
||||
return PrinterProbe(config, ProbeEndstopWrapper(config))
|
||||
return PrinterProbe(config)
|
||||
|
||||
464
klippy/extras/probe_eddy_current.py
Normal file
464
klippy/extras/probe_eddy_current.py
Normal file
@@ -0,0 +1,464 @@
|
||||
# Support for eddy current based Z probes
|
||||
#
|
||||
# Copyright (C) 2021-2024 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging, math, bisect
|
||||
import mcu
|
||||
from . import ldc1612, probe, manual_probe
|
||||
|
||||
OUT_OF_RANGE = 99.9
|
||||
|
||||
# Tool for calibrating the sensor Z detection and applying that calibration
|
||||
class EddyCalibration:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
self.name = config.get_name()
|
||||
self.drift_comp = DummyDriftCompensation()
|
||||
# Current calibration data
|
||||
self.cal_freqs = []
|
||||
self.cal_zpos = []
|
||||
cal = config.get('calibrate', None)
|
||||
if cal is not None:
|
||||
cal = [list(map(float, d.strip().split(':', 1)))
|
||||
for d in cal.split(',')]
|
||||
self.load_calibration(cal)
|
||||
# Probe calibrate state
|
||||
self.probe_speed = 0.
|
||||
# Register commands
|
||||
cname = self.name.split()[-1]
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
gcode.register_mux_command("PROBE_EDDY_CURRENT_CALIBRATE", "CHIP",
|
||||
cname, self.cmd_EDDY_CALIBRATE,
|
||||
desc=self.cmd_EDDY_CALIBRATE_help)
|
||||
def is_calibrated(self):
|
||||
return len(self.cal_freqs) > 2
|
||||
def load_calibration(self, cal):
|
||||
cal = sorted([(c[1], c[0]) for c in cal])
|
||||
self.cal_freqs = [c[0] for c in cal]
|
||||
self.cal_zpos = [c[1] for c in cal]
|
||||
def apply_calibration(self, samples):
|
||||
cur_temp = self.drift_comp.get_temperature()
|
||||
for i, (samp_time, freq, dummy_z) in enumerate(samples):
|
||||
adj_freq = self.drift_comp.adjust_freq(freq, cur_temp)
|
||||
pos = bisect.bisect(self.cal_freqs, adj_freq)
|
||||
if pos >= len(self.cal_zpos):
|
||||
zpos = -OUT_OF_RANGE
|
||||
elif pos == 0:
|
||||
zpos = OUT_OF_RANGE
|
||||
else:
|
||||
# XXX - could further optimize and avoid div by zero
|
||||
this_freq = self.cal_freqs[pos]
|
||||
prev_freq = self.cal_freqs[pos - 1]
|
||||
this_zpos = self.cal_zpos[pos]
|
||||
prev_zpos = self.cal_zpos[pos - 1]
|
||||
gain = (this_zpos - prev_zpos) / (this_freq - prev_freq)
|
||||
offset = prev_zpos - prev_freq * gain
|
||||
zpos = adj_freq * gain + offset
|
||||
samples[i] = (samp_time, freq, round(zpos, 6))
|
||||
def freq_to_height(self, freq):
|
||||
dummy_sample = [(0., freq, 0.)]
|
||||
self.apply_calibration(dummy_sample)
|
||||
return dummy_sample[0][2]
|
||||
def height_to_freq(self, height):
|
||||
# XXX - could optimize lookup
|
||||
rev_zpos = list(reversed(self.cal_zpos))
|
||||
rev_freqs = list(reversed(self.cal_freqs))
|
||||
pos = bisect.bisect(rev_zpos, height)
|
||||
if pos == 0 or pos >= len(rev_zpos):
|
||||
raise self.printer.command_error(
|
||||
"Invalid probe_eddy_current height")
|
||||
this_freq = rev_freqs[pos]
|
||||
prev_freq = rev_freqs[pos - 1]
|
||||
this_zpos = rev_zpos[pos]
|
||||
prev_zpos = rev_zpos[pos - 1]
|
||||
gain = (this_freq - prev_freq) / (this_zpos - prev_zpos)
|
||||
offset = prev_freq - prev_zpos * gain
|
||||
freq = height * gain + offset
|
||||
return self.drift_comp.unadjust_freq(freq)
|
||||
def do_calibration_moves(self, move_speed):
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
kin = toolhead.get_kinematics()
|
||||
move = toolhead.manual_move
|
||||
# Start data collection
|
||||
msgs = []
|
||||
is_finished = False
|
||||
def handle_batch(msg):
|
||||
if is_finished:
|
||||
return False
|
||||
msgs.append(msg)
|
||||
return True
|
||||
self.printer.lookup_object(self.name).add_client(handle_batch)
|
||||
toolhead.dwell(1.)
|
||||
self.drift_comp.note_z_calibration_start()
|
||||
# Move to each 40um position
|
||||
max_z = 4.0
|
||||
samp_dist = 0.040
|
||||
req_zpos = [i*samp_dist for i in range(int(max_z / samp_dist) + 1)]
|
||||
start_pos = toolhead.get_position()
|
||||
times = []
|
||||
for zpos in req_zpos:
|
||||
# Move to next position (always descending to reduce backlash)
|
||||
hop_pos = list(start_pos)
|
||||
hop_pos[2] += zpos + 0.500
|
||||
move(hop_pos, move_speed)
|
||||
next_pos = list(start_pos)
|
||||
next_pos[2] += zpos
|
||||
move(next_pos, move_speed)
|
||||
# Note sample timing
|
||||
start_query_time = toolhead.get_last_move_time() + 0.050
|
||||
end_query_time = start_query_time + 0.100
|
||||
toolhead.dwell(0.200)
|
||||
# Find Z position based on actual commanded stepper position
|
||||
toolhead.flush_step_generation()
|
||||
kin_spos = {s.get_name(): s.get_commanded_position()
|
||||
for s in kin.get_steppers()}
|
||||
kin_pos = kin.calc_position(kin_spos)
|
||||
times.append((start_query_time, end_query_time, kin_pos[2]))
|
||||
toolhead.dwell(1.0)
|
||||
toolhead.wait_moves()
|
||||
self.drift_comp.note_z_calibration_finish()
|
||||
# Finish data collection
|
||||
is_finished = True
|
||||
# Correlate query responses
|
||||
cal = {}
|
||||
step = 0
|
||||
for msg in msgs:
|
||||
for query_time, freq, old_z in msg['data']:
|
||||
# Add to step tracking
|
||||
while step < len(times) and query_time > times[step][1]:
|
||||
step += 1
|
||||
if step < len(times) and query_time >= times[step][0]:
|
||||
cal.setdefault(times[step][2], []).append(freq)
|
||||
if len(cal) != len(times):
|
||||
raise self.printer.command_error(
|
||||
"Failed calibration - incomplete sensor data")
|
||||
return cal
|
||||
def calc_freqs(self, meas):
|
||||
total_count = total_variance = 0
|
||||
positions = {}
|
||||
for pos, freqs in meas.items():
|
||||
count = len(freqs)
|
||||
freq_avg = float(sum(freqs)) / count
|
||||
positions[pos] = freq_avg
|
||||
total_count += count
|
||||
total_variance += sum([(f - freq_avg)**2 for f in freqs])
|
||||
return positions, math.sqrt(total_variance / total_count), total_count
|
||||
def post_manual_probe(self, kin_pos):
|
||||
if kin_pos is None:
|
||||
# Manual Probe was aborted
|
||||
return
|
||||
curpos = list(kin_pos)
|
||||
move = self.printer.lookup_object('toolhead').manual_move
|
||||
# Move away from the bed
|
||||
probe_calibrate_z = curpos[2]
|
||||
curpos[2] += 5.
|
||||
move(curpos, self.probe_speed)
|
||||
# Move sensor over nozzle position
|
||||
pprobe = self.printer.lookup_object("probe")
|
||||
x_offset, y_offset, z_offset = pprobe.get_offsets()
|
||||
curpos[0] -= x_offset
|
||||
curpos[1] -= y_offset
|
||||
move(curpos, self.probe_speed)
|
||||
# Descend back to bed
|
||||
curpos[2] -= 5. - 0.050
|
||||
move(curpos, self.probe_speed)
|
||||
# Perform calibration movement and capture
|
||||
cal = self.do_calibration_moves(self.probe_speed)
|
||||
# Calculate each sample position average and variance
|
||||
positions, std, total = self.calc_freqs(cal)
|
||||
last_freq = 0.
|
||||
for pos, freq in reversed(sorted(positions.items())):
|
||||
if freq <= last_freq:
|
||||
raise self.printer.command_error(
|
||||
"Failed calibration - frequency not increasing each step")
|
||||
last_freq = freq
|
||||
gcode = self.printer.lookup_object("gcode")
|
||||
gcode.respond_info(
|
||||
"probe_eddy_current: stddev=%.3f in %d queries\n"
|
||||
"The SAVE_CONFIG command will update the printer config file\n"
|
||||
"and restart the printer." % (std, total))
|
||||
# Save results
|
||||
cal_contents = []
|
||||
for i, (pos, freq) in enumerate(sorted(positions.items())):
|
||||
if not i % 3:
|
||||
cal_contents.append('\n')
|
||||
cal_contents.append("%.6f:%.3f" % (pos - probe_calibrate_z, freq))
|
||||
cal_contents.append(',')
|
||||
cal_contents.pop()
|
||||
configfile = self.printer.lookup_object('configfile')
|
||||
configfile.set(self.name, 'calibrate', ''.join(cal_contents))
|
||||
cmd_EDDY_CALIBRATE_help = "Calibrate eddy current probe"
|
||||
def cmd_EDDY_CALIBRATE(self, gcmd):
|
||||
self.probe_speed = gcmd.get_float("PROBE_SPEED", 5., above=0.)
|
||||
# Start manual probe
|
||||
manual_probe.ManualProbeHelper(self.printer, gcmd,
|
||||
self.post_manual_probe)
|
||||
def register_drift_compensation(self, comp):
|
||||
self.drift_comp = comp
|
||||
|
||||
# Tool to gather samples and convert them to probe positions
|
||||
class EddyGatherSamples:
|
||||
def __init__(self, printer, sensor_helper, calibration, z_offset):
|
||||
self._printer = printer
|
||||
self._sensor_helper = sensor_helper
|
||||
self._calibration = calibration
|
||||
self._z_offset = z_offset
|
||||
# Results storage
|
||||
self._samples = []
|
||||
self._probe_times = []
|
||||
self._probe_results = []
|
||||
self._need_stop = False
|
||||
# Start samples
|
||||
if not self._calibration.is_calibrated():
|
||||
raise self._printer.command_error(
|
||||
"Must calibrate probe_eddy_current first")
|
||||
sensor_helper.add_client(self._add_measurement)
|
||||
def _add_measurement(self, msg):
|
||||
if self._need_stop:
|
||||
del self._samples[:]
|
||||
return False
|
||||
self._samples.append(msg)
|
||||
self._check_samples()
|
||||
return True
|
||||
def finish(self):
|
||||
self._need_stop = True
|
||||
def _await_samples(self):
|
||||
# Make sure enough samples have been collected
|
||||
reactor = self._printer.get_reactor()
|
||||
mcu = self._sensor_helper.get_mcu()
|
||||
while self._probe_times:
|
||||
start_time, end_time, pos_time, toolhead_pos = self._probe_times[0]
|
||||
systime = reactor.monotonic()
|
||||
est_print_time = mcu.estimated_print_time(systime)
|
||||
if est_print_time > end_time + 1.0:
|
||||
raise self._printer.command_error(
|
||||
"probe_eddy_current sensor outage")
|
||||
reactor.pause(systime + 0.010)
|
||||
def _pull_freq(self, start_time, end_time):
|
||||
# Find average sensor frequency between time range
|
||||
msg_num = discard_msgs = 0
|
||||
samp_sum = 0.
|
||||
samp_count = 0
|
||||
while msg_num < len(self._samples):
|
||||
msg = self._samples[msg_num]
|
||||
msg_num += 1
|
||||
data = msg['data']
|
||||
if data[0][0] > end_time:
|
||||
break
|
||||
if data[-1][0] < start_time:
|
||||
discard_msgs = msg_num
|
||||
continue
|
||||
for time, freq, z in data:
|
||||
if time >= start_time and time <= end_time:
|
||||
samp_sum += freq
|
||||
samp_count += 1
|
||||
del self._samples[:discard_msgs]
|
||||
if not samp_count:
|
||||
# No sensor readings - raise error in pull_probed()
|
||||
return 0.
|
||||
return samp_sum / samp_count
|
||||
def _lookup_toolhead_pos(self, pos_time):
|
||||
toolhead = self._printer.lookup_object('toolhead')
|
||||
kin = toolhead.get_kinematics()
|
||||
kin_spos = {s.get_name(): s.mcu_to_commanded_position(
|
||||
s.get_past_mcu_position(pos_time))
|
||||
for s in kin.get_steppers()}
|
||||
return kin.calc_position(kin_spos)
|
||||
def _check_samples(self):
|
||||
while self._samples and self._probe_times:
|
||||
start_time, end_time, pos_time, toolhead_pos = self._probe_times[0]
|
||||
if self._samples[-1]['data'][-1][0] < end_time:
|
||||
break
|
||||
freq = self._pull_freq(start_time, end_time)
|
||||
if pos_time is not None:
|
||||
toolhead_pos = self._lookup_toolhead_pos(pos_time)
|
||||
sensor_z = None
|
||||
if freq:
|
||||
sensor_z = self._calibration.freq_to_height(freq)
|
||||
self._probe_results.append((sensor_z, toolhead_pos))
|
||||
self._probe_times.pop(0)
|
||||
def pull_probed(self):
|
||||
self._await_samples()
|
||||
results = []
|
||||
for sensor_z, toolhead_pos in self._probe_results:
|
||||
if sensor_z is None:
|
||||
raise self._printer.command_error(
|
||||
"Unable to obtain probe_eddy_current sensor readings")
|
||||
if sensor_z <= -OUT_OF_RANGE or sensor_z >= OUT_OF_RANGE:
|
||||
raise self._printer.command_error(
|
||||
"probe_eddy_current sensor not in valid range")
|
||||
# Callers expect position relative to z_offset, so recalculate
|
||||
bed_deviation = toolhead_pos[2] - sensor_z
|
||||
toolhead_pos[2] = self._z_offset + bed_deviation
|
||||
results.append(toolhead_pos)
|
||||
del self._probe_results[:]
|
||||
return results
|
||||
def note_probe(self, start_time, end_time, toolhead_pos):
|
||||
self._probe_times.append((start_time, end_time, None, toolhead_pos))
|
||||
self._check_samples()
|
||||
def note_probe_and_position(self, start_time, end_time, pos_time):
|
||||
self._probe_times.append((start_time, end_time, pos_time, None))
|
||||
self._check_samples()
|
||||
|
||||
# Helper for implementing PROBE style commands (descend until trigger)
|
||||
class EddyEndstopWrapper:
|
||||
REASON_SENSOR_ERROR = mcu.MCU_trsync.REASON_COMMS_TIMEOUT + 1
|
||||
def __init__(self, config, sensor_helper, calibration):
|
||||
self._printer = config.get_printer()
|
||||
self._sensor_helper = sensor_helper
|
||||
self._mcu = sensor_helper.get_mcu()
|
||||
self._calibration = calibration
|
||||
self._z_offset = config.getfloat('z_offset', minval=0.)
|
||||
self._dispatch = mcu.TriggerDispatch(self._mcu)
|
||||
self._trigger_time = 0.
|
||||
self._gather = None
|
||||
# Interface for MCU_endstop
|
||||
def get_mcu(self):
|
||||
return self._mcu
|
||||
def add_stepper(self, stepper):
|
||||
self._dispatch.add_stepper(stepper)
|
||||
def get_steppers(self):
|
||||
return self._dispatch.get_steppers()
|
||||
def home_start(self, print_time, sample_time, sample_count, rest_time,
|
||||
triggered=True):
|
||||
self._trigger_time = 0.
|
||||
trigger_freq = self._calibration.height_to_freq(self._z_offset)
|
||||
trigger_completion = self._dispatch.start(print_time)
|
||||
self._sensor_helper.setup_home(
|
||||
print_time, trigger_freq, self._dispatch.get_oid(),
|
||||
mcu.MCU_trsync.REASON_ENDSTOP_HIT, self.REASON_SENSOR_ERROR)
|
||||
return trigger_completion
|
||||
def home_wait(self, home_end_time):
|
||||
self._dispatch.wait_end(home_end_time)
|
||||
trigger_time = self._sensor_helper.clear_home()
|
||||
res = self._dispatch.stop()
|
||||
if res >= mcu.MCU_trsync.REASON_COMMS_TIMEOUT:
|
||||
if res == mcu.MCU_trsync.REASON_COMMS_TIMEOUT:
|
||||
raise self._printer.command_error(
|
||||
"Communication timeout during homing")
|
||||
raise self._printer.command_error("Eddy current sensor error")
|
||||
if res != mcu.MCU_trsync.REASON_ENDSTOP_HIT:
|
||||
return 0.
|
||||
if self._mcu.is_fileoutput():
|
||||
return home_end_time
|
||||
self._trigger_time = trigger_time
|
||||
return trigger_time
|
||||
def query_endstop(self, print_time):
|
||||
return False # XXX
|
||||
# Interface for ProbeEndstopWrapper
|
||||
def probing_move(self, pos, speed):
|
||||
# Perform probing move
|
||||
phoming = self._printer.lookup_object('homing')
|
||||
trig_pos = phoming.probing_move(self, pos, speed)
|
||||
if not self._trigger_time:
|
||||
return trig_pos
|
||||
# Extract samples
|
||||
start_time = self._trigger_time + 0.050
|
||||
end_time = start_time + 0.100
|
||||
toolhead = self._printer.lookup_object("toolhead")
|
||||
toolhead_pos = toolhead.get_position()
|
||||
self._gather.note_probe(start_time, end_time, toolhead_pos)
|
||||
return self._gather.pull_probed()[0]
|
||||
def multi_probe_begin(self):
|
||||
self._gather = EddyGatherSamples(self._printer, self._sensor_helper,
|
||||
self._calibration, self._z_offset)
|
||||
def multi_probe_end(self):
|
||||
self._gather.finish()
|
||||
self._gather = None
|
||||
def probe_prepare(self, hmove):
|
||||
pass
|
||||
def probe_finish(self, hmove):
|
||||
pass
|
||||
def get_position_endstop(self):
|
||||
return self._z_offset
|
||||
|
||||
# Implementing probing with "METHOD=scan"
|
||||
class EddyScanningProbe:
|
||||
def __init__(self, printer, sensor_helper, calibration, z_offset, gcmd):
|
||||
self._printer = printer
|
||||
self._sensor_helper = sensor_helper
|
||||
self._calibration = calibration
|
||||
self._z_offset = z_offset
|
||||
self._gather = EddyGatherSamples(printer, sensor_helper,
|
||||
calibration, z_offset)
|
||||
self._sample_time_delay = 0.050
|
||||
self._sample_time = gcmd.get_float("SAMPLE_TIME", 0.100, above=0.0)
|
||||
self._is_rapid = gcmd.get("METHOD", "scan") == 'rapid_scan'
|
||||
def _rapid_lookahead_cb(self, printtime):
|
||||
start_time = printtime - self._sample_time / 2
|
||||
self._gather.note_probe_and_position(
|
||||
start_time, start_time + self._sample_time, printtime)
|
||||
def run_probe(self, gcmd):
|
||||
toolhead = self._printer.lookup_object("toolhead")
|
||||
if self._is_rapid:
|
||||
toolhead.register_lookahead_callback(self._rapid_lookahead_cb)
|
||||
return
|
||||
printtime = toolhead.get_last_move_time()
|
||||
toolhead.dwell(self._sample_time_delay + self._sample_time)
|
||||
start_time = printtime + self._sample_time_delay
|
||||
self._gather.note_probe_and_position(
|
||||
start_time, start_time + self._sample_time, start_time)
|
||||
def pull_probed_results(self):
|
||||
if self._is_rapid:
|
||||
# Flush lookahead (so all lookahead callbacks are invoked)
|
||||
toolhead = self._printer.lookup_object("toolhead")
|
||||
toolhead.get_last_move_time()
|
||||
results = self._gather.pull_probed()
|
||||
# Allow axis_twist_compensation to update results
|
||||
for epos in results:
|
||||
self._printer.send_event("probe:update_results", epos)
|
||||
return results
|
||||
def end_probe_session(self):
|
||||
self._gather.finish()
|
||||
self._gather = None
|
||||
|
||||
# Main "printer object"
|
||||
class PrinterEddyProbe:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
self.calibration = EddyCalibration(config)
|
||||
# Sensor type
|
||||
sensors = { "ldc1612": ldc1612.LDC1612 }
|
||||
sensor_type = config.getchoice('sensor_type', {s: s for s in sensors})
|
||||
self.sensor_helper = sensors[sensor_type](config, self.calibration)
|
||||
# Probe interface
|
||||
self.mcu_probe = EddyEndstopWrapper(config, self.sensor_helper,
|
||||
self.calibration)
|
||||
self.cmd_helper = probe.ProbeCommandHelper(
|
||||
config, self, self.mcu_probe.query_endstop)
|
||||
self.probe_offsets = probe.ProbeOffsetsHelper(config)
|
||||
self.probe_session = probe.ProbeSessionHelper(config, self.mcu_probe)
|
||||
self.printer.add_object('probe', self)
|
||||
def add_client(self, cb):
|
||||
self.sensor_helper.add_client(cb)
|
||||
def get_probe_params(self, gcmd=None):
|
||||
return self.probe_session.get_probe_params(gcmd)
|
||||
def get_offsets(self):
|
||||
return self.probe_offsets.get_offsets()
|
||||
def get_status(self, eventtime):
|
||||
return self.cmd_helper.get_status(eventtime)
|
||||
def start_probe_session(self, gcmd):
|
||||
method = gcmd.get('METHOD', 'automatic').lower()
|
||||
if method in ('scan', 'rapid_scan'):
|
||||
z_offset = self.get_offsets()[2]
|
||||
return EddyScanningProbe(self.printer, self.sensor_helper,
|
||||
self.calibration, z_offset, gcmd)
|
||||
return self.probe_session.start_probe_session(gcmd)
|
||||
def register_drift_compensation(self, comp):
|
||||
self.calibration.register_drift_compensation(comp)
|
||||
|
||||
class DummyDriftCompensation:
|
||||
def get_temperature(self):
|
||||
return 0.
|
||||
def note_z_calibration_start(self):
|
||||
pass
|
||||
def note_z_calibration_finish(self):
|
||||
pass
|
||||
def adjust_freq(self, freq, temp=None):
|
||||
return freq
|
||||
def unadjust_freq(self, freq, temp=None):
|
||||
return freq
|
||||
|
||||
def load_config_prefix(config):
|
||||
return PrinterEddyProbe(config)
|
||||
123
klippy/extras/pwm_cycle_time.py
Normal file
123
klippy/extras/pwm_cycle_time.py
Normal file
@@ -0,0 +1,123 @@
|
||||
# Handle pwm output pins with variable frequency
|
||||
#
|
||||
# Copyright (C) 2017-2023 Kevin O'Connor <kevin@koconnor.net>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
PIN_MIN_TIME = 0.100
|
||||
MAX_SCHEDULE_TIME = 5.0
|
||||
|
||||
class MCU_pwm_cycle:
|
||||
def __init__(self, pin_params, cycle_time, start_value, shutdown_value):
|
||||
self._mcu = pin_params['chip']
|
||||
self._cycle_time = cycle_time
|
||||
self._oid = None
|
||||
self._mcu.register_config_callback(self._build_config)
|
||||
self._pin = pin_params['pin']
|
||||
self._invert = pin_params['invert']
|
||||
if self._invert:
|
||||
start_value = 1. - start_value
|
||||
shutdown_value = 1. - shutdown_value
|
||||
self._start_value = max(0., min(1., start_value))
|
||||
self._shutdown_value = max(0., min(1., shutdown_value))
|
||||
self._last_clock = self._cycle_ticks = 0
|
||||
self._set_cmd = self._set_cycle_ticks = None
|
||||
def _build_config(self):
|
||||
cmd_queue = self._mcu.alloc_command_queue()
|
||||
curtime = self._mcu.get_printer().get_reactor().monotonic()
|
||||
printtime = self._mcu.estimated_print_time(curtime)
|
||||
self._last_clock = self._mcu.print_time_to_clock(printtime + 0.200)
|
||||
cycle_ticks = self._mcu.seconds_to_clock(self._cycle_time)
|
||||
if self._shutdown_value not in [0., 1.]:
|
||||
raise self._mcu.get_printer().config_error(
|
||||
"shutdown value must be 0.0 or 1.0 on soft pwm")
|
||||
if cycle_ticks >= 1<<31:
|
||||
raise self._mcu.get_printer().config_error(
|
||||
"PWM pin cycle time too large")
|
||||
self._mcu.request_move_queue_slot()
|
||||
self._oid = self._mcu.create_oid()
|
||||
self._mcu.add_config_cmd(
|
||||
"config_digital_out oid=%d pin=%s value=%d"
|
||||
" default_value=%d max_duration=%d"
|
||||
% (self._oid, self._pin, self._start_value >= 1.0,
|
||||
self._shutdown_value >= 0.5, 0))
|
||||
self._mcu.add_config_cmd(
|
||||
"set_digital_out_pwm_cycle oid=%d cycle_ticks=%d"
|
||||
% (self._oid, cycle_ticks))
|
||||
self._cycle_ticks = cycle_ticks
|
||||
svalue = int(self._start_value * cycle_ticks + 0.5)
|
||||
self._mcu.add_config_cmd(
|
||||
"queue_digital_out oid=%d clock=%d on_ticks=%d"
|
||||
% (self._oid, self._last_clock, svalue), is_init=True)
|
||||
self._set_cmd = self._mcu.lookup_command(
|
||||
"queue_digital_out oid=%c clock=%u on_ticks=%u", cq=cmd_queue)
|
||||
self._set_cycle_ticks = self._mcu.lookup_command(
|
||||
"set_digital_out_pwm_cycle oid=%c cycle_ticks=%u", cq=cmd_queue)
|
||||
def set_pwm_cycle(self, print_time, value, cycle_time):
|
||||
clock = self._mcu.print_time_to_clock(print_time)
|
||||
minclock = self._last_clock
|
||||
# Send updated cycle_time if necessary
|
||||
cycle_ticks = self._mcu.seconds_to_clock(cycle_time)
|
||||
if cycle_ticks != self._cycle_ticks:
|
||||
if cycle_ticks >= 1<<31:
|
||||
raise self._mcu.get_printer().command_error(
|
||||
"PWM cycle time too large")
|
||||
self._set_cycle_ticks.send([self._oid, cycle_ticks],
|
||||
minclock=minclock, reqclock=clock)
|
||||
self._cycle_ticks = cycle_ticks
|
||||
# Send pwm update
|
||||
if self._invert:
|
||||
value = 1. - value
|
||||
v = int(max(0., min(1., value)) * float(self._cycle_ticks) + 0.5)
|
||||
self._set_cmd.send([self._oid, clock, v],
|
||||
minclock=self._last_clock, reqclock=clock)
|
||||
self._last_clock = clock
|
||||
|
||||
class PrinterOutputPWMCycle:
|
||||
def __init__(self, config):
|
||||
self.printer = config.get_printer()
|
||||
self.last_print_time = 0.
|
||||
cycle_time = config.getfloat('cycle_time', 0.100, above=0.,
|
||||
maxval=MAX_SCHEDULE_TIME)
|
||||
self.last_cycle_time = self.default_cycle_time = cycle_time
|
||||
# Determine start and shutdown values
|
||||
self.scale = config.getfloat('scale', 1., above=0.)
|
||||
self.last_value = config.getfloat(
|
||||
'value', 0., minval=0., maxval=self.scale) / self.scale
|
||||
self.shutdown_value = config.getfloat(
|
||||
'shutdown_value', 0., minval=0., maxval=self.scale) / self.scale
|
||||
# Create pwm pin object
|
||||
ppins = self.printer.lookup_object('pins')
|
||||
pin_params = ppins.lookup_pin(config.get('pin'), can_invert=True)
|
||||
self.mcu_pin = MCU_pwm_cycle(pin_params, cycle_time,
|
||||
self.last_value, self.shutdown_value)
|
||||
# Register commands
|
||||
pin_name = config.get_name().split()[1]
|
||||
gcode = self.printer.lookup_object('gcode')
|
||||
gcode.register_mux_command("SET_PIN", "PIN", pin_name,
|
||||
self.cmd_SET_PIN,
|
||||
desc=self.cmd_SET_PIN_help)
|
||||
def get_status(self, eventtime):
|
||||
return {'value': self.last_value}
|
||||
def _set_pin(self, print_time, value, cycle_time):
|
||||
if value == self.last_value and cycle_time == self.last_cycle_time:
|
||||
return
|
||||
print_time = max(print_time, self.last_print_time + PIN_MIN_TIME)
|
||||
self.mcu_pin.set_pwm_cycle(print_time, value, cycle_time)
|
||||
self.last_value = value
|
||||
self.last_cycle_time = cycle_time
|
||||
self.last_print_time = print_time
|
||||
cmd_SET_PIN_help = "Set the value of an output pin"
|
||||
def cmd_SET_PIN(self, gcmd):
|
||||
# Read requested value
|
||||
value = gcmd.get_float('VALUE', minval=0., maxval=self.scale)
|
||||
value /= self.scale
|
||||
cycle_time = gcmd.get_float('CYCLE_TIME', self.default_cycle_time,
|
||||
above=0., maxval=MAX_SCHEDULE_TIME)
|
||||
# Obtain print_time and apply requested settings
|
||||
toolhead = self.printer.lookup_object('toolhead')
|
||||
toolhead.register_lookahead_callback(
|
||||
lambda print_time: self._set_pin(print_time, value, cycle_time))
|
||||
|
||||
def load_config_prefix(config):
|
||||
return PrinterOutputPWMCycle(config)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user