Notifications
Clear all

ArduCam and libcamera

132 Posts
6 Users
4 Likes
5,749 Views
Ron
 Ron
(@zander)
Father of a miniature Wookie
Joined: 3 years ago
Posts: 7026
 

@emeyeraway Here is a clue. I used google search with [gpiozero motion sensor example] as the search arguments.

Screenshot 2023 02 18 at 14.55.39

You could use either the method wait_for_motion and when true, take the picture like you did in the original sketch you showed us, or you could use the method motion_detected in an if and the true part would be the same take a picture code, with the else side whatever you want, maybe a second camera etc or nothing, or some other task. I doubt you need or even want the 2 sleep(3).

NOTE I do not know python, I did not compile or run this, I do not have the hardware but from the several samples I have seen and common sense, I think what you want is the following. To 'use' headless, just use VNC, no change to the code is needed AFAIK.

import os
import datetime
import time
from gpiozero import MotionSensor

pir = MotionSensor(17)

time.sleep(2)   // needed ???
print("Waiting for motion detection...")

while True:
    if pir.motion_detected:
        timestamp = str((datetime.datetime.now()))
        timestamp = timestamp[5:19]
        print("Motion detected")
        os.system("libcamera-jpeg -o "+timestamp[6:15]+".jpg --vflip --hflip")
        print("Image captured at ", timestamp)
        time.sleep(3)   // needed ???
        print("Ready")
        time.sleep(3)   // needed ???
    else:
        time.sleep(3)   // needed ???

 

 

 

First computer 1959. Retired from my own computer company 2004.
Hardware - Expert in 1401, and 360, fairly knowledge in PC plus numerous MPU's and MCU's
Major Languages - Machine language, 360 Macro Assembler, Intel Assembler, PL/I and PL1, Pascal, Basic, C plus numerous job control and scripting languages.
Sure you can learn to be a programmer, it will take the same amount of time for me to learn to be a Doctor.


   
ReplyQuote
byron
(@byron)
No Title
Joined: 5 years ago
Posts: 1122
 

@zander @emeyeraway

Blimey Ron is doing python 😀.  But a reminder, the code is good for a play, but controlling the camera by shelling out to the operating system to run a command line statement is, imho, never going to give you proper control of your camera and one really needs to use the picamera2 library.

And also do consider what your motion sensor does when motion is detected, how long does it signal high?  What happens if there is continued motion, does the pin stay high until all motion ceases?  Do you want to take a picture every time the pin goes high, but wait until it goes high again for the next pic.  But if the pin stays high due to continued motion, then how many pics do you want to take, maybe, for example, you want one pic every 5 seconds, but for a limit of 3 pics until the pin goes low and to start the cycle again when a high is detected.  I'm sure you get the pic 🙂

The code below is an alternative that will only take one pic when the pin goes high, but will only take the next pic when the pin has gone low, and the high again.  The pir.wait_for_motion() wll pause the program until the motion pin goes high, and will only take the next pic when its gone low and high again.  I expect you are reading all the different options available in the gpiozero doc so I will say no more, but, again, just to emphasise it much better to use picamer2 and directly control the camera rather than using command line commands. 👍 

import os
import datetime

from gpiozero import MotionSensor

pir = MotionSensor(17)
print("Waiting for motion detection...")

while True:
    pir.wait_for_motion()
    timestamp = str((datetime.datetime.now()))
    timestamp = timestamp[5:19]
    print("Motion detected")
    os.system("libcamera-jpeg -o "+timestamp[6:15]+".jpg --vflip --hflip")
    print("Image captured at ", timestamp)
This post was modified 1 year ago by byron

   
ReplyQuote
Ron
 Ron
(@zander)
Father of a miniature Wookie
Joined: 3 years ago
Posts: 7026
 

@byron Like I said I don't know python and did mention the other method. I was assuming there was a state machine in the super high-level code that Python is, The operation will be controlled by one jumper, a pot (TX) and some board-level soldering to adjust TI. I discovered I do have a sensor although not sure if it's the same as the OP. I will try to use some C to analyze what is happening although I have read the datasheet so am fairly sure. Once I know for sure what signals are bouncing off the pin then I can try python as I do have Thonny on the Mac. Unfortunately, the newer Macs with the M1 or M2 chipset don't allow the Raspberry Pi OS to run or I would use the same setup as the OP. I could also use my Pi4 but the seating at my desk is hard on my recently injured back.

BTW, your example code does not seem to agree with your description.

