---

Wednesday, January 24, 2024

Lies, Damn Lies and Analog Inputs (comparing ADCs on ESP32, Pico and Arduino)

After some inconsistent and unreliable results reading an analog input from an ESP32 board, I decided to get all scientific and do some experimenting with an ESP32, a Raspberry Pi Pico and an Arduino Uno R3.

Method

My test setup was a bench power supply providing the reference voltage to be measured by the test board. The output of the bench PSU had a dummy load of a 470Ω resistor and a 100nF capacitor in parallel (the latter largely for superstitions reasons) as the voltage output looks extremely stable on a DMM voltmeter.

This output from the bench power supply was then applied directly to an analog input and GND of the board being tested.

I was particularly interested in three things:

* finding any dead-zones at each end of the analog input voltage range

* measuring the reproducibility of the readings

* linearity through the range

Another time, I'd like to look at the input impedance of the ADC (analog to digital convertor) and the effects of how rapidly you sample. But I'll leave that for another day.

To measure the reproducibility of the readings, each time the test voltage was changed, 100 readings would be taken, and the mean and standard deviation of that set recorded. That way, when it came to plotting the readings from the boards, I could add some error bars.

For the ESP32 and Pico, I used MicroPython and for the Arduino Uno, I used Arduino C. The Arduino readings were scaled up to 16bit unsigned values (max value 65536) to be consistent with the MicroPython version. In all cases, the default ADC settings were used.

ESP32

For this experiment, I used an ESP32 Lite (sometimes also called LOLIN32 Lite). These are a ubiquitous low-cost ESP32 board, with built-in WiFi and Bluetooth.

Analog input maximum voltage 1.0V



Here's the plot

The red error bars show +- 3 standard deviations (SDs) from 100 samples. Nearly all of the sample values would fall within 3 SDs and 60% would fall within 1 SD.

There is a sizeable dead zone until the voltage rises to about 0.05V and a lot of noise around the readings, evidenced by the large error bars. But it retains pretty good linearity once you get past that up to the 1V upper limit.

Raspberry Pi Pico

The Raspberry Pi Pico uses Raspberry Pi's RP2040 chip. It'a another popular, good value board.

It's maximum analog input voltage is the full 3.3V supply range.


Here's the plot for the Pico - 


This is considerably better than the ESP32, with smaller 3 x SD error bars, a small dead zone at the low voltage end and some slight tail-off in linearity at the 3.3V end.

Arduino Uno R3

Despite its age, the Arduino Uno R3 (not the fancy new one) is still my go-to board for any experimentation or early stage project work that doesn't need a specific microcontroller. I'll admit, it's partly out of familiarity and inertia on my part.



And here are the results.


And there we have it. Very little deviation between readings and great linearity across the whole range, right up to 5V. The Uno with it's ancient Atmega328 is streets ahead of the other two boards.

Conclusion

On looking at the documentation in MicroPython and learning that the analog readings for a Pico and ESP32 come at a massive 16 bit precision (a number between 0 and 65536) it's easy think that their analog inputs are much better than the paltry 10 bits of an Arduino (0 to 1023 reading range). But this is to confuse precision with accuracy. It's why pure megapixels is not the best way to judge a camera. So much depends on the lens.

So, if you are trying to get decent accuracy and reproducibility from your analog readings, then you probably want to take a set of readings and average them -- or use an Arduino Uno R3!

Test Programs

ESP32

from machine import ADC, Pin
from time import sleep
from math import sqrt

analog = ADC(12)

p = 0.05
n = 100

while True:
    readings = []
    for i in range(0, n):
        readings.append(analog.read_u16())
        sleep(p)
    total = 0
    for i in range(0, n):
        total += readings[i]
    mean = total / n
    dist_tot = 0
    for i in range(0, n):
        dist = readings[i] - mean
        dist_tot += dist * dist
    
    print(mean, sqrt(dist_tot / n))
    
    input('Press enter to read again')

Pico

from machine import ADC, Pin
from time import sleep
from math import sqrt

analog = ADC(28)

p = 0.05
n = 100


while True:
    readings = []
    for i in range(0, n):
        readings.append(analog.read_u16())
        sleep(p)
    total = 0
    for i in range(0, n):
        total += readings[i]
    mean = total / n
    dist_tot = 0
    for i in range(0, n):
        dist = readings[i] - mean
        dist_tot += dist * dist
    
    print(mean, sqrt(dist_tot / n))
    
    input('Press enter to read again')

Arduino

int p = 50;

const int n = 100;


unsigned int readings[n];


void setup() {

  Serial.begin(9600);

}


