Help needed with Python coding for taking photos with TouchPhat buttons

I have a TouchPhat and Noir camera attached to a PiZero w. I am attempting to take a still photo with the press of one button and a short video with another. The Python script I have attempted is below. I am getting a Syntax error on the ‘def my_function()’ line and I cannot fathom why.
Here is the full script. Excuse my ignorance as this is my first attempt at Python

import touchphat
import time
import picamera

camera = picamera.PiCamera()

while True:
    @touchphat.on_touch("A")
    def my_function()
        touchphat.led_on("A")
        camera.capture('image.jpg')
        touchphat.led_off("A")

    @touchphat.on_touch("B")
    def my_functiona()
        touchphat.led_on("B")
        camera.start_recording('video.h264')
        sleep(10)
        camera.stop_recording()
        touchphat.led_off("B")
except KeyboardInterrupt():
    sys.exit()

Thanks in advance for any help on this

While it’s not the cause of the problem, you should bind your Touch functions outside of your while True: loop, like so:

@touchphat.on_touch("A")
...

while True:
   ...

The syntax error you’re seeing is due to missing colons from the end of the function declarations.

It should be def my_function(): rather than def my_function()

Ideally you should not actually do the recording in the touch function, but rather set some sort of global state you can later rely on. Something like:

record = False
@touchphat.on_touch("B")
def start_record():
    global record
    record = True

while True:
    if record:
        touchphat.led_on("B")
        camera.start_recording("video.h264")
        sleep(10)
        camera.stop_recording()
        touchphat.led_off("B")
        record = False

You could then extend this to track that you’re currently recording, and have the single touch button toggle the recording on/off.

Thank you so much. I will study your code and apply it.

I will be ‘looking over your shoulder’! As I’ve just ordered (and recieved) a button shim to allow me to opperate the PiCam. What would interest me is to be able to use one of the buttons to power down the Pi.

Hi Andy. In that case I shall share my coding progress in this thread. I am new to Python and Pis so progress might be slow. I programmed in Basic back in the Spectrum days and have written some Java a few years back so we shall see how it goes…