EEVblog Electronics Community Forum

Electronics => RF, Microwave, Ham Radio => Topic started by: thinkfat on December 23, 2021, 05:00:58 pm

Title: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on December 23, 2021, 05:00:58 pm
I have a project on my mind that I'm looking for inspiration for.

The background of it is my son. He was born with chromosomal anomaly, Trisomy 21, aka "Down Syndrome". He's eight years old now but due to his condition he's quite a bit different from "standard issue" kids of the same age. He tends to get lost in his own world quite a bit, which is sometimes stressful especially when we're out and about in places where it's difficult to keep an eye on him. He tends to just wander about and get lost and is then unable to find us or ask for help. Think mall or grocery store. I have another kid (6y) and keeping track of them both is a challenge.

There are parents who put they kids on a leash out of desperation, which is a pragmatic approach but I would like our "bond" to be a bit more subtle. So I would like to make a "distance alert".

The idea is to have two transceiver boxes that "ping" each other every couple of seconds, and when they cannot hear each other any more, an audible alarm would sound from both. I would be carrying one of the boxes, my son the other one. When he gets out of range, the alarm from my box would alert me and the sound from his box would allow me to track where he went. 

The range should be no more than 10 meters. The RF frequency should be high enough to allow for small antennas yet at the same time be a manageable task to develop with hobby-grade equipment. 2.4 GHz ISM band would be suitable, I think. Battery autonomy should be a couple of hours from a full charge. The total size should make it wearable, maybe with a wristband or on a belt.

I can pretty much cover all of the topics, except for the RF platform.

I'm guessing something like a TI CC1352P could be used, but maybe there is something simpler?

Title: Re: "Distance Alert", looking for inspiration for project.
Post by: MK14 on December 23, 2021, 05:13:15 pm
You could consider the esp (esp8266/esp32) range of devices. If their range is sufficient.

Interestingly, for this application. is, the latest/newer ones (possibly not released yet and/or delayed by chip shortages), have a new range finder feature (time of flight). Which uses the speed of light, to detect the exact distance between the units (if I remember/understand it correctly).

EDIT:
Example mentioning it, trying to measure exactly 10 metres (like you, by coincidence), mentioned later in the posts:

https://github.com/espressif/esp-idf/issues/5059
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: DrG on December 23, 2021, 05:39:35 pm
I would suggest that you evaluate a BLE beacon and a phone app as the receiver. Look into RSSI, which you would need to specifically evaluate programmatically.

I am not saying that this approach will absolutely work for you, but I think it is worth investigating because the hardware and software are out there and relatively cheap. Battery life would not be a problem.

Some searching, including; RSSI, ble beacon, programmable advertising interval and so on will give you a good idea of usability.

Let us know how this project progresses - ok?
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on December 23, 2021, 08:39:59 pm
I would suggest that you evaluate a BLE beacon and a phone app as the receiver. Look into RSSI, which you would need to specifically evaluate programmatically.

I am not saying that this approach will absolutely work for you, but I think it is worth investigating because the hardware and software are out there and relatively cheap. Battery life would not be a problem.

Some searching, including; RSSI, ble beacon, programmable advertising interval and so on will give you a good idea of usability.

Let us know how this project progresses - ok?

Thanks for the suggestion. My use case would involve both sides being aware of the maximum distance violation, though. So both boxes need to transmit and also receive. But a BLE beacon could still be used.

The 10m distance doesn't need to be exact. It is a sensible value that allows a good degree of personal freedom for my son and at the same time peace of mind for me because I should still be able to see him and hear the alert from his box.

The solution can not be too simple, as both boxes need to sound the alert as soon as one of them loses contact. So, when one of them doesn't receive the transmission from its partner any more, it would change it's own signal from "I can hear you" to "I cannot hear you". This should counter asymmetric transmit/receive scenarios.

I will keep this thread alive, though when I start the actual development I will likely create a new thread.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: jpanhalt on December 23, 2021, 08:47:16 pm
User on-the-fly programmable GPS might be a better option.  See: Invisible Fence.  Of course, you would not use a shock.

My best friend in elementary school had a slightly younger brother with Trisomy 21.  We were all great friends.  His brother used to visit me frequently and unannounced on his own.  That was no problem for me, of course, but it involved him crossing a busy street in LA.  Everyone worried about that.  Good luck is finding a solution.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on December 23, 2021, 09:12:16 pm
User on-the-fly programmable GPS might be a better option.  See: Invisible Fence.  Of course, you would not use a shock.

My best friend in elementary school had a slightly younger brother with Trisomy 21.  We were all great friends.  His brother used to visit me frequently and unannounced on his own.  That was no problem for me, of course, but it involved him crossing a busy street in LA.  Everyone worried about that.  Good luck is finding a solution.

