How to code for automatically execute an AT command on HM-10?

Hi, I am doing some sketching on HM-10, and I want it to automatically run the AT+DISC? command.
My code is as follow

#include <SoftwareSerial.h>

SoftwareSerial ble(7, 8 );

void setup() {
Serial.begin(9600);
ble.begin(9600);
if (ble.isListening()) {
Serial.println(“ble is listening!”); }
}

void loop() {
int a=1;
while (a=1){
ble.write(“AT+DISC?”);
char b= ble.read();
Serial.print(b);
delay(500);
}
}

it can only search for one beacon successfully,
and error happens after that. (see the attachment)
anyone have some ideas on it? thanks

Some suggestions. Let loop() do what it does best. Ditch the a = 1. and the while loop which is wrong anyway. Next only read a byte when one is available.

htyeung:
anyone have some ideas on it? thanks

I’d separate the sending of the discovery command with the parsing of the response… because you are going to want to look for other responses as well.

Try like this:

#include <SoftwareSerial.h>

const uint16_t MAX_MESSAGE_LENGTH = 64;
SoftwareSerial BLE(7, 8 );

void setup() 
{
  Serial.begin(9600);
  BLE.begin(9600);
  
  if (BLE.isListening()) 
  {
    Serial.println("BLE is listening!");
  }
}

void loop() 
{
  uint32_t lastUpdateMillis = 0;
  const uint16_t interval = 500;
  if(millis() - lastUpdateMillis > interval) // send the AT request each interval
  {
    lastUpdateMillis = millis();
    BLE.write("AT+DISC?");
  }
  
  if (const char* newMessg = checkForNewMessage(BLE, '\n')) // constantly look for responses
  {
    Serial.println(newMessg);
  }
}

const char* checkForNewMessage(Stream& stream, const char endMarker)
{
  static char incomingMessage[MAX_MESSAGE_LENGTH] = "";
  static byte idx = 0;
  if(stream.available())
  {
    incomingMessage[idx] = stream.read();
    if(incomingMessage[idx] == endMarker)
    {
      incomingMessage[idx] = '\0';
      idx = 0;
      return incomingMessage;
    }
    else
    {
      idx++;
      if(idx > MAX_MESSAGE_LENGTH - 1)
      {
        //stream.print(F("{\"error\":\"message too long\"}\n"));  //you can send an error to sender here
        idx = 0;
        incomingMessage[idx] = '\0';
      }
    }
  }
  return nullptr;
}