You mention 'proper control of the camera', but this is just a point-and-shoot, no control is required.

Your entire second paragraph is what I have been looking at and commenting on quite a bit. My hunch is that Python deals with all the low-level stuff thus the naming of the methods as motion_detected or wait_for_motion. Maybe I will dig deeper in the docs to see what it says about the setting of the jumper and the recommendations regarding TX. I assume they will either ignore TI or at least treat it with care as it does require soldering.

First computer 1959. Retired from my own computer company 2004.
Hardware - Expert in 1401, and 360, fairly knowledge in PC plus numerous MPU's and MCU's
Major Languages - Machine language, 360 Macro Assembler, Intel Assembler, PL/I and PL1, Pascal, Basic, C plus numerous job control and scripting languages.
Sure you can learn to be a programmer, it will take the same amount of time for me to learn to be a Doctor.


   
ReplyQuote
byron
(@byron)
No Title
Joined: 5 years ago
Posts: 1122
 

@zander

just a few points to make with regard to your last post that may be worth making. (maybe not 😎)

When using micropython on a rpi pico then you use the Thonny on your mac connected to your pico via usb. I remember there was some issue with this for the new macs.  However when programming the rpi4 you use the Thonny that runs on the rpi4 itself not the Thonny on your mac.  You just do everything on the rpi4 via your VNC connection.  I don't think there is any issue with doing this.    

Just in case this removes the impediment to your getting stuck in with python on your rpi4, then before you get too dangerous perhaps it would be well to find a comfy chair (hope your back improves 🙂) grab your ipad, take a short break from the forum (just half a day) and have a read of the following python intro.

https://thepythoncodingbook.com/

It is written so that raw beginners can get a grasp both programming and python, so you will find yourself fast reading through some bits, but it explains very well the basic use of python and its a relatively quick read for the likes of an experienced programmer like yourself.   Hopefully it will rest your mind about "assuming there was a state machine in the super high-level code that Python is" and prevent you getting frustrated by diving into python without the good grounding this short read will give you.

You mention that you are just going to use the camera for point and shoot and no need for more control is required.  But there are many options that are available to set the camera up for getting the best picture with regard to where its situated like saturation, white balance, well you can look up all the options.  I remember I put up a small program on this forum for dear old RoboPi way back when that showed a preview with the ability to adjust various options to see the effect on the fly. But this was for the old legacy way of using the camera that does not work with rpi os.  But if just taking the camera with is defaults is your bag then the choice is yours but its surly worth being fully aware of the options.  I'm sure there are sample programs to be found in the picamera2 examples that will be well worth exploring.

You also mention "BTW, your example code does not seem to agree with your description".   Thats correct I did allure to the desirability of considering just when and how many pictures would be taken with program.  The program you valiantly presented, albeit with all your caveats, would produce just the same outcome as the original program the OP presented, but just using a different library.  As the older library for using the gpio pins works just fine, why bother?  My point of using the newer and alternative library was that more options are available for those less versed in programming such as automatically waiting to trigger on a rising edge.   So I showed a very brief alternative for the OP to play with.   I will only suggest further programming improvement once the specification of when and how many pics should be taken has been analysed and stated.

Lastly I don't think you need to over analyse how the motion sensor works with a c program.  The datasheet should tell all, with a confirmation of a waving hand in front of your motion sensor and a multimeter attached to pin and ground,  why complicate you life 😀 

 

 


   
ReplyQuote
byron
(@byron)
No Title
Joined: 5 years ago
Posts: 1122
 

@zander

Its just after my lunch, and whilst I drinking my coffee I hooked up my rpi4 to an my old rpi camera and on my mac used VNC to connect to the rpi Thonny.  I grabbed an example program off the picamer2 web site and gave it a whirl.  I made a screenshot so you can see the preview of the camera. (which shows my very untidy office  😎 ).  The preview of this post shows a miniature screen so I hope this will expand or can be expanded when posted.    That enough of all this camera malarky for now as I must get on with other stuff but I intend to make some proper programs in a week or so. 

Screenshot 2023 02 19 at 14.33.52
This post was modified 1 year ago by byron

   
ReplyQuote
Ron
 Ron
(@zander)
Father of a miniature Wookie
Joined: 3 years ago
Posts: 7026
 

@byron That's a decent looking picture. I am just doing an update/upgrade and later will get VNC going between the Mac and Pi so I can copy the test code. My problem will be figuring out if I can use the camera installed in my Pi which is like a webcam setup. Anyway, it's a start.

