BME280 on Raspberry Pi using Python 3 - Odd first reading - python

I have 2 x Pimoroni BME280 and they both produce the same initial reading of 21.95*C 698.09hPa 76.34% humidity.
Using this simple code
import time
from smbus2 import SMBus
from bme280 import BME280
bus = SMBus(1)
bme280 = BME280(i2c_dev=bus)
while True:
temperature = bme280.get_temperature()
pressure = bme280.get_pressure()
humidity = bme280.get_humidity()
print('{:05.2f}*C {:05.2f}hPa {:05.2f}%'.format(temperature, pressure, humidity))
time.sleep(1)
and I always get as the first line of output as...
21.95*C 698.09hPa 76.34%
followed by the correct data for example...
18.70*C 993.54hPa 55.88%
18.70*C 993.53hPa 56.12%
18.71*C 993.54hPa 56.06%
18.71*C 993.54hPa 55.95%
Does anybody know why this is?
Currently I have the same thing on both of my BME280 so presume it's some sort of initialization thing on the first reading which must be discarded. If I run my program the only solution I can see it to ask twice what thr readings are and discard the first reading..
Thanks for reading and helping...

I would presume that this is caused due to an initial transient value being outputted by the sensor as a result of initialising your sensor.
It would be interesting to see how an Arduino would handle the initialisation process
vis-à-vis said transient value with your sensor.
As you said, if your continuous readings are 'correct', I would try to perhaps delay the output process or omit the first reading in some way or another.

Related

Arduino pyfirmata analog reading problems

I am having some problems reading analog values from my Arduino Mega using pyfirmata.
I use Arduino Mega with a Mega Sensor Shield.
I would like to read analog values from a HW-201 IR sensor (pin A5).
I have uploaded the Standard firmata sketch on Arduino IDE, and I am running the following code using Anaconda Spyder:
import serial
import serial.tools.list_ports
from pyfirmata import ArduinoMega, util
from time import sleep
def readArduinoPort():
COM = []
ports = list(serial.tools.list_ports.comports())
for p in ports:
if "Arduino" in p.description:
COM.append(str(p.device))
return COM
COM = readArduinoPort()
board = ArduinoMega(COM[0])
pin = board.get_pin('a:5:i')
it = util.Iterator(board)
it.start()
try:
while True:
print(pin.read())
sleep(0.1)
except KeyboardInterrupt:
pass
Now, this code runs just fine the first time I use it, generating numbers close to 1 when the sensor is detecting proximity and numbers close to 0 when not detecting anything.
However, whenever I try to run the Iterator a second time (without restarting the kernel), the code generates seemingly random numbers (almost like the pin was floating, like nothing was connected to it).
Any idea why this is happening? Is this a normal behavior?
Thank you!
I already checked these questions that do not entirely address my issue:
arduino pyfirmata analog reading
Analog readings on Arduino returns wrong values
I have the same result by not having anything pinned to pin A5 of the Arduino Mega.
I wasn't sure, but I tried adding:
board.analog[5].enable_reporting()
before the iterator and then:
board.analog[5].disable_reporting()
but nothing changed.
Board Differences
I ran into the same problem. I own both a Mega and an Uno and needed to select the appropriate Board and Processor in the tools menu:
Tools > Board > _board_
Tools > Processor > _processor_

Serial stops reading after about 6 hours

When reading the serial port in python, all works fine until after hours where receiving data stops. This happens both on a laptop running Linux and on a Raspberry PI 2. Sending data still works at that point.
The source is still sending data (now and again). Restarting the python script helps.
The source sends small packages (4 - 12 bytes) and interval times may vary from minutes to over 12 hours.
My code, just only the receiving part, extracted from a bigger part, looks like this:
#!/usr/bin/python3
import tkinter
import os
import serial
class Transceiver():
def __init__(self, main):
self.port = serial.Serial(
port = "/dev/ttyUSB0",
baudrate = 38400,
bytesize = serial.EIGHTBITS,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
timeout = 0
)
self.ReceivedData = bytearray()
self.Time = 0
def Receiver(self):
while (self.port.in_waiting > 0):
# Receiving data
self.Time = 0 # Reset time elapsed to 0
self.ReceivedData += self.port.read(1) # Add data to bytearray
if (self.Time == 20): # Some time elapsed, packet considered complete
print(''.join('{:02x} '.format(x) for x in self.ReceivedData))
self.port.reset_input_buffer()
self.ReceivedData = bytearray()
if (self.Time < 2000): # Just avoid running to 0 again
self.Time += 1 # Increment time elapsed
root.after(5, self.Receiver)
root = tkinter.Tk()
transceiver = Transceiver(root)
transceiver.Receiver()
root.mainloop()
It is just this receiving part that stops working after hours, I am trying to find the root cause.
So the above script is just an extract from a bigger script.
It controls the lights in the house. I want to run it on a raspberry PI, instead of a PC. The R'PI has a little 7" touch screen.
The bigger scripts has some decoding of the received data and updates a very simple GUI, just a bunch of small rectangles with some short name as text in it, indicating which lamps are on and off, and they act as buttons too, to toggle the lamps on and off. All works well, apart from the receiving part, though, in the end it may be possible that some other part disturbs the receiving part.
I have just started running just the above extraction of the script, to see if it keeps working without the GUI updates. I suspect the function Receiver fails to be restarted after some time. I need to have the above script running for a day to see of it keeps receiving though. I will update with the findings.
Update: The above script keeps working. The above is the extraction of a bigger program where only this part stops working after some hours. Receiving stops, but transmitting keeps working, hence I did not include that part.
By now I found the problem. In the receiver function, a decode function is called where above is the print line. Without calling the decode function, there is no problem. The decode function has some conditions, depending on the packet length and some values. Code for one of these conditions contained an error. I always started to run the script again in early evening, and then about 6 hours later a timer (at a fixed time late in the evening) would send the offending packet (a different format) that then caused the problem. The packet was not at fault, but my decoding of that packet.
Strange is that the script kept working, only the reception part stopped. I thought it stopped silently, but I printed quite a lot in this stage, hence I didn't see the error message telling me the problem of the use of an uninitialised variable. It's not in the above code. Hope the above code is useful for other people.

