How can I measure the bluetooth connection force with ESP32? I'm using the available example of BLE to detect the possibility of connection, but I need to measure its strength. Thank you.
I'm using:
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
int scanTime = 30; //In seconds
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
}
};
void setup() {
Serial.begin(115200);
Serial.println("Scanning...");
BLEDevice::init("");
BLEScan* pBLEScan = BLEDevice::getScan(); //create new scan
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
BLEScanResults foundDevices = pBLEScan->start(scanTime);
Serial.print("Devices found: ");
Serial.println(foundDevices.getCount());
Serial.println("Scan done!");
}
void loop() {
// put your main code here, to run repeatedly:
delay(2000);
}`
Just a few lines added to your MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks :
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str
int rssi = advertisedDevice.getRSSI();
Serial.print("Rssi: ");
Serial.println(rssi);
}
};
in wifi i am using this function:
// Take a number of measurements of the WiFi strength and return the average result.
int getStrength(int points){
long rssi = 0;
long averageRSSI=0;
for (int i=0;i < points;i++){
rssi += WiFi.RSSI(); // put your BLE function here
delay(20);
}
averageRSSI=rssi/points;
return averageRSSI;
}
and you have the same function for BLE than WiFi.RSSI(): (see in github source code)
int BLEAdvertisedDevice::getRSSI() {
return m_rssi;
} // getRSSI
Related
I am using the below code to get the RSSI value. I am able to get the value successfully for one Device at a time. But I am confused about how to get the RSSI value for multiple devices while scanning by ESP32.
The below code snippet I am using.
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
int scanTime = 10; //In seconds
BLEScan* pBLEScan;
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
Serial.print(" RSSI: ");
Serial.println(advertisedDevice.getRSSI());
}
};
void setup() {
Serial.begin(115200);
Serial.println("Scanning...");
BLEDevice::init("");
pBLEScan = BLEDevice::getScan(); //create new scan
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
pBLEScan->setInterval(100);
pBLEScan->setWindow(99); // less or equal setInterval value
}
void loop() {
// put your main code here, to run repeatedly:
BLEScanResults foundDevices = pBLEScan->start(scanTime, true);
Serial.print("Devices found: ");
Serial.println(foundDevices.getCount());
// you can access first device with foundDevices.getDevice(0).getAddress()
Serial.println("Scan done!");
pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory
delay(2000);
}
Can anyone advice how Do I get the multiple RSSI value while scanning devices
I'm trying make an mqtt co2 sensor for home assistant. And I got it to work, but only for a couple of hours. At some point it starts giving me -1 values instead of the proper co2 value. What could this be?
Below my code:
#include <Arduino.h>
#include <Mhz19.h>
#include <SoftwareSerial.h>
SoftwareSerial softwareSerial(D3, D4);
Mhz19 sensor;
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "ID";
const char* password = "pw";
const char* MQTT_BROKER = "192.168.1.25";//"test.mosquitto.org";
int mqttPort = 1883;
const char* mqttUser ="mqtt-user";
const char* mqttPassword ="pw";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(100);
// Connect to Wi-Fi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("Connected to Wi-Fi");
}
void reconnect() {
// Loop until connected
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("Test1", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT");
} else {
Serial.print("Failed MQTT connection with state: ");
Serial.println(client.state());
// Re-try in 3 seconds
delay(3000);
}
}
// Once connected, publish an announcement, and subscribe
client.publish("sensor/test", "Hello from ...");
client.subscribe("sensor/test");
}
void setup() {
Serial.begin(115200);
setup_wifi(); // Connect to Wi-Fi network
client.setServer(MQTT_BROKER, mqttPort);
//client.setCallback(callback);
reconnect(); // Connect to MQTT broker
softwareSerial.begin(9600);
sensor.begin(&softwareSerial);
sensor.setMeasuringRange(Mhz19MeasuringRange::Ppm_5000);
sensor.enableAutoBaseCalibration();
Serial.println("Preheating..."); // Preheating, 3 minutes
while (!sensor.isReady()) {
delay(50);
}
Serial.println("Sensor Ready...");
}
void loop() {
if (!client.connected()) { reconnect(); }
//client.publish("Time", ctime(&now));
auto carbonDioxide = sensor.getCarbonDioxide();
if (carbonDioxide >= 0) {
Serial.println(String(carbonDioxide) + " ppm");
}
char co2String[8];
dtostrf(carbonDioxide, 1,0, co2String);
//Serial.println(co2String);
client.publish("Floating/climate/CO2", co2String);
delay(2000);
}
I also tried flashing it via ESPHome, but then I run into issues from UART. The chip doesn't work propperly as long as the sensor is connected to it.
The sensor may not be receiving enough current. Try connecting the sensor directly to a separate breadboard power supply. The sensor seems to have a warm up time. Try waiting for longer with the independent power supply connected. I hope this will solve your issue.
Thank You,
Naveen PS
I want to use timer interrupter combined with BLE to transmit in esp32.
I found that an error occurs when the transmission cycle is too fast.
I don't know what caused this error.
Help me plz.............................................................................................
The error
This is my code
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
////////////////////////////////////////////////////////////
#include <BLE2902.h>
#define PERIOD_MS 5
#define BAUD_RATE 115200
#define BLE_WR_EN 0x5A
#define BLE_WR_DIS 0x55
#define SERVICE_UUID "0000ffe0-0000-1000-8000-00805f9b34fb"
#define CHARACTERISTIC_UUID_RX "0000ffe2-0000-1000-8000-00805f9b34fb"
#define CHARACTERISTIC_UUID_TX "0000ffe1-0000-1000-8000-00805f9b34fb"
int PERIOD_US=PERIOD_MS*1000;
/* create a hardware timer */
hw_timer_t * timer = NULL;
/* LED pin */
int led = 2;
/* LED state */
volatile byte state = LOW;
int i=0;
BLEServer *pServer;
BLEService *pService;
BLECharacteristic *pCharacteristic;
void IRAM_ATTR onTimer(){
//state = !state;
if(i<700){
i++;
}
else{
i=0;
}
//Serial.println(state);
char txString[8];
dtostrf(i, 1, 2, txString);
pCharacteristic->setValue(txString);
pCharacteristic->notify();
std::string txValue=pCharacteristic->getValue();
Serial.print("txValue:");
Serial.println(txValue.c_str());
//digitalWrite(led, state);
}
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
Serial.println("********************************");
Serial.println("Connected");
Serial.println("********************************");
timerAlarmEnable(timer);
};
void onDisconnect(BLEServer* pServer) {
Serial.println("********************************");
Serial.println("Disconnected");
Serial.println("********************************");
timerAlarmDisable(timer);
//delay(1000);
///*
// Start the service
//pService->start();
// Start advertising
//pServer->getAdvertising()->start();
pServer->startAdvertising();
//*/
//ESP.restart();
}
};
class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string rxValue = pCharacteristic->getValue();
std::string EN="Z";
std::string DIS="U";
Serial.print("rxValue:");
Serial.println(rxValue.c_str());
/*
//Serial.println(getvalue);
if (rxValue==EN ) {
//g_Timer.enable(g_TimerId);
timerAlarmEnable(timer);
digitalWrite(LED, HIGH);
}
else if (rxValue==DIS) {
//g_Timer.disable(g_TimerId);
timerAlarmDisable(timer);
//data_count = 0;
digitalWrite(LED, LOW);
}
*/
}
};
void setup() {
Serial.begin(115200);
Serial.begin(BAUD_RATE);
////////////////////////////////////////
Serial.println("Starting BLE Server!");
BLEDevice::init("ESP32-INTERRUT-Server");
/////////////////////////////////////////////////////////////////////////////////////
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create the BLE Service
BLEService *pService = pServer->createService(SERVICE_UUID);
// Create a BLE Characteristic
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_TX,
BLECharacteristic::PROPERTY_READ|
BLECharacteristic::PROPERTY_NOTIFY
);
pCharacteristic->addDescriptor(new BLE2902());
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_RX,
BLECharacteristic::PROPERTY_WRITE
);
pCharacteristic->setCallbacks(new MyCallbacks());
// Start the service
pService->start();
// Start advertising
pServer->getAdvertising()->start();
////////////////////////////////////////////////////////////////////
timer = timerBegin(0, 80, true);
timerAttachInterrupt(timer, &onTimer, true);
timerAlarmWrite(timer, PERIOD_US, true);
timerAlarmDisable(timer);
}
void loop() {
}
I am doing a project where I need to send data from ultrasonic sensor wirelessly present in one arduino to other arduino where I need these values in Serial monitor. But the problem is I cannot able to send these values through bluetooth. I tried to send one character, it is appearing in serial monitor.. But when I tried to the same for integer values it is not appearing in serial monitor.
I have configured Master and Slave modes for the Bluetooth. I have uploaded the image of the code which I am using to send these values. Please help me on this. Thanks in advance .
code
//# transmitting end
#define trigPin 12
#define echoPin 11
void setup() {
Serial.begin(38400); // Default communication rate of the Bluetooth module
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration;
float distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
Serial.println(distance,2); // Sends floatValue
delay(500);
}
//# receving end
#include <SoftwareSerial.h>
#define led 13
SoftwareSerial BTSerial(10, 11);
int data=0;
void setup() {
pinMode(led,OUTPUT);
Serial.begin(38400);
BTSerial.begin(38400); // Default communication rate of the Bluetooth module
}
void loop() {
int number;
if(Serial.available() > 0){ // Checks data is from the serial port
data = BTSerial.read(); // Reads the data from the serial port
//analogWrite(led,data);
delay(10);
//Serial.println(data);
}
Serial.println(data);
}
I need integer values at the serial monitor. But there I am getting some symbols like ?/<>..
From the Arduino reference, Serial.read() only reads the first available byte available in the Serial buffer. As an int is coded on 8 bytes, I would say that you need to read the incoming bytes sequentially in order to get the full value.
Maybe you can implement this by putting (Serial.available() > 0) in a while loop, concatenate the values you get in a char[8] for instance and then convert this char to a integer value.
Also, beware that you are sending floats and not int.
Thanks for the help..!
I modified the code in the receiver end to get the float values from the transmitter.. Here is my modified code
#include <SoftwareSerial.h>
int bluetoothTx = 10;
int bluetoothRx = 11;
String content; //content buffer to concatenate characters
char character; //To store single character
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup(){
bluetooth.begin(38400);
Serial.begin(9600);
}
void loop(){
bluetooth();
}
void bluetooth(){ //
while(bluetooth.available()){
character = bluetooth.read();
content.concat(character);
if(character == '\r'){ // find if there is carriage return
Serial.print(content); //display content (Use baud rate 9600)
content = ""; //clear buffer
Serial.println();
}
}
}
I Am working with arduino mega 2560....
Here I want to toggle two led simultaneously using threading.....
but there is problem that it is running one by one...
here is the code...
it would b your pleasure...
#include <SPI.h>
#include <Thread.h>
#include <ThreadController.h>
Thread Led1=Thread();
Thread Led2=Thread();
ThreadController controll=ThreadController();
void Led1run()
{
Serial.println("Led1");
Led2.run();
for(int i=0;i<5;i++)
{
digitalWrite(13,HIGH);
delay(1000);
digitalWrite(13,LOW);
delay(1000);
}
}
void Led2run()
{
Serial.println("Led2");
for(int i=0;i<5;i++)
{
digitalWrite(53,HIGH);
delay(1000);
digitalWrite(53,LOW);
delay(1000);
}
}
void setup()
{
Serial.begin(9600);
Led1.onRun(Led1run);
Led2.onRun(Led2run);
controll.add(&Led1);
pinMode(13,OUTPUT);
pinMode(53,OUTPUT);
}
void loop()
{
if(Serial.available())
{
Serial.println("loop");
Led1.run();
}
}