Running multiple programs on Raspberr Pi - python

I just finished all of the prototyping of this project:, and I encountered 2 problems: https://www.pubnub.com/blog/2015-03-17-building-a-model-smart-home-with-raspberry-pi/
I cant run all of the programs at once(Humidity and Temperature, LEDs, Micro Servo motors, etc...)
I can't have more than three LED's (technically two)
What can I do to run everything at once, so it is all displayed in the WEB UI? How can I have more LED's, since the limit is 50mah which is about 2 LED's? (they can be three per 'room', so three per GPIO pin or just per GPIO). I dont see hoe it could work with such a power limit. Also, they need to be controlled with PWM. There simply isn't enough power on the Raspberry Pi!
the code for the DHT22 sensor is:
import time
import sys
from pubnub import Pubnub
import Adafruit_DHT as dht
pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'
def callback(message):
print(message)
#published in this fashion to comply with Eon
while True:
h,t = dht.read_retry(dht.DHT22, 4)
temp='{0:0.1f}'.format(t)
hum='{0:0.1f}'.format(h)
message = {'temperature': temp, 'humidity': hum}
print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t, h)
pubnub.publish(channel=channel, message=message, callback=callback, error=callback)
the code for the led's is:
import RPi.GPIO as GPIO
import time
import sys
from pubnub import Pubnub
GPIO.setmode(GPIO.BCM)
PIN_LIVING = 22
PIN_PORCH = 17
PIN_FIREPLACE = 27
GPIO.setup(PIN_LIVING,GPIO.OUT)
GPIO.setup(PIN_PORCH,GPIO.OUT)
GPIO.setup(PIN_FIREPLACE,GPIO.OUT)
FREQ = 100 # frequency in Hz
FIRE_FREQ = 30 # flickering effect
# Duty Cycle (0 <= dc <=100)
living = GPIO.PWM(PIN_LIVING, FREQ)
living.start(0)
porch = GPIO.PWM(PIN_PORCH, FREQ)
porch.start(0)
fire = GPIO.PWM(PIN_FIREPLACE, FIRE_FREQ)
fire.start(0)
# PubNub
pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'
def _callback(m, channel):
print(m)
dc = m['brightness'] *10
if m['item'] == 'light-living':
living.ChangeDutyCycle(dc)
elif m['item'] == 'light-porch':
porch.ChangeDutyCycle(dc)
elif m['item'] == 'fireplace':
fire.ChangeDutyCycle(dc)
def _error(m):
print(m)
pubnub.subscribe(channels='pi-house', callback=_callback, error=_error)
try:
while 1:
pass
except KeyboardInterrupt:
GPIO.cleanup()
sys.exit(1)
Thanks!

Related

Is there a way to sync sending information across sockets on a network?

I am programming ada fruit ring LED lights in python, I have setup a local network for a midi controller to read data into my Raspberry Pi 3 and send to the 3 Pi Zero W through web sockets. I am running into the issue where some of the functions I have that run on threads will get out of sync with each other. In other words, one of the LED lights will go at a slightly faster or slower rate and eventually look not synced. I was curious if anyone has run into an issue like this or if I am just using the threads and events the incorrect way.
Here is some of my server side code:
import socket
from socket import *
from threading import Thread
import threading
import board
import neopixel
import sys
import time
import random
import os
from adafruit_led_animation.animation.comet import Comet
def handle_client(client):
p = None
connected = True
lights_on_default()
while True:
global thread_running
data=client.recv(1024).decode()
if not data:
connected = False
thread_running = False
break
if 'Pad' in data:
thread_running = False
thread = threading.Event()
if data == 'Pad 1':
thread_running = False
if p:
p.join()
p = Thread(target=slow_circles, args=(thread,))
p.daemon = True
p.start()
def slow_circles(event):
global thread_running
thread_running = True
while not event.isSet():
if not thread_running:
event.set()
break
for i in range(num_of_pixels):
// goes through the lighting of pixels
if not thread_running:
event.set()
break
pixels.show()
Here is some of my client side code:
import rtmidi.midiutil as midiutil
import time
import socket
buttons = {
36: 'Pad 1',
}
try:
s1 = socket.socket()
s2 = socket.socket()
except:
print('Error making socket')
port1 = 12346
port2 = 12347
serverOne = '192.168.1.18' // 1st Pi Zero W
serverTwo = '192.168.1.17' // 2nd Pi Zero W
def start():
global s1
global s2
notConnected = True
while True:
while notConnected:
connected = False
try:
s1.connect((serverOne, port1))
s2.connect((serverTwo, port2))
connected = True
break
except:
s1.close()
s2.close()
s1.socket.socket()
s2.socket.socket()
if connected:
midiin, port = midiutil.open_midiinput(1)
midiin.set_callback(midiCallback) // gets pad from midi controller
while True:
retry = False
try:
s1.sendall('red connected'.encode('utf8'))
s2.sendall('yellow connected'.encode('utf8'))
except:
retry = True
if retry:
s1.close()
s2.close()
midiin.delete()
break
else:
time.sleep(15)
def midiCallback(message, data):
control = message[0][1]
try:
value = message[0][2]
if (control in button.keys()):
name = buttons[control]
if (value > 0):
return buttonDown(name)
except IndexError:
pass
def buttonDown(button):
s1.sendall(f'{button}'.encode('utf8'))
s2.sendall(f'{button}'.encode('utf8'))
start()
And when I hit the pad and do the function I send data to the two PIs and they start at the same time but over time get out of sync. All help would be appreciated thanks.

