how to format 12 hours time in Raspi lcd with I2C - python

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!

Related

About "write()" change string to byte

i want to use "ser.write()" ,but error say a is not byte.
so ,what can i do?
import serial
from time import sleep
import sys
ser = serial.Serial('/dev/ttyS0',9600,timeout=1);
try:
whiel True:
a = input()
ser.write(a)
sleep(1)
except KeyboardInterrupt:
ser.close()

run code every X seconds

I Have infinite loop that read bytes from serial port, I want to save the read data to firebase database every X seconds.
I used this code snippet but it's not helping:
import threading
def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"
printit()
This is my code
import serial
ser = serial.Serial()
ser.baudrate = 115200
ser.port = "/dev/ttyUSB0"
ser.timeout = 30
try:
try:
while 1:
line = ser.readline().rstrip().decode('utf-8')
# print("save data here every X seconds)
except KeyboardInterrupt:
ser.close() # Close port
pass
except serial.serialutil.SerialException as e:
print(str(e))
I can't use sleep because it blocking the main thread,So how to let the code read continuously and print "data saved" every X seconds (I'll save to database in my case)
Thanks to Lutz Horn for the suggestion in the comment, I resolve the problem like that :
import schedule
import time
import serial
ser = serial.Serial()
ser.baudrate = 115200
ser.port = "/dev/ttyUSB0"
ser.timeout = 30
schedule.every(10).seconds.do(save_db)
try:
try:
while 1:
schedule.run_pending()
line = ser.readline().rstrip().decode('utf-8')
# here every 10 seconds the function save_db will be called
except KeyboardInterrupt:
ser.close() # Close port
pass
except serial.serialutil.SerialException as e:
print(str(e))
I hope i have understood you correctly. Use time.time() to set timer.
import time
def doEvery_X_Seconds():
print("I do it every X seconds")
time.sleep(1)
TIMER_LIMIT = 5
setTimer = time.time()
while(1):
print("hello world")
if(time.time() - setTimer >= TIMER_LIMIT):
doEvery_X_Seconds()
setTimer = time.time()
There is time.sleep(1) only to demonstrate, that it works.

Print time output on one line instead of scrolling, python 2

Is there a way of printing the time output on one line instead of scrolling down the page.
while True:
import datetime
import pytz
T = datetime.datetime.now()
print(T)
in python 2, do below, i try on my python2.7, its also working even without the sys.stdout.flush()
while True:
import datetime
T = datetime.datetime.now()
print "{}\r".format(T), ;sys.stdout.flush()
in python 3
while True:
import datetime
T = datetime.datetime.now()
print(T, end='\r', flush=True)
import datetime
import sys
import os
os.system('setterm -cursor off')
while True:
T = datetime.datetime.now()
sys.stdout.write(str(T))
sys.stdout.write('\b' * 50)
you can import print from python 3 and do:
from __future__ import print_function
import time
import sys
import datetime
while True:
T = datetime.datetime.now()
print(T, end="\r")
sys.stdout.flush()
time.sleep(.4)
This solution is based on the following gist

Sensor data log csv in python

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).

Python - Raspberry pi GPIO to SQlite3 - High/Lov with timestamp

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()

Categories