Thanks for the suggestion. The use case is that both of us are roaming. Both would therefore need to transmit their position to establish the fence. Using GPS sounds like adding needless complexity.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: jpanhalt on December 23, 2021, 09:14:17 pm
Coordinates are easily converted to line-of-sight distance apart.  Maybe a little more math than signal strength, but much more robust.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on December 23, 2021, 09:44:52 pm
Coordinates are easily converted to line-of-sight distance apart.  Maybe a little more math than signal strength, but much more robust.

The distance calculation may be more robust indeed, but as I said, we might be in a mall without GPS coverage. I need the system to be autonomous. Also, I don't need precisely 10m maximum distance. If the alert comes up at 7 or 12 meters that's also fine. Actually, if it's a crowded, confusing location it's a plus if the alert comes on at a smaller distance. A weak'ish point-to-point link is likely the best choice.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: RoGeorge on December 23, 2021, 09:49:32 pm
WiFi range is rather large.  My guess is you may want to test more detection methods first, before committing to a proprietary design that fits in a wristband.

Probably a Bluetooth device would fit better for that range.  Bluetooth range is rather small, and you may use mobile phones for testing.  Even a player and a paired Bluetooth headphones might be enough.  You can listen to music/audiobooks from a mobile phone used as a player and wear by the kid, while you will wear a single headphone/headset paired with the playing phone.

As an extra advantage, Bluetooth headphones with A2DP (I know this from a pair a Sennheiser I have with A2DP) will start to have choppy sound quality before loosing the link, so you will be warned in advance, and the range is about right for an application like yours.

I don't now if normal Bluetooth used in a hands-free headsets (usually without A2DP) are acting the same way, or if they just suddenly loose the connection.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: jpanhalt on December 23, 2021, 09:50:29 pm
Signal strength in a mall is no more reliable than a "smart phone" which gives GPS.  That's just theory, of course.  I avoid malls as i don't like being run over with shopping carts by women glued to their cell phones. :)  In the US, they open at 10AM, I am never there a minute later.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: xmo on December 23, 2021, 11:30:25 pm
Anything RF is going to have different range depending on the environment.

You might consider some sort of RFID tag like those used for inventory control.  There are several systems with different ranges.  At the 'parent' end, a microcontroller could trigger the reader to 'ping' for the tag at preset intervals.  A missed ping would engage a re-try protocol.  After so many failed attempts, the controller would alert the parent and a small radio transmitter could send an alert back to a simple receiver at the user end.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: MK14 on December 24, 2021, 12:44:14 am
I have a project on my mind that I'm looking for inspiration for.

If you don't mind me thinking out loud (and out of the box).

These days, you can buy very cheap, and very small, mobile phones. Which are considerably smaller, than the usual mobile phones. Sort of domino sized, which could easily clip onto a belt clip, or similar.

It would have most/all of the required features, already built into it. Rechargeable battery, case, GPS as final last resource of tracking where they managed to run off to, after 10 minutes of searching.
Accelerometers and compass, for estimating where they have moved to (direction and distance).
Can be phoned up, to find out, where they managed to get to, if wi-fi and/or Bluetooth signals, out of range.

Then it would be a matter of creating the software, or using existing app(s) and/or git-hub and other resources.

You could even make it ring to talk to the child and/or people near-by.

Speaker already built in.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: DrG on December 24, 2021, 01:45:12 am
I would suggest that you evaluate a BLE beacon and a phone app as the receiver. Look into RSSI, which you would need to specifically evaluate programmatically.

I am not saying that this approach will absolutely work for you, but I think it is worth investigating because the hardware and software are out there and relatively cheap. Battery life would not be a problem.

Some searching, including; RSSI, ble beacon, programmable advertising interval and so on will give you a good idea of usability.

Let us know how this project progresses - ok?

Thanks for the suggestion. My use case would involve both sides being aware of the maximum distance violation, though. So both boxes need to transmit and also receive. But a BLE beacon could still be used.

The 10m distance doesn't need to be exact. It is a sensible value that allows a good degree of personal freedom for my son and at the same time peace of mind for me because I should still be able to see him and hear the alert from his box.

The solution can not be too simple, as both boxes need to sound the alert as soon as one of them loses contact. So, when one of them doesn't receive the transmission from its partner any more, it would change it's own signal from "I can hear you" to "I cannot hear you". This should counter asymmetric transmit/receive scenarios.

I will keep this thread alive, though when I start the actual development I will likely create a new thread.

Hmmm food for thought and a juicy problem. I don't manufacture or sell ble beacons. I have used them but have never tried to use RSSI for distance - it seems like it can be useful in non signal loss cases. But as an exercise, I wonder how you might go about evaluating suitability for the problem.

