After i added more code (Check if Filename already exists on SDCard, otherwise the File on the SDCard wont be overwritten) I got the error message: "InvalidPulseCount: Expected 84 but got 76 pulses" and no Data can be collected by the DHT11.
I tried different wiring, different time of utime.sleep to give the DHT11 more time to cool down and refresh, but nothing worked out.
My Code:
Code: Select all
from machine import Pin, RTC
import machine
from dht import DHT11, InvalidChecksum
import sdcard
import uos
import utime
# DHT 11 setup
# Defining the Pin of the DHT11 Sensor
dhtPIN = 28
sensor = DHT11(Pin(dhtPIN, Pin.IN, Pin.PULL_UP))
# Real Time Clock (RTC) Setup
# The logged Data get a Time Reference
rtc = RTC()
rtc.datetime((2017, 8, 23, 2, 12, 48, 0, 0)) # set a specific date and
# time, eg. 2021/10/18 11:21:48
# SD Card setup
# On the SD Card, the collected Data will be stored.
# Assign chip select (CS) pin (and start it high)
cs = machine.Pin(9, machine.Pin.OUT)
# Intialize SPI peripheral (start with 1 MHz)
spi = machine.SPI(1,
baudrate=1000000,
polarity=0,
phase=0,
bits=8,
firstbit=machine.SPI.MSB,
sck=machine.Pin(14),
mosi=machine.Pin(15),
miso=machine.Pin(12))
# Initialize SD card
sd = sdcard.SDCard(spi, cs)
# Mount filesystem
vfs = uos.VfsFat(sd)
uos.mount(vfs, "/sd")
# Check if Filename already exists on SDCard
fname = "/sd/Datalog.txt"
i = 0
while True:
try:
f = open(fname, "r")
exists = True
f.close()
print ("File " +str(fname)+ " exists")
i +=1
fname = "/sd/DataLog_"+str(i)+".txt"
utime.sleep(0.01)
except:
exists = False
print("File Datalog_" + str(i) +".txt does not exists")
break
# Create the file with the non-existing Filename and write the Headline
with open(fname, "w") as file:
file.write("Date" + "\t"+ "Temperature" + "\t" + "Humidity" + "\r\n")
while True:
# Temperature will be saved on the Variable temp
temp = (sensor.temperature)
# Humidity will be saved on the Variable hum
hum = (sensor.humidity)
print(rtc.datetime())
file.write(str(rtc.datetime()) + "\t"+ str(temp) +"" + "\t" + str(hum) +"%" +"\r\n") # \t produces a tab between the Values. With the Function read.delim() in RStudio: for reading “tab-separated value” files (“.txt”). By default, point (“.”) is used as decimal points.
# The Intervall for DHT11 has to be greater than 4 Seconds
utime.sleep(4)