Pico W Micro Python for SHT30 Temp/Humidity HELP!

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
Rissy
Posts: 116
Joined: Sun Aug 14, 2022 8:15 am

Re: Pico W Micro Python for SHT30 Temp/Humidity HELP!

Post by Rissy » Thu Nov 10, 2022 8:31 am

Roberthh wrote:
Wed Nov 09, 2022 1:33 pm
You can measure the existing pull-up resistors between a data line and Vcc, if the sensor is not powered. And you can always connect additional resistors fomr SDA to Vcc and SCL to Vcc. They would be simply in parallel to the existing resistor. Let's assume, the existing value is 4700, and you add 390 Ohm. Then the resulting value is 1 / ((1 / 4700) + (1 / 390)) = 360.
Ah yes of course. I wasn't sure which wires i'd have to put additional resistors across, or this was even permissible. I could try that then.

Any idea why my error "ex" from my code wont write into my errorlog.txt file? Only the 'Error:' part gets printed even though on the Thonny screen, I get the whole message of 'Error: Bus error' where 'Bus error' is "ex" in my code.


I also got my sensor reset to work (i think. The real test will be a real error instead of me entering a wrong i2c address for the sensor). I had to flash_nuke.uf2 my Pico W because it got into an irrecoverable reboot loop, which I then fixed with a 10 secs delay and a print to screen as a heads up that the Pico W is going to reboot. So my readsensor() funtion now looks like this:

Code: Select all

def readsensor():
    global temperature
    global humidity
    try:
        sensor = sht.measure()
    except SHT30Error as ex:
        sht_error(ex)
        try:
            print("resetting SHT30")
            restartsensor = SHT30(i2c)
            time.sleep(1)
            restartsensor.reset()
            time.sleep(2)
            print("SHT30 reset")
            sensor = sht.measure()
        except:
            print("rebooting Pico W")
            time.sleep(10)
            machine.reset()
    temperature, humidity = sensor
I just need the error "ex" to log to my txt file now.... any ideas anyone?

Rissy
Posts: 116
Joined: Sun Aug 14, 2022 8:15 am

Re: Pico W Micro Python for SHT30 Temp/Humidity HELP!

Post by Rissy » Mon Nov 14, 2022 1:38 pm

Still nobody got any ideas on why my text file isn't being populated with my error?

beetle
Posts: 51
Joined: Sat Oct 16, 2021 11:35 am

Re: Pico W Micro Python for SHT30 Temp/Humidity HELP!

Post by beetle » Mon Nov 14, 2022 11:58 pm

Rissy, still plugging away I see :D
Looking at your code from a few posts back I think I see that your ex variable prints out as 'Bus error' ?? I expect some other error message could also be generated. I see you want to preface your error log with 'SHT Error' or whatever and I think you want to put a ',' between your preface and the error code.

Anyway you may like to play with the following code for appending to your errorlog file, amending it to suit your requirements as to commas, quotation marks and whatever. The '\n' is to end your append with a new line ready for the next error message.

Code: Select all

def appendfile(message, error):
    with open('errorlog.txt', 'a') as f:
        f.write(message1)
        f.write(',')
        f.write(error)
        f.write('\n')
    
    
message1 = 'SHT Error:'
ex = 'Bus error'

appendfile(message1, ex)

Rissy
Posts: 116
Joined: Sun Aug 14, 2022 8:15 am

Re: Pico W Micro Python for SHT30 Temp/Humidity HELP!

Post by Rissy » Tue Nov 15, 2022 1:23 pm

beetle wrote:
Mon Nov 14, 2022 11:58 pm
Rissy, still plugging away I see :D
Looking at your code from a few posts back I think I see that your ex variable prints out as 'Bus error' ?? I expect some other error message could also be generated. I see you want to preface your error log with 'SHT Error' or whatever and I think you want to put a ',' between your preface and the error code.

Anyway you may like to play with the following code for appending to your errorlog file, amending it to suit your requirements as to commas, quotation marks and whatever. The '\n' is to end your append with a new line ready for the next error message.

Code: Select all

def appendfile(message, error):
    with open('errorlog.txt', 'a') as f:
        f.write(message1)
        f.write(',')
        f.write(error)
        f.write('\n')
    
    
message1 = 'SHT Error:'
ex = 'Bus error'

appendfile(message1, ex)
Hello beetle! Yes. Still plugging away! :lol:

My coding has gotten a lot better over the months since I started in August in my opinion.

Still having to use Global variables in places, as can be seen from this Pico W code of mine, but I'm mostly now passing variables in and out of functions as you should without Global variables now.

If you look at my code in one of my previous posts, you'll see that "ex" is generated from the library file on the occurrence of whatever fault it is exhibiting, so in the example I showed, the text "Bus error" is actually generated there. I'm not typing it or generating it myself. There are a few potential errors from the library file which can be generated. "Bus error" is just one of them. The others are "Data error" and "CRC error", and then a fallback "Unknown error" thrown in for good measure.

