Go Down

Topic: Trouble in Serial.write() while using bluetooth  (Read 171 times) previous topic - next topic

ks1ksi

Hello, I apologize that my English may be a little poor before the question!
I'm using Arduino Nano 33 BLE Sense for my project.
In my project, I use two Nano 33 BLE.
One of them is "Peripheral", and sends a number of 1,2,3 integers.
The other one is "Central", and here's my problem.

My "Central" has to receive a number from "Peripheral", and send it to my game (with Unity, C#)
I know that it can be done by "Serial.write(number)", but it doesn't work. 
When I use Serial.write() without using bluetooth, it works perfectly fine.
And if I use only bluetooth without using Serial.write(), it receives number from "Peripheral" perfectly.
Problem just occurs when I use them together.

I tried many things. I tried using Serial1 (not Serial), but it doesn't work either.
Uploading the code by partially deleting it, I found that the problem occurs when I put "Serial.write()" and bluetooth related func (like"peripheral.connected()" or "gestCharacteristic.valueUpdated()" in my code) in loop together.
But for my project, I have to put it together in loop.
I desperately need help.


Code: [Select]
#include <ArduinoBLE.h>

void setup() {
  Serial.begin(9600);
  BLE.begin();
}

void loop() {
  BLEDevice peripheral;
  BLE.scanForUuid("19B10000-E8F2-537E-4F6C-D104768A1214");
  peripheral = BLE.available();
  
  if (peripheral){
    Serial.println(peripheral.localName());
    Serial.println(peripheral.address());
    Serial.println(peripheral.advertisedServiceUuid());
    BLE.stopScan();
    
    getData(peripheral);
  }
  
}

void getData(BLEDevice peripheral){
  peripheral.connect();
  peripheral.discoverAttributes();
  BLECharacteristic gestCharacteristic = peripheral.characteristic("19B10000-E8F2-537E-4F6C-D104768A1214"); 
  gestCharacteristic.subscribe();
  while (peripheral.connected()){
    if (gestCharacteristic.valueUpdated()){
      byte gest;
      gestCharacteristic.readValue(gest);
      Serial.println(gest); //for Debug
      
      Serial.write(gest); //Problem occcur!
      Serial.flush();
      delay(20);
    }
  }
}



Klaus_K

Welcome to the forum

Did you try without the delay()? Delay will use sleep on the Arduino Nano 33 BLE. Maybe this interferes with Serial. Just a guess.

Serial.flush() does not work on the Arduino Nano 33 BLE. It is an empty function.

ks1ksi

Thanks for reply!
I don't know why, but when I woke up the problem was solved :)
Maybe Serial port was too busy last night(?)

Go Up