Micropython – Pin change timing and MongoDB notes

I’ve got the door sensor mounted and running today, after a couple of days of tweaking stats and code.

First up – smoother timing of the 555 square wave high / low logic levels:

Smoooooth!

This looks better to me. Since last time I noticed that I seemed to be getting noisy graphs and WDT resets, and after checking against the breadboard saw that I forgot to add a couple of larger capacitors to smooth out the bumps of using WiFi on the ESP-8266. No big deal, but it didn’t help the resets (about one every four hours) or data noise.

The answer to both is that my timing code was to blame. Trying to start/stop times with an ISR and millisecond math:

tS = utime.ticks_diff( utime.ticks_ms() , tStart)

Is no match for this:

tS = time_pulse_us(p0, L, 100000) / 1000

For whatever reason, the ESP is doing background tasks (probably servicing WiFi packets). So if you need to measure something like a pin change timing (maybe you don’t like the ultrasonic sensor library, or whatever), then use time_pulse_us.

And at the same time, not servicing 400 IRQ’s a second made it stable; no more WDT resets! Go figure.

Next up – a little info on using MongoDB in node-RED. I’ve been using the mongodb3 driver node, and all is peachy. I use it to insert changes in door state, since the ‘msg’ data easily written. Reading data was a little more challenging, since there wasn’t a clear example of what to pass to the mongodb3 node to query; turns out it’s this:

A quick run through; left to right:

  • The node ‘UpdateTextHistory‘ injects time every 15 minutes (this will look like unixtime, ie a big number)
  • CreateFind‘ preps the msg that will form the query; I want to see two fields (datetime and state) from the events of the last day, so:
var day = msg.payload - 86400000;
msg.payload = [{unixtime:{$gt: day }},{"fields": { "_id": 0, "datetime": 1, "state": 1 }}];
return msg;

loginfo‘ does the query (a ‘find.toArray’)

split‘ breaks up the returned array (comma as delimiter)

Stringify‘ turns the data into nice text rows:

msgOut = ""; 
msgOut = msg.payload.datetime; 
msgOut+= " -- "; 
msgOut+= msg.payload.state;
var msg = {};
msg.payload = msgOut;
return msg;

join‘ glues all the row data together; I use <br/> as the joiner, and a 2 second timeout.

DayLogs‘ is just a simple dashboard text node to display the string. I change the font size with this as the Value format:

<font size='1'>{{msg.payload}}</font>

That’s it!

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.