First computer 1959. Retired from my own computer company 2004.
Hardware - Expert in 1401, and 360, fairly knowledge in PC plus numerous MPU's and MCU's
Major Languages - Machine language, 360 Macro Assembler, Intel Assembler, PL/I and PL1, Pascal, Basic, C plus numerous job control and scripting languages.
Sure you can learn to be a programmer, it will take the same amount of time for me to learn to be a Doctor.


   
ReplyQuote
(@emeyeraway)
Member
Joined: 3 years ago
Posts: 21
Topic starter  

@byron


   
ReplyQuote
robotBuilder
(@robotbuilder)
Member
Joined: 5 years ago
Posts: 2043
 

@byron 

The preview of this post shows a miniature screen so I hope this will expand or can be expanded when posted.

Right click image and choose Open link in new window?

 

 

 


   
ReplyQuote
(@emeyeraway)
Member
Joined: 3 years ago
Posts: 21
Topic starter  

I have been messing around with picamera2 and getting nowhere!  Can you please give me (a reference to) the sample code that produced that preview picture for you?  I need detail; people always assume that I know more than I do.

BTW, I have discovered that when I use a fresh SD card, and simply watch the output of the sensor, everything works fine.  It is only after I set my Raspi 3B+ up to take pictures that things go haywire.  So I'm somewhat resistant to using my "os.system..." code because it may be what is contaminating the SD.

I am now using a Raspi 4B and an Arducam.  "libcamera-hello" works fine so far but I haven't been able to get any new code working using picamera2.

I do appreciate all the time you have given me and I am optimistic that you'll help me solve my difficulties.


   
ReplyQuote
Ron
 Ron
(@zander)
Father of a miniature Wookie
Joined: 3 years ago
Posts: 7026
 

@emeyeraway When you post a request for help from a specific person, either use the Reply link on their post or preface your request with @name.

As far as 'knowing' I simply typed picamera2 into my web browser and the first hit was the github entry for the library and some examples. It includes a ton of help on installation so you will not need any help with that, then select each sample program and determine which one will form the base of your project. Now make the modification needed using the knowledge gained in my previous post showing you the methods available with the PIR sensor and you are done.

EDIT I see that picamera2 is pre-installed on current images so you don't need to do an install. The documentation is at HERE Byron's sample he used above is on your Pi4 somewhere, just browse around to find them.

First computer 1959. Retired from my own computer company 2004.
Hardware - Expert in 1401, and 360, fairly knowledge in PC plus numerous MPU's and MCU's
Major Languages - Machine language, 360 Macro Assembler, Intel Assembler, PL/I and PL1, Pascal, Basic, C plus numerous job control and scripting languages.
Sure you can learn to be a programmer, it will take the same amount of time for me to learn to be a Doctor.


   
ReplyQuote
byron
(@byron)
No Title
Joined: 5 years ago
Posts: 1122
 

@zander @emeyeraway

To the memory of Bernard Cribbins:

'Right' said Em, Ron an me together
One on each computer and steady as we go
Programmed it to shift it, couldn't even start it
We was getting nowhere
And so we had a cuppa tea and

'Right' said Em, 'Give a shout for Byron'
Up comes Byron from the floor below.
After strainin, coding and camplainin
We was getting nowhere
And so we had a cuppa tea.

Strewth, I forget which example program it was so I will just post the whole code below.

Whilst the latest rpi os comes with the picamera modules installed that would not include the example programs you have already found on the github site.   I tried it out with my rpi camera (V1 or V2 not too sure) which connects to the rpi via a ribbon cable.  I presume the arducam is similarly connected and its comparable with the rpi cams?

You may well get there before me, but if you are still needing assistance in a weeks time give another post and I will have more time to spare.  But do let me know of how you want the motion detection to work in relation to how many pics to take on continued motion to save filling your SD card with loads of images.

The code:

#!/usr/bin/python3

# This example is essentially the same as app_capture.py, however here
# we use the Qt signal/slot mechanism to get a callback (capture_done)
# when the capture, that is running asynchronously, is finished.

from PyQt5 import QtCore
from PyQt5.QtWidgets import (QApplication, QHBoxLayout, QLabel, QPushButton,
                             QVBoxLayout, QWidget)

from picamera2 import Picamera2
from picamera2.previews.qt import QGlPicamera2


def post_callback(request):
    label.setText(''.join(f"{k}: {v}\n" for k, v in request.get_metadata().items()))


picam2 = Picamera2()
picam2.post_callback = post_callback
picam2.configure(picam2.create_preview_configuration(main={"size": (800, 600)}))

