Raspberry Pi picamera2 AfMode not working: control not advertised by libcamera

Hi all, I’m trying to get autofocus working with picamera2 on my Raspberry Pi, but my script crashes as soon as it tries to enable AF. The line in question is:

piCam.set_controls({"AfMode": 2})

And I get this traceback:

File "/home/pi/Desktop/picam/Raspi/start_camera.py", line 17, in <module>
    piCam()
File "/home/pi/Desktop/picam/Raspi/start_camera.py", line 10, in piCam
    piCam.set_controls({"AfMode": 2})
File "/usr/lib/python3/dist-packages/picamera2/picamera2.py", line 1234, in set_controls
    self.controls.set_controls(controls)
File "/usr/lib/python3/dist-packages/picamera2/controls.py", line 58, in set_controls
    self.__setattr__(k, v)
File "/usr/lib/python3/dist-packages/picamera2/controls.py", line 33, in __setattr__
    raise RuntimeError(f"Control {name} is not advertised by libcamera")
RuntimeError: Control AfMode is not advertised by libcamera

I’ve also attached the bug report files. Any idea what’s going on?

From your traceback, the exception is coming from picamera2’s controls module. When you pass {“AfMode”: 2} to set_controls(), it iterates through the keys and tries to assign each one, and it fails with:

raise RuntimeError(f"Control {name} is not advertised by libcamera")

That tells us libcamera is not advertising an “AfMode” control for the camera you have. In other words, either the module doesn’t expose autofocus to libcamera, or the control name isn’t supported by your current camera/libcamera version.

Which ArduCAM module are you using? Does it have a motorized focus lens?

For the autofocus part, I’d avoid setting AfMode directly like that. ArduCAM has a picamera2 autofocus example that does it the supported way:

Replace the direct piCam.set_controls({“AfMode”: 2}) call with the autofocus control method shown in that example. Also, with picamera2 it’s a good idea to verify a control is actually advertised before you try to set it.

I tried it again but I’m still getting the exact same error, no change:

raise RuntimeError(f"Control {name} is not advertised by libcamera")
RuntimeError: Control AfMode is not advertised by libcamera

Not sure what I’m doing wrong here.

Just to make sure - did you actually swap out that line in your script, or are you still running the same code that calls set_controls({“AfMode”: 2})? The error will be identical if the old call is still there, because libcamera still doesn’t advertise AfMode for this camera.

To sum up where we are:

  • Don’t set {“AfMode”: 2} directly - that’s what’s triggering the RuntimeError.
  • Use the autofocus control approach from ArduCAM’s AutofocusControl.py example instead.
  • Before setting any control, check that it’s advertised by libcamera for your camera (list the available controls and confirm).

If you’ve already switched to the example and it’s still failing, paste the current code you’re running and we’ll take another look.