Multiple reproducible errors with a Brecknell Scale

I'm working on getting a weight from a usb scale using python and PyUSB. Here's my code
import sys
import usb.core
import usb.util
from reports import \
ReportFactory, STATUSES, ZERO_WEIGHT, STABLE_WEIGHT, DATA_REPORT
device = usb.core.find(idVendor=0x67b, idProduct=0x2303)
if device is None:
raise ValueError('Device Not Found')
if device.is_kernel_driver_active(0) is True:
device.detach_kernel_driver(0)
usb.util.claim_interface(device, 0)
device.set_configuration()
collected = 0
attempts = 50
while collected < attempts:
ret = device.read(0x2,0x0040)
sret=''.join([chr(x) for x in ret])
print "Return Raw: ",ret
print "Return : ", sret
print ReportFactory.build(ret)
# release the device
usb.util.release_interface(device, 0)
device.attach_kernel_driver(0)
The first time I run this program I get Resource busy error
The second run I get Operation timed out on the 5th dump.
Subsequent runs after that result in immediate timeouts.
There are several things going on here
Why do I get a resource busy error on first run? I would think the kernel_driver if statement I have should take care of it.
Why do I get data that looks nothing like what a USB scale should produce?
Why the timeout after 4 dumps of data? Everytime!
The device information is thus
Any help would be much appreciated!
Ok, anyone that is struggling to get anything from the GP100 Brecknell scale using PyUSB, switch to PySerial. Since this is one of the cheapest USB scales on the market, I'm guessing this information will help many.
I emailed the manufacturer for documentation and they've sent me some valuable serial protocol information.
If you set the protocol of the scale to 7010 you can use python code that looks like this
import time
import serial
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=2400,
bytesize=8,
parity='N',
stopbits=2
)
while 1:
x = ser.read(100)
print(x)
This will stream 8 bytes of data.
The first byte is status information that can be interpreted thusly
Bits 2-4
Bits 5-8
Bytes 2 & 3 can be safely ignored.
Bytes 4-8 have the weight information, represented by characters 0-9 (e.g. 00023 = 2.3 lbs). This scale is only accurate +- 0.6 lbs and does not work in ounces, perhaps other models using the same serial controller utilize the oz capabilities. The PG100 does not.

Raspberry Pi MAX31856 Thermocouple Temperature Reading Error

I'm working with t-type thermocouple and needs to read the temperature data using python on Raspberry Pi 3. I used Adafruit MAX31856 to connect the thermocouple to the Pi and and tried to read it using this module.
I want to read the temperature for an extended period of time so I tried to print it out in a while loop However, anytime I run my code, I only get few 'correct' readings then the temperature resets to 0 until I re-run the code again - see the attached image.
I don't know what is causing this, and I don't think this is a connection problem since it prints the correct temperature when I re-run the code without touching the set-up.
Does anyone know why the reading is resetting to 0?
Here is my code:
from Adafruit_MAX31856 import MAX31856
import time
# Raspberry Pi software SPI configuration.
CLK = 4
CS = 22
DO = 17
DI = 27
sensor = MAX31856(clk=CLK, cs=CS, do=DO, di=DI)
while True:
temp = sensor.readTempC()
print('Thermocouple Temperature: {0:0.3F}*C'.format(temp))
time.sleep(1.0)
Try resetting sensor by putting sensor = MAX31856(clk=CLK, cs=CS, do=DO, di=DI) in the while loop.

arduino read in pyfirmata gives output as none

I wrote a basic code for reading values from analog pin 0(I have a light sensor attached to it and the output is coming at analog pin 0) in python3 using pyfirmata, but it is giving the output as none no matter what. I tried the same code in arduino IDE and that is giving the right answer. Please help.
Code is :
from pyfirmata import Arduino, util
import time
board = Arduino('/dev/cu.usbmodem1411')
it = util.Iterator(board)
it.start()
board.analog[0].enable_reporting()
while True :
print (board.analog[0].read())
time.sleep(1)
Even when it gives an output after few seconds, it gives 0.29 which isn't actually the sensor value that comes on serial monitor. That value varies between 0 and 1023 and is relatively quite larger than this.
The analog pins of Arduino linearly translate the input voltages between 0 and +5V to 0
and 1023. However, in pyFirmata , the values between 0 and +5V are linearly translated
into the float values of 0 and 1.0. For example, if the voltage at the analog pin is 1V, an
Arduino program will measure a value somewhere around 204, but you will receive the
float value as 0.2 while using pyFirmata’s read() method in Python.
You'll need to start an Iterator thread before reading
board = pyfirmata.Arduino("COM5") # change com port
board.digital[3].mode = pyfirmata.INPUT
it = pyfirmata.util.Iterator(board)
it.start()
board.digital[3].read()
Most of the time it work, but sometimes None still show up. Sometimes time.sleep can help.
You have to do an if conditional first, something like this (and try running analogfirmata):
while True:
if board.analog[0].read() == None:
pass
else:
print("board.analog[0].read()")

Categories

Resources