Geekzone: technology news, blogs, forums
Guest
Welcome Guest.
You haven't logged in yet. If you don't have an account you can register now.


View this topic in a long page with up to 500 replies per page Create new topic
1 | 2 
Nate001
312 posts

Ultimate Geek


  #2560363 8-Sep-2020 15:39
Send private message quote this post

Yes in a nut shell thats the easy way to calculate the required resistance. No I did mean 4.7, but you can use whatever you like. My reasoning was I know the cut off voltage for my charger is 4.3V, and the next available resistor I had was 150k - this also allows for any voltage spikes. The difference in resolution of ADC bits between using say a 130k (4.5V max) vs 150k (4.7V max) is 1.96e-4 V, which is meaningless for this purpose. 

 

If you're comfortable with using transistors to switch I can't see why not... 


chimera

431 posts

Ultimate Geek


  #2560550 8-Sep-2020 23:08
Send private message quote this post

So batteries are in 2P now after hacking the battery holder to suit.

 

I also found the sensor, https://www.aliexpress.com/item/33036884695.html actually accepts 3-5.5V.

 

It also seems to function in one of 5 modes, one of which is a very low power mode (still to test though, once I solder a resistor on it to alter modes)

 

I tested with 3.3V LDO, powering the Wemos at that voltage. Then DC boost to up the voltage to 5V to the sensor (did this before I realised it could support ~3V)  I then saw that the echo/trigger pins on the board output 5V back to the GPIO pins as there logic level, not so sure the board can handle being powered at 3.3V and receive logic at 5V - coz well, it just didn't work. Also had issues with using the MOSFET (2N7000) to switch the sensor on/off it just wouldn't work consistently.

 

So after noticing the board could do 3V, as a test I removed the DC boost and powered (via 3.3 LDO) to the sensor board. However it simply wouldn't run at that voltage no matter what, multimeter showed it receiving 2.99V (assumingly because the Wemos was sucking some juice too) so it's probably bordering on the minimum voltage it can accept to run reliably.

 

So I've reverted for now to powering the DC boost direct, up'ing V to 5V and feeding both Wemos 5V Vcc and sensor at the same. I've ditched the MOSFET as the draw is low anyway, plus will play around with the modes as mentioned above. So it works, while idle is using 10mA and when "sensing" it consumes about 120mA for about 10 seconds. 

 

Also, now that it's wired like this when it takes voltage reading via A0, it's the voltage of the circuit whilst it's powering the Wemos and DC boost - so obviously lower than what the battery is. Taking readings with multimeter battery is 4.07, when powering it all on it drops to 3.97V, yet A0 reports ~3.81V. With LDO in place, the battery was separated off from the output voltage to the rest of the circuit and was much more accurate.

 

So I don't like this current method, seems wasteful. Be good if I can work out how to use 3.3V LDO and power both Wemos and sensor at that voltage. Tomorrows fun.

 

 





 

 


 
 
 
 


Shimmer
54 posts

Master Geek


  #2560790 9-Sep-2020 11:04
Send private message quote this post

I found the tpl5110 useful for timed based applications where you want it to run semi frequently in the uA when in standby. Use that before your step up and then a pin out to send signal when done doing it's routine to turn it back to sleep mode.

 

https://www.adafruit.com/product/3435


chimera

431 posts

Ultimate Geek


  #2561271 9-Sep-2020 18:01
Send private message quote this post

Soldered 300K resistor on the sensor board, hooked back up to 3.3V reg and ditched DC boost, running both wemos and sensor off 3.3V now working adequately and voltage reading via A0 is fairly close to actual voltage.  Will try 2 x 1.5W 12V PV panels in parallel to charge the batteries. Will post end result later on when done. Just 3D printing a case I designed to house it all.

 

 





 

 


neb

neb
3040 posts

Uber Geek

Trusted
Lifetime subscriber

  #2561415 9-Sep-2020 22:53
Send private message quote this post

chimera:

For home automation I also run OpenHAB, so am building a small ESP project to report the percentage water level back to OpenHAB via MQTT.  It's a pretty straight forward and whilst lab'd up on my desk, it works well.

 

 

Do you have any more details on the design? I was thinking about putting water level sensing in for the underground tank we're adding but the choice seems to be between several-hundred-dollar off-the-shelf units and an Arduino and toothpicks and rubber bands...

chimera

431 posts

Ultimate Geek


  #2561449 10-Sep-2020 08:03
Send private message quote this post

neb:
chimera:

 