I'm confused because I cannot get "ex" (which was a "Bus error" in the given example) to print to my text file, even though it prints to the screen in Thonny just fine at the time of the error. I've managed to write, read and append content into text files without issue on my raspberry pi coded environments, but this is the first time I am trying to do similar for a Pico W. The reason I want it to write to a text file is so that when I do get an error, I can open up the text file later on and see what the error being reported actually was. Otherwise I have to sit at the Pico W with my laptop connected to it, permanently and full time waiting for a real error to occur. Not practical.

I've got the code for my Pico W pretty resilient now I think. It tries multiples times to connect to my wifi. It tries multiple times to connect to the MQTT broker. It tries multiple times to successfully read from the SHT30 sensor. etc. Upon the occurrence of any of these persisting to not work, then the final result is that the code reboots the Pico W completely and starts all over again. This is what I needed as I was fed up coming home every time it was raining heavily outside and finding my code had crashed with an error from the SHT (I am suspecting) and at the same time, losing hours or even a full day's worth of data to too. Now though, if any occurrence of a fault occurs, instead of crashing my program, it attempts to sort itself out. I think it's doing that ok now, although I'm still waiting to see how long it goes before it's really challenged with the weather. Today as an example, is really wet outside, so today might be the challenge on my code i've been waiting for.... I'll know when I get home.

beetle
Posts: 51
Joined: Sat Oct 16, 2021 11:35 am

Re: Pico W Micro Python for SHT30 Temp/Humidity HELP!

Post by beetle » Tue Nov 15, 2022 4:51 pm

If you look at my code in one of my previous posts, you'll see that "ex" is generated from the library file on the occurrence of whatever fault it is exhibiting, so in the example I showed, the text "Bus error" is actually generated there.
I understood that Rissy but not having your set up I was mimicking the ex variable and assigning a text string to it. Of course the ex variable in your code will be whatever the error string is that is assigned to it by your program. If you replace your appendfile function with the one I created for you then you should get a lovely errorlog.txt file. :D

PS: Prompted by you I did get my SHT31 connected to a rpi picoW and tapped into a handy bit of the ring main in the loft to power it all. My rpi-pico set up also has one of those dallas onewire waterproof sensors poked outside to get an outside temperature reading. It sends an mqtt messages every 20 minutes via my rpi based mqtt broker that is then displayed by a python program that receives the mqtt messages and displays the results on a small rpi monitor screen. Its all been working splendidly. 8-)

You have probably considered the following but i mention it for the birds. Instead of trying to communicate via longish i2c cables through a wall to the outside I would have constructed a waterproof box to hold an rpi picoW and sensors and just poked a 5v power lead through the wall. It can be tricky to construct a waterproof box that also allows for air to circulate but it can be done, and I think I have seen some in connection with weather station kits.

Good to hear you are now at an advanced stage with you project. I expect you've had a lot of fun.

beetle
Posts: 51
Joined: Sat Oct 16, 2021 11:35 am

Re: Pico W Micro Python for SHT30 Temp/Humidity HELP!

Post by beetle » Tue Nov 15, 2022 5:03 pm

It tries multiple times to connect to the MQTT broker.
Rissy, just another throwaway remark, once the rpi picoW has a wifi connection established, depending I suppose on using a good micropython mqtt client library, there should not be any reason to have to try to connect multiple time to a mqtt broker. In my set up I connect to the mqtt broker right after I connect the rpi picoW to the network and in my case it stays connected forever unless the wifi router goes down.

Rissy
Posts: 116
Joined: Sun Aug 14, 2022 8:15 am

Re: Pico W Micro Python for SHT30 Temp/Humidity HELP!

Post by Rissy » Wed Nov 16, 2022 8:57 am

I'll give it a shot then, but the first time I wrote some code for this purpose, I did the "with open('errorlog.txt', 'a') as f:" method rather than the "file=open("errorlog.txt","a")" method, and it didn't work at all. I've used the "with open('errorlog.txt', 'a') as f:" method in my raspberry pi code and it worked fine there. So with it not working on MicroPython, I considered that you perhaps can't use this method, and so i referred back to the "file=open("errorlog.txt","a")" method.

Tell me though, even if it works, then considering all of the below, what makes you think your version will work, even though mine does not?

My solution:

Code: Select all

def sht_error(ex):
    print("something went wrong reading the SHT-30!")
    print('Error:', ex)
    message1 = ', SHT Error: '
    ex2 = str(ex)
    appendfile(message1, ex2) #message, error

def appendfile(message, error):
    file=open("errorlog.txt","a")
    file.write(str(message, error)+",")
    file.close()
    #file.flush()
