DHT22 sensor for RaspberryPi system setup issues - python

So I am using a raspberry pi system and am trying to write code in the python to have the system read the humidity and temperature. We are able to get the humidity sensor to read the humidity and temperature in terminal, so we are somewhat sure we set it up right. When we try to import Adafruit_DHT into python (out written code) we get an error when we run the code. Any help would be greatly appreciated!
Here is more info about the code:
Terminal entry:
pi#raspberrypi:~/Adafruit_Python_DHT/examples $ python AdafruitDHT.py 22 4
Temp=24.1* Humidity=48.4%
Python Code:
import Adafruit_DHT
#set sensore type : options are DHT11, DHT22
sensor=Adafruit_DHT.DHT22
#white is 22
#set GPIO sensor is connected to
gpio=4
#use read_retry method, this will retry up to 15 times to get
#a sensor reading (waiting two seconds between each try
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
#reading the DHT11 is very sensitive to timings and sometimes the Pi might
#fail to get a valid reading (so check)
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get reading. Try again!')
Error from running:
Traceback (most recent call last):
** IDLE Internal Exception:
File "/usr/lib/python3.4/idlelib/run.py", line 353, in runcode
exec(code, self.locals)
File "/home/pi/hopeful dht run.py", line 1, in <module>
import Adafruit_DHT
ImportError: No module named 'Adafruit_DHT'
Thank you so much!
Izzy

You haven't installed the adafruit_dht library. Need to:
Enter the following in your terminal to install the Adafruit Python DHT Library:
sudo pip3 install Adafruit_DHT
https://learn.adafruit.com/adafruit-io-basics-temperature-and-humidity/python-setup
https://www.raspberrypi.org/forums/viewtopic.php?t=235179
***if you have done this, and getting the same error, try running python, python2, or python3. You might not have everything updated.

Related

Problems reading a .pcap file in Python using scapy