For home automation I also run OpenHAB, so am building a small ESP project to report the percentage water level back to OpenHAB via MQTT.  It's a pretty straight forward and whilst lab'd up on my desk, it works well.

 

Do you have any more details on the design? I was thinking about putting water level sensing in for the underground tank we're adding but the choice seems to be between several-hundred-dollar off-the-shelf units and an Arduino and toothpicks and rubber bands...

 

Sure thing.  Still a work in progress but here's the details so far.

 

Parts:

 

1 x Wemos D1 mini: https://www.aliexpress.com/item/4001295464144.html

 

1 x Waterproof Ultrasonic Sensor: https://www.aliexpress.com/item/33036884695.html?

 

1 x 2S battery holder pack (although bear in mind I rewired this to be in parallel): https://www.aliexpress.com/item/4000859859685.html

 

2 x Lithium 18650 4.2V 3600mAh batteries: (bought these off Trademe)

 

1 x AMS1117 3.3V LDO regulator: https://www.aliexpress.com/item/32774098119.html

 

 

 

Also resistor to measure battery voltage on A0 as per earlier discussion in this thread, a 2N7000 MOSFET to switch sensor board on/off (to be honest, don't think it's needed as doesn't make much difference) all wired up like this:

 

Click to see full size

 

 

 

Wemos runs every 1 hour, takes approx ~10 seconds or so to connect to WiFi, then take a reading from the sensor and send via MQTT to OpenHAB then goes into deep sleep mode for another hour. Calculated last night that it will run for 26 days off batteries without charging (leaving 20% charge on batteries so not fully depleted) that's ~10mA when idle (deep sleep) and takes ~120mA for 10 seconds when running every hour. 

 

Could easily increase this to every 3 hours to be fair and get a longer runtime.  Also about to test adding PV to charge it (yet to do calcs on this, only just planning on doing more tonight on it)

 

2 x 12V 1.5W PV panels: https://www.aliexpress.com/item/4000058808114.html

 

Still to hook up PV panels but will run in parallel.  Also will test using this:

 

1 x MPPT controller: https://www.aliexpress.com/item/4000815410884.html

 

 

 

 

 

Here's the Arduino source code, change top parts to suit (ssid, password, mqtt broker IP, tank height etc)

 

//
// Calculates a Water Tank water level percentage and reports to an MQTT broker
//
// Last update: 10/09/2020
// Author: chimera
//

 

#include <PubSubClient.h>
#include <ESP8266WiFi.h>

 

// *************************************************************************************

 

// Deep sleep time in microseconds between sending updates, examples:
// 3600e6 = 3,600,000,000 µs = 3,600s = 1 hour
// 10800e6 = 10,800,000,000 µs = 10,800s = 3 hours
#define SLEEP_INTERVAL_DURATION 3600e6

 

// Number of times to attemp WiFi connectivity
#define numberWiFiRetries 5

 

// Tolerance between first and second readings in centimetres
#define defToleranceCMs 2

 

// Wifi
const char* ssid     = "your_ssid";
const char* password = "your_password";

 

// MQTT Broker - change to IP of your broker
IPAddress MQTT_SERVER(172, 16, 223, 254);

 

// Water tank height (cm's) - height from bottom of tank to sensor
const int ciTankHeight = 240;

 

// Water tank air gap (cm's) - height between sensor and top of water (when 100% full)
const int ciAirGap = 20;

 

// Pin connection to mosfet
const int ciMosfetPin = D1;

 

// Echo and Trigger pins
const int ciEchoPin = D6;
const int ciTrigPin = D7; 

 

// MQTT - Publish these
const char* OPENHABSTATUS = "openhab/watertank/status";
const char* OPENHABMYIPADDRESS = "openhab/watertank/ipaddress";
const char* OPENHABTANKLEVEL = "openhab/watertank/level";
const char* OPENHABTANKVOLTS = "openhab/watertank/voltage";
const char* OPENHABBATTERYVOLTAGE = "openhab/watertank/batteryvoltage";
const char* OPENHABTANKDEBUG = "openhab/watertank/debug";

 

// MQTT - Subscribe to these
const char* OPENHABREQUEST = "openhab/watertank/request";

 

// *************************************************************************************

 

// Define message buffer and publish string
char mqtt_topic[30];
char message_buff[64];

 

// Variables
bool bReset = false;
bool bDebug = false;

 

// Read distance
unsigned long lDuration;
int iDistance;
int iPercentageFull;

 

// Status and states
String wemosIPAddress = "";
String sDebugData = "";

 

// Wifi Client
WiFiClient wifiClient;

 

// Callback to Arduino from MQTT (inbound message arrives for SUBSCRIPTIONS)
void callback(char* topic, byte* payload, unsigned int length)
{

 

  // Messaging inbound from MQTT broker
  int iChar = 0;
  for (iChar = 0; iChar < length; iChar++) {
    message_buff[iChar] = payload[iChar];
  }
  message_buff[iChar] = '\0';

 

  // Convert buffer to string
  String msgString = String(message_buff);
  Serial.println("Inbound: " + String(topic) + ":" + msgString);

 

  // Flash pin
  if (bDebug)
  {
    digitalWrite(LED_BUILTIN, LOW);
    delay(15);
    digitalWrite(LED_BUILTIN, HIGH);
  }

 

  if (strcmp(topic, OPENHABREQUEST) == 0)
  {
    // Perform MQTT callback request
    if (msgString == "RESET")
    {
      // Caught in next loop
      Serial.print("Rebooting ESP!");
      bReset = true;
    }
    else if (msgString == "DEBUG")
    {
      Serial.println("Debugging ON");
      bDebug = true;
    }
    else if (msgString == "NODEBUG")
    {
      Serial.println("Debugging OFF");
      bDebug = false;
    }
    else
    {
      Serial.print("Unknown Message: ");
      Serial.println(msgString);
    }
  }
  
}

 

// Define Publish / Subscribe client (must be defined after callback function above if in use)
PubSubClient mqttClient(MQTT_SERVER, 1883, callback, wifiClient);

 


//
// Setup the ESP for operation
//
void setup()
{

 

  Serial.println("Starting...");
  Serial.print("The Flash size is: ");
  Serial.println(ESP.getFlashChipSize());
  
  // Set builtin LED as connection indicator
  if (bDebug)
  {
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH);
  }

 

  // Define mosfet, trigger and echo pins
  pinMode(ciMosfetPin, OUTPUT);  // Mosfet pin
  pinMode(ciTrigPin, OUTPUT);  // Trigger sensor
  pinMode(ciEchoPin, INPUT);   // Read Height

 

  // Debug USB Serial
  Serial.begin(115200);
  Serial.println(" ");

 

  // Turn on sensor (do early allow sensor to calibrate)
  digitalWrite(ciMosfetPin, HIGH);

 

  // Check its not cause WiFi dropped
  startWIFI();

 

  // If not MQTT connected, blink LED 5 times in succession
  Serial.println("Connecting to MQTT Broker");

 

  int iRetries;

 

  // WiFi must be connected, try connecting to MQTT
  while (mqttClient.connect("watertank", OPENHABSTATUS, 0, 0, "0") != 1)
  {

 

    Serial.println("Error connecting to MQTT (State:" + String(mqttClient.state()) + ")");
    for (int iPos = 1; iPos <= 5; iPos++)
    {
      // Flash pin
      if (bDebug)
      {
        digitalWrite(LED_BUILTIN, LOW);
        delay(75);
        digitalWrite(LED_BUILTIN, HIGH);
      }
      Serial.print(".");
    }

 

    // Double check WiFi state or # retries while in this loop just incase we timed it badly!
    if (WiFi.status() != WL_CONNECTED || iRetries > numberWiFiRetries)
    {
      Serial.println("No MQTT connection...");
      break;
    }

 

    // Make sure we're not stuck here forever, loop and reconnect WiFi if needed
    iRetries++;

 

  }

 

  if (mqttClient.connected())
  {
    // Tell MQTT we're awake (won't happen if not connected)
    PublishMQTTMessage(OPENHABSTATUS, "1");
    wemosIPAddress=WiFi.localIP().toString();
    PublishMQTTMessage(OPENHABMYIPADDRESS, wemosIPAddress);
  
    // Subscribe to trigger (for rebooting)
    Serial.println("Subscribed to topics");
    mqttClient.subscribe(OPENHABREQUEST);
  
    // Call back to reboot ESP has been requested  
    if (bReset == true)
    {
        mqttClient.disconnect();
        delay(2000);
        ESP.reset();
    }
    else
    {
      
      // Get two readings
      int iFirstReading;
      bool bAccurate = false;
      
      // Get two readings for better accuracy
      while (bAccurate == false)
      {
        for (int iPos = 1; iPos <= 2; iPos++)
        {
          // Pulse trigger pin
          digitalWrite(ciTrigPin, HIGH);
          delayMicroseconds(2000);  
          digitalWrite(ciTrigPin, LOW);
    
          // Get echo pulse
          lDuration = pulseIn(ciEchoPin, HIGH);
          iDistance = microsecondsToCentimeters(lDuration);
          Serial.println("Distance Reading #" + String(iPos) + " = " + String(iDistance) + "cms");
          
          // Store first reading, wait 1/2 a second
          if (iPos == 1)
          {
             iFirstReading = iDistance;
             delay(500);
          }
          else
          {
             int iDifference = iFirstReading - iDistance;
             if (iDifference <= defToleranceCMs && iDifference >= -defToleranceCMs)
             {
                bAccurate = true;
             }
          }
        }
      }
    }
    
    // Turn off Mosfet pin
    digitalWrite(ciMosfetPin, LOW);
  
    // Check distance is not greater than tank height
    if (iDistance > ciTankHeight) 
    {
      iDistance = ciTankHeight;
      iPercentageFull = 0;
    }
    else
    {
      // Calculate percentage full
      iPercentageFull = (((float)ciTankHeight - (float)iDistance) / ((float)ciTankHeight - (float)ciAirGap)) * 100;
      if (iPercentageFull > 100)
      {
        iPercentageFull = 100;
      }
    }
  
    // Debug mode, send full data
    if (bDebug == true)
    {
      sDebugData = "Distance: " + String(iDistance) + "cm (Height: " + ciTankHeight + "cm, Gap: " + ciAirGap + "cm, Level: " + iPercentageFull + "%)";
      Serial.println(sDebugData);
      PublishMQTTMessage(OPENHABTANKDEBUG, sDebugData);
    }
    else
    {
      // Publish water level height in percent
      PublishMQTTMessage(OPENHABTANKLEVEL, String(iPercentageFull));
    }
  
    // Get a voltage reading (5.4 assumes 220K ohm resistor to A0)
    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.4 / 1023.0);
  
    // Publish voltage reading
    PublishMQTTMessage(OPENHABBATTERYVOLTAGE, String(voltage));
  
    // Publish going into sleep mode 
    PublishMQTTMessage(OPENHABSTATUS, "0");
    delay(200);
  }
  
  Serial.println("Going into deep sleep now");
  ESP.deepSleep(SLEEP_INTERVAL_DURATION);

 

}

 


