# Working with numbers larger than 65000

#### johndo

##### Member
Hi All

Needing a little help with a project currently on the bench. A water tank level indicator with pump control etc.

I am using an ultrasonic distance module to determine tank level and have got it working and sending data ok. The module outputs data in serial format in millimeters. I need to keep the output from the module as whole as possible for maximum resolution. Running into problems calculating total capacity using PI in the calculation. The method I'm using for a vertical cylinder in code is as follows:

314 (PI without decimal point) x 9 (radius 900mm) x 9 (radius 900mm) / 1000 x 1500mm (maximum height of water level in mm) / 10 = 3,815Ltrs
Then 3,851Ltrs minus current reading to give current tank level.

Where the normal way to calculate would be (I think?) :
3.14 x .9m x .9m x 1500mm = 3851Ltrs

All this to keep the working numbers under 65,000. When this method is used I think you lose resolution. I need 1Ltr resolution but this method yields 5Ltr resolution per step.

Is there a fancy way to do the math's without overflowing 65,000 when using a word variable? Perhaps process each digit individually?

Please excuse my mathematical ignorance...If I have any of the calculations wrong please let me know.

Last edited:

#### AllyCat

##### Senior Member
Hi,

You might find that 22 / 7 (put towards the end of the calculation) gives a better result for PI, but personally I just resort to 32-bit (i.e. double-word) calculations. PICaxe Basic already supports multiplication (in two parts); the Low word is given by the normal * operator and the High word by using the ** operator (which effectively includes a division by 65536). The problem is in division back down to values supported by PICaxe's "printing" capacity, but I've written several "Code Snippets"; the one I use most commonly is HERE.

There are also some other threads on the forum (by me and others) dealing with more comprehensive 32-bit maths and "Floating Point" methods.

Cheers, Alan.

#### inglewoodpete

##### Senior Member
314 (PI without decimal point) x 9 (radius 900mm) x 9 (radius 900mm) / 1000 x 1500mm (maximum height of water level in mm) / 10 = 3,815Ltrs
Then 3,851Ltrs minus current reading to give current tank level.

Where the normal way to calculate would be (I think?) :
3.14 x .9m x .9m x 1500mm = 3851Ltrs (Typo?)
A 900mm radius tank will hold 2.545714 litres per mm of depth. 28 divided by 11 gives a value of 2.545455, which results in an error of about 0.01% (1 in 10,000), so not too bad!

So, first calculate the depth of water in millimetres into a word register Wx. Using PICAXE integer maths, Litres = Wx * 28 / 11 keeps everything within 16 bits. Multiplying 1500 x 28 (a full tank) gives 42000, so it won't overflow a 16-bit word variable.

#### johndo

##### Member
Thank you for your replies guys. Will let my brain warm up first then tackle your suggestions...Never thought of the 22/7, maths were never my strong point. though.

Last edited:

#### AllyCat

##### Senior Member
Hi,
The module outputs data in serial format in millimeters.
I need 1Ltr resolution ......
It was late at night so I didn't read your full post in detail.