app = QApplication([])


def on_button_clicked():
    button.setEnabled(False)
    cfg = picam2.create_still_configuration()
    picam2.switch_mode_and_capture_file(cfg, "test.jpg", signal_function=qpicamera2.signal_done)


def capture_done(job):
    picam2.wait(job)
    button.setEnabled(True)


qpicamera2 = QGlPicamera2(picam2, width=800, height=600, keep_ar=False)
button = QPushButton("Click to capture JPEG")
label = QLabel()
window = QWidget()
qpicamera2.done_signal.connect(capture_done)
button.clicked.connect(on_button_clicked)

label.setFixedWidth(400)
label.setAlignment(QtCore.Qt.AlignTop)
layout_h = QHBoxLayout()
layout_v = QVBoxLayout()
layout_v.addWidget(label)
layout_v.addWidget(button)
layout_h.addWidget(qpicamera2, 80)
layout_h.addLayout(layout_v, 20)
window.setWindowTitle("Qt Picamera2 App")
window.resize(1200, 600)
window.setLayout(layout_h)

picam2.start()
window.show()
app.exec()
This post was modified 1 year ago 2 times by byron

   
ReplyQuote
(@emeyeraway)
Member
Joined: 3 years ago
Posts: 21
Topic starter  

to byron:

I tried to answer to the individual, but there was no place to do that on my screen.

I have tried several different code examples from picamera2 and they all give me a long list of errors.  The same ones I get when I try to run the most recent code you sent me.  The main idea: "Camera __init__ sequence did not complete."

When I started, "libcamera-hello" worked as expected.  After trying these examples, when I enter "libcamera-hello" I get an error: ***failed to acquire camera /base/soc/i2c0mux/i2c@1/imx519@1a ***

Does the code you are running use libcamera?  Is the fact that I am using ArduCam the source of my problems?

 


   
ReplyQuote
(@emeyeraway)
Member
Joined: 3 years ago
Posts: 21
Topic starter  

byron

I repeated the steps from Bill's video to set up Arducam on Raspi, and libcamera AND your code worked!  Your code, though, is way beyond my comprehension.  I'm going to keep fooling around to see if I can simplify things closer to my level of understanding.  But THANKS for getting me this far!


   
ReplyQuote
byron
(@byron)
No Title
Joined: 5 years ago
Posts: 1122
 

@emeyeraway

Don't forget to put the @ before my forum name otherwise I will not get an email informing me that someone mentioned me in a post.

It was not my program, just one I grabbed from somewhere in the picamera2 examples.  And we should note that it does state the picamera2 is a beta release, though seemingly good enough to include in the rpi os.

And B**er me I got the same result as you.  I run libcamera-hello ok, but after I run that demo code I cannot run the libcamera-hello again.  I get an error message:

[0:04:07.095460165] [2185] ERROR V4L2 v4l2_device.cpp:352 'imx219 10-0010': Unable to set controls: Device or resource busy

So I have a look at the code and think I see that whilst there is a picam2.start() theres nothing about stopping this on exit.  

Are you using Thonny as your IDE ?  If I make sure I hit the Thonny 'Stop/Restart backend'  button when I've finished with the demo program then I'm back in business, and can run libcamera-hello again.

The example program needs amending to have an exit button that properly closes all its process down.  Also, Thonny does sometimes interfere with the running of programs in peculiar ways.  Maybe its better to use the vscode IDE that also comes with rpi os.  But don't take this as a recommendation as you may end up with a similar issue, but with no stop button to assist 🤨 

In a weeks time I expect I may be asking you how to use picamera2, so do keep plugging away. 👍 

 

 


   
ReplyQuote
Ron
 Ron
(@zander)
Father of a miniature Wookie
Joined: 3 years ago
Posts: 7026
 

@emeyeraway If you wanted to 'reply' to this message, click the word  'reply' at the bottom of this post. Here is a screen shot showing the 'reply' icon.

Screenshot 2023 02 19 at 13.26.04

First computer 1959. Retired from my own computer company 2004.
Hardware - Expert in 1401, and 360, fairly knowledge in PC plus numerous MPU's and MCU's
Major Languages - Machine language, 360 Macro Assembler, Intel Assembler, PL/I and PL1, Pascal, Basic, C plus numerous job control and scripting languages.
Sure you can learn to be a programmer, it will take the same amount of time for me to learn to be a Doctor.


   
ReplyQuote
Page 5 / 9