since i didnt really get the Adafruit-Library going to read the sensor correctly, i started using PIGPIO to read the DHT22. It works and i can see the Temperature and Humidity. My problem is now, how do i get those values into InfluxDB to use them in Grafana.
I already installed my DB and connected it with Grafana and made a DB called temp. The connection worked, now i just need to input some data.
!/usr/bin/env python
# 2014-07-11 DHT22.py
import time
import atexit
import pigpio
class sensor:
"""
A class to read relative humidity and temperature from the
DHT22 sensor. The sensor is also known as the AM2302.
The sensor can be powered from the Pi 3V3 or the Pi 5V rail.
Powering from the 3V3 rail is simpler and safer. You may need
to power from 5V if the sensor is connected via a long cable.
For 3V3 operation connect pin 1 to 3V3 and pin 4 to ground.
Connect pin 2 to a gpio.
For 5V operation connect pin 1 to 5V and pin 4 to ground.
The following pin 2 connection works for me. Use at YOUR OWN RISK.
5V--5K_resistor--+--10K_resistor--Ground
|
DHT22 pin 2 -----+
|
gpio ------------+
"""
def __init__(self, pi, gpio, LED=None, power=None):
"""
Instantiate with the Pi and gpio to which the DHT22 output
pin is connected.
Optionally a LED may be specified. This will be blinked for
each successful reading.
Optionally a gpio used to power the sensor may be specified.
This gpio will be set high to power the sensor. If the sensor
locks it will be power cycled to restart the readings.
Taking readings more often than about once every two seconds will
eventually cause the DHT22 to hang. A 3 second interval seems OK.
"""
self.pi = pi
self.gpio = gpio
self.LED = LED
self.power = power
if power is not None:
pi.write(power, 1) # Switch sensor on.
time.sleep(2)
self.powered = True
self.cb = None
atexit.register(self.cancel)
self.bad_CS = 0 # Bad checksum count.
self.bad_SM = 0 # Short message count.
self.bad_MM = 0 # Missing message count.
self.bad_SR = 0 # Sensor reset count.
# Power cycle if timeout > MAX_TIMEOUTS.
self.no_response = 0
self.MAX_NO_RESPONSE = 2
self.rhum = -999
self.temp = -999
self.tov = None
self.high_tick = 0
self.bit = 40
pi.set_pull_up_down(gpio, pigpio.PUD_OFF)
pi.set_watchdog(gpio, 0) # Kill any watchdogs.
self.cb = pi.callback(gpio, pigpio.EITHER_EDGE, self._cb)
def _cb(self, gpio, level, tick):
"""
Accumulate the 40 data bits. Format into 5 bytes, humidity high,
humidity low, temperature high, temperature low, checksum.
"""
diff = pigpio.tickDiff(self.high_tick, tick)
if level == 0:
# Edge length determines if bit is 1 or 0.
if diff >= 50:
val = 1
if diff >= 200: # Bad bit?
self.CS = 256 # Force bad checksum.
else:
val = 0
if self.bit >= 40: # Message complete.
self.bit = 40
elif self.bit >= 32: # In checksum byte.
self.CS = (self.CS << 1) + val
if self.bit == 39:
# 40th bit received.
self.pi.set_watchdog(self.gpio, 0)
self.no_response = 0
total = self.hH + self.hL + self.tH + self.tL
if (total & 255) == self.CS: # Is checksum ok?
self.rhum = ((self.hH << 8) + self.hL) * 0.1
if self.tH & 128: # Negative temperature.
mult = -0.1
self.tH = self.tH & 127
else:
mult = 0.1
self.temp = ((self.tH << 8) + self.tL) * mult
self.tov = time.time()
if self.LED is not None:
self.pi.write(self.LED, 0)
else:
self.bad_CS += 1
elif self.bit >= 24: # in temp low byte
self.tL = (self.tL << 1) + val
elif self.bit >= 16: # in temp high byte
self.tH = (self.tH << 1) + val
elif self.bit >= 8: # in humidity low byte
self.hL = (self.hL << 1) + val
elif self.bit >= 0: # in humidity high byte
self.hH = (self.hH << 1) + val
else: # header bits
pass
self.bit += 1
elif level == 1:
self.high_tick = tick
if diff > 250000:
self.bit = -2
self.hH = 0
self.hL = 0
self.tH = 0
self.tL = 0
self.CS = 0
else: # level == pigpio.TIMEOUT:
self.pi.set_watchdog(self.gpio, 0)
if self.bit < 8: # Too few data bits received.
self.bad_MM += 1 # Bump missing message count.
self.no_response += 1
if self.no_response > self.MAX_NO_RESPONSE:
self.no_response = 0
self.bad_SR += 1 # Bump sensor reset count.
if self.power is not None:
self.powered = False
self.pi.write(self.power, 0)
time.sleep(2)
self.pi.write(self.power, 1)
time.sleep(2)
self.powered = True
elif self.bit < 39: # Short message receieved.
self.bad_SM += 1 # Bump short message count.
self.no_response = 0
else: # Full message received.
self.no_response = 0
def temperature(self):
"""Return current temperature."""
return self.temp
def humidity(self):
"""Return current relative humidity."""
return self.rhum
def staleness(self):
"""Return time since measurement made."""
if self.tov is not None:
return time.time() - self.tov
else:
return -999
def bad_checksum(self):
"""Return count of messages received with bad checksums."""
return self.bad_CS
def short_message(self):
"""Return count of short messages."""
return self.bad_SM
def missing_message(self):
"""Return count of missing messages."""
return self.bad_MM
def sensor_resets(self):
"""Return count of power cycles because of sensor hangs."""
return self.bad_SR
def trigger(self):
"""Trigger a new relative humidity and temperature reading."""
if self.powered:
if self.LED is not None:
self.pi.write(self.LED, 1)
self.pi.write(self.gpio, pigpio.LOW)
time.sleep(0.017) # 17 ms
self.pi.set_mode(self.gpio, pigpio.INPUT)
self.pi.set_watchdog(self.gpio, 200)
def cancel(self):
"""Cancel the DHT22 sensor."""
self.pi.set_watchdog(self.gpio, 0)
if self.cb is not None:
self.cb.cancel()
self.cb = None
if __name__ == "__main__":
import time
import pigpio
import DHT22
# Intervals of about 2 seconds or less will eventually hang the DHT22.
INTERVAL = 3
pi = pigpio.pi()
s = DHT22.sensor(pi, 2, LED=16, power=8)
r = 0
next_reading = time.time()
while True:
r += 1
s.trigger()
time.sleep(0.2)
print("{} {} {} {:3.2f} {} {} {} {}".format(
r, s.humidity(), s.temperature(), s.staleness(),
s.bad_checksum(), s.short_message(), s.missing_message(),
s.sensor_resets()))
next_reading += INTERVAL
time.sleep(next_reading-time.time()) # Overall INTERVAL second polling.
s.cancel()
pi.stop()
Related
from microbit import *
from ssd1306 import initialize, clear_oled
from ssd1306_stamp import draw_stamp
from ssd1306_img import create_stamp
from ssd1306_text import add_text
import utime as time
window = []
threshold = 550 # limit
count = 0
sample = 0
beat = False
start = False
good = create_stamp(Image.HAPPY)
bad = create_stamp(Image.SAD)
heart = create_stamp(Image.HEART)
values = []
def mean(datalist):
sum = 0
for i in datalist:
sum += i
if len(datalist) > 0:
return sum/len(datalist)
else:
return None
while True:
if button_a.was_pressed():
while True:
signal = pin1.read_analog()
window.append(signal)
avg = round(mean(window))
values.append(avg)
if len(window) == 11:
window.pop(0)
if beat is False and avg >= threshold+10:
beat = True
count += 1
display.show(Image.HEART, wait=False)
if count == 1:
t1 = time.ticks_ms()
if count == 11:
t2 = time.ticks_ms()
T = t2 - t1
bpm = round(600*1000/(T))
display.scroll(str(bpm))
initialize()
clear_oled()
add_text(0, 0, "Heart rate :")
add_text(0, 3, str(bpm) + " bpm")
if 60 <= bpm <= 100:
draw_stamp(38, 24, good, 1)
else :
draw_stamp(38, 24, bad, 1)
count = 0
sleep(2000)
if button_b.was_pressed():
break
count = 0
elif beat is True and avg <= threshold-10:
beat = False
display.clear()
sample += 1
if sample == 250:
threshold = mean(values)
values = []
sample = 0
sleep(20)
sleep(20)
This is the code connect to the microbit, and the function is about the heart rate sensor, which it will appear the average beat per minute when sensing 10 beats of the heart.
I am thinking of adding a function that if button b is pressed, the loop will pause, and press the button a to start again. I tried to add a break function in the loop, it worked when I click the button b, it pause the loop, however, the count of beat won't reset, and the time between the beat is also recorded although I break the loop.
Is there any way that I can break the loop and reset the count?
You should reset the counter before breaking. In your current code the line for the count is not executing since it breaks out before it reaches it.
if button_b.was_pressed():
count = 0
break
I have a 2 x 16 LCD display with the I2C piggy back adapter. As a simple start I'm just displaying the encoder value. However, when I turn the encoder I get weird text written on the lcd in different areas. Also sometime the display recovers and just displays "Encoder: X" with an empty second line:
The code
#!/usr/bin/python3 -u
import time
import RPi.GPIO as GPIO
import lcd_i2c
from encoder import Encoder
GPIO.setmode(GPIO.BCM)
switch_pin = 13
encoder_down_pin = 6
encoder_up_pin = 5
GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
encoder_value = 0
mylcd = lcd_i2c.lcd()
def valueChanged(value):
encoder_value = value
print(encoder_value)
mylcd.lcd_clear()
mylcd.lcd_display_string(f"Encoder: {encoder_value}", 1)
e1 = Encoder(encoder_down_pin, encoder_up_pin, callback=valueChanged)
while True:
time.sleep(60)
# lcd_i2c.py
# -*- coding: utf-8 -*-
# Original code found at:
# https://gist.github.com/DenisFromHR/cc863375a6e19dce359d
"""
Compiled, mashed and generally mutilated 2014-2015 by Denis Pleic
Made available under GNU GENERAL PUBLIC LICENSE
# Modified Python I2C library for Raspberry Pi
# as found on http://www.recantha.co.uk/blog/?p=4849
# Joined existing 'i2c_lib.py' and 'lcddriver.py' into a single library
# added bits and pieces from various sources
# By DenisFromHR (Denis Pleic)
# 2015-02-10, ver 0.1
"""
# i2c bus (0 -- original Pi, 1 -- Rev 2 Pi)
I2CBUS = 1
# LCD Address
ADDRESS = 0x27
import smbus
from time import sleep
class i2c_device:
def __init__(self, addr, port=I2CBUS):
self.addr = addr
self.bus = smbus.SMBus(port)
# Write a single command
def write_cmd(self, cmd):
self.bus.write_byte(self.addr, cmd)
sleep(0.0001)
# Write a command and argument
def write_cmd_arg(self, cmd, data):
self.bus.write_byte_data(self.addr, cmd, data)
sleep(0.0001)
# Write a block of data
def write_block_data(self, cmd, data):
self.bus.write_block_data(self.addr, cmd, data)
sleep(0.0001)
# Read a single byte
def read(self):
return self.bus.read_byte(self.addr)
# Read
def read_data(self, cmd):
return self.bus.read_byte_data(self.addr, cmd)
# Read a block of data
def read_block_data(self, cmd):
return self.bus.read_block_data(self.addr, cmd)
# commands
LCD_CLEARDISPLAY = 0x01
LCD_RETURNHOME = 0x02
LCD_ENTRYMODESET = 0x04
LCD_DISPLAYCONTROL = 0x08
LCD_CURSORSHIFT = 0x10
LCD_FUNCTIONSET = 0x20
LCD_SETCGRAMADDR = 0x40
LCD_SETDDRAMADDR = 0x80
# flags for display entry mode
LCD_ENTRYRIGHT = 0x00
LCD_ENTRYLEFT = 0x02
LCD_ENTRYSHIFTINCREMENT = 0x01
LCD_ENTRYSHIFTDECREMENT = 0x00
# flags for display on/off control
LCD_DISPLAYON = 0x04
LCD_DISPLAYOFF = 0x00
LCD_CURSORON = 0x02
LCD_CURSOROFF = 0x00
LCD_BLINKON = 0x01
LCD_BLINKOFF = 0x00
# flags for display/cursor shift
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00
LCD_MOVERIGHT = 0x04
LCD_MOVELEFT = 0x00
# flags for function set
LCD_8BITMODE = 0x10
LCD_4BITMODE = 0x00
LCD_2LINE = 0x08
LCD_1LINE = 0x00
LCD_5x10DOTS = 0x04
LCD_5x8DOTS = 0x00
# flags for backlight control
LCD_BACKLIGHT = 0x08
LCD_NOBACKLIGHT = 0x00
En = 0b00000100 # Enable bit
Rw = 0b00000010 # Read/Write bit
Rs = 0b00000001 # Register select bit
class lcd:
#initializes objects and lcd
def __init__(self):
self.lcd_device = i2c_device(ADDRESS)
self.lcd_write(0x03)
self.lcd_write(0x03)
self.lcd_write(0x03)
self.lcd_write(0x02)
self.lcd_write(LCD_FUNCTIONSET | LCD_2LINE | LCD_5x8DOTS | LCD_4BITMODE)
self.lcd_write(LCD_DISPLAYCONTROL | LCD_DISPLAYON)
self.lcd_write(LCD_CLEARDISPLAY)
self.lcd_write(LCD_ENTRYMODESET | LCD_ENTRYLEFT)
sleep(0.2)
# clocks EN to latch command
def lcd_strobe(self, data):
self.lcd_device.write_cmd(data | En | LCD_BACKLIGHT)
sleep(.0005)
self.lcd_device.write_cmd(((data & ~En) | LCD_BACKLIGHT))
sleep(.0001)
def lcd_write_four_bits(self, data):
self.lcd_device.write_cmd(data | LCD_BACKLIGHT)
self.lcd_strobe(data)
# write a command to lcd
def lcd_write(self, cmd, mode=0):
self.lcd_write_four_bits(mode | (cmd & 0xF0))
self.lcd_write_four_bits(mode | ((cmd << 4) & 0xF0))
# write a character to lcd (or character rom) 0x09: backlight | RS=DR<
# works!
def lcd_write_char(self, charvalue, mode=1):
self.lcd_write_four_bits(mode | (charvalue & 0xF0))
self.lcd_write_four_bits(mode | ((charvalue << 4) & 0xF0))
# put string function with optional char positioning
def lcd_display_string(self, string, line=1, pos=0):
if line == 1:
pos_new = pos
elif line == 2:
pos_new = 0x40 + pos
elif line == 3:
pos_new = 0x14 + pos
elif line == 4:
pos_new = 0x54 + pos
self.lcd_write(0x80 + pos_new)
for char in string:
self.lcd_write(ord(char), Rs)
# clear lcd and set to home
def lcd_clear(self):
self.lcd_write(LCD_CLEARDISPLAY)
self.lcd_write(LCD_RETURNHOME)
# define backlight on/off (lcd.backlight(1); off= lcd.backlight(0)
def backlight(self, state): # for state, 1 = on, 0 = off
if state == 1:
self.lcd_device.write_cmd(LCD_BACKLIGHT)
elif state == 0:
self.lcd_device.write_cmd(LCD_NOBACKLIGHT)
# add custom characters (0 - 7)
def lcd_load_custom_chars(self, fontdata):
self.lcd_write(0x40);
for char in fontdata:
for line in char:
self.lcd_write_char(line)
# encoder.py
# Class to monitor a rotary encoder and update a value. You can either read the value when you need it, by calling getValue(), or
# you can configure a callback which will be called whenever the value changes.
import RPi.GPIO as GPIO
class Encoder:
def __init__(self, leftPin, rightPin, callback=None):
self.leftPin = leftPin
self.rightPin = rightPin
self.value = 0
self.state = '00'
self.direction = None
self.callback = callback
GPIO.setup(self.leftPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(self.rightPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(self.leftPin, GPIO.BOTH, callback=self.transitionOccurred)
GPIO.add_event_detect(self.rightPin, GPIO.BOTH, callback=self.transitionOccurred)
def transitionOccurred(self, channel):
p1 = GPIO.input(self.leftPin)
p2 = GPIO.input(self.rightPin)
newState = "{}{}".format(p1, p2)
if self.state == "00": # Resting position
if newState == "01": # Turned right 1
self.direction = "R"
elif newState == "10": # Turned left 1
self.direction = "L"
elif self.state == "01": # R1 or L3 position
if newState == "11": # Turned right 1
self.direction = "R"
elif newState == "00": # Turned left 1
if self.direction == "L":
self.value = self.value - 1
if self.callback is not None:
self.callback(self.value)
elif self.state == "10": # R3 or L1
if newState == "11": # Turned left 1
self.direction = "L"
elif newState == "00": # Turned right 1
if self.direction == "R":
self.value = self.value + 1
if self.callback is not None:
self.callback(self.value)
else: # self.state == "11"
if newState == "01": # Turned left 1
self.direction = "L"
elif newState == "10": # Turned right 1
self.direction = "R"
elif newState == "00": # Skipped an intermediate 01 or 10 state, but if we know direction then a turn is complete
if self.direction == "L":
self.value = self.value - 1
if self.callback is not None:
self.callback(self.value)
elif self.direction == "R":
self.value = self.value + 1
if self.callback is not None:
self.callback(self.value)
self.state = newState
def getValue(self):
return self.value
Credits for the i2c lcd script go to its author DenisFromHR
Your LCD module is internally using a 4-bit interface mode; each byte of command or data is written in two 4-bit chunks. There's no way to tell which chunk is expected next, and no way to force the start of a new byte other than completely reinitializing the LCD - you just have to be careful to always send the chunks in pairs. If you ever lose one of the chunks, the LCD is going to display gibberish from that point onward (until another chunk gets lost), since the bytes it's receiving would consist of halves from two different bytes that were sent.
And that's exactly what's going wrong here. This is the first few bytes of the "Encoder:" message, in hex:
45 6E 63 6F 64 65 72 3A
And this is the start of the repeated garbage string you're getting, again in hex:
56 E6 36 F6 46 57 23 A2
Note that it's exactly the same data, just shifted over by one hex digit.
I see no obvious reason why this would be happening, but the first thing I'd try is increasing those sleep()s in lcd_strobe() by a factor of 100 or so, in case they're not long enough for the chunk to be reliably read by the LCD module.
I did get rid of the issue. It seems to be a problem to update the lcd from within a callback. So how I solved the issue is by merely changing the state of the program and to regularly check for updates in that state and then display the results accordingly:
#!/usr/bin/python3 -u
import os
import time
import RPi.GPIO as GPIO
import lcd_i2c
from encoder import Encoder
GPIO.setmode(GPIO.BCM)
os.system('say start')
switch_pin = 13
encoder_down_pin = 6
encoder_up_pin = 5
encoder_value = 0
dirty = True
pressed = True
mylcd = lcd_i2c.lcd()
def switch_pressed(v):
global pressed, dirty
print("OK")
pressed = True
dirty = True
GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(switch_pin, GPIO.FALLING)
GPIO.add_event_callback(switch_pin, switch_pressed)
def update():
global encoder_value, dirty, pressed
if not dirty: return
mylcd.lcd_clear()
mylcd.lcd_display_string(f"Encoder: {encoder_value}", 1)
if pressed:
mylcd.lcd_display_string("Pressed", 2)
pressed = False
dirty = False
def valueChanged(value):
global encoder_value
global dirty
dirty = True
encoder_value = max(0, value)
print(encoder_value)
e1 = Encoder(encoder_down_pin, encoder_up_pin, callback=valueChanged)
update()
try:
while True:
update()
time.sleep(.5)
finally:
print("Cleanup")
GPIO.cleanup()
I'm using a variable called dirty to determine if the display should be updated. This prevents the display from flickering.
Does that piggyback use 5v logic levels or 3.3v? This looks to me like either
a floating clock/data line(s) (maybe check with a scope whether they are correctly pulled up by the Pi's pullup resistors)
mismatching logic levels. It the device expects "high" to be 5v, but the RPi pulls it up to 3.3v, strange behaviour can occur when the bus is idle, as the device may interpret the 3.3v as if the master pulled the bus low.
This document describes what you should expect electrically
I am trying to code ultrasonic sensors to count the number of cars in a parking lot. I am relatively new to Python, so I am asking here for help.
I have three parking slots, in which each of them has an ultrasonic sensor.
How do I make it so that the sensors and their counters work together? For example, when the parking slots are empty, the counter shows three parking slots available. When two parking slots are filled, the counter shows one availability, etc.
I have done the following code, and I am wondering how I could continue to achieve my objective?
# Sensor 1
def distance_1():
time.sleep(0.5)
GPIO.output(TRIG_1, True)
time.sleep(0.00001)
GPIO.output(TRIG_1, False)
print("Reading Sensor 1")
while GPIO.input(ECHO_1) == 0:
start = time.time()
while GPIO.input(ECHO_1) == 1:
end = time.time()
duration = end - start
sound = 34000 / 2
distance = duration * sound
round(distance, 0)
total = 3
count = total
if distance <= 10:
count -= 1
elif distance > 10:
count += 1
if count < 0:
count = 0
elif count > total:
count = total
print(count)
mylcd.lcd_display_string("{}".format(count), 2)
# Sensor 2
def distance_2():
time.sleep(0.5)
GPIO.output(TRIG_2, True)
time.sleep(0.00001)
GPIO.output(TRIG_2, False)
print("Reading Sensor 2")
while GPIO.input(ECHO_2) == 0:
start = time.time()
while GPIO.input(ECHO_2) == 1:
end = time.time()
duration = end - start
sound = 34000 / 2
distance = duration * sound
round(distance, 0)
total = 3
count = total
if distance <= 10:
count -= 1
elif distance > 10:
count += 1
if count < 0:
count = 0
elif count > total:
count = total
print(count)
mylcd.lcd_display_string("{}".format(count), 2)
# Sensor 3
def distance_3():
time.sleep(0.5)
GPIO.output(TRIG_3, True)
time.sleep(0.00001)
GPIO.output(TRIG_3, False)
print("Reading Sensor 3")
while GPIO.input(ECHO_3) == 0:
start = time.time()
while GPIO.input(ECHO_3) == 1:
end = time.time()
duration = end - start
sound = 34000 / 2
distance = duration * sound
round(distance, 0)
total = 3
count = total
if distance <= 10:
count -= 1
elif distance > 10:
count += 1
if count < 0:
count = 0
elif count > total:
count = total
print(count)
mylcd.lcd_display_string("{}".format(count), 2)
while True:
distance_1()
distance_2()
distance_3()
GPIO.cleanup()
The trouble with programming is there are so many ways to achieve the same result.
Looking at your code, I would suggest taking a step back and refactoring it to use Python classes instead. You have a lot of code repetition happening, and eventually, the code will break if you need to keep adding more sensors.
For example:
class Parking:
"This is a parking class"
def __init__(self, space):
self.space = space
def empty(self):
if self.space == 0:
print('Parking space is empty')
def full(self):
if self.space == 1:
print('Parking space is full')
def distance(self):
time.sleep(0.5)
GPIO.output(TRIG, True)
. . .
# Input:
sensor1 = Parking(1)
sensor2 = Parking(1)
sensor3 = Parking(0)
# Output:
sensor1.empty()
sensor2.empty()
sensor3.empty()
# Output:
sensor1.full()
sensor2.full()
sensor3.full()
You can then update a dictionary with the output to monitor the latest sensor information. Ideally, the dictionary would be written to a central file accessible by all the sensors or raspberry pis to read.
available_spaces = {"sensor1": 0, "sensor2": 1, "sensor3": 0}
I analyzed your code and I did some refactorings.
I suggest you to use constant values initialization (the config section you see in the code below). The values I used are random.
A function can be parametrized, so you can pass arguments to functions, and avoid writing the same piece of code changing only a few values in the same place.
You should set up your microcontroller when the script starts, to tell the board how you are using the pins (as input or output).
I didn't dig into on the snippet above the lcd_display_string and why are you doing those operations. I suppose that these are required to print on screen the distance.
## configuration
# trigger
TRIG_1 = 17
TRIG_2 = 27
TRIG_3 = 22
# echo
ECHO_1 = 10
ECHO_2 = 9
ECHO_3 = 11
# timings
INITIAL_DELAY = 0.5
TRIGGERING_DELAY = 0.00001
## support functions
# initializing GPIO
def set_up():
# set trigger GPIOs as output pins
GPIO.setup(TRIG_1, GPIO.OUT)
GPIO.setup(TRIG_2, GPIO.OUT)
GPIO.setup(TRIG_3, GPIO.OUT)
# set echo GPIOs as input pins
GPIO.setup(ECHO_1, GPIO.IN)
GPIO.setup(ECHO_2, GPIO.IN)
GPIO.setup(ECHO_3, GPIO.IN)
# I didn't dig into these values and why are you doing these operations. I suppose that these are required to print on screen the distance.
def print_distance_on_lcd(distance):
total = 3
count = total
if distance <= 10:
count -= 1
elif distance > 10:
count += 1
if count < 0:
count = 0
elif count > total:
count = total
print(count)
mylcd.lcd_display_string("{}".format(count), 2)
def trigger(trigger):
time.sleep(INITIAL_DELAY)
GPIO.output(trigger, True) # set output pin on HIGH state
time.sleep(TRIGGERING_DELAY)
GPIO.output(trigger, False) # set output pin on LOW state
def distance(t, echo):
trigger(t)
# initializing the variables here, allows you to use it outside the while block below
# using variable names that explains their content
start_time = time.time()
end_time = time.time()
# this block is not wrong, but unnecessary: initializing the variable like above is enough
'''
while GPIO.input(echo) == 0:
start_time = time.time()
'''
while GPIO.input(echo) == 1:
end_time = time.time()
duration = end_time - start_time
sound = 34000 / 2
distance = duration * sound
return distance
# call initialization function (this will be executed only one time)
set_up()
# loop forever
while True:
set_up()
print("Reading Sensor 1")
distance_sensor_1 = distance(TRIG_1, ECHO_1)
print_distance_on_lcd(distance_sensor_1)
print("Reading Sensor 2")
distance_sensor_2 = distance(TRIG_2, ECHO_2)
print_distance_on_lcd(distance_sensor_2)
print("Reading Sensor 3")
distance_sensor_3 = distance(TRIG_3, ECHO_3)
print_distance_on_lcd(distance_sensor_3)
GPIO.cleanup()
I am monitoring and controlling a smart light bulb from my dashboard(User Interface Dashboard) and every time I open or close the light bulb it sends back a data that shows the light bulb is on or off, what I want to do is to change this "ON/OFF" data string in to binary of 1/0, is there anyway I can get 1 or 0 instead of 'ON/OFF'.
this is some of the API code I have used to control the light bulb
def identifyDevice(self):
identifyDeviceResult = False
print(" {0}Agent for {1} is identifying itself by doing colorloop. Please observe your lights"
.format(self.variables.get('agent_id', None), self.variables.get('model', None)))
try:
devicewasoff = 0
if self.get_variable('status') == "OFF":
devicewasoff = 1
self.setDeviceStatus({"status": "ON"})
elif self.only_white_bulb:
self.setDeviceStatus({"status": "OFF"})
if self.only_white_bulb is False:
self.setDeviceStatus({"effect": "colorloop"})
if self.only_white_bulb:
time_iden = 3
else:
time_iden = 10 # time to do identification
t0 = time.time()
self.seconds = time_iden
while time.time() - t0 <= time_iden:
self.seconds = self.seconds - 1
print("wait: {} sec".format(self.seconds))
time.sleep(1)
self.setDeviceStatus({"effect": "none"})
if devicewasoff == 1:
self.setDeviceStatus({"status": "OFF"})
else:
self.setDeviceStatus({"status": "ON"})
identifyDeviceResult = True
except:
print("ERROR: classAPI_PhilipsHue connection failure! # identifyDevice")
return identifyDeviceResult
If you can guarantee that the returned value is always one of 'ON' or 'OFF', you can use the fact that True and 1 are interchangeable
result = state == 'ON'
If you need some error handling, something like this might work.
if state in {'ON', 'OFF'}:
result = state == 'ON'
else:
# handle error state
If you need an int to serialise, call int with the result
>>> state_on = 'ON'
>>> state_off = 'OFF'
>>> int(state_on == 'ON')
1
>>> int(state_off == 'ON')
0
I'm trying to create a setup to blink a led and be able to control the frequency.
Right now I'm just printing 10s as placeholders for testing.
Everything runs and does what should, but getch is throwing me off.
freq = 1
while freq > 0:
time.sleep(.5/freq) #half dutycycle / Hz
print("1")
time.sleep(.5/freq) #half dutycycle / Hz
print("0")
def kbfunc():
return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
#print(kbfunc())
if kbfunc() == 27: #ESC
break
if kbfunc() == 49: #one
freq = freq + 10
if kbfunc() == 48: #zero
freq = freq - 10
Now when it starts up, the freq change portion seems buggy like it's not reading all the time or I have to time the press just right. The break line has no problem whenever pressed though.
There should be only one kbfunc() call. Store the result in a variable.
E.g.: In your code if the key isn't Esc, you'll read the keyboard again.
from msvcrt import getch,kbhit
import time
def read_kb():
return ord(getch()) if kbhit() else 0
def next_state(state):
return (state + 1)%2 # 1 -> 0, 0 -> 1
freq = 1.0 # in blinks per second
state = 0
while freq > 0:
print(state)
state = next_state(state)
key = read_kb()
if key == 27: #ESC
break
if key == 49: #one
freq = freq + 1.0
if key == 48: #zero
freq = max(freq - 1.0, 1.0)
time.sleep(0.5/freq)