As Pete indicates, problems of this type can often be solved by "pre-calculation" (on a pocket calculator or 'phone, etc.) and leave the PICaxe to do just a final "scaling". The ** operator can be particularly useful because it performs a scaling down by a factor of: constant / 65536 , but you can sometimes also process the integer part separately, if a high accuracy calculation is really required.

However, I have to disappoint you that even if you're measuring the level to +/- 1mm, as Pete points out that represents a change of 2.5 litres, so you cannot possibly produce a result to 1Litre resolution, let alone accuracy. Also beware that ultrasonic sensors can be severely upset by reflections (echos) from the sides of a tank and many people have come to the conclusion that ultrasonic methods are not satisfactory for (their) tank/well calculations. There are a number of threads on the forum, one quite recently, albeit for a quite unusual (deep) well. Also remember that the speed of sound (i.e. its wavelength) in air is not constant but varies with humidity and particularly temperature (around 0.6% per degree C), so you may also need to measure these parameters (for which there are numerous PICaxe projects documented).

But before I go into more detail, or other methods, do you really need 1 litre resolution and/or a high measurement accuracy?

Cheers, Alan.

#### johndo

##### Member
Hi Alan

Yes now coming to the realization that 1ltr resolution is impossible using the current method. I'm just a bit OCD with my projects and demand perfection but not always obtaining it. I really do appreciate your input Pete and Alan and will keep plugging away

Last edited:

#### johndo

##### Member
Here is my protoype project in field testing on our water tank...

#### AllyCat

##### Senior Member
Hi,

A nice looking project, so I've been considering how one might achieve a "real" resolution of 1 litre (in 2500) ! But IMHO the "fun" is in the planning, not the doing.

The bad news is that the speed of sound in air changes by about 0.2% per degree C. That's a change of 2 mm on a throw of 1 metre, which represents an "error" of 5 litres for every degree C. But measurement of absolute temperature to 1 degree C is possible, with a resolution far better than that, even with a humble PICaxe (0.1 - 0.01 C for a modern I2C bus sensor). Personally, the "Organ Pipe" principle appeals to me (but I've never tried it), where the length of a resonant air column in a pipe (from water level to open end) corresponds to a quarter wavelength, whose frequency can be measured very accuracy. But that still needs at least thermal compensation (the worst humidity and air pressure variations are equivalent to less than 1 C change).

Some of the projects described on this forum have finally resorted to the "plumb line and float" method, which could in theory be extended to the required 0.4 mm resolution desired here. The float would hang on a "cord" which is wound up onto a spool by a geared stepper motor. The cord would need to be wound into a single layer, or might take the form of a tape (which increases the diameter as it is wound on, but can be calculated and compensated if its thickness is known). Then the tension in the cord would be kept constant (by driving the stepper motor and counting pulses) at perhaps half the weight of the float, probably by "weighing" the complete winch assembly.