void loop() {

  if (Serial.available()) {

    Serial.read();

    Serial.println("measuring");

    for (int i = 0; i < n; i++) {

      readings[i] = analogRead(A0) * 64; // 16 bit not 10

      delay(p);

    }

    float total = 0.0;

    for (int i = 0; i < n; i++) {

      total += float(readings[i]);

    }

    float mean = total / n;

    float dist_total = 0.0;

    for (int i = 0; i < n; i++) {

      float dist = float(readings[i] - mean);

      dist_total += (dist * dist);

    }

    float sd = sqrt(dist_total / n);

    Serial.print(mean); Serial.print(' '); Serial.println(sd);

  }

}



Wednesday, September 27, 2023

Raspberry Pi 5 Review

I was lucky enough to get hold of a pre-release Raspberry Pi 5. Here are my impressions of this latest incarnation of the Raspberry Pi Single Board Computer.



First Impressions

The first thing to strike me was the almost minimalist PCB layout, the top-side being mostly big chips with a lot of the tiny little capacitors and resistors on the underside of the board.

Reassuringly, the 40 pin GPIO connector fixing holes and usual great selection of USB and HDMI morts on the Raspberry Pi are all still there.

My version was supplied with an Active Cooler kit. One criticism of the Pi 4 was that it did tend to get quite hot. The complex self-monitoring of the SoC (system on a chip) meant that the hardware was not in danger, but it's a little disconcerting when the top surface of the chips feel like you could fry an egg on them. (I exaggerate!).

So a little fan to keep things cool will allow the Pi 5 to run at full speed.



The 'Active Cooler' is simplicity itself to fit. You just peel off the backing paper from the heatsink pads and push two sprung-loaded plastic pegs through holes on the board for that purpose. It makes the Pi 5 look pretty badass!


However, with the Active Cooler attached, there is very little room between the edge of the heatsink and the GPIO pins. This means that GPIO templates like the Raspberry Leaf are not going to fit. So anyone wanting to use the GPIO is going to be back to counting pin positions. 

Specifications

The Pi 5 is between two and three times faster than Raspberry Pi 4 (itself no slouch). It has a 64-bit quad-core Arm Cortex-A76 processor clocked at 2.4GHz. This time using a SoC designed by the Raspberry Pi team themselves.

