How can I read a GPIO pin in an Octoprint GCODE script?

In an Octoprint GCODE script, is there a way to read a Raspberry Pi GPIO pin and do something based on it's state? For example, if GPIO pin 23 is 1, I want to execute a certain GCODE command. I need to do this in an Octoprint script (because I can safely send GCODE commands from there), not an external python program (I can't safely send GCODE commands from an external program because Octoprint already has the serial port open). Here's pseudo code of what I want in my Octoprint script:

gcode command
gcode command
if GPIO pin 23 is 1
send gcode command
end
gcode command
gcode command

etc

I can do conditional stuff (if, for, etc) thanks to the Jinja2 engine, but I'm stumped on how to get the value of a GPIO pin.

Hello @pwelka !

You need a plugin for this.

in the OctoPrint repository are some plugins that read the GPIO and react to this, like filament run out sensors:

That can be a start to create one that fits your needs.

1 Like

Out of curiosity:

Would it be a possible alternative to go via the api instead?

Some python or bash script having an eye on that GPIO pin (gpio read 23) and when it changes it issues something like:

curl -s -X POST  -H "Content-Type: application/json" -H "X-Api-Key":"$OCTOPRINT_X_API_KEY" -d '{"command":"M117 GPIO 23 is up right now"}' http://$PRINT_HOST/api/printer/command
1 Like