void loop() {
}

 


//
// Starts WIFI connection
//
void startWIFI()
{

 

  // If we are not connected
  if (WiFi.status() != WL_CONNECTED)
  {
    int iTries;
    iTries = 0;
    if (bDebug) { digitalWrite(LED_BUILTIN, LOW); }
    Serial.println("Starting WIFI connection");
    WiFi.mode(WIFI_STA);
    WiFi.disconnect();
    WiFi.begin(ssid, password);

 

    // If not WiFi connected, retry every 3 seconds for 1 minute
    while (WiFi.status() != WL_CONNECTED)
    {
      iTries++;
      Serial.print(".");
      delay(3000);

 

      // If can't get to Wifi after 1 minute, reboot ESP
      if (iTries > 20)
      {
        Serial.println("TOO MANY WIFI ATTEMPTS, REBOOTING!");
        ESP.reset();
      }
    }

 

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println(WiFi.localIP());

 

    // Turn off LED
    if (bDebug) { digitalWrite(LED_BUILTIN, HIGH); }

 

    // Let network have a chance to start up
    delay(500);

 

  }

 

}

 

// Publish MQTT data to MQTT broker
void PublishMQTTMessage(String sMQTTSub, String sMQTTData)
{

 

  // Quick check we're connected (otherwise crash!)
  if (mqttClient.connected())
  {
    // Define and send message about zone state
    sMQTTData.trim();
    sMQTTSub.trim();

 

    // Convert to char arrays
    sMQTTSub.toCharArray(mqtt_topic, sMQTTSub.length() + 1);
    sMQTTData.toCharArray(message_buff, sMQTTData.length() + 1);

 

    // Publish MQTT message
    mqttClient.publish(mqtt_topic, message_buff);

 

    // Visual debug
    if (bDebug)
    {
      digitalWrite(LED_BUILTIN, LOW);
      delay(150);
      digitalWrite(LED_BUILTIN, HIGH);
    }
  }

 

}

 