python for Raspberry 0W surveillance camera write to NAS

I have made a raspi0 PIR cam and am trying to get it to write to my network storage device. The .py writes to the drive but just keeps re-saving over the same file unless I ctrl C and manually restart.
from picamera import PiCamera
import time
from time import sleep
import os
import sys
from datetime import datetime
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pir_sensor = 17 #GPIO physical pin 11
GPIO.setup(pir_sensor, GPIO.IN, GPIO.PUD_DOWN)
current_state = 0
filename_part1="surv"
file_ext=".mp4"
now = datetime.now()
current_datetime = now.strftime("%d-%m-%Y_%H:%M:%S")
filename=filename_part1+"_"+current_datetime+file_ext
filepath="/mnt/local_share/Surveillance_Captures/"
def capture_video():
camera.start_preview()
camera.start_recording('/home/pi/python_code/capture/newvideo.h264')
camera.wait_recording(10)
camera.stop_recording()
camera.stop_preview()
def remove_file():
if os.path.exists("/home/pi/python_code/capture/newvideo.h264"):
os.remove("/home/pi/python_code/capture/newvideo.h264")
else:
print("file does not exist")
camera=PiCamera()
while True:
i = GPIO.input(17)
if i==1:
print("Motion Detected")
capture_video()
sleep(2)
res=os.system("MP4Box -add /home/pi/python_code/capture/newvideo.h264 /home/pi/python_code/capture/newvideo.mp4")
os.system("mv /home/pi/python_code/capture/newvideo.mp4 "+filepath+filename)
print("File Moved")
print("Scanning Sector")
sleep(2)
remove_file()
Because you put filename=filename_part1+"_"+current_datetime+file_ext out of while loop, so the filename never change.
while True:
now = datetime.now()
current_datetime = now.strftime("%d-%m-%Y_%H:%M:%S")
filename=filename_part1+"_"+current_datetime+file_ext

Error while Working with US-100 on Raspberry pi 3

I wrote the following code for my US-100 ultrasonic distance measurement sensor. But I am getting junk results everytime. when ever I am moving my sensor, I dont get any change in reading. Also, when I am connecting GND and VCC to sensor, input stops generating. Need help with Circuit diagram for connecting US-100 to Raspberry pi 3 and errors in this code which lead to junk results
import RPi.GPIO as GPIO
import time
import logging
LOG_FILENAME='US_100.log'
logging.basicConfig(format='%(asctime)s %(message)s',filename='US_100',
level=logging.DEBUG)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
TRIG = 23
ECHO = 24
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
while True:
GPIO.output(TRIG,False)
time.sleep(1.5)
print("Waiting for sensor to settle")
GPIO.output(TRIG,True)
time.sleep(0.0001)
GPIO.output(TRIG, False)
pulse_start=time.time()
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = (pulse_end-pulse_start)
print("Pulse duration =%1f " %pulse_duration)
distance = (pulse_duration*343/2)
if distance >0.5 and distance <400:
print("Distance = %1f" %distance)
else:
print("Out of Range")
logging.debug(distance)
Image of results which I am getting even though the object is 15-20cm apart.
Output Image

Controlling LED's with PCA9685

