First of all, please know that i have no idea about coding.
Device <-Serial-> ESP32c3+HM-10 <-BLE-> Smartphone App
I want to control the device with the above configuration and it was successful.
Below is the code.
#include <HardwareSerial.h>
HardwareSerial MySerial0(0);
HardwareSerial MySerial1(1);
void setup() {
MySerial0.begin(38400, SERIAL_8N1, -1, -1);
MySerial1.begin(38400, SERIAL_8N1, 9, 10);
}
void loop() {
if(MySerial0.available()){
MySerial1.write(MySerial0.read());
}
if(MySerial1.available()){
MySerial0.write(MySerial1.read());
}
}
I want to configure using ESP32c3 own BLE instead of ESP32c3+HM-10 to reduce the size, but I don’t know how.
Like HM-10, smartphone apps are built based on TI’s chips and send and receive Rx and Tx with one Characteristic UUID.
However, the BLE example of ESP32c3 uses two Rx, Tx Characteristic UUID to send and receive, can I use only one like HM-10?
Below is the code I made when I exchanged conversations with ChatGPT.
The code worked very well when we exchanged texts like putty and hyperterminal.
However, controlling the device failed.
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include <HardwareSerial.h>
HardwareSerial MySerial1(1);
BLECharacteristic *pCharacteristic;
bool deviceConnected = false;
uint8_t txValue = 0;
#define SERVICE_UUID "0000ffe0-0000-1000-8000-00805f9b34fb"
#define CHARACTERISTIC_UUID "0000ffe1-0000-1000-8000-00805f9b34fb"
#define MAX_CHUNK_SIZE 20
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
class MyCharacteristicCallback : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string value = pCharacteristic->getValue();
if (value.length() > 0) {
for (int i = 0; i < value.length(); i++) {
MySerial1.write(value[i]);
}
}
}
};
void setup() {
Serial.begin(115200);
MySerial1.begin(115200, SERIAL_8N1, 9, 10);
BLEDevice::init("BLEtool");
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService *pService = pServer->createService(SERVICE_UUID);
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY
);
pCharacteristic->setCallbacks(new MyCharacteristicCallback());
pCharacteristic->addDescriptor(new BLE2902());
pCharacteristic->setValue("Hello World");
pService->start();
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->start();
}
void loop() {
if (deviceConnected) {
uint8_t dataBuffer[MAX_CHUNK_SIZE];
size_t dataSize = 0;
while (MySerial1.available() && dataSize < MAX_CHUNK_SIZE) {
dataBuffer[dataSize++] = MySerial1.read();
}
if (dataSize > 0) {
pCharacteristic->setValue(dataBuffer, dataSize);
pCharacteristic->notify();
}
}
}