Let's say the device consists of a BLE beacon transmitter and an ESP32 receiver. Additionally, the ESP32 can run the alarm functions. So, in theory, you have one segment addressed, i.e., each device has to have a transmitter and a receiver.

The beacon sends a brief transmission (let's say a millisecond or so) at some interval. That interval can be programmed - let's say you use  a 100 ms interval.

The esp32 is mostly scanning and scanning for all ble activity and then parses what it found and looks for the other guys beacon transmission. That part is easy because of the information in the advertisement, which easily includes a unique identifier and normally some other stuff (like rssi). The good thing for this problem is that there is no real standard in that there are usually some fields that you can manipulate - so, for example, this is how beacons can transmit temperature - the just stick the value in the field.

But, you want:
Quote
both boxes need to sound the alert as soon as one of them loses contact.

Well on your end, when you can't receive a beacon after a couple of scans (let's say 15 seconds), you can sound an alarm that you can hear. You can also change your advertising packet to reflect that you can't 'see' your son. If your son's unit has NOT lost reception of your unit, he can have a different alarm (one lost signal) and vice versa. Ok, so far so good.

What happens when both signals are lost? Both unit start alarming - so far, so good.

Beacons can have a range that exceeds your 10 m - so far so good. This allows your device to have a comfort zone and an alerting zone and a caution zone. You can take multiple readings before determining that an alarm has occurred.

Batteries - always an issue. Not so much for the beacon but the ESP32 is a bit of a hog but probably not insurmountable because you say:
Quote
Battery autonomy should be a couple of hours from a full charge.

Belt wearable is no problem with the battery probably being the largest part.

But what about how good rssi will be for distance? That is a big one. As I recall, in the heyday of advertising beacons, zones were setup to determine which advertisement (in this case an actual market advertisement) would be received/displayed - in the case of inside one large building, they probably could determine which junk stand you were closest to, but you are doing something different.

You could evaluate one beacon and one esp32 receiver and a battery for about $25 I would guess. That's important because it would first have to work well in no-loss situations, like an open area. Then advance to more complicated areas with walls and beams and so on.

You do have the benefit of recent work, not just in beacons but in patient tracking (for hospital and dementia centers) and even pandemic-inspired social distance detection (although you want the inverse, it is still relevant).

Don't know. It's a good problem.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on December 27, 2021, 04:51:39 pm
Currently looking at different platform options.

TI CC2640, STM32WB and obviously there should be something from Nordic as well. I think a BLE beacon is generally good idea, but maybe I can do something with ToF over BLE, might be better than just RSSI, if I can pull it off. GPS is pretty much out of the picture for me. Too power hungry and only useful under open sky conditions. Also, it'd need a quite sizeable antenna.

But there are also a number of ready-made BLE modules that have a SPI or UART interface, maybe it's going to be one of those if they can do what I need.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: DrG on December 27, 2021, 05:24:17 pm
Your design/construction skills may exceed mine for sure. I would not bother getting a BLE (like a Microchip BM70 or similar) component that I would then have to interface with a CPU. Not when the ESP32 is around and so easily available and programmable. I have also used a Linkit  7697, not terribly popular, but feasible. Then there are the Arduino NANO 33 IOT and MKR WiFi 1010, each of which have BLE capability and are easy to use and also have some battery options considerations. The 33 IoT (ceramic resonator) is only about $15-$20 as I recall.

As far as a BLE beacon, I have only played with one of these https://www.hackster.io/bigboystoys13/diymall-bluetooth-beacon-getting-started-656c6b (https://www.hackster.io/bigboystoys13/diymall-bluetooth-beacon-getting-started-656c6b) and I do have a few others hanging around (on the virtual To-Do list).

Improving on RSSI outside of GPS would be an accomplishment that I would like to learn about. I have been thinking about this within the context of the (now old) luggage tags, which are supposed to tell you when your luggage is being stolen (or arrives on the conveyor, I suppose) and perhaps need to update my thinking to whatever that Apple tag [edit Air tag as @ shocked posted while I was typing this] is that I see articles about where they are used to stalk people :)

BTW: I doubt this would interest you, but I would like to get one of these to play with for no other reason that it looks like fun <-- that is the mentality that fills my drawers with bread-boarded projects that never get to the finished stage.

https://www.amazon.com/Location-Tracker-Bluetooth-Temperature-Developer/dp/B07HJ6N67N/ref=sr_1_12?crid=1JCZH20037AGB&keywords=ble+beacons&qid=1640299166&sprefix=ble+beacons%2Caps%2C60&sr=8-12 (https://www.amazon.com/Location-Tracker-Bluetooth-Temperature-Developer/dp/B07HJ6N67N/ref=sr_1_12?crid=1JCZH20037AGB&keywords=ble+beacons&qid=1640299166&sprefix=ble+beacons%2Caps%2C60&sr=8-12)

