Right now i have a simple python solution that's working perfect.
it is making a log.txt file and update everytime there is a connection on/off GPIO 12.
But the file is getting longer and longer, and it's time to upgrade to a little database (SQlite3) to make it more easy to read and sort, on the webpage.
It has been some years since i last had my hands on SQL, so i need some help to get this working.
Here is the Python log-file script i want to update to use SQlite
#!/usr/bin/python
import datetime
import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
DS = 12
GPIO.setup(DS,GPIO.IN,pull_up_down = GPIO.PUD_UP)
logfile = "/var/www/html/log.txt"
start = GPIO.input(DS)
while True:
while GPIO.input(DS) == start:
time.sleep(.25)
now = datetime.datetime.now()
start = GPIO.input(DS)
timp = now.strftime("%d %B %Y - %H:%M:%S") + " - " + str(start)
print timp
with open(logfile, "a") as file:
file.write(timp +chr(10))
#!/usr/bin/python
import datetime
import time
import RPi.GPIO as GPIO
import sqlite3
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
DS = 12
GPIO.setup(DS,GPIO.IN,pull_up_down = GPIO.PUD_UP)
logfile = "/var/www/html/log.txt"
start = GPIO.input(DS)
while True:
while GPIO.input(DS) == start:
time.sleep(.25)
now = datetime.datetime.now()
start = GPIO.input(DS)
timp = now.strftime("%d %B %Y - %H:%M:%S") + " - " + str(start)
print timp
conn = sqlite3.connect(Data Source=\mydb.db;Version=3;Password=myPassword;)
c = conn.cursor()
c.execute("INSERT INTO table VALUES('%s')",timp)
conn.commit()
conn.close()
Related
I work on a sequencial started audio recorder on Raspberry pi, my problem is the following:
I tried several ways ,I described under the code, to get Pyaudio open a stream after the second time it recorded and saved the stream in .wav format.
in the second run it wont start over opening the stream and gives me this error,
I simply don't get why the default input device only gets accepted once is it my still used by the last stream even If I terminated it?
I am using an external USB as input since raspberry still has no option to take Mic. input.
I also took .open() and tried every possible input device I found.
Traceback (most recent call last):
File "/home/fabian/Documents/Zusammenschluss_REC()_mit_Interrupt_BACKUP1.py", line 122, in <module>
stream = audio.open(format= pyaudio.paInt16, channels = 1, rate=44100, input= True, frames_per_buffer=1024)
File "/home/fabian/.local/lib/python3.9/site-packages/pyaudio.py", line 754, in open
stream = Stream(self, *args, **kwargs)
File "/home/fabian/.local/lib/python3.9/site-packages/pyaudio.py", line 445, in __init__
self._stream = pa.open(**arguments)
OSError: [Errno -9996] Invalid input device (no default output device)
#imports to be made:
import RPi.GPIO as GPIO
import time
import os
import sys
import signal
import datetime
import pyaudio
import wave
#variables to be defined:
BUTTON_GPIO = 16
LED_REC_GPIO = 20
LED_ON_GPIO = 21
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
global TIME_LAST_PRESSED
TIME_LAST_PRESSED = time.time()
global TIME_LAST_SWITCHED
TIME_LAST_SWITCHED = time.time()
global timeout
timeout = 1
TIME_MIN = 0.2
TIME_MAX = 0.6
Loop = True
REC = False
audio = pyaudio.PyAudio()
parent_dir = "/home/fabian/Dokumente/Speicherordner_Audiofiles"
global person
person = "fabian"
#Definition of functions:
def signal_handler(sig, frame):
GPIO.cleanup()
sys.exit(0)
def button_pressed_callback(channel):
print("Button has been pressed")
global TIME_LAST_PRESSED
global TIME_LAST_SWITCHED
global REC
print("CALLBACK activated, now checking sequence")
x = time.time() - TIME_LAST_PRESSED
print(x)
if x > TIME_MIN and x < TIME_MAX:
print("Sequence succeded! Sequence time:" + str(x))
y = time.time() - TIME_LAST_SWITCHED
if timeout < y:
TIME_LAST_SWITCHED = time.time()
REC = not REC
print("REC has now the value off:" + str(REC))
TIME_LAST_PRESSED = time.time()
#setup of GPIO:
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_GPIO,GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(LED_REC_GPIO, GPIO.OUT)
GPIO.setup(LED_ON_GPIO, GPIO.OUT)
GPIO.add_event_detect(BUTTON_GPIO, GPIO.FALLING, callback = button_pressed_callback, bouncetime = 100)
signal.signal(signal.SIGINT, signal_handler)
#setup of savingpath:
saving_path = parent_dir + "/" + person
if os.path.isfile(saving_path):
os.makedirs(saving_path)
#"Main" loop:
GPIO.output(LED_ON_GPIO, GPIO.HIGH)
while Loop:
if REC:
stream = audio.open(format= pyaudio.paInt16, channels = 1, rate=44100, input= True, frames_per_buffer=1024)
frames = []
REC_TIME = time.time()
GPIO.output(LED_REC_GPIO, GPIO.HIGH)
while REC:
data = stream.read(1024)
frames.append(data)
GPIO.remove_event_detect(BUTTON_GPIO)
stream.stop_stream()
stream.close()
audio.terminate()
now = datetime.datetime.now()
REC_TIME = time.time()-REC_TIME
date =str(now.day) + "." + str(now.month) + "." + str(now.year) + " " + str(now.hour) + ":" + str(now.minute) + " "
os.makedirs(saving_path +"/"+ date + str(REC_TIME))
sound_file = wave.open(saving_path + date + str(REC_TIME), "w")
sound_file.setnchannels(1)
sound_file.setsampwidth(audio.get_sample_size(pyaudio.paInt16))
sound_file.setframerate(44100)
sound_file.writeframes(b"".join(frames))
sound_file.close()
GPIO.add_event_detect(BUTTON_GPIO, GPIO.FALLING, callback = button_pressed_callback, bouncetime = 100)
else:
GPIO.output(LED_REC_GPIO, GPIO.LOW)
if Loop == False:
print ("cleanup")
GPIO.cleanup
I created .asoundrc set the default card and device after I looked it up with aplay -l and arecord -l
I changed the default in alsa.conf
First run everything works just fine, second time in the recording loop it won't take the input device.
So I added this line to my crontab at the end of the file, but I cannot seem to get my program to run. I'm not logging anything in my scubot.log so that's not very helpful. Not sure what I'm doing wrong, I've tried several solutions to this but can't seem to find any good information, at least nothing that fits my case.
#reboot sleep 15; /usr/bin/python3 /home/pi/Documents/scubot/scubot.py >> /home/pi/Documents/scubot/scubot.log
from sqlite3 import Date, Error
import ssl
import requests
import configparser
from datetime import date, datetime
import schedule
import time
import emailHelper
from email_templates import emails
# import RPi.GPIO as GPIO
# import time
config = configparser.ConfigParser()
config.read(".config")
configstuff = config['Weather_API']['weatherAPIKey']
lat = "41.6884"
long = "-93.7925"
import pymongo
# Replace the uri string with your MongoDB deployment's connection string.
conn_str = "mongodb+srv://sensitive.nqx9x.mongodb.net/?retryWrites=true&w=majority"
# set a 5-second connection timeout
client = pymongo.MongoClient(conn_str, serverSelectionTimeoutMS=5000)
db = client.scubot
weatherDataCollection = db.weatherdata
# create env to only run this when on the raspberry pi?
import os
import time
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
device_file = '/sys/devices/w1_bus_master1/28-0620111704e4/w1_slave'
print('Scubot Started')
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
print('lines', lines)
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
print('temp string', temp_string)
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_f
response = requests.get("https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&units=imperial&appid=" + configstuff + "").json()
weather = response['main']
city = response['name']
icon = response['weather'][0]['icon']
number1 = 498474239847239
boolean = True
# print(city)
# print(weather)
def storeWeatherData():
try:
weatherData = {
"city": city,
"outsideTemp" : weather['temp'],
"humidity" : weather['humidity'],
"outsidePressure" : weather['pressure'],
"lat": lat,
"long": long,
"shallowProbeTemp": "{:.2f}".format(read_temp()),
"dateOfTempReading": datetime.now()
}
weatherDataCollection.insert_one(weatherData)
print(weatherData, 'Successfully inserted into the database')
except Exception:
print(Exception)
# emailHelper.sendEmail(['test'], 'testing scuba app', emails.temperatureEmail(weather['temp'], lat, long))
# # This uses a scheduler to run a certain function every day. We can set this to minutes or hours or days.
schedule.every(1).minutes.do(storeWeatherData)
while True:
schedule.run_pending()
time.sleep(1)
I would like to change my lcd 24 hours time format to 12 hours
import lcddriver
import time
import datetime
display = lcddriver.lcd()
try:
print("Writing to display")
display.lcd_display_string("Time", 1)
while True:
display.lcd_display_string(str(datetime.datetime.now().time()), 2)
except KeyboardInterrupt:
print("Cleaning up!")
display.lcd_clear()
You could use datetime module in python like this:
import lcddriver
import time
import datetime
display = lcddriver.lcd()
try:
print("Writing to display")
display.lcd_display_string("Time", 1)
while True:
datestr = datetime.datetime.now().strftime("%I:%M:%S %p")
display.lcd_display_string(datestr, 2)
except KeyboardInterrupt:
print("Cleaning up!")
display.lcd_clear()
For example, if current time is 15:40:50 then datetime.datetime.now().strftime("%I:%M:%S %p") outputs 03:40:50 PM
Hope it helps you!
In this script I am taking the temperature from a DHT11 sensor and parsing the data that another script can read. Everything works except for writing the file to another pc using the path I placed in the f = open part of the script below. Everything works great except that the file doesn't get written or saved.
Any Help?
#!/usr/bin/env python
# encoding: utf-8
import sys
import time
import dht11
import RPi.GPIO as GPIO
#define GPIO 14 as DHT11 data pin
Temp_sensor=14
def main():
# Main program block
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers
instance = dht11.DHT11(pin = Temp_sensor)
while True:
#get DHT11 sensor value
result = instance.read()
temp = '{:.0f}'.format(result.temperature * 1.8 + 32)+"°"
# The path to send the txt file to and save is /10.1.1.28/c$/Temperature_RETR/kvoa_temp.txt
if result.is_valid():
print temp
f = open('\\10.1.1.28\c$\Temperature_RETR\new_temp.txt','w')
#f = open('/home/pi/Desktop/new_temp.txt','w')
y = temp
z = str(y)
f.write(z)
f.close()
time.sleep(60) # 60 second delay
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
I am new to programming and want to write a code for an infrared sensor to log a timestamp in a .csv file whenever it detects motion. So far I have found code for the detection but now need to add code to specify for it to write an entry in a csv file. Credits for motion detection code: https://www.modmypi.com/blog/raspberry-pi-gpio-sensing-motion-detection
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)
def MOTION(PIR_PIN):
print ("Motion Detected")
print ("PIR Module Test (CTRL+C to exit)")
time.sleep(2)
print ("Ready")
try:
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
while 1:
time.sleep(100)
except KeyboardInterrupt:
print("Quit")
GPIO.cleanup()
Next I am trying to add something along the following lines which will then write in two columns TIMESTAMP and "motion detected":
import csv
import strftime
row = [strfttime("%a, %d %b %Y %H:%M:%S"), motion_detected]
with open('datalog.csv', 'a') as f:
w = csv.writer(f)
w.writerow(row)
I have only found ways to write to CSV's from static files so they didn't seem to provide a straightforward answer to my question. So any help in joining these codes or correcting the second would be great!
import RPi.GPIO as GPIO
import time
import csv
import strftime
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)
def MOTION(PIR_PIN):
print ("Motion Detected")
print ("PIR Module Test (CTRL+C to exit)")
row = [strfttime("%a, %d %b %Y %H:%M:%S"), 'motion_detected']
with open('datalog.csv', 'a') as f:
w = csv.writer(f)
w.writerow(row)
time.sleep(2)
print ("Ready")
try:
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
while 1:
time.sleep(100)
except KeyboardInterrupt:
print("Quit")
GPIO.cleanup()
Note: For a string motion detected, you need to add quotaion marks around it(in Python both single and double ones are supported).