Hi everyone,
I am working on making a proximity detection system that allows the user to choose the detection range using 2 or more push buttons.
Here's an example of how the program should work:
When I press button1 the code enters a loop and starts running a function that detects a range of 1m, and then when I press button2 it should break the first loop and enters a new one where a new function detects at a range of 2m...
The problem is that I want to use the push buttons as toggle switches because the user won't be able to keep holding the button forever.
I tried many things but the closest I could get was getting the first button to work as a toggle switch but without breaking the while loop meaning if press the button again or press a different button nothing happens.
Another problem is that button2 never works even if I just switch the variables and I checked if it was a circuit problem but it was not the case, it works fine with other codes.
I am using 2 esp32 to detect each other using BLE.
P.S: Sorry if the code might be a mess because I was trying many things and didn't bother to change some variables or names.
#include <BLEAdvertisedDevice.h>
#include <BLEDevice.h>
#include <BLEScan.h>
#include <Ewma.h>
const int PIN = 19;
const int switch1_PIN = 2;
const int switch2_PIN = 21;
const int CUTOFF = -69;
int state = 0;
int button1New, button2New;
int button1Old, button2Old = 1;
int dt = 500;
Ewma filtreSignal(0.8);
void proximity1(){
BLEScan *scan = BLEDevice::getScan();
scan->setActiveScan(true);
BLEScanResults resultats = scan->start(1);
int best = -100;
for (int i = 0; i < resultats.getCount(); i++) {
BLEAdvertisedDevice device = resultats.getDevice(i);
int rssi = device.getRSSI();
if (rssi > best) {
best = rssi;
}
}
float filtered = filtreSignal.filter(best);
Serial.println(filtered);
digitalWrite(PIN, filtered > -69 ? HIGH:LOW);
}
void proximity2(){
BLEScan *scan = BLEDevice::getScan();
scan->setActiveScan(true);
BLEScanResults resultats = scan->start(1);
int best = -100;
for (int i = 0; i < resultats.getCount(); i++) {
BLEAdvertisedDevice device = resultats.getDevice(i);
int rssi = device.getRSSI();
if (rssi > best) {
best = rssi;
}
}
float filtered = filtreSignal.filter(best);
Serial.println(filtered);
digitalWrite(PIN, filtered > -75 ? HIGH:LOW);
}
void setup() {
Serial.begin(115200);
pinMode(PIN, OUTPUT);
pinMode(switch1_PIN, INPUT);
pinMode(switch2_PIN, INPUT);
BLEDevice::init("");
BLEAdvertising *adv = BLEDevice::getAdvertising();
adv->setScanResponse(true);
BLEDevice::startAdvertising();
}
void loop() {
button1New = digitalRead(switch1_PIN);
button2New = digitalRead(switch2_PIN);
while (button1New == 1 && button1Old == 0){
proximity1();
}
while (button2New == 1 && button2Old == 0){
proximity2();
}
}