I'm trying to create a program where I have to read a pcap file and then count the number of packets related to some IPs. I'm not used to program in Python but I have to use it because I'm using it on a Raspberry Pi and depending of the output I have to control several pins.
Right now I have this, but I have an error and I donĀ“t know how to solve it.
from scapy.all import *
from scapy.utils import RawPcapReader
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, TCP
def read_pcap(name_pcap):
print("Opening", name_pcap)
client_1 = '192.168.4.4:48878'
server = '10.0.0.2:80'
(client_1_ip, client_1_port) = client_1.split(':')
(server_ip, server_port) = server.split(':')
counter = 0
for(pkt_data, pkt_metadata,) in RawPcapReader(name_pcap):
counter += 1
ether_pkt = Ether(pkt_data)
# Below here are functions to filter the data
read_pcap("captura.pcap")
And the error is this one:
NameError: name 'Packet' is not defined
The error apears to be in this (for(pkt_data, pkt_metadata,) in RawPcapReader(name_pcap):) line.
Someone knows how to solve it?
Thnak you :)
As Carcigenicate pointed out, that's a known bug. It's fixed in https://github.com/secdev/scapy/commit/ff644181d9bee35979a84671690d8cd1aa1971fa
You can use the development version (over https://scapy.readthedocs.io/en/latest/installation.html#current-development-version) in the meantime
Uninstall previous version & Install Latest version from https://pypi.org/project/scapy/
pip install scapy==2.5.0rc1
This should fix the error

winpcapy errors when moving from python 3.5.2 to python 3.7.4

I've been happily using some python to generate raw Ethernet frames and sending them out an interface of choice on Windows 7 using Python 3.5.2 with winpcapy. I've just installed Python 3.7.4 and now receive an error when trying to run the same code.
import ctypes
import winpcapy
import sys
errbuf = ctypes.create_string_buffer(winpcapy.PCAP_ERRBUF_SIZE)
alldevs = ctypes.POINTER(winpcapy.pcap_if_t)()
winpcapy.pcap_findalldevs(ctypes.byref(alldevs), errbuf)
device = alldevs.contents
interfaces = []
while True:
interfaces.append(device)
if not device.next:
break
device = device.next.contents
print(interfaces)
The code snippet when run in 3.5 prints a list of the interfaces found. However if I run it in 3.7 I get:
Traceback (most recent call last): File "Z:\proj\eth\socket.py", line 5, in
<module> errbuf = ctypes.create_string_buffer(winpcapy.PCAP_ERRBUF_SIZE)
AttributeError: module 'winpcapy' has no attribute 'PCAP_ERRBUF_SIZE'
Now, I could replace 'PCAP_ERRBUF_SIZE' with an integer value but then I get further issues which looks like there's something generally wrong with how i'm using winpcapy in 3.7. Has anyone else hit these sort of issues?
How did you obtain winpcapy?
The PyPI winpcapy package is not the same as the historical winpcapy script that was on Google Code. The PyPI package exposes the libpcap API in the winpcapy.winpcapy_types module.
In the original winpcapy script PCAP_ERRBUF_SIZE was a value defined in the winpcapy module. You could import it just like in the code you provided:
import winpcapy
print(winpcapy.PCAP_ERRBUF_SIZE)
However, in the newer PyPI package PCAP_ERRBUF_SIZE is defined in winpcapy.winpcapy_types. So you would need to do something like:
from winpcapy import winpcapy_types as wtypes
print(wtypes.PCAP_ERRBUF_SIZE)

Saving video file the time and date in filename

Expected Behavior
Automatically run a program to record a video for a short length of time.
Save the video to a unique filename within a specific directory (to avoid overwriting). Ideally, this filename would include the date and time.
Actual Behavior
Success
Filename is always video.h264.
I have tried all sorts of things that I have found on the net, but they only result in the file name showing part of the code. Annoyingly it worked once, but saved it to somewhere I was not expecting and I changed the code before I realized it had worked!
Full File
# Import Libraries
import os #Gives Python access to Linux commands
import time #Proves time related commands
import RPi.GPIO as GPIO #Gives Python access to the GPIO pins
GPIO.setmode(GPIO.BCM) #Set the GPIO pin naming mode
GPIO.setwarnings(False) #Supress warnings
# Set GPIO pins 18 as output pin
LEDReady = 18 #Red
GPIO.setup(LEDReady,GPIO.OUT)
GPIO.output (LEDReady,GPIO.HIGH)
from subprocess import call
call(["raspivid", "-o", "video.h264", "-t", "50000n"])
time.sleep(10) #Sleep for 10 seconds
GPIO.output (LEDReady,GPIO.LOW)
Adding DATE=$(date +"%Y-%m-%d_%H%M")
and changing video.h264 to $DATE.h264 results in a syntax error for $DATE.
Tantalizingly, I have a file called 20180308_021941.h264 which is exactly what I am after, but I cannot tell you how I managed it!
P.S. the Red LED lighting up is so that I can tell if the Raspberry Pi has fired up properly and has run the Python script.
Thank you for taking the trouble to read this.
Try adding this
from datetime import datetime
date = datetime.now().strftime("%Y%m%d%H:%M:%S")
Then change your call to this
videoFile = date + ".h264"
call(["raspivid", "-o", videoFile, "-t", "50000n"])

Python: Why is my Slack-Bot not working in CMD?

I'm trying to code a Slack-Bot which is asking for lunch and is taking orders for lunch.
I'm working with this tutorial.
My problem is: I'm trying to run my script in CMD (yes, windows!) but I receive this error:
C:\Users\Dave\PycharmProjects\lunchbot>python lunchbot.py
Traceback (most recent call last):
File "lunchbot.py", line 167, in <module>
if slack_client.rtm_connect(with_team_state=False):
TypeError: rtm_connect() got an unexpected keyword argument 'with_team_state'
This is the part of the code that's not working correctly:
if __name__ == "__main__":
if slack_client.rtm_connect(with_team_state=False):
print("Lunchbot is ready to go!")
starterbot_id = slack_client.api_call("auth.test")["user_id"]
while True:
command, channel = parse_bot_commands(slack_client.rtm_read())
if command:
handle_command(command, channel)
time.sleep(RTM_READ_DELAY)
else:
print("No connection.")
What actually confuses me is every time I'm trying to run this code in my IDE everything is fine. Does anybody have an idea of what could be wrong?
There is a known issue with the websocket-client and Slack. It's buggy and has been a problem for some time now. I wonder if your Pycharm environment is pointing to a different version and hence why it is working.
I would try to force the value of the websocket-client with a known working version.
websocket-client==0.40.0 for example:

How to use IR Remote with Raspberry Pi using Python?

I bought this [IR Sensor and Remote][1] to use with my Raspberry Pi 3.
I have LIRC setup and I am able to detect an input from the IR Remote using the commands below:
sudo /etc/init.d/lirc stop
mode2 -d /dev/lirc0
When I run the above commands, I am able to detect input from the IR Remote. When I press any button on the IR REmote, I get an output like:
My question is - in the output above, I pressed '2" on the remote. How shall I go about deciphering (in python) which button is really pressed?
Update 1:
I tried using the python-lirc package but I get error on this line:
The previous answers shortcuts the lirc decoding. Since you have a working mode2 the kernel driver works and sends correct data to lircd. However, mode2 does not tell you if the decoding works.
To check the decoding you use irw(1). Until you have working output from this program, you don't know if lirc can decode your remote.
The lircrc file described above is used to transform the generic button presses (as shown by irw) to application-specific commands. To debug this file you use ircat(1).
When you have working output from irw(1) and ircat(1) your lirc setup is complete. A working lirc setup is really required before using any python package. BTW, as of upcoming 0.10.0 lirc will have native python bindings.
A comprehensive guide to setup lirc can be found at http://lirc.org/html/configuration-guide.html
You probably do not want to use the mode2 output for this. There is a Python library available (Here) which would likely be a much better way to go for this project.
Code:
import lirc
sockid = lirc.init("myprogram")
print(lirc.nextcode())
lirc.deinit()
lircrc configuration file
begin
button = 1 # what button is pressed on the remote
prog = myprogram # program to handle this command
config = one, horse # configs are given to program as list
end
begin
button = 2
prog = myprogram
config = two
end
Results after pressing button 1
['one', 'horse']
These days there is no need to use lirc as IR events are handled through the kernel.
In my case I setup an IR receiver on a GPIO pin in /boot/config.txt
dtoverlay=gpio-ir,gpio_pin=16
Then installed evdev
pip install evdev
Reboot, and the following worked (your input device path my vary)
from evdev import InputDevice, categorize, ecodes
dev = InputDevice('/dev/input/event0')
for event in dev.read_loop():
print(event)
When pressing some buttons on the remote I get:
$> sudo python3 irtest.py
device /dev/input/event0, name "gpio_ir_recv", phys "gpio_ir_recv/input0"
event at 1639133806.295636, code 04, type 04, val 64
event at 1639133806.295636, code 00, type 00, val 00
event at 1639133806.405607, code 04, type 04, val 64
event at 1639133806.405607, code 00, type 00, val 00
event at 1639133808.745610, code 04, type 04, val 16
...

Categories