errorlog.txt Result:
, SHT Error: ,

Thonny Terminal screen Result:
something went wrong reading the SHT-30!
Error: Bus error <---- important to note that the error DOES appear onscreen even if not in file!?
Traceback (most recent call last):
File "<stdin>", line 60, in <module>
File "<stdin>", line 49, in readsensor
File "sht30.py", line 45, in __init__
ValueError: An I2C object is required.


beetle proposed solution:

Code: Select all

def sht_error(ex):
    print("something went wrong reading the SHT-30!")
    print('Error:', ex)
    message1 = ', SHT Error: '
    ex2 = str(ex)
    appendfile(message1, ex2) #message, error
    
 
 def appendfile(message, error):
    with open('errorlog.txt', 'a') as f:
        f.write(message)
        f.write(',')
        f.write(error)
        f.write('\n')   
With a Bus error, expected result in file:
, SHT Error: ,Bus error

Rissy
Posts: 116
Joined: Sun Aug 14, 2022 8:15 am

Re: Pico W Micro Python for SHT30 Temp/Humidity HELP!

Post by Rissy » Wed Nov 16, 2022 9:03 am

beetle wrote:
Tue Nov 15, 2022 4:51 pm
If you look at my code in one of my previous posts, you'll see that "ex" is generated from the library file on the occurrence of whatever fault it is exhibiting, so in the example I showed, the text "Bus error" is actually generated there.
I understood that Rissy but not having your set up I was mimicking the ex variable and assigning a text string to it. Of course the ex variable in your code will be whatever the error string is that is assigned to it by your program. If you replace your appendfile function with the one I created for you then you should get a lovely errorlog.txt file. :D

PS: Prompted by you I did get my SHT31 connected to a rpi picoW and tapped into a handy bit of the ring main in the loft to power it all. My rpi-pico set up also has one of those dallas onewire waterproof sensors poked outside to get an outside temperature reading. It sends an mqtt messages every 20 minutes via my rpi based mqtt broker that is then displayed by a python program that receives the mqtt messages and displays the results on a small rpi monitor screen. Its all been working splendidly. 8-)

You have probably considered the following but i mention it for the birds. Instead of trying to communicate via longish i2c cables through a wall to the outside I would have constructed a waterproof box to hold an rpi picoW and sensors and just poked a 5v power lead through the wall. It can be tricky to construct a waterproof box that also allows for air to circulate but it can be done, and I think I have seen some in connection with weather station kits.

Good to hear you are now at an advanced stage with you project. I expect you've had a lot of fun.
Glad i could inspire someone with something they've done in micropython and using a Pico W considering i'm just new to this game!

I've considered putting my Pico W outside in a box to shorten the length of the cable requirements, but in the end, especially because I had to drill a hole in my house for what I have now, I decided to stick with what I have.

Rissy
Posts: 116
Joined: Sun Aug 14, 2022 8:15 am

Re: Pico W Micro Python for SHT30 Temp/Humidity HELP!

Post by Rissy » Wed Nov 16, 2022 9:05 am

beetle wrote:
Tue Nov 15, 2022 5:03 pm
It tries multiple times to connect to the MQTT broker.
Rissy, just another throwaway remark, once the rpi picoW has a wifi connection established, depending I suppose on using a good micropython mqtt client library, there should not be any reason to have to try to connect multiple time to a mqtt broker. In my set up I connect to the mqtt broker right after I connect the rpi picoW to the network and in my case it stays connected forever unless the wifi router goes down.
I realise I shouldn't have to, but i'm accounting for times where Virgin media upset my wifi connection with any work they do, or of course, a power cut, resulting in perhaps the Pico W being ready quicker compared to the Raspberry Pi broker. Anyway, I tested this functionality under different test conditions, and it seemed to work ok.

beetle
Posts: 51
Joined: Sat Oct 16, 2021 11:35 am

Re: Pico W Micro Python for SHT30 Temp/Humidity HELP!

Post by beetle » Wed Nov 16, 2022 11:45 am

The error in your code is in the line

file.write(str(message, error)+",")

Firstly to mention the variables message and error are strings so no need to change them to string with str(). But nevertheless this needless conversion will not stop the code from working. The problem lies in the , twixt message and error. Python does not know what to do with , but it does know what to do with ",". So if you wrote your code as file.write(str(message + ',' + error)+","), horrible though this is, it will work but file.write(message1 + "," + error + ",") is the more correct way.

The best way to test your code for the file write is to substitute the file.write with a variable and to then print the variable out to get a better handle on whats happening.

Thus temporarily changing your function to the following will show you what's happening and you can them play with the assignments to the mytest variable until you get your desired result.

Code: Select all

def appendfile(message, error):
    mytest = str(message, error)+",")
    print(mytest)

Post Reply