Title: Re: "Distance Alert", looking for inspiration for project.
Post by: ogden on December 27, 2021, 06:02:04 pm
I hate to disappoint, but all that RSSI stuff will work reliably in open field only where you can locate your kid with your eyes. As soon as there are reflections or obstructions - simple radio signal strength approach most likely will give way too much false alarms to render system useless.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: DrG on December 27, 2021, 06:19:28 pm
I hate to disappoint, but all that RSSI stuff will work reliably in open field only where you can locate your kid with your eyes. As soon as there are reflections or obstructions - simple radio signal strength approach most likely will give way too much false alarms to render system useless.

I can't speak for the OP, but you are not disappointing me as I have experienced the interruption of BLE beacon signals when interfacing solar beacons to an ESP32. Obviously, *some* kinds of barriers are going to prevent reception of the advertisement containing the RSSI field - that is understood and it is why you stating as much is not particularly disappointing. It has also been my experience that some obstructions are tolerable, e.g., I can read the beacons from a location when the beacon is not in the same room and another is outside and so on - it depends on the material and the extent of disruption. Clearly, it is not just line-of-sight reception.

As I hinted at, it may be possible to program your way to mitigating this problem (to some degree) by establishing a criterion before alarming, e.g., waiting some length of time of no signal (or RSSI-indicated out of zone). This would mitigate the effects of moving temporarily behind a steel column, for example. Since there is an assumption that there is no intention to specifically avoid detection, the approach is worth investigating - unless you can suggest another and much better approach - that becomes the challenge, the crux of the biscuit :)
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on December 27, 2021, 07:46:31 pm
I hate to disappoint, but all that RSSI stuff will work reliably in open field only where you can locate your kid with your eyes. As soon as there are reflections or obstructions - simple radio signal strength approach most likely will give way too much false alarms to render system useless.

I get that. But a potentially exploitable side effect is that the range is going to be smaller in complex environments where it's also easier to lose sight of the kid. It might actually work in my favor.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: ogden on December 28, 2021, 06:13:37 am
I get that. But a potentially exploitable side effect is that the range is going to be smaller in complex environments where it's also easier to lose sight of the kid. It might actually work in my favor.

Ok. Try something like: https://www.apple.com/airtag/ (https://www.apple.com/airtag/). There's more: https://expertworldtravel.com/best-smart-luggage-trackers/ (https://expertworldtravel.com/best-smart-luggage-trackers/)
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: Neomys Sapiens on December 29, 2021, 06:08:17 pm
I hate to disappoint, but all that RSSI stuff will work reliably in open field only where you can locate your kid with your eyes. As soon as there are reflections or obstructions - simple radio signal strength approach most likely will give way too much false alarms to render system useless.

I get that. But a potentially exploitable side effect is that the range is going to be smaller in complex environments where it's also easier to lose sight of the kid. It might actually work in my favor.
You should not bet on that. I can easily imagine settings where parts of the store furniture or articles presented form a resonator and make deviations to the other side by a factor of ten!
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on December 30, 2021, 09:47:47 am
Okay. I think I will have to prototype something to evaluate conceptual feasibility. In order to get some results rapidly, ESP32 seems to be the right experimental platform. I will order some and then see if I can get something up and running quickly. BTW, I found out that u-blox has some modules based on the ESP32 platform, the NINA series. But bare ESP32 is more versatile.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: MK14 on December 30, 2021, 12:02:46 pm
You can get ESP32 units, already built into watch strap cased versions, at amazingly low prices. Such as around $17. There are multiple suppliers, including EU (I think). I've forgotten the EU one I was planning to use.

Here is an example:
https://www.waveshare.com/m5stickc-watch-kit.htm (https://www.waveshare.com/m5stickc-watch-kit.htm)