However, one of the most popular methods for "electronically" detecting water level, for example in washing machines, is by air pressure (in a tube) operating a diaphragm switch. But to measure a precise analogue level (or depth), I believe a known technique is to run a small-bore air pipe to the bottom of the tank and measure the increased air pressure needed to force small bubbles from the end of the pipe. The raised air pressure could be measured by a differential barometric sensor, or by duplicated sensor measurements. A depth of 1 meter of water represents about 100 milliBars, which with a modern, low cost sensor such as the BMP280 can be resolved down to about 0.01 mB. This corresponds to a change in altitude (in air) of around 10 cms, or (with water's 800 times higher density) a water level change of little more than 0.1 mm might be detectable, i.e. significantly less than 1 litre.

Cheers, Alan.

#### papaof2

##### Senior Member
I'm always impressed by the details the people on this forum can provide. Given time, they will find a way to measure a 1 liter change in a 2500 liter tank ;-) Not a bit of information I need now, but if I needed to measure the water in the rainwater collection tank (250 gallons/950 liters, used for shrubs and flowers) a water column pressure sensor would be an easy addition to the existing plumbing.

#### johndo

##### Member
Yes I agree Alan...The fun is waking up with a new idea and going into the lab to put it into action. The anticipation is addictive!

Further to your comment's yes I have noticed a drift in readings with temperature but assumed it to be oscillator drift in the 20x2 or the module. So designed a board with a high stability smd crystal for the 20x2 (now upgraded to 28x2 running at 64Mhz). Yet to be fully tested. The module does have a crystal controlled pic also but more than likely to be the actual speed of sound in air changing with temp. I reckon I could compensate for that with a thermistor or DS18B20.

Also been down the pressure sensor road with little success. You need a sensor with a nipple to attach an air tube without any leaks, and finding one with enough range of psi to suit any kind of tank regardless of size. Tried a few off Ebay but lowest one i could find is minimum 5PSI so the resolution is not great. May look into this again after reading your comments. Great info!

Truth be told I have actually managed to get 1Ltr resolution. The distance module also has an option for an "analog" output being an output pulse proportional to the "distance". Using the pulsout and pulsin commands was able get some fairly big relative numbers which could then be divided down for a maximum tank size of 3000Ltrs. It worked remarkably well, you could actually see the tank level drop in direct proportion to the transferred value (via a flow sensor also integrated into the project), it was awesome, albeit the sizable changes in readings between night and day. It also required a rather awkward calibration and tweaking to make everything line up and "work". This is NOT a commercial enterprise I just like to cover all bases "if" some neighbour's would also like to try it. We have a lot of tanks is Adelaide...

The beauty of the digital readings IMHO is that it is easily calibrated with only a separate program slot for entering tank width and height a few calculations and back to the main program and your done...

Thank you all for your valuable insights...If you have any more suggestions, bring it on!

Cheers,
Kurt

#### AllyCat

##### Senior Member
Hi Kurt,

Ah, from the time of posting, I wondered if you were in USA or Australia; both nationalities seem to have a much greater preoccupation with "tanks" (and wells) than we do in UK. For us it's just the general topic of "The Weather" - should we wear a coat or carry an umbrella (usually both).

The maths for accurately reading a thermistor's temperature is horrible, so I'd strongly recommend the 18B20, particularly in its "waterproof probe" form, which is not necessarily much more expensive (particularly if buying several). It was only quite recently that I learnt the reason that the speed of sound at high altitudes is much less (about -15%) than at ground level, not because of the lower pressure, but because it's cold up there (~-60C). Your "1 Litre" (in ~4000) requires a resolution of about 0.025%, so would need to measure the air temperature to around +/- 0.1 degree C. That (resolution) is perfectly practical, but how do you ensure it's the average of the complete air path? An air "stirring" fan comes to mind.

The reason I mentioned a "mechanical" (tape) method is because you can "see" how (and that) it's working. It's a method I used to test the torque of mini stepper motors (using standard 1/4" reel-reel tape recorder Leader Tape as the "rope") and a revised version might be that the "float" would be a disc held on the water by surface tension, against the (weak) torque from a stepper motor (which "slips"). But then, some other method, probably a type of optical encoder, would be needed to "measure" the active length of the tape/cord.

However, IMHO a "pressure" method offers the greatest ruggedness, with potentially a "just throw a flexible pipe over the side of the tank" installation procedure. The concept I envisaged is an air "pressure vessel" outside the tank, with a pipe leading to the (inside) base of the tank, one BMP280 (barometric sensor) on the inside of the vessel and another on its outside (so the pressure difference can be calculated). The reason I suggest the BMP280 is that they have incredible resolution at low cost (about the same as an 18B20) and I've written a VERY LONG THREAD dealing with their calculation of pressure (and temperature to +/- 0.01 C) for any modern PICaxe.

With a "sealed" vessel, some water would be forced into the pipe, which is satisfactory to measure a relative pressure increase, but an "absolute" calculation can only measure the water level inside the pipe. Hence the need to pump a small amount of air into the system to push the gas to the bottom of the pipe, where any excess bubbles out. I did "research" this a little and a good ebay search term is "USB mini Aquarium pump", but most of the low-cost hits come from China. There's a particularly interesting Lime Green box, the size of 3 x AA cells; the two outer compartments can contain AA cells and the middle section is the pump (e.g. THIS). It quotes 0.5 litre/min at 80 cms head, whilst the ideal would be a (much) lower flow rate, at up to 1.5 metres head, but it could be a potential "off-the-shelf" component for testing.

For that 1 litre target (and I'm aiming for better ) the bubbles may need to be tiny, probably from a pinhole. I've never considered before that the water pressure at the top and bottom of a bubble is (slightly) different, so what shape is it? Thus ideally, bubbles less than 1mm in diameter might be created and the pressure continuously measured whilst each bubble expands, then take an average? Therefore, probably an exceptionally low air flow is needed, and I thought in terms of a diaphragm pump driven by a small reciprocating servo motor (since I happen to be playing with some at the moment). The directional flow valves would need some consideration, but possibly simple rubber "flap" valves could work?

However, the required operational "air flow" is so low that I had a crazy idea - What about Electrolysis (of water)? The gas doesn't need to be "air" (80% Nitrogen); a tiny volume of 66% Hydrogen+33% Oxygen in a capillary tube under water shouldn't be too dangerous. But of course it would be necessary to research the risks of corrosion for all the materials in the system. Thus my (current) "fit and forget" system proposal would employ a USB power supply, 2 x BMP280 sensors with a PICaxe and display, a length of narrow-bore polythene pipe carrying a length of (for example) "bell wire" to a "terminal", consisting two electrodes inside a pin-holed insulating container? Maybe also a temperature sensor, but the variation of water's density and coefficient of expansion look small, and to (partly) cancel each other? Monitoring the electrode current and the slight change in pressure when each bubble departs might give a good confidence that the system is functioning correctly.

Cheers, Alan.

#### WhiteSpace

##### Well-known member
Would a laser range sensor like the TOF10120 work? Laser range detection, using light, is, as far as I understand, only negligibly affected by temperature, so no need for correction or adjustment. Nor will it suffer from echoes from the sides of the tank. A quick and fairly unscientific experiment shows that the laser will detect accurately the surface of a glass of beer, and presumably therefore also water. The TOF10120 is claimed to detect range to within a millimeter or so - I'm not sure it's quite that, but it's pretty good. The maximum range is just under 2 meters, so that should work OK with your tank depth (1500mm if I read your first post correctly). I realise that doesn't help with the maths which was your original question!

#### johndo

##### Member
Wow, you guys are WAY smarter than me.

Alan your research and inquiring mind is outstanding mate! Most of it going way over my head though brother.

Your really getting serious aren't you

You must be an engineer, you think like one...

That's why I love this forum and completely agree with papaof2!

I see your angle with a "sealed box", does away with the need for a barb on the sensor. I will continue to experiment and may post some updates in the future and would love your feedback when its all finished.

Great suggestion Whitespace, I wasn't aware of low cost laser TOF sensors. Yes, solves the temperature problem but as you mentioned still leaves the math's and resolution problem. Will look into it

Thank you all once again for sharing your valuable knowledge!

Cheers,
Kurt

#### AllyCat

##### Senior Member
Hi,

Theoretically, the light reflection at an air-water surface is only around 1.5%, so I wouldn't expect a satisfactory result if the depth of the water is rather small, above a non-black surface. Also remember that the depth of water doesn't look (i.e. optically) to be as deep as it is (because of the refractive index). On another forum, a guy has put considerable effort in using a "real" consumer-grade Laser Rangefinder (maximum ~20 - 40 metres) to continuously measure the depth of snow (when there is any). But finding one with an RS232 interface added significantly to the cost and there's still the issue here of reflection/transmission through a "transparent" medium.

There's also the ST VL53L0X TOF sensor, but both this and the TOF10120 seem quite problematic above about 1 metre. The VL53L0X appears to use some obscure internal compensations and only claims an accuracy of +/- some percent (7% for less favourable reflectances and distances). There appears to be little (non-Chinese) data available for the TOF10120, but an independent test by the DroneBot Workshop failed to get a reliable range above about 60 cms. There are also some threads on this forum, but at best the reported range can be only of integer mm.

Yes, I was a professional electronics engineer and the fun always was (and still is) looking for new ways to use a microcontoller.

Cheers, Alan.

#### inglewoodpete

##### Senior Member
A quick and fairly unscientific experiment shows that the laser will detect accurately the surface of a glass of beer, and presumably therefore also water. The TOF10120 is claimed to detect range to within a millimeter or so - I'm not sure it's quite that, but it's pretty good.
By the sounds of it, you're going to have to fill your tank with beer (for scientific purposes, of course!). It would be sad to let all that good beer go to waste, so you could drain the tank, glass by glass (I was thinking 250ml glasses would allow accurate measurement).

(So says I, who probably doesn't drink more than 5 litres of beer in a year!!)

#### AllyCat

##### Senior Member
Hi,

Yes, my idea in #12 of using electrolysis of water to generate a little "gas" was crazy. What I'd forgotten is that electrolysis of "pure" water is almost impossible, it needs a catalyst or electrolyte, even though it's primarily the water which is split (into H2 and O). Efficient electrolytes, such as Sulphuric Acid or Caustic Soda are nasty, but you probably wouldn't want to contaminate your water tank even with Baking Soda (I haven't found any data for beer). Therefore, I'm reverting to the "pumped air" concept, envisaging a "box", anything from the OP's beautiful prototype, down to the "Green AA battery box" linked in #12. It would be powered by a USB supply (either continuously or to charge a battery) with a PVC "air pipe" that is simply tossed over the side (or into the top) of the tank.

The green box particularly appeals, because of my "specialty" of fitting complete PICaxe Circuit Boards into the size and shape of a single AA cell. That includes a SSD1306 OLED bit-mapped display module, which can show anything from 84 (tiny) ASCII characters (i.e. 4 rows of 21) down to a single row of ~8 "High Quality" digits or characters/symbols, or even a "graph". The second cell bay might hold a (rechargeable) Lithium cell (3.2 or 3.7 volts) or additional hardware, such as the barometric sensor(s) and/or a radio transmitter. Because ebay listings have a habit of disappearing over the years, a couple of screenshots follow, but if you hate Lime Green or want more control over the air flow (than my planned single PWM/switch transistor), then "Aquarium" seems a good keyword for finding pumps, pipes, couplings and "check" (one-way) valves, etc..

But is the air pump essential? The answer is probably No, except to achieve an exceptional resolution / accuracy of better than <~1% (that's ~40 litres for Kurt's tank ). The problem is that when the empty (of water) PVC pipe (open at its lower end and closed at the top end) is tossed into the tank, then the pressure will force some water into the pipe (typically 10% of the total pipe+vessel volume) and it's only the pressure at this interface that we can measure. If we know all the dimensions, the pipe is practically vertical, and there are no air leaks, then we could possibly predict a correction factor from the barometric pressure. Alternatively, if the lowest ~20% of the pipe is arranged to be perfectly horizontal (i.e. resting on the flat base of a tank), then no correction is required, but I doubt if we could resolve the effective water level to better than the diameter of the pipe, say 4mm (or 10 litres for the OP tank).

Note that it's not possible to "permanently" empty the pipe of water, because the atmospheric pressure is continuously changing, over a range similar to the total head of water in the tank. When the pressure rises, more water will be forced into the pipe, and if the pressure falls, any surplus air will bubble out of the end (leaving space for water to enter when the pressure rises again). Also, the pump gives other benefits, it overcomes any possible air leaks and allows the pipe to be emptied of water before it is removed from the tank (e.g. in a "portable" product). It also offers a cheaper design using only one (non-differential) pressure sensor; if the air is intentionally allowed to leak out of the pipe until the water levels balance, then the same sensor can be used to measure the reference "atmospheric" pressure (or to occasionally calibrate two sensors against each other). But its primary purpose is (I hope) that the pressure can be measured at the precise level where bubbles are formed, perhaps by a pinhole around 0.1mm in diameter.

Finally (for now), the barometric sensor: My preferred BMP280 breakout board has 4 pins (power + Bus SCL and SDA) so is about 10 mm in width. That would fit into quite a small "pressure vessel" (perhaps a pill bottle) but is still an "inconvenience" to connect to the pipe and pump. The actual sensors are typically 3 mm x 1 mm cross-section, so would fit inside a 3 - 4 mm PVC pipe, or maybe a cut-down breakout into a (heatshrink) "sleeve" onto the outside of the pipe? Since only 4 connections are required, I wonder if it would be practical to solder wires directly onto the package (typically 0.65 - 1.25 mm pad spacings) and slide it into the tube? This becomes more significant because I've noticed that the BMP280 is specified up to only 1.1 Bar, corresponding to a water head of around 1 meter above normal atmospheric pressure (and less above a "High" pressure). I doubt if that is a true "Absolute" limit, but other manufacturers do produce 1.2 Bar sensors in similar packages (and are easier to calibrate), but these tend not to be available on low-cost breakout modules.

Cheers, Alan.

Last edited:

#### Solar Mike

##### New Member
Has anyone thought of making a long capacitive type sensor; two strips of copper tape stuck inside a length of thin flat rectangular plastic conduit on the side facing the water. This is attached to the outside of your tank running top to bottom. As the liquid moves in height it acts as an electrolyte and linearly changes the capacitance between the two strips of copper.

All you need is a circuit to charge and discharge the "Capacitor" using a low constant current source, your CPU can measure the time to to this and will be directly proportional to the height of water in the tank.

Cheers
Mike

#### AllyCat

##### Senior Member
Hi,

Hmm, water does indeed have a "usefully" high Dielectric Constant (permittivity), but unfortunately it's very dependent on temperature, around 0.5% per degree C at "room" temperatures, several times times worse than the speed of sound currently being used by the OP. So I think you're going to need a few temperature sensors, since water tends to "layer" with temperature (whilst diffusion and convection should help with air). I don't know if this is for "pure" water or the effect of "contaminants", and again no data for beer.

Cheers, Alan.

#### BillBWann

##### Member
Many years ago, just after Stan (Manuka) introduced me to the early Picaxe, I used a peristaltic pump and small bore PVC tubing to try to measure evaporation rates from a pond in something like real time. The peristaltic pump could be rotated at very low revs to reduce the air flow rate to practically nothing so as to minimize the air pressure losses along the pvc tubing. However, I found that there was a practical limit to the accuracy and repeatability that I could obtain due (I think) to the surface tension effects from the shape of the escaping air bubble at the end of the tube. There may be ways to overcome this but I didn’t find them.

On another project, I also attempted to use a trapped air column in a PVC pipe hanging down into a pump well to start a drainage sump pump using an air pressure switch as found in a washing machine. For it to be successful, the sump pump needed to operate for long enough to draw the water level to below the bottom of the PVC pipe to allow the pipe to be refilled with air. It wasn’t possible to simply use the pressure switch to operate the drainage pump directly - it needed to continue to operate for some longer period until the bottom of the PVC pipe was exposed. I found that the pressurized air in the PVC pipe slowly dissolved into the water so it needed to be periodically replaced.

#### AllyCat

##### Senior Member
Hi,
.... I used a peristaltic pump and small bore PVC tubing ..... there was a practical limit to the accuracy and repeatability that I could obtain due (I think) to the surface tension effects from the shape of the escaping air bubble at the end of the tube.
.... I found that the pressurized air in the PVC pipe slowly dissolved into the water so it needed to be periodically replaced.
Thanks Bill, yes there is no substitute for good practical experience to complement any "theory". I was coming to the realisation that a "pump" (of some type) would be required for any permanently-installed system (as opposed to a "portable" tester) to flush the pipe occasionally. After all, dissolving air into water is the purpose of an aquarium pump! and it's bound to occur spontaneously over a period of some weeks or months? Also, I have concerns about the choice of pump - I selected the "green box" (as a possible test vehicle) because it has the lowest flow rate (of the aquarium pumps found) and it includes a "box" (enclosure) to simplify construction. But since it's promoted as a portable/temporary (occasional use) product, the long-term reliability might be an issue. A "normal" USB pump (which should be continuously rated) may have a longer life, but those pumps have a higher flow rate, IIRC specified as 3 Litres/min, compared with 0.5.

But even 0.5 Litre/min is probably far too high, so I've assumed PWM speed control + intermittent operation, perhaps with a "reservoir" (vessel/tank) to "smooth" any pressure peaks. Normally, a "water/plumbing" analogy is used to explain the operation of electric circuits, but in this forum perhaps the reverse is appropriate. i.e. The pump is equivalent to a Power Supply (voltage with a significant source resistance), the pipe is equivalent to a Resistance (or strictly a transmission line), any volume of air (including a reservoir tank and the pipe itself) represents the charge on one or more "Capacitors", and the flow rate is equivalent to current. Therefore, I've been considering the operation with a brief burst of air (c.f. raised pressure = voltage), that is "stored" and then decays, in a mode similar to the application of a sphygmomanometer (blood pressure monitor). It would be a bonus if a "pulse" (heartbeat) could be detected as each bubble departs, but otherwise the "terminal" (final asymptotic) pressure should suffice.

Although I had originally considered a capillary tube, I'm now thinking in terms of a 3 - 4 mm bore (if only for compatibility with simple aquarium hardware) with a pinhole nozzle to create small, consistent bubbles. I've not determined yet how one might manufacture the pinhole of whether it should be on a horizontal or vertical face for the best release of bubbles. What size and consistency of bubbles/measurements did you manage to achieve, Bill? BTW if anyone is looking for a small pump of peristaltic/dosing or diaphragm type, etc. for some trials, I was surprised by the range and low prices from bee_studio , although some appear to be removed from (perhaps unused) equipment?
______

I've been looking in more detail at the barometric pressure sensor specifications and the bare BMP280 package seems far too small to handle "on the kitchen table", but it should be possible to cut down the 6-pin breakout modules to about 5 - 6 mm width. The two side pads specifically for the SPI bus can be cut off, and on the other side the Vdd (and maybe GND) pads could be removed, as there are other locations to connect the wires (e.g. at the supply-decoupling capacitor). Thus I'm thinking in terms of cutting slots in the sides of the PVC pipe to accept the sensor, and then covering this area with a heat-shrink sleeve (and sealant). The second (reference) sensor could fit on the PICaxe board and they share the same two pins of the I2C bus, since most of these devices have alternative Slave Addresses. The maximum 1.1 Bar range might be a limitation, presumably set by the worst-case overflow of its 20-bit internal ADC, but probably would be acceptable in practice.

However, the MS563702 seems a far more "useful" sensor; its nominal limit is 1.2 Bar but this may be "extended" to 2.0 Bar (i.e. around 10 metres head of water). Also its "calibration" calculation appears to be much simpler than the horrors of the BMP280. Its package is only 3 mm square (so would fit inside a PVC air tube), but it has only 4 pads at its corners, spaced at 2 mm centres, so it's almost "friendly" to a standard 0.1 inch PCB grid. Not particularly expensive, but mainly available from suppliers who have high small-quantity shipping costs, for example HERE (with a link to its Data Sheet).

Cheers, Alan.

Last edited:

#### johndo

##### Member
Alan...

After some considerable thought maybe just a percentage indication would suffice as i would have enough resolution to show a 1% drop per step. All other commercial units I've seen show % as opposed to liters.

Will likley stick to the ultrasonic measuring method as it is easy to calibrate with
pi x radius2 x height etc. Will just add some temperature compensation.

Thoughts?

Cheers, Kurt

#### AllyCat

##### Senior Member
Hi Kurt,

If you can get reliable ultrasonic measurements when the tank is (almost) empty, then that is probably the way to go. With temperature compensation you might even get to around 0.1% resolution, however, I'm concerned that several people have reported issues with echos in similar applications. Theoretically, the first returned signal would be the shortest path (i.e. from the water) and any echos should arrive later. Any "irregularity" of the internal sides of the tank should be "invisible" (i.e. not return an echo) if they are "small" compared with the wavelength of the sound. But that is less than 1 cm at 40 kHz, so there might be issues if a float valve or exit pipes (for overflow, or drain if the water level is lower), etc., are present.

However, if I were developing a "product" for sale, or a system for third-party use, then I would definitely test an air-pressure system, as outlined above. My most recent thoughts are that an air pump is necessary, but can be tiny and low-cost. Primarily required to flush the pipe with fresh air occasionally (days/weeks?), or when high accuracy is required, or if the level changes significantly. Two barometric sensors, one mounted probably inside (or onto) the pipe and another (reference) open to the atmosphere beside the PICaxe. Perhaps disconnect the sensor pipe every few months (or open a valve) to calibrate the two sensors against each other. Then a "modular" design to optionally add a Display and/or Radio Transmitter, Alarm, Controls, etc..

The MS563702 pressure sensor looks particularly "interesting", with its 2 Bar capability, size and simpler code, etc.. I might be tempted to get a sample if ordering anything else from (e.g.) Farnell, but otherwise a single MS563702 costs as much as four BMP280 modules. Also, (with only 4 pins) it doesn't have a configurable I2C Slave address, so the "reference" sensor may still need to be a BMP280 or similar. These sensors have an (atmospheric altitude) resolution of down to ~15 cms, which with water's x 800 density, could correlate to a level of about +/- 0.2 mm. It would be interesting to see how close one can get to that; temperature correction shouldn't be needed, but is available from the sensor (on the outside of the tank) if required.

Cheers, Alan.

#### johndo

##### Member
Alan,

Did not mention in any of my previous post's that I have had great success using a "Stilling Tube/Well".

This is a length of PVC tubing, its length is set by the maximum depth of the tank with an open end which sits submerged in the water and a "vented" end at the top in which the sensor in mounted. I used 30mm ID PVC which is almost a snug fit for the sensor. The idea is that the ultrasonic waves propagate down the smooth insides of the PVC hit the water and return up the smooth inside of the PVC without hindrance where it then can be measured without interference from tank walls, inlet pipe etc. The inside of the pipe does need to be very smooth otherwise you will get erroneous readings.

This method has given very consistent readings barring the temperature variations and a very strange almost off scale anomaly around midday. I'm thinking this could be condensation on the inside of the tube due to the extremely humid conditions inside the tube especially when it heats up during daytime peak temps. Another explanation may be the" layering" of still air in the tube which you touched upon in one of your previous post's. All this may point to perhaps going the barometric method.

Cheers,
Kurt

#### AllyCat

##### Senior Member
Hi,
... I used 30mm ID PVC which is almost a snug fit for the sensor. The idea is that the ultrasonic waves propagate down the smooth insides of the PVC ...
Hmm, that tube makes analysis quite complex and I'm not sure what physical "theory" might apply. How "snug" a fit the sensor is, could make quite a difference. I would have expected the "sound" waves to travel along the centre of the tube and smooth walls not to be particularly necessary, but as the sound is a longitudinal (pressure) wave, maybe friction at the walls has some effect. Perhaps the nearest equivalent is the "speaking tube" that was used for example on ships, but there, the frequency was much lower, the speed of travel of the sound not of significance, and I believe the tapered "horn" at the end(s) is an important part of its functionality.

Elsewhere, I have proposed the use of a "sound pipe" for your type of application, but using the "Organ Pipe" principle, where the frequency of a resonance would be measured. A normal organ pipe is energised by a whistle/reed vent at the closed bottom end; with an open top the length is a quarter wavelength or about 100 Hz for a 1 metre height (or a half wavelength, 200 Hz, with both ends closed). However, the column can be also energised at the top, such as in a Bottle Organ. Thus the height of the air column could be calculated from the frequency or period, which can be measured very accurately. It might be energised by an air jet, by a sinusoidal microphone-amplifier-loudspeaker feedback system, or by simple pulses (like the tick-tock of a grandfather clock maintains the pendulum swing).

My concern is that this tube resonance might inter-react with your ultrasonic measurement, either a sub-harmonic of the 40 kHz, or a multiple of the ultrasonic burst period, and "pull" (or disturb) the measured transit times. I wonder if that is the cause of your "midday" issue. For the alternative method, a 30 mm pipe is much larger than I envisaged for a "pressure" system, but might have some advantages. I calculate the capacity as about 7 litres/metre column, so it could take several minutes to fully pump down the water level, but then would act as a large reservoir/filter that could make the pressure measurement simpler.

Cheers, Alan.

#### inglewoodpete

##### Senior Member
I once tried to use an ultrasonic transmitter and receiver to determine the distance to an object suspended in a 100mm smooth-walled PVC pipe. The concept worked up to a distance of about 200mm but I needed to measure to 2 metres. Beyond about 200mm, echoes from the walls began to dominate the reflected signal (observed on an oscilloscope). I tried adding cardboard tubes to the transducers but this did not help much.

Having said that, your water tank has a much larger diameter, so you may get better results.