import time import os from gpiozero import Button from picamera2 import Picamera2, encoders, outputs # GPIO pin for the button BUTTON_PIN = 17 # Connect the button to GPIO17 (pin 11) # Set up the camera camera = Picamera2() camera_config = camera.create_video_configuration() camera.configure(camera_config) # USB storage path USB_PATH = "/media/sanderrochat/USBDISK" # Button setup button = Button(BUTTON_PIN) # Recording state recording = False start_time = None MAX_RECORDING_TIME = 60 # Stop after 1 minute def is_usb_mounted(): """Check if USB stick is mounted.""" return os.path.ismount(USB_PATH) def toggle_video_recording(): """Start or stop video recording.""" global recording, start_time if not is_usb_mounted(): print("USB stick not found. Check if it's connected.") return if recording: print("\nStopping video recording...") camera.stop_recording() recording = False else: timestamp = time.strftime("%Y%m%d_%H%M%S") filename = f"{USB_PATH}/video_{timestamp}.mp4" print(f"Starting video recording: {filename}") encoder = encoders.H264Encoder() output = outputs.FfmpegOutput(filename, audio=True) # ✅ FIXED: Use encoders.H264Encoder() for MP4 format camera.start_recording(encoder, output) output.start() recording = True start_time = time.time() def main(): global recording # Ensure we can modify the recording state print("Press the button to start/stop recording (max 1 minute).") print(f"Videos will be saved in: {USB_PATH}") try: while True: if button.is_pressed: toggle_video_recording() time.sleep(0.1) # Debounce to avoid multiple presses if recording: elapsed_time = time.time() - start_time print(f"Recording time: {int(elapsed_time)} seconds", end="\r") if elapsed_time >= MAX_RECORDING_TIME: print("\nMax recording time reached (1 minute).") toggle_video_recording() time.sleep(0.1) # Reduce CPU usage except KeyboardInterrupt: print("\nProgram terminated by user.") finally: if recording: # Only stop if recording is active print("Stopping active recording before exit...") camera.stop_recording() recording = False print("Exiting program.") # ✅ Corrected if __name__ == "__main__": if __name__ == "__main__": main()