Serial interrupt

Hello
Is there a way to set interrupt for serial rx pin on esp8266?
This is a function in my code that sends data to the sensor and gets the response back.
I want to send the data in my main loop and continue doing the rest of the code and when the response is received from the serial and rx pin, I interrupt the code to read the response.

why i want to do this ?? because the response time of my sensor is 1 second and i want to remove this 1 second gap

const byte ph[] = { 0x02, 0x03, 0x00, 0x06, 0x00, 0x01, 0x64, 0x38 };  //NPK
byte ph_values[8];



void multi_sensor_ph_detect() {

  uint32_t startTime;
  uint8_t i;
  uint32_t checkserial;

  // flush the receive buffer
  checkserial = millis();
  while (millis() - checkserial <= 100UL) {
    while (mod.available()) mod.read();
  }


  mod.write(ph, sizeof(ph));
  mod.flush();


  i = 0;
  startTime = millis();
  // wait for up to 500ms for a response
  while (millis() - startTime <= 1000UL) {

    if (mod.available() && i < sizeof(ph_values)) {
      ph_values[i++] = mod.read();
      //      if(i>2&&i<5){
      float ph_reg3and4 = ((ph_values[3] << 8) + ph_values[4]);
      ph_reg3and4 = ph_reg3and4 / 100;
      pubPH = ph_reg3and4;
      //Serial.println("PH : "+(String)ph_reg3and4+"");
      if (ph_reg3and4 >= 0) {
        NPKPublish = 1;
        PHtrigger = 1;
        PHtriggerPUB = 1;
        OtherParameterignore = 0;
        Serial.println("PH : " + (String)ph_reg3and4 + "");
      }
    }
  }
  int ph;
  ph = (int)(pubPH * 10L);
  if (phcomp != ph) {
    phcomp = ph;
    client.publish(toCharArray("/angizeh/" + SerialNumber + "/02/PH"), toCharArray(String(pubPH)));
    Serial.println("Published");
    oneWillPH = true;
  }
  if (PHtrigger != 1) {
    OtherParameterignore = 1;
    NPKPublish = 0;
    Serial.println("check NPK sensor");
    if (oneWillPH == true) {
      client.publish(toCharArray("/angizeh/" + SerialNumber + "/02/Will"), toCharArray("Check Sensor"));
      PHtriggerPUB = 0;
      oneWillPH = false;
    }
  }
  PHtrigger = 0;
}

For the pin itself not. In fact while the pin is used as the RX (or TX) pin of the UART it does not function as a normal GPIO pin.

You can simply poll for characters in the rx-buffer on a regular basis, say at the end of loop() or where ever is appropriate in your code.

The serial data is already interrupt driven and buffered. Instead of checking Serial available is greater than 0, check that it is as large as the package and don't read until it is.

1 Like

thanks guys for helping. i will check the size of data for comparison.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.