Raspberry Pi 5 also offers significantly improved graphics performance and camera support, and some neat little extras:

  • A connector for a fan.
  • A connector for a backup battery, allowing time to be kept on the Real-time clock. (In most situations, this isn't really very useful as the Pi will set its clock from the internet. However for offline applications, this could come in handy.
  • A connector for UART (serial interface)
  • a PCIe 2.0 connector (for attaching SSDs etc)
  • A Reset switch
The Pi 5 is available with either 4 or 8 GB of RAM.

Who's it for?

The Raspberry Pi 4 was already a very worthy desktop/laptop replacement. At MonkMakes, we use the closely related (to Pi 4) Pi400 as a very capable office machine. With the increase in performance of the Pi 5 and with the edition of a PCIe SSD and a sturdy little case, then this device can replace a laptop or desktop computer in many situations. I sincerely hope that a Pi 500 built into a keyboard will be coming along soon.

This Pi is much more about being a proper computer, and I wouldn't be surprised to see the GPIO pins to eventually disappear altogether in some future version. 

Verdict

Top marks as a desktop replacement at a very competitive price. As a Single Board Computer (SBC), the huge community and availability of resources and add-ons make this (IMHO) the best SBC option.

However, if you don't need the performance, and are more interested in doing things with GPIO pins than you are browsing the internet or watching videos, then stick with a Pi 3. They use much less power and are perfectly adequate for most embedded applications, and you can attach a GPIO template so you know which pin is which.

For more information, see the official Raspberry Pi announcement.

Saturday, August 19, 2023

Disposable e-cigarette - Part 4 (Making batteries safe)

 In the fourth part of this series of posts, we'll take a look at making a battery extracted from an e-cig safe to use in your products. 

DANGER: 

There is a really good chance that the battery of a discarded e-cig is still holding quite a lot of energy. The fluid runs out first. So if, during disassembly, the unit triggers (quite likely), then a big current will flow and the heating element will get hot. Similarly any accidental short between the leads to the battery could easily cause a fire.

Cut the leads to the element (one at a time) and to the battery (again one at a time) as soon as you can access them. 

Also have a contingency plan such as fire blanket (not a bucket of water) or open window through which the flaming device can safely be thrown in the event of it catching fire.

If in any doubt that you can do this safely, then don't do it.

The e-cig batteries generally lack the 'protection circuit' found ready soldered across the terminals of the LiPo cell that carry out the following functions:

  • Preventing overcharging (can cause the battery to get hot and catch fire)
  • Preventing over discharging (rendering the battery incapable of holding charge)
  • Over-current protection, safeguarding against short-circuit of battery terminals. (can cause the battery to get hot and catch fire)
Fortunately these protection chips are, well, cheap as chips, because they are used in the billions. You can buy a small panel like this for a few dollars:


Here's the link for the one I bought.
That's right 10 for $1.30!

The idea is that the LiPo cell terminals are soldered to one pair of terminals on the protection PCB and then another pair of terminals are then used to connect to the battery that add the protections.


The terminals B+ and B- are for the LiPo cell and P+ and P-. The protection PCB is more likely to stay attached to the cell, if it's soldered close to the terminals, like this:


Notice I have also attached flying leads to protection PCB. It's a good idea not to strip the far ends of these leads until you need to, to prevent accidental short-circuits.

From now on, you should only connect to these leads and not directly to the cell. This will in most cases work exactly the same, except that there is now minimal risk of starting a fire with it.

Note that the protection PCB is not a charging circuit. It makes the LiPo cell safe, but that doesn't mean that you can just connect it to a voltage source and charge it. You will need a LiPo charging circuit to do that properly.

If you have a bench power supply, where you can set both the voltage and the current limit, then a safe way to charge the cell is to:
  1. To be ultra-safe, set the bench power supply's current limit to 1/10 of the cells capacity. For example, for 360mAh like the one shown, set the current limit to 36mA. 
  2. Set the voltage to 4.2V
  3. Connect the battery terminals (the connection PCB terminals - NOT the LiPo cell) and wait until the current drops to 0mA after about 10 hours.
At your own risk, you might like to charge the battery a lot faster - say at 500mA by setting that as the maximum current and still using 4.2V. Because the cells in e-cigs are designed for quite high-current use (several Amps) they should be fine for charging at this sort of current. But keep and eye on it, and stop immediately if the battery starts to get hot.

Monday, August 14, 2023

New Book: Coding: The 21st Century's Most Valuable Skill

MonkMakes Press Publishes Getting Started Guide to the Software Industry

August 10, 2023. Preston, UK.


Press Release

Coding: The 21st Century’s Most Valuable Skill is the latest book by best-selling non-fiction author Simon Monk. 

Aimed squarely at anyone contemplating a career in the software industry, this book gives the reader a taste of coding, as well as a guide to the real-life experiences of working in software. 

[Author Quote] Drawing on my 30 year career in software, as well as interviews with coders from the very biggest and smallest of software companies in the USA and UK, I hope I have shone a light on this industry that is so often hidden from outsiders.

The book is not afraid to pull the reader into the world of coding, with some real world practice. No prior coding experience is required and the reader is led step-by-step through installing the necessary software on  their Mac or PC and taking some first tentative steps.

The paperback and eBook editions are both in full color and are illustrated with comic-strips that make for an amusing and easy read.

If you are interested in a career in software, or just want to learn a bit more about what makes coders tick, then this book will provide you with valuable insights. Released in August 2023, the book is available from Amazon and Barnes and Noble.

Simon Monk, is best known for his books on programming the Raspberry Pi computer and the Arduino. He has sold over 750,000 books in 10 languages. Simon has a doctorate in Software Engineering and worked in the software industry for many years before switching from writing code to writing books. He has published over 20 titles on software and electronics.

Contact (author): simon@monkmakes.com 

Tuesday, August 8, 2023

Disposable e-cigarette Teardown - Part 3

DANGER: 

There is a really good chance that the battery is still holding quite a lot of energy. The fluid runs out first. So if, during disassembly, the unit triggers (quite likely), then a big current will flow and the heating element will get hot. Similarly any accidental short between the leads to the battery could easily cause a fire.

Cut the leads to the element (one at a time) and to the battery (again one at a time) as soon as you can access them. 

Also have a contingency plan such as fire blanket (not a bucket of water) or open window through which the flaming device can safely be thrown in the event of it catching fire.

If in any doubt that you can do this safely, then don't do it.

In the third part of this series of posts, we'll take a look at exactly what's going on in one of the minimal disposable e-cogs -- the type that appears to jus have 3 components: a battery, a heating element and something that looks like an electret microphone.


The 'mic' turns out to be a lot more than just a microphone. For a start it has a blue LED on it that lights for a few seconds when it detects a strong pressure difference. I got this to work by attaching a short length of tubing to it and then blowing into it. 


I attached a load resistor to the output in order to measure the output voltage when the e-cig is activated. No real surprise here, but it matched the battery voltage closely.

Here, you can also see wha happens a the output when the e-cig is activated. Here is the wiring diagram for the e-cig.


The mystery 'mic' is acting as a high-side switch. That is. one side of the heater element is connected to the battery negative (GND) and the 'mic' (when activated) connects the other end of the heater to the positive terminal of the battery.

I think that the 'mic' might actually be a pressure detector plus microcontroller MOSFET and LED all in an electret-insert-style case. The back of the case being a thin PCB with the LED on the outside. The only reason that I think the 'mic' might have a microcontroller in it, is the way that the output is timed and that the LED blinks just before the e-cig deactivates.

Here's my best guess as to what's in the 'mic' can.


The pressure sensor may actually be a microphone, and the microcontroller does some thresholding and to decide if the air rushing over it constitutes someone drawing on the e-cig and then sets the output low to turn the P-channel MOSFET on. The LED does not seem to be in parallel with the output load, as applying a voltage back to the output when the e-cig is not activated does not light the LED. So, it looks like the LED is either connected to a different GPIO pin to the MOSFET, or its on the gate side.

Anyway - my collection of handy LiPos, of various sizes, is gradually increasing. There are just so many of these out there discarded on the street.

Sunday, August 6, 2023

Disposable e-cigarette Teardown - Part 2

I seem to be inadvertently gaining a new hobby. A short cycle ride last week yielded 3 more 'disposable' e-cigs.



DANGER: 

There is a really good chance that the battery is still holding quite a lot of energy. The fluid runs out first. So if, during disassembly, the unit triggers (quite likely), then a big current will flow and the heating element will get hot. Similarly any accidental short between the leads to the battery could easily cause a fire.

Cut the leads to the element (one at a time) and to the battery (again one at a time) as soon as you can access them. 

Also have a contingency plan such as fire blanket (not a bucket of water) or open window through which the flaming device can safely be thrown in the event of it catching fire.

If in any doubt that you can do this safely, then don't do it.

This time, two ENG Legends and a more substantial R and M Tornado. The latter had a USB-C connector and although I couldn't see a way to refill it with fluid, looked like a reusable model. This turned up some interesting clues, as you will see later.

First, the ENG model. This is very similar to the models I took apart in my previous post.


Again, it's much the same arrangement with a thing looking for all the world like an electret mic insert switching the battery to the heating element. It has a nice useable 5.5Wh battery -- again without any protection PCB.

The insides of the R and M Tornado are altogether much more interesting. 


Not only does this board have a little PCB holding a LiPo charging circuit and USB-C socket, but also the PCB is nicely designed and silkscreen labels for the parts and terminals. A second PCB for the heating element has what I assume to be a SOT-23 MOSFET. The heater PCB receives power from the battery and a control signal from the first PCB,

This PCB has the USB socket and LiPo charging on one side.


The other side has a microphone that supplies the control signal to turn the heating element on.


This PCB is a handy little charging circuit. There is no obligation to use the 'puff sensing' feature. With the addition of a switch and a CREE LED bulb, you could make a great little USB torch. Maybe something for the next blog post.






Wednesday, July 19, 2023

Disposable e-cigarette Teardown - Part 1

I went for a lunch-time walk with the intention to look out for a discarded 'disposable' e-cigarette. I found by the side of the road almost immediately.


DANGER: 

There is a really good chance that the battery is still holding quite a lot of energy. The fluid runs out first. So if, during disassembly, the unit triggers (quite likely), then a big current will flow and the heating element will get hot. Similarly any accidental short between the leads to the battery could easily cause a fire.

Cut the leads to the element (one at a time) and to the battery (again one at a time) as soon as you can access them. 

Also have a contingency plan such as fire blanket (not a bucket of water) or open window through which the flaming device can safely be thrown in the event of it catching fire.

If in any doubt that you can do this safely, then don't do it.

This was quite a big one, and looking on the Internet sells for about £10 ($12). Far from being a flimsy thing, the case was well made and looked like it was designed to be taken apart. One end was held in place by push clips that opened easily with a screwdriver.



So what did I find! Well, a lot less than I was expecting! There are just 3 electronic components:

  • The battery - 5.18Wh cylindrical LiPo. This was still measuring 3.4V
  • The heating element - showing a cold resistance of 1Ω
  • What looked like an electret mic insert, but I believe from the wiring, detects the cigarette being sucked, and switches power from the battery to the coil



There was no sign of any microcontroller or protection chip for the battery. The wiring is 0.4mm including insulation and not something that looked like it would cope with 3-4A. Hot wires and a heating element next to a LiPo cell - what could possibly go wrong!

Anyway, the battery is on charge and I'm pretty sure will come in very handy in some project or other.




I think it's a terrible waste of resources that these things are sold as disposable with insincere promises that they will be recycled properly. They aren't - people just drop them in the street.