//
// Return distance in cm from microseconds
//
long microsecondsToCentimeters(long microseconds) 
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the object we
  // take half of the distance travelled.
  return microseconds / 29 / 2;
}

 


/*
//
// Return distance in inches from microseconds
//
long microsecondsToInches(long microseconds) 
{
  // According to Parallax's datasheet for the PING))), there are 73.746
  // microseconds per inch (i.e. sound travels at 1130 feet per second).
  // This gives the distance travelled by the ping, outbound and return,
  // so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}
*/

 

 





 

 


chimera

431 posts

Ultimate Geek


  #2562026 11-Sep-2020 08:46
Send private message quote this post

Change this part of the code though:

 

      // If can't get to Wifi after 1 minute, reboot ESP
      if (iTries > 20)
      {
        Serial.println("TOO MANY WIFI ATTEMPTS, REBOOTING!");
        ESP.reset();
      }

 

 

 

To:

 

      // If can't get to Wifi after 1 minute, reboot ESP
      if (iTries > 20)
      {
        Serial.println("TOO MANY WIFI ATTEMPTS, SLEEPING");
        break;
      }

 

 

 

I noticed if my WiFi AP wasn't running that it would basically try connecting indefinitely eventually depleting the batteries (WiFi is the most power intensive part of the ESP).  Changing to the above, it will try several times to get to WiFi, if it fails it will continue then go into deep sleep and retry on next wake up.

 

 

 

 





 

 


 
 
 
 