I have bought an Adafruit PCA9685 and completed the library installation, however, I have no clue of how to Program it. I want to base it on the following code I wrote:
import RPi.GPIO as GPIO
import time
import sys
from pubnub import Pubnub
GPIO.setmode(GPIO.BCM)
PIN_LIVING = 22
PIN_PORCH = 17
PIN_FIREPLACE = 27
GPIO.setup(PIN_LIVING,GPIO.OUT)
GPIO.setup(PIN_PORCH,GPIO.OUT)
GPIO.setup(PIN_FIREPLACE,GPIO.OUT)
FREQ = 100 # frequency in Hz
FIRE_FREQ = 30 # flickering effect
# Duty Cycle (0 <= dc <=100)
living = GPIO.PWM(PIN_LIVING, FREQ)
living.start(0)
porch = GPIO.PWM(PIN_PORCH, FREQ)
porch.start(0)
fire = GPIO.PWM(PIN_FIREPLACE, FIRE_FREQ)
fire.start(0)
# PubNub
pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'
def _callback(m, channel):
print(m)
dc = m['brightness'] *10
if m['item'] == 'light-living':
living.ChangeDutyCycle(dc)
elif m['item'] == 'light-porch':
porch.ChangeDutyCycle(dc)
elif m['item'] == 'fireplace':
fire.ChangeDutyCycle(dc)
def _error(m):
print(m)
pubnub.subscribe(channels='pi-house', callback=_callback, error=_error)
try:
while 1:
pass
except KeyboardInterrupt:
GPIO.cleanup()
sys.exit(1)
I dont know if on this its similar. I bought it because I wanted to be able to control more LED's with PWM from the Raspberry pi. I looked into it and found all kinds of weird commands and terms specific to this Chip.
Thanks!
First, If you look at page 29 of the data sheet (fig. 15) it shows that for Direct LED connection, you need to connect your LEDs inverted. i.e. connect the ground of the LED to the PWM line on the PCA9685 and the positive of the LED to the V+
Code is pretty simple (below is for an Arduino) And you use the function pwm.setPWM(uint8_t num, uint16_t on, uint16_t off) to turn the LEDs on and off and to different levels of brightness.
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
void setup()
{
Serial.begin(9600);
pwm.begin();
pwm.setPWMFreq(1600); //This is the maximum PWM frequency
pwm.setPWM(1,0,4095); //this turns on the LED connected to channel one (I suspect the only line you're really looking for)
}
Hope that answers your question!
See below how to do this in python
import Adafruit_PCA9685
pwm = Adafruit_PCA9685.PCA9685()
pwm.set_pwm_freq(60)
# Demo using LED on Channel 12 of the PCA9685
# Wire up the LED on Channel 12 such that
# Shortleg of LED goes to GND and
# Long leg goes to PWM pin on channel 12
pwm.set_pwm(12,0,4095) # Full bright
time.sleep(5)
pwm.set_pwm(12,1024,3072) # half bright
time.sleep(5)
pwm.set_pwm(12,0,0) #off
time.sleep(5)

Python and gpio raspberry

I have a problem with my project, I have a little python script to read my gas meter.
Every revolution of digits a small magnet inside the gas meter close to the reed switch makes an input for my raspberry. The problem is when the magnet stops close to the sensor circuit leaving on a high level, which cause false inputs, here my script.
Any suggestion? thanks to all
#!/usr/bin/env python
import time
import datetime
import os.path
import pycurl
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(10, GPIO.RISING, bouncetime = 5000)
def GetGas(arg):
time.sleep(0.01) # need to filter out the false positive of some power fluctuation
if GPIO.input(10) != GPIO.HIGH:
return
gastotale=0
if os.path.isfile('/var/www/myscripts/gas/gastotale.txt'):
file = open("/var/www/myscripts/gas/gastotale.txt","r")
gastotale = float(file.read())
file.close()
gastotale = gastotale+0.01
file = open("/var/www/myscripts/gas/gastotale.txt","w")
file.write(str(gastotale))
file.close()
now = datetime.datetime.now()
fileday = '/var/www/myscripts/gas/'+now.strftime("%Y-%m-%d")+'.txt'
gasday = 0
if os.path.isfile(fileday):
file = open(fileday,"r")
gasday = float(file.read())
file.close()
gasday = gasday+0.01
file = open(fileday,"w")
file.write(str(gasday))
file.close()
oem = pycurl.Curl()
oem.setopt(oem.URL, 'http://emoncms.org/input/post.json?node=0
csv=0,'+str(gasday)+',0,0,'+str(gastotale)+'&apikey=dfb6ccf')
oem.perform()
laststate = 0
while True:
if (GPIO.input(10) == 1 ):
if (laststate == 0):
gastotale = gastotale+0.01
laststate=1
else:
laststate=0
time.sleep(30)

Categories

Resources