But, the Later S2 (ESP32-S2, https://www.espressif.com/en/products/socs/esp32-s2 (https://www.espressif.com/en/products/socs/esp32-s2) ) and probably later, 'new' ESP32 devices have more features, such as time of flight (which may or may not, help you).
I.e. ESP-S2's (newish), have ToF (I strongly think), and perhaps other new ones, such as ESP-S3, also have it, or even more.

There may even be child sized watch strapped versions (I'm not sure, if that applies to ESP32 or not, e.g. Micro-bit BBC kits do them, which also have a rf device built in, but they are not ESP32 ones).

Many features built into those $17 (approx) modules, such as battery, display, switches, mic, multi axis movement sensors, etc.

Quote
Powered by ESP32 module, supports WiFi and Bluetooth 4.2
0.96" true color LCD, 80×160 pixels
6-axis IMU, with 3-axis gyroscope and 3-axis accelerometer
Digital mini high SNR microphone
Onboard button, IR transmitter, and LED, for human-machine interaction
Power management chip, for battery charging/discharging management
80mAh Li-po battery, allows short term operation
USB Type-C port, for power input, battery charging, or debugging
Onboard expansion interface, supports external sensors
Supports MicroPython, Arduino, and UIFlow (graphic programming) development
Small form factor, comes with watch strap and mount holder, wearable
Comes with development resources and manual (SDK and tutorials)
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: MK14 on December 30, 2021, 12:31:38 pm
The new time-of-flight ones and new ESP32 versions, I've wanted myself (for a wearable ESP32 project, not ToF), for a period of time. But because they are new and/or chip shortages/delays, I have been unable to find any stock of them (and/or not with suppliers I wanted to use), when I last tried, a while ago.

If I remember right, the watch strapped versions (there are different ones, some at a higher price), don't do time of flight, but can be available for sale, when I last looked (some time ago).

There is a growing list of things I want to buy, but can't, because of component shortages. I will just have to wait.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: NiHaoMike on December 31, 2021, 06:31:13 pm
There's a pair of boards intended to solve that exact problem.
https://www.youtube.com/watch?v=HEb13WsMTtg (https://www.youtube.com/watch?v=HEb13WsMTtg)
It's open source for those who want to make their own version of it:
https://github.com/DFRobot/DFResources/tree/master/KittyFlower (https://github.com/DFRobot/DFResources/tree/master/KittyFlower)
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on January 01, 2022, 01:19:55 pm
Yep.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on January 19, 2022, 04:48:14 pm
I meanwhile bought two ESP32-C3 devkit boards. I've cobbled together a small sketch that sends out iBeacon advertisements and at the same time listens to iBeacon packets from other transmitters. The C3 devkit has a neopixel LED on it, I guess I should be able to make it so that the color changes with the distance between the two boards. That will allow me to explore how the solution will behave in real life settings.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on January 20, 2022, 10:11:30 pm
This is the current prototype sketch for the ESP32-C3-DevKitM-1, which is based on the ESP32-C3-MINI-1 module. I'm using the Arduino IDE, simply because it had the lowest entry hurdle. I usually use a baremetal SDK or toolchain and Eclipse as the IDE but the Arduino framework has something going for it, which is it allows to quickly code up simple stuff.

The functionality implemented is quite simple but I don't think I will need more.

The sketch initializes a beacon and starts advertising it and configures a passive scan.

In the main loop, it scans for two seconds (passive scan), then evaluates the scan results, then goes to sleep for one second to save battery.

If a beacon was received during the 2 seconds, it simply goes back to sleep.

If a beacon was not received for 8 seconds, it enters "ALARM" mode. This is when the buzzer on both devices would go off. For now only the RGB LED on the board turns from green to red.

Both devices stay in ALARM mode until they receive a beacon with sufficient signal strength (-60 dBm). That is roughly equivalent to being an arms length away. So the buzzer would keep sounding until I was near to my son again.

I made an experiment today with my little daughter, asked her to walk away from me with the "don't go too far away"-device until the light turned red and then come back. The range in free area is quite remarkable, maybe 50 meters or more. I expected it to be less, but I can still introduce an artificial RSSI limit.

I haven't yet checked power consumption or optimized anything. This evaluation will decide whether I'll just use an ESP32 module or go for a fully custom design.

Code: [Select]
/*
   Based on Neil Kolban example for IDF: [url]https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp[/url]
   Ported to Arduino ESP32 by pcbreflux
*/


#include "BLEDevice.h"
#include "BLEUtils.h"
#include "BLEScan.h"
#include "BLEAdvertisedDevice.h"
#include "BLEBeacon.h"
#include "Adafruit_NeoPixel.h"
#include "esp_sleep.h"

#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00) >> 8) + (((x)&0xFF) << 8))

static BLEAdvertising *pAdvertising;
static BLEScan *pBLEScan;

// See the following for generating UUIDs:
// [url]https://www.uuidgenerator.net/[/url]
#define BEACON_UUID           "94e82029-3762-45f2-befb-7fd39711751f" // UUID 1 128-Bit (may use linux tool uuidgen or random numbers via [url]https://www.uuidgenerator.net/[/url])
#define SERVICE_UUID          "c9a70b84-027e-4cf5-b8d5-708f1f9956a1"

// NeoPixel
#define NEO_PIN 8
#define NEO_NUM 1

Adafruit_NeoPixel pixel(NEO_NUM, NEO_PIN, NEO_GRB + NEO_KHZ800);

static void setScan()
{
  pBLEScan = BLEDevice::getScan(); //create new scan
}

static void setBeacon()
{
  BLEBeacon oBeacon = BLEBeacon();
  oBeacon.setManufacturerId(ENDIAN_CHANGE_U16(0xDEAF));
  oBeacon.setProximityUUID(BLEUUID(BEACON_UUID));
  oBeacon.setMajor(0);
  oBeacon.setMinor(0);
  oBeacon.setSignalPower(-50);
  BLEAdvertisementData oAdvertisementData = BLEAdvertisementData();
  BLEAdvertisementData oScanResponseData = BLEAdvertisementData();

  oAdvertisementData.setFlags(0x04); // BR_EDR_NOT_SUPPORTED 0x04

  std::string strServiceData = "";

  strServiceData += (char)26;     // Len
  strServiceData += (char)0xFF;   // Type
  strServiceData += oBeacon.getData();
  oAdvertisementData.addData(strServiceData);

  pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->setAdvertisementData(oAdvertisementData);
  pAdvertising->setScanResponseData(oScanResponseData);
  pAdvertising->setAdvertisementType(ADV_TYPE_NONCONN_IND);

  // set advertising intervals
  pAdvertising->setMinInterval(500);
  pAdvertising->setMaxInterval(1000);
  pAdvertising->setMinPreferred(500);
  pAdvertising->setMaxPreferred(800);

  // Start advertising
  pAdvertising->start();
}

void setup()
{
  Serial.begin(115200);

  // Create the BLE Device
  BLEDevice::init("ESP32 as iBeacon");
  // configure beacon and scan
  setBeacon();
  setScan();

  // clear the pixel for now
  pixel.begin();
  pixel.clear();
}

void loop()
{
  static int alarmState = -1;
  static int lastRssi = 0;
  static int lastSeen = 0;
  bool beaconFound = false;
   
  // start a 2 second passive scan
  BLEScanResults foundDevices = pBLEScan->start(2, false);

  // check what we found
  for (int i = 0; i < foundDevices.getCount(); ++i) {
    BLEAdvertisedDevice advertisedDevice = foundDevices.getDevice(i);
   
      if (advertisedDevice.haveManufacturerData() == true) {
        std::string strManufacturerData = advertisedDevice.getManufacturerData();

        uint8_t cManufacturerData[100];
        strManufacturerData.copy((char *)cManufacturerData, strManufacturerData.length(), 0);

        if (strManufacturerData.length() == 25 && cManufacturerData[0] == 0xAF && cManufacturerData[1] == 0xDE) {
          lastRssi = advertisedDevice.getRSSI();
          beaconFound = true;
        }
      }
  }

  pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory

  if (beaconFound) {
    lastSeen = 0;
    // call off alarm only when in near vicinity
    if ((alarmState < 0 || alarmState == 1) && lastRssi > -60) {
      pixel.setPixelColor(0, 0, 32, 0);
      pixel.show();
      alarmState = 0;
    }

  } else {
    ++lastSeen;
    if ((alarmState <= 0) && lastSeen > 3) {
      pixel.setPixelColor(0, 32, 0, 0);
      pixel.show();
      alarmState = 1;
    }
  }

  Serial.printf("Beacon last seen %i cycles ago with RSSI %i dBm, ALARM %s\n",
    lastSeen, lastRssi, alarmState == 1 ? "ON":"OFF");

  // flush serial before going to sleep
  Serial.flush();
  // enter light sleep for one seconds
  esp_sleep_enable_timer_wakeup(1000 * 1000);
  esp_light_sleep_start();
}


Title: Re: "Distance Alert", looking for inspiration for project.
Post by: A.Z. on January 21, 2022, 12:58:32 pm
Nice ! I'd just change the timings and use prime numbers to have a bit better distribution; an alternate approach could be listening for beacons and using a timer so that if a beacon isn't received for a given time, the device will go into alert mode, such an approach would avoid the poll and turn the code into event driven mode
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on January 21, 2022, 01:23:14 pm
Nice ! I'd just change the timings and use prime numbers to have a bit better distribution; an alternate approach could be listening for beacons and using a timer so that if a beacon isn't received for a given time, the device will go into alert mode, such an approach would avoid the poll and turn the code into event driven mode

Thanks for the response and suggestion. I don't understand what you mean with "prime numbers" for the timing, though.

I still have to explore the BLE API a bit more to understand what can be made asynchronous with callbacks, and whether it's truly async to the loop() function or must from from its context. The BLEScan API hints that a scan can be started without waiting for completion, but then I need to check what happens while the device is in sleep mode.

I can imagine, that if the BT module can be a wakeup source, I could have a mainloop that does nothing but sleep indefinitely and only wake up when a beacon is received. But then power consumption would depend on how crowded the environment is. Maybe the hardware can do filtering and only generate a wake-up events for certain packets received.

But I'm getting ahead of myself.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on January 24, 2022, 09:33:33 am
The system architecture is coming together. For the first functional prototype I will sandwich a second PCB under the DevKit board, which will have a PMIC, piezo driver and a LiPo battery.

I'm going to use the BQ25015 as PMIC, it integrates a LiPo charger and a buck converter that can output up to 300mA. That should be enough for the use case. The PMIC will be wired such that it gets its charge voltage from the DevKit when it's connected to USB.

The piezo driver is just a small mosfet that will be driven by a PWM pin from the DevKit. I'm connecting it directly to the battery to give it some more "Oomf".

The battery is going to be a 250mAh LiPo pouch cell, 503020 type.

The piezo buzzer will be resonating at around 1kHz, I'm going to use a passive type without integrated driver.

I will have to remove the onboard 3.3V LDO from the DevKit, though.

I'll post the schematic when it's ready.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: A.Z. on January 25, 2022, 07:53:02 am
Thanks for the response and suggestion. I don't understand what you mean with "prime numbers" for the timing, though.

It's mostly an idiosyncrasy of mine ;D what I meant was changing the code somewhat like

Code: [Select]
  pAdvertising->setMinInterval(503);
  pAdvertising->setMaxInterval(1009);
  pAdvertising->setMinPreferred(503);
  pAdvertising->setMaxPreferred(809);

  ...
 
  esp_sleep_enable_timer_wakeup(1000003);

that is using prime numbers for the timings, that way you'll obtain a bit better distribution of polls/beacons, but again, it was just off the top of my head

Quote
I still have to explore the BLE API a bit more to understand what can be made asynchronous with callbacks, and whether it's truly async to the loop() function or must from from its context. The BLEScan API hints that a scan can be started without waiting for completion, but then I need to check what happens while the device is in sleep mode.

I can imagine, that if the BT module can be a wakeup source, I could have a mainloop that does nothing but sleep indefinitely and only wake up when a beacon is received. But then power consumption would depend on how crowded the environment is. Maybe the hardware can do filtering and only generate a wake-up events for certain packets received.

Yes, my line of thought was to check if the library/API allows to setup callbacks, in such a case your code may just setup a callback and a timer, if a callback due to a received beacon arrives before the timer ticks the timer is cancelled and restarted, if not the timer increases a counter and (which gets reset by beacon callback) when the counter reaches a given value (say 3 or whatever) the timer callback code sends an audio alert and restarts the timer w/o resetting the counter, this way the device will "beep" at intervals as long as it doesn't receive a new beacon; hope it's clear, this way your code won't need to "loop" but will just setup the callbacks (beacon and timer) and do nothing until one of the callbacks is received, this will lower the load on the CPU and allow the battery to last longer


Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on January 25, 2022, 08:37:22 am
Okay, thanks a lot for the explanation. I'll take your suggestion into account. I believe, though, that the BLE stack will choose the beacon intervals by itself within the bounds set by the min and max values.

Regarding the API - it seems scanning can be done asynchronously to the main loop function, the handling is performed in a separate thread. I'm not sure if it will be of any advantage unless it helps letting the chip sleep more. The synchronous scan function just waits on a semaphore until the scan handler thread signals completion. If I can send the chip into light-sleep during the scan and still get proper results, that would certainly help, though.

Schematic of the companion board attached.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on January 25, 2022, 05:51:04 pm
PCB done.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on January 27, 2022, 03:48:47 pm
I've researched on the topic of BLE power-saving strategy and it seems to be possible to drop down the current consumption to less than 10mA when configuring the power management to go into light sleep automatically. But only if there is an external 32kHz crystal available for the SoC to use for timekeeping during sleep, as the main oscillator is switched off then.

This means I will definitely have to make my own PCB with either a module or bare ESP32 SoC as the DevKit does not have a 32kHz crystal that could be used, and also the Arduino library is not compiled with the correct options.

Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on February 13, 2022, 09:22:35 am
I managed to get the first prototype board made, the PCBs have arrived meanwhile. Not yet fired them up but I already found I had a wrong resistor placed in the feedback path for the BQ25015. Also, as it turns out there's an error in the reference design I copied the BQ25015 circuit from, which would violate some abs-max constraint for its enable pin, but that will not be a problem for the initial testing. As soon as I replace the wrong resistor I can fire the thing up and then do some field testing.

Meanwhile I completed the schematic and PCB for the "final" device. As soon as I've validated the prototype, I will have a couple of them manufactured and can go for optimizing the power consumption.

Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on March 05, 2022, 04:40:20 pm
Finally got around to replacing the wrong resistor and connected a battery and power supply to see if the DC/DC converter and the charge circuit work: both seem to be OK.

In other news, I gave in to a year-long craving and bought a 3D printer. Now dabbling in constructing a case for the thing so that it can be carried on a belt or something. FreeCAD is a whiny b*tch.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on March 05, 2022, 05:49:37 pm
Here's the case.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on March 30, 2022, 08:30:19 pm
Just a quick update on the progress: I've meanwhile tested all the functional units of the circuit, charger, DC/DC converter, piezo buzzer driver, went through at least 3 iterations of the enclosure design as I learned about sketches, constraints and parameters in FreeCAD.

Wasted a lot of PLA printing the parts, too (3D printers sure are fun!).

Next step: launch final PCBs and have as many components assembled by JLCPCB as are in stock. Unfortunately, the BQ25015 doesn't seem to be available at LCSC and so they will not be able to place that part. Unfortunate, but not a deal breaker.

I keep you posted.
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on April 12, 2022, 04:21:45 pm
So, yesterday something unexpected happened, and today something even less expected happened.

When JLCPCB finished the boards and DHL Express picked it up, they gave an expected delivery date some time next week. I wouldn't be at home then so i scheduled a delivery for the week after. Now, yesterday I checked on the delivery status (as you do), and the said the shipment was already in the local distribution center and would stay there until the scheduled delivery was up.

Naturally (as you do) I rescheduled the delivery for today and indeed a couple hours ago it showed up at my door.

So, I transplanted a BQ25015 from a spare out of the previous prototype run, connected a battery, hooked it up my laptop, fired up the Arduino IDE and lo and behold, was able to program the sketch and it worked right out of the box. Even the sketchy CP2102 I glued on last minute to make development and future firmware updates easier worked. No magic smoke, nothing.

I'm literally shaking of joy. Or, it's that third cup of coffee I had for lunch today.  :scared:
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: thinkfat on April 13, 2022, 10:05:27 pm
Alright, time for a quick update:

I switched from the Arduino IDE to Eclipse and the Espressif plugin for ESP32 and after a bit of tinkering I was able to put together a test program that uses power management, tickless idle and modem sleep while advertising a BLE beacon. It wasn't working initially, but I guessed that the 32khz crystal was probably off frequency, and indeed, after removing the two load capacitors, I can now receive the BLE beacons on my Android phone.

Next step will be to get the scanning going and then it will be time to optimize power consumption and write the actual software.
Title: [DONE] "Distance Alert", looking for inspiration for project.
Post by: thinkfat on July 10, 2022, 12:43:03 pm
I feel I should give closure to this project. It is mostly complete, the hardware is done, the software is mostly functional for the intended purpose, the only thing left is fine tuning of parameters and trying to make it as convenient as possible.

I've attached some photos of the final hardware. The case is 3D printed out of blue PETG, I think it turned out well.

The PCB is 55mm by 36,6mm, the size is mainly dominated by the battery, which is a 40x30x4 mm LiPo pouch cell with 500mAh capacity. The PCB itself could by way smaller still. But I don't want to spend time on it, unless I decide to make more of them to sell: initial feedback from other parents of kids with the same genetic condition were positive.

I was able to characterize the power consumption and it mostly depends on how long the ESP32 can spend in "light sleep", and that in turn depends on the advertisement and scan intervals.

An interesting complication was, and still is, the 32kHz sleep clock. I can't seem to get it quite right. I computed the load capacitors to be around 15pF, based on the xtal datasheet, but when I place them, the oscillation becomes unstable. It's also a couple Hz off. I had best results with two 5.8pF capacitors, or none at all, but on one board the oscillator frequently wouldn't start at all of I don't place the caps. So, something's marginal here and that doesn't instill full confidence. Unfortunately, unlike for the STM32, there is no detailed design procedure for the oscillators and no part recommendations. The reference manual only states to choose the load capacitors to be compliant with the crystal datasheet. Well, that's what I did and it didn't work.

The first "field tests" were successful, though. Another topic I might pick up is writing an Android app so that one of the devices could be replaced by a smartphone.

Thanks to all who tagged along, cheerio for now.

Title: Re: "Distance Alert", looking for inspiration for project.
Post by: RoGeorge on July 10, 2022, 04:49:17 pm
Congratz!  :-+
Title: Re: "Distance Alert", looking for inspiration for project.
Post by: mag_therm on July 10, 2022, 06:58:45 pm
Congratulations on the project.
My son with DS is now 18, and when younger, crowds alleyways museums  etc were a significant challenge.
I tried a commercial version of what you have built which also had a crude direction indicator,
but it was too troublesome ( not really fit for purpose )  and I only used it about 2 times.

Now he has a an ordinary cell device and uses sms  email , and the video phone.

When I looked a cell phone location apps a few years ago the main item was the costly subscription.
Not sure if same now.