chimera

431 posts

Ultimate Geek


  #2563413 14-Sep-2020 08:38
Send private message quote this post

For any others reading this... I'll be ditching the AMS1117 regulator as it has a high cutoff voltage (eg: stops working when battery hits 3.7V) whereas the ESP is actually capable of running off voltages from 3.0V - 3.6V.  It also draws 5mA by itself (although not sure how much of that is from the LED that I removed from it). From some research, the recommendation is to run MCP1700-3302E or HT7333-A.  They have a max draw of 250mA and the Wemos states it can draw current higher than this - although I haven't measured it greater than 130mA on this particular circuit (the MCP1700-3302E or HT7333-A recommendations are for a ESP01 which is fairly low current draw so I could swap the Wemos for an ESP v01)

 

I found this LDO which may be better for the Wemos...

 

https://nz.mouser.com/datasheet/2/196/Infineon-TLS208D1-DS-v01_00-EN-1228146.pdf

 

• 3.3 V Fixed and Adjustable Output Voltage from 0.8 V to 5.25 V
• Static Output Currents up to 800 mA
• Undervoltage Reset with Power-On Reset Delay
• Extended Input Voltage Operating Range of 2.7 V to 18 V
• Low Dropout Voltage: typ. 400mV at 400mA- Extended Input Voltage Operating Range of 2.7 V to 18 V

 

• Very Low Current Consumption: typ. 90 µA
• Overtemperature Shutdown

 

Seems to cover the Wemos + sensor requirements.

 

More to learn!

 

 





 

 


1 | 2 
View this topic in a long page with up to 500 replies per page Create new topic





News »

Nanoleaf enhances lighting line with launch of Triangles and Mini Triangles
Posted 17-Oct-2020 20:18


Synology unveils DS16211+
Posted 17-Oct-2020 20:12


Ingram Micro introduces FootfallCam to New Zealand channel
Posted 17-Oct-2020 20:06


Dropbox adopts Virtual First working policy
Posted 17-Oct-2020 19:47


OPPO announces Reno4 Series 5G line-up in NZ
Posted 16-Oct-2020 08:52


Microsoft Highway to a Hundred expands to Asia Pacific
Posted 14-Oct-2020 09:34


Spark turns on 5G in Auckland
Posted 14-Oct-2020 09:29


AMD Launches AMD Ryzen 5000 Series Desktop Processors
Posted 9-Oct-2020 10:13


Teletrac Navman launches integrated multi-camera solution for transport and logistics industry
Posted 8-Oct-2020 10:57


Farmside hits 10,000 RBI customers
Posted 7-Oct-2020 15:32


NordVPN starts deploying colocated servers
Posted 7-Oct-2020 09:00


Google introduces Nest Wifi routers in New Zealand
Posted 7-Oct-2020 05:00


Orcon to bundle Google Nest Wifi router with new accounts
Posted 7-Oct-2020 05:00


Epay and Centrapay partner to create digital gift cards
Posted 2-Oct-2020 17:34


Inseego launches 5G MiFi M2000 mobile hotspot
Posted 2-Oct-2020 14:53









Geekzone Live »

Try automatic live updates from Geekzone directly in your browser, without refreshing the page, with Geekzone Live now.


Support Geekzone »

Our community of supporters help make Geekzone possible. Click the button below to join them.

Support Geezone on PressPatron



Are you subscribed to our RSS feed? You can download the latest headlines and summaries from our stories directly to your computer or smartphone by using a feed reader.

Alternatively, you can receive a daily email with Geekzone updates.