mmap() failed: Cannot allocate memory - python

With this code I have connected a breadboard to a Raspberry pi 3. When a button on the breadboard is pressed a random audiofile from a specified folder is played.
import RPi.GPIO as GPIO
import vlc
import random
import os
def button_callback(channel):
print("Button was pushed!")
path = "/home/pi/Downloads/Slutprojekts_inspelningar_Kung-Fu_Panda"
files=os.listdir(path)
d = random.choice(files)
p = vlc.MediaPlayer(f"/home/pi/Downloads/Slutprojekts_inspelningar_Kung-Fu_Panda/{d}")
p.play()
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 10 to be an input pin and set initial value to be pulled low (off)
GPIO.add_event_detect(10,GPIO.RISING,callback=button_callback) # Setup event on pin 10 rising edge
message = input("Press enter to quit\n\n") # Run until someone presses enter
GPIO.cleanup() # Clean up
After pressing the button a couple of times, it stops working and I get these error messages:
Failed to create permanent mapping for memfd region with ID = 4052867084
Failed to regester memfd mempool. Reason: could not attach memfd SHM ID to pipe
Cannot send block reference with non-registered memfd ID = 4052867084
Fallig back to copying full block data over socket
mmap() failed: Cannot allocate memory
Expected output:
Button was pushed! #while playing the audiofile

Make sure that the previously started instances of VLC are actually terminating. Otherwise you're exhausting the memory available. That might also be a limit imposed by the OS, check with ulimit -a

Related

Need to take the whole python code into a function that can be access from another python file

import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import time
def privacyfunc():
# Pin Definitions:
led_pin_1 = 7
led_pin_2 = 21
but_pin = 18
# blink LED 2 quickly 5 times when button pressed
def blink(channel):
x=GPIO.input(18)
print("blinked")
for i in range(1):
GPIO.output(led_pin_2, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(led_pin_2, GPIO.LOW)
time.sleep(0.5)
mqttBroker="mqtt.fluux.io"#connect mqtt broker
client=mqtt.Client("privacybtn") #create a client and give a name
client.connect_async(mqttBroker)#from the client -connect broker
while True:
client.publish("privacy", x)#publish this random number to the topic called temparature
print("Just published"+str(x)+"to Topc to privacy")#just print random no to topic temparature
break
def main():
# Pin Setup:
GPIO.setmode(GPIO.BOARD) # BOARD pin-numbering scheme
GPIO.setup([led_pin_1, led_pin_2], GPIO.OUT) # LED pins set as output
GPIO.setup(but_pin, GPIO.IN) # button pin set as input
# Initial state for LEDs:
GPIO.output(led_pin_1, GPIO.LOW)
GPIO.output(led_pin_2, GPIO.LOW)
GPIO.add_event_detect(but_pin, GPIO.FALLING, callback=blink, bouncetime=10)
print("Starting demo now! Press CTRL+C to exit")
try:
while True:
x=GPIO.input(18)
print(x)
# blink LED 1 slowly
GPIO.output(led_pin_1, GPIO.HIGH)
time.sleep(2)
finally:
GPIO.cleanup() # cleanup all GPIOs
if __name__ == '__main__':
main()
need to take this whole code into a function that can be accessed from another python file.plz, help me with this coding part.
In the new python file call import module where module is the name of the file. Like led_blink.py would be import led_blink
Then you can call the methods like so:
led_blink.blink(channel)
This is assuming the files are in the same folder.
Easiest way that I do this is to take a .py file and put it in the same directory you created the python script you are working with. From there you can do the following code from The_Python_File import *
Additionally note that the "The_Python_File" is the name of the .py file that contains the function you are trying to call, but you do not include .py when importing the file.

Screen Blanking/Reducing back light on RPI while running a Kivy App

I have a kivy app that has multiple screens and widgets. I am using a motion sensor to check if there is motion and if there isn't any motion detected for 1 minute then the rpi reduces the screen's backlight or blanks the screen. Im not sure where I should place the rpi code. does it go inside the App class ?
Pir Module that works really well.
import time
from gpiozero import MotionSensor
import board
import adafruit_dht
import subprocess
def turn_on():
CONTROL = "vcgencmd"
CONTROL_UNBLANK = [CONTROL, "display_power", "1"] subprocess.call(CONTROL_UNBLANK)
def turn_off():
CONTROL = "vcgencmd"
CONTROL_BLANK = [CONTROL, "display_power", "0"] subprocess.call(CONTROL_BLANK)
pir = MotionSensor(4)
dhtDevice = adafruit_dht.DHT22(board.D23)
while True:
if pir.motion_detected:
turn_on()
print("Motion Detected!")
try:
#Print the values to the serial port
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
print("Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(temperature_f, temperature_c, humidity))
except RuntimeError as error:
# Errors happen fairly often, keep going
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
dhtDevice.exit()
raise error
time.sleep(60.0)
print("sleeping for 1 minute")
else:
turn_off()
print("No Motion Detected!")
So I think I found a proper solution. The idea would be to use threading on the rpi. Its pretty simple to be honest. Here is the link to some code that has a gui but also uses a pir sensor to sense motion and adjust back lighting on the screen.
https://github.com/norrisredhi/kivy/blob/norrisredhi-patch-1/Kivyapp_with_threading_RPI.py

RaspberryPi: TypeError: unsupported format string passed to NoneType.__format__ dht22 lcd 16x2

Using DHT22 sensor, display LCD 16x2 and raspberry pi to collect temperature and humidity value.Please help me out with this error.Thanks in advance
import drivers # Imports Custom LCD Display Driver
import socket # Imports socket function
import struct # Imports structure function
import fcntl # Imports networking function
import time # Imports time function
import os # Imports Operating System function
import re # Imports Reg Ex function
from time import sleep # Imports sleep function from time module
import Adafruit_DHT
DHT = 4
disp = drivers.Lcd() # Initializes LCD Display
def tempcpu(): #Defines "tempcpu"
for _ in range(5): # Sets up timer
cputemp = os.popen("vcgencmd measure_temp").readline()
celsius = re.sub("[^0123456789\.]", "", cputemp)
h,t = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, DHT)
disp.lcd_display_string("CpuRpi: {}C".format(celsius), 1)
disp.lcd_display_string("T={0:0.1f}C H={1:0.1f}%".format(t,h), 2 )
sleep(1) # Sleeps for one second before restarting loop
while True: # Forever loop
tempcpu() # Calls "tempcpu"
disp.lcd_clear() # Clears the LCD Display
except KeyboardInterrupt: # If interrupted by the keyboard ("Control" + "C")
disp.clear() #clear the lcd display
sleep(1) #sleeps 1 second
disp.backlight(0) #Turn Off Backlight
# Exits the python interpreter
exit()
Error :
disp.lcd_display_string("T={0:0.1f}C H={1:0.1f}%".format(t,h), 2 )
type Error:unsupported format string passed to NoneType.format
I can reproduce your error with the following line (or similarly if t is the one set to None):
h = None,
t = 1
str_to_be_printed = "T={0:0.1f}C H={1:0.1f}%".format(t,h)
The method Adafruit_DHT.read_retry returned None. It probably happens when failing to read the sensor values. Maybe there is an error in your circuit, or the sensor is faulty.
More complete example on https://www.programcreek.com/python/example/92777/Adafruit_DHT.read_retry

Module Object is not Callable, using a PIR Sensor

I'm trying to build a Motion Detected play video for my store as a Welcome Introduction, so I'm using a PIR Sensor connected to the raspberry, and here is my code:
import RPi.GPIO as GPIO
import time
import os
import sys
GPIO.setmode(GPIO.BOARD)
PIR_PIN=7
GPIO.setup(PIR_PIN,GPIO.IN)
def MOTION(PIR_PIN):
os.sys("omxplayer -o local -b /home/pi/g1.mp4")
print("My Store Name")
time.sleep(2)
print ("Wating for Customers...")
try:
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
while 1:
time.sleep(100)
except KeyboardInterrupt:
print("Quit")
GPIO.cleanup()
My problems comes once the sensors detect a movement, a video should have to be played, but I got the error message: 'Module'object is not callable
Any clue?
Thanks in Advance, Im will really appreciate your help.

Raspberry Pi crash during python program (OR how is it possible to kill Linux???)

I build a keypad activated sensor with a Raspberry Pi and Python. Everything seems to go well but after a few minutes and several keypad entries, the Pi has a total crash and switches off immediately - no error messages pop up.
The script will continously wait for a keypad entry and if the code is correct, switch on a sensor, if it's not you have to try again. If the sensor is activated you have to put in the correct numbers to avoid an alarm being triggered after 30s)
Could anyone point me in the direction of what might be the problem? Here are the things I've tried so far without success
1) Exchange Pi to new Pi 2
2) Different OS, both NOOBS and Raspbian Wheezy
3) Different sensor (accelerometer vs IR sensor)
4) Disconnect monitor, keyboard and use SSH connection via Cygwin
5) Get log file until crash - log file was empty after reboot
python bad_script &> full_log.txt
6) Different log file command: causes instant crash and is also empty after reboot:
python script.py >> /logdir/script.py.log 2>&1
The question is: how am I able to crash Linux? If it's a memory problem, isn't there a prevention in linux to stop processed before they appear?
Here is the full script I am running:
import sys
from time import sleep
import threading
import signal
from matrix_keypad import RPi_GPIO1
import RPi.GPIO as GPIO
import smbus
import time
passcode = [1,2,3,4] # this is the correct code you have to enter
kp = RPi_GPIO1.keypad(columnCount = 3)
alarm_active = threading.Event() # shared variable used to control the sensor monitoring thread
alarm_active.clear() # Clear the alarm initially
monitor_thread = None # Global variable used to store the monitoring thread
#Set up all the pins correctio
GPIO.setmode(GPIO.BCM)
PINIR=7
GPIO.setup(7, GPIO.IN) # infrad-sensor
#Now activate the kaypad and listen for keypad inputs
def digit():
r = None
while r == None:
r = kp.getKey()
return r
def get_keycode():
# Function to loop around reading 4 keypresses in a row
# Compare against chosen code
# If match, switch the alarm state
entered = []
while len(entered) < 4:
key = digit()
sleep(0.5)
print key
entered.append( key )
if entered == passcode:
entered = []
print "Code correct"
switch_alarm_state()
else:
# Just clear the keypad buffer if the wrong code went in
# Could say "BAD CODE!" here, or even force immediate alarm perhaps
print "Wrong Code - Try again"
GPIO.output(27, True) # let red LED blink as indicator that code was wrong
time.sleep(1)
GPIO.output(27, False)
entered = []
def switch_alarm_state():
# Function to control the state of the alarm
# If the alarm should be on, run a thread monitoring the sensor
# If the alarm should be off, make sure the thread is stopped
global monitor_thread
if alarm_active.is_set():
# If the alarm is currently set, stop it
print "Alarm was abolished"
GPIO.output(17, False) #switch green LED off
alarm_active.clear() # Signals to the monitor thread that we wish to shut it down
monitor_thread.join() # Wait until the monitor thread has stopped
else:
# Alarm is not currently set, so start the sensor monitor thread going
print "Alarm was activated"
GPIO.output(17, True)
monitor_thread = threading.Thread( target=sensor_monitor )
alarm_active.set()
monitor_thread.start()
def sensor_monitor():
# Function to be run in a separate thread, monitoring the sensor
alarm_timer = None # Variable to hold a timer object that will fire the alarm
while alarm_active.is_set():
#print xrota
if GPIO.input(PINIR):
print "Alarm has been triggered"
if alarm_timer is None:
alarm_timer = threading.Timer( 30.0, fire_alarm )
alarm_timer.start()
sleep(0.5)
# The alarm must have been deactivated to get here
# Stop any outstanding alarms and shutdown
if alarm_timer is not None:
alarm_timer.cancel()
return
def fire_alarm():
# Here you implement the actions to be carried out by an alarm
print "Alarm is send to server"
msg = "Alarm"
publish.single("alarm/demo",msg, hostname="52.17.194.125")
def shutdown_handler( signum, frame ):
# Shut down the child thread nicely
alarm_active.clear()
monitor_thread.join()
if __name__ == '__main__': # This is the Python way to check you are being directly run, and not just imported by another script
signal.signal( signal.SIGINT, shutdown_handler ) # If you stop the script with ctrl+C, make sure it shuts down properly
signal.signal( signal.SIGTERM, shutdown_handler )
try:
while True:
get_keycode()
except KeyboardInterrupt:
GPIO.cleanup()
print "Quit program"

Categories