Hello, I have a problem with a program written in arduinio using seeed xiao board nrf52840, HC-SR04 distance sensor.
The board is supposed to connect to the phone via the built-in bluetooth module.
I wrote the program using the arduinoble.h library, based on the
examples from this library. When the program is simple and is supposed to turn off
or turn on the LED after receiving data sent from the application there is no
problem. The same with the control of a servo motor powered by a separate
inverter.
The problem arises when trying to read the distance using the aforementioned
aforementioned sensor. In this case, when trying to connect, it pops up a
information about the time lapse being too long. The sensor at that time works and
shows the correct distance and sends it to the serial monitor.
Does anyone know why I can't make the connection, or how to modify the program so I can connect to the board.
I am attaching my program below.
#include <ArduinoBLE.h>
#define trigPin 0
#define echoPin 1
#define SOUND_SPEED 34300 // cm/s
#define TIME_TO_DIST 0.5 * SOUND_SPEED // cm/us
BLEService sensor("23a157c2-14f7-4e5f-88cd-bc39298c1579");
BLEIntCharacteristic move("23a157c3-14f7-4e5f-88cd-bc39298c1579", BLERead | BLEWrite);
long distance;
void setup() {
Serial.begin(115200);
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1)
;
}
pinMode(LEDB, OUTPUT);
digitalWrite(LEDB, HIGH);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
BLE.setLocalName("sensor");
BLE.setAdvertisedService(sensor);
sensor.addCharacteristic(move);
BLE.addService(sensor);
move.writeValue(0);
BLE.advertise();
Serial.println("starting Bluetooth®");
}
delayMicroseconds
void loop() {
BLEDevice central = BLE.central();
if (central) {
digitalWrite(LEDB, LOW);
Serial.print("Connected to central: ");
Serial.println(central.address());
if (central.connected()) {
while (central.connected()) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
distance = duration * TIME_TO_DIST;
delay(1);
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(1);
}
}
Serial.print("Disconnected from central: ");
Serial.println(central.address());
digitalWrite(LEDB, HIGH);
}
}