I can enter if but not execute statements inside

I am using an arduino mega 2560 and when sending string through the uart

String respuesta="";
  while (Serial2.available() > 0) {
    char receivedChar = Serial2.read();
    if (receivedChar == '\n') {
      Serial.println(respuesta);
      delay(1000); // Print the received message in the Serial monitor
      respuesta= ""; // Reset the received message
    } else {
      respuesta+= receivedChar; // Append characters to the received message
    }
  }

The rest of the code down below dies.

if (respuesta == "/sube_persiana") {

    //persiana
    knx.groupWriteBool("2/0/0", 0);
  }

  if (respuesta == "/baja_persiana") {

    //persiana
    knx.groupWriteBool("2/0/0", 1);
  }

  if (respuesta == "/enciende_luz_dormitorio") {
    //dormitorio
    Serial.println(respuesta);
    bool xd = true;
    knx.groupWriteBool("1/0/1", xd);
  }

  if (respuesta == "/apaga_luz_dormitorio") {
    //dormitorio
    Serial.println(respuesta);

    knx.groupWriteBool("1/0/1", 0);
  }

  if (respuesta == "/enciende_luz_salon") {

    //salon
    knx.groupWriteBool("1/0/0", 1);
  }

  if (respuesta == "/apaga_luz_salon") {

    //salon
    knx.groupWriteBool("1/0/0", 0);
  }

I can enter if and check it with Serial.println which passes but does not execute statements.

On the other hand, if I send bytes using read and write, the program does not do that.

Any ideas? Thanks!

Welcome to the forum

You started a topic in the Uncategorised category of the forum

Your topic has been moved to a relevant category. Please be careful in future when deciding where to start new topics

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum

Please post your full sketch, using code tags when you do

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"
#include <Keypad.h>
#include <KnxTpUart.h>
#include <stdio.h>
#include <stdlib.h>
#include "DHT.h"
#if defined(ARDUINO) && ARDUINO >= 100
#define printByte(args) write(args);
#else
#define printByte(args) print(args, BYTE);
#endif

int estado_luz_salon = 0;
int estado_luz_dormitorio = 0;
//Variables KNX
KnxTpUart knx(&Serial1, "1.1.30");
//Variables RTC
uint8_t clock[8] = { 0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0 };
RTC_DS3231 RTC;
//Variables LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
String diasSemana[7] = { "DOM", "LUN", "MART", "MIER", "JUEV", "VIER",
                         "SAB" };
//Variables Teclado Matricial
const byte filas = 4;
const byte columnas = 4;
const byte pinesColumnas[filas] = { 5, 4, 3, 2 };
const byte pinesFilas[columnas] = { 9, 8, 7, 6 };
char formatoTeclado[filas][columnas] = {
  { '1', '2', '3', 'A' },
  { '4', '5', '6', 'B' },
  { '7', '8', '9', 'C' },
  { '*', '0', '#', 'D' }
};
Keypad teclado = Keypad(makeKeymap(formatoTeclado),
                        (byte*)pinesFilas, (byte*)pinesColumnas, filas, columnas);
//Variables Zumbador
const int zumbador = 10;
//Variables PIR
#define pinSensor 11
//Variables DHT11
const int pinDTH = 12;
DHT dht(pinDTH, DHT11);

//Variables globales
int movimiento = 0;
int intentos = 0;
int repeticionesPantalla = 0;
bool alarmaSalirActivada = false;
bool alarmaDespertarActivada = false;
void setup() {

  Serial.begin(19200);        // Inicia Serial
  pinMode(zumbador, OUTPUT);  //Establece el pin 10 de salida al que

  Wire.begin();  //Inicializa la biblioteca Wire para permitir la

  //Inicializacion del RTC
  if (!RTC.begin()) {
    while (1)
      ;
  }
  // Si se ha perdido la corriente, fijar fecha y hora de compilacion
  if (RTC.lostPower()) {
    RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  // Inicializa la pantalla LCD y luz de fondo
  lcd.init();
  lcd.backlight();

  //Inicia el sensor DHT
  dht.begin();
  //Inicia KNX
  Serial1.begin(19200, SERIAL_8E1);
  Serial2.begin(19200);

  knx.uartReset();
  //Escena Me voy
  knx.addListenGroupAddress("0/1/1");
  //Escena Dormir
  knx.addListenGroupAddress("0/1/2");
  Serial.println("Added listen group adress ");

  delay(1000);

  knx.groupRead("0/1/1");
  knx.groupRead("0/1/2");
  Serial.println("Read group address ");
}
//Se recorre de manera repetitiva y a la velocidad del procesador
void loop() {


  if (repeticionesPantalla != 5) {
    pantallaLCD();
  } else {
    pantallaTempHumedad();
  }

  //Código para la puesta de la alarma despertar
  while (alarmaDespertarActivada) {
    if (preguntarEstablecerDespertador()) {
      String hora = insertarHoraDespertar();
      esperarDespertador(hora);
    }
    alarmaDespertarActivada = false;
  }

  //Código para la puesta de la alarma al irnos de casa
  while (alarmaSalirActivada) {
    activarBuzzerPonerAlarma();

    while (movimiento == LOW) {
      pantallaLCD();
      lecturaPIR();
    }
    LCDMovimientoDetectado();
    movimiento = LOW;
  }

  String respuesta="";
  while (Serial2.available() > 0) {
    char receivedChar = Serial2.read();
    if (receivedChar == '\n') {
      Serial.println(respuesta);
      delay(1000);     // Print the received message in the Serial monitor
      respuesta = "";  // Reset the received message
    } else {
      respuesta += receivedChar;  // Append characters to the received message
    }
  }


  if (respuesta == "/sube_persiana") {

    //persiana
    knx.groupWriteBool("2/0/0", 0);
  }

  if (respuesta == "/baja_persiana") {

    //persiana
    knx.groupWriteBool("2/0/0", 1);
  }

  if (respuesta == "/enciende_luz_dormitorio") {
    //dormitorio
    Serial.println(respuesta);
    bool xd = true;
    knx.groupWriteBool("1/0/1", xd);
  }

  if (respuesta == "/apaga_luz_dormitorio") {
    //dormitorio
    Serial.println(respuesta);

    knx.groupWriteBool("1/0/1", 0);
  }

  if (respuesta == "/enciende_luz_salon") {

    //salon
    knx.groupWriteBool("1/0/0", 1);
  }

  if (respuesta == "/apaga_luz_salon") {

    //salon
    knx.groupWriteBool("1/0/0", 0);
  }
}

void serialEvent1() {
  KnxTpUartSerialEventType tipoEvento = knx.serialEvent();
  Serial.println("knx.serialEvent()");

  if (tipoEvento == KNX_TELEGRAM) {


    KnxTelegram* telegram = knx.getReceivedTelegram();
    KnxCommandType tipoComando = telegram->getCommand();

    if (tipoComando == KNX_COMMAND_WRITE) {

      Serial.println("Received KNX_COMMAND_WRITE");

      String grupoOrigen =
        String(0 + telegram->getTargetMainGroup()) + "/" + String(0 + telegram->getTargetMiddleGroup()) + "/" + String(0 + telegram->getTargetSubGroup());

      Serial.println("GrupoOrigen :" + grupoOrigen);

      if (grupoOrigen == "0/1/1") {
        Serial.println("Activada escena Me voy");
        alarmaSalirActivada = true;
      } else if (grupoOrigen == "0/1/2") {
        Serial.println("Activada escena Dormir");
        alarmaDespertarActivada = true;
      }
    }
  }
}


//Mostrar fecha y hora en LCD
void pantallaLCD() {

  lcd.clear();
  DateTime valorRTC = RTC.now();
  //FECHA
  lcd.setCursor(0, 0);
  lcd.print("");
  lcd.print(diasSemana[valorRTC.dayOfTheWeek()]);
  lcd.print(" ");
  lcd.print(valorRTC.day(), DEC);
  lcd.print('/');
  lcd.print(valorRTC.month(), DEC);
  lcd.print('/');
  lcd.print(valorRTC.year(), DEC);
  //HORA
  lcd.setCursor(0, 1);
  lcd.print("HORA: ");
  lcd.print(valorRTC.hour(), DEC);
  lcd.print(':');
  lcd.print(valorRTC.minute(), DEC);
  lcd.print(':');
  lcd.print(valorRTC.second(), DEC);

  delay(1000);

  repeticionesPantalla++;
}
void pantallaTempHumedad() {
  float humed = dht.readHumidity();
  float temper = dht.readTemperature();
  if (isnan(humed) || isnan(temper)) {
    Serial.println("Fallo en la lectura del sensor DHT11");
  }
  lcd.clear();
  //TEMPERATURA
  lcd.setCursor(0, 0);
  lcd.print("TIEMPO: ");
  lcd.print(temper);
  lcd.print((char)223);
  lcd.print("C");

  //HUMEDAD
  //TEMPERATURA
  lcd.setCursor(0, 1);
  lcd.print("HUMEDAD: ");
  lcd.print(humed);
  lcd.print(" %");


  delay(3000);

  repeticionesPantalla = 0;
}
//Lectura del sensor PIR
int lecturaPIR() {
  movimiento = digitalRead(pinSensor);
  return movimiento;
}
bool preguntarEstablecerDespertador() {
  char establecerAlarma;
  bool establecerBool = false;
  int establecer = 0;

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("PONER ALARMA?");
  lcd.setCursor(0, 1);
  lcd.print("A=SI B=NO");

  while (establecer != 1) {
    establecerAlarma = teclado.getKey();

    if (establecerAlarma == 'A') {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("ACTIVAR ALARMA");
      delay(3000);
      lcd.clear();
      establecerBool = true;
      establecer++;
    } else if (establecerAlarma == 'B') {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("ALARMA");
      lcd.setCursor(0, 1);
      lcd.print("NO ACTIVADA");
      delay(3000);
      lcd.clear();
      establecer++;
    }
  }
  return establecerBool;
}
String insertarHoraDespertar() {

  int i;
  lcd.setCursor(0, 0);
  lcd.print("INTRODUZCA HORA");
  String horaCompleta = "";
  char horaAlarma;
  char correcto;
  String caracterPuntos = ":";
  for (i = 0; i <= 4; i++) {

    if (i == 2) {
      lcd.setCursor(i, 1);
      lcd.print(caracterPuntos);
      horaCompleta = horaCompleta + caracterPuntos;
    } else {
      horaAlarma = teclado.waitForKey();
      lcd.setCursor(i, 1);
      lcd.print(horaAlarma);
      horaCompleta = horaCompleta + String(horaAlarma);
    }
  }

  validarHoraDespertar(horaCompleta);

  lcd.clear();
  return horaCompleta;
}
void validarHoraDespertar(String horaInsertada) {
  char horaAlarma;
  bool hora = getValidarHora(horaInsertada, 0);
  bool minutos = getValidarHora(horaInsertada, 1);
  Serial.println(String(hora));
  Serial.println(String(minutos));

  if (hora && minutos) {

    delay(2000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("CORRECTO?" + horaInsertada);
    lcd.setCursor(0, 1);
    lcd.print("A=SI B=NO C=EX");

    horaAlarma = teclado.waitForKey();

    if (horaAlarma == 'A') {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("ALARMA");
      lcd.setCursor(0, 1);
      lcd.print("ESTABLECIDA");
      delay(3000);
      lcd.clear();
    } else if (horaAlarma == 'B') {
      lcd.clear();
      insertarHoraDespertar();
    } else if (horaAlarma == 'C') {
      alarmaDespertarActivada = false;
    }
  } else {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("HORA INVALIDA");
    delay(2000);
    lcd.clear();
    insertarHoraDespertar();
  }
}
void esperarDespertador(String hora) {
  DateTime valorRTC = RTC.now();
  int horas = getValue(hora, ':', 0).toInt();
  int minutos = getValue(hora, ':', 1).toInt();
  do {
    pantallaLCD();
    valorRTC = RTC.now();
  } while (valorRTC.hour() != horas || valorRTC.minute() != minutos);

  activarBuzzerDespertador();
  activarEscenaDespertar();
  alarmaDespertarActivada = false;
}
void activarEscenaDespertar() {
  Serial.println("Activada escena Despertar");
  Serial.println("Subo persiana");
  knx.groupWrite4BitInt("2/0/0", 0);
  Serial.println("Subo enciendo luz dormitorio");
  knx.groupWriteBool("1/0/1", true);
}
//Indica si se ha detectado movimiento
void LCDMovimientoDetectado() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("INSERTE CODIGO");
  lcd.setCursor(0, 1);
  lcd.print("DESBLOQUEO");
  delay(3000);
  indicarCorrectoCodigoDesbloqueo();
}
//Indica al lcd si el código introducido es correcto
void indicarCorrectoCodigoDesbloqueo() {
  bool correcta = false;
  intentos = 0;

  while ((intentos != 3) && (correcta == false)) {
    correcta = pedirCodigoDesbloqueo();
    //Contraseña introducida es correcta
    if (correcta == true) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.println("***BIENVENIDO***");
      lcd.setCursor(0, 1);
      lcd.println("*****A CASA*****");
      delay(3000);
      intentos = 0;
      alarmaSalirActivada = false;

    }
    //Contraseña incorrecta.
    //Hasta 3 imprime mensaje de que continue.
    //En 3 suena buzzer
    else {
      lcd.clear();
      delay(1000);
      //Muchas veces equivocando
      if (intentos == 3) {
        lcd.setCursor(0, 0);
        lcd.print("****DETECTADO***");
        lcd.setCursor(0, 1);
        lcd.print("*****LADRON*****");
        delay(2000);
        activarBuzzerLadron();

      } else {
        lcd.setCursor(0, 0);
        lcd.print("CODIGO ERRONEO");
        lcd.setCursor(0, 1);
        lcd.print("VUELVE A PROBAR");
        delay(2000);
      }
    }
  }
}
//Pide al usuario el código de 4 dígitos de desbloqueo
bool pedirCodigoDesbloqueo() {
  bool correcta = false;
  int posicion = 1;
  lcd.clear();
  char digitoPass;
  int digitoCorrecto = 0;
  bool passCorrecta = false;

  //Pedir los 4 dígitos de la contraseña
  while (posicion != 5) {

    char caracter = teclado.getKey();
    if (caracter) {

      if (posicion == 1) {
        digitoPass = 'A';
        lcd.clear();
        lcd.print("*");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass,
                                                    caracter);
        posicion++;
      } else if (posicion == 2) {
        digitoPass = '3';
        lcd.clear();
        lcd.print("**");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass, caracter);
        posicion++;
      } else if (posicion == 3) {
        digitoPass = '2';
        lcd.clear();
        lcd.print("***");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass, caracter);
        posicion++;
      } else {
        digitoPass = '1';
        lcd.clear();
        lcd.print("****");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass, caracter);
        posicion++;
      }
    }
  }
  intentos++;
  if (digitoCorrecto == 4) {
    passCorrecta = true;
  }

  return passCorrecta;
}
//Comprueba si el dígito establecido en la contraseña es igual al
int comprobarCodigoDesbloqueo(char caracterEstablecido, char caracterIntroducido) {
  int digitoCorrecto = 0;

  //Compruebo si la contraseña es igual a la establecida
  if (caracterEstablecido == caracterIntroducido) {
    digitoCorrecto = 1;

  } else {
    digitoCorrecto = 0;
  }
  return digitoCorrecto;
}
void activarBuzzerLadron() {

  int contador = 0;
  while (contador != 2) {
    tone(zumbador, 50);  // Envía señal de 1Khz al zumbador
    delay(1000);
    noTone(zumbador);  // Detiene el zumbador
    delay(1000);       //Espera un segundo y vuelve a repetir el bucle
    contador++;
  }

  alarmaSalirActivada = false;
}
void activarBuzzerPonerAlarma() {

  int contador = 0;
  while (contador < 3) {
    tonoInicio();
    contador++;
  }
  contador = 0;
  while (contador < 2) {
    tonoMedio();
    contador++;
  }
  contador = 0;

  while (contador < 4) {
    tonoFinal();
    contador++;
  }
}
void tonoInicio() {
  tone(zumbador, 440);
  delay(500);
  noTone(zumbador);  // Detiene el zumbador
  delay(1500);       //Espera un segundo y vuelve a repetir el bucle
}
void tonoMedio() {
  tone(zumbador, 440);
  delay(500);
  noTone(zumbador);  // Detiene el zumbador
  delay(750);        //Espera un segundo y vuelve a repetir el bucle
}
void tonoFinal() {
  tone(zumbador, 440);
  delay(250);
  noTone(zumbador);  // Detiene el zumbador
  delay(250);        //Espera un segundo y vuelve a repetir el bucle
}
void activarBuzzerDespertador() {
  int contador = 0;
  while (contador != 1) {
    tone(zumbador, 50);  // Envía señal de 1Khz al zumbador
    delay(1000);
    noTone(zumbador);  // Detiene el zumbador
    delay(1000);       //Espera un segundo y vuelve a repetir el bucle
    contador++;
  }
  contador = 0;
}

bool getValidarHora(String datos, int index) {
  String hora = getValue(datos, ':', index);
  int datosLong = datos.length();
  char datosChar[datosLong + 1];
  bool valido = true;
  hora.toCharArray(datosChar, datosLong);
  for (int i = 0; i < datosLong; i++) {
    switch (datosChar[i]) {
      case 'A':
        return false;
        break;
      case 'B':
        return false;
        break;
      case 'C':
        return false;
        break;
      case 'D':
        return false;
        break;
      case '#':
        return false;
        break;
      case '*':
        return false;
        break;
    }
  }
  int horaInt = hora.toInt();

  if (index == 0 && ((horaInt >= 0 && horaInt <= 23))) {
    return true;
  } else if (index == 1 && ((horaInt >= 0 && horaInt <= 59))) {
    return true;
  }
}
String getValue(String data, char separator, int index) {
  int found = 0;
  int strIndex[] = { 0, -1 };
  int maxIndex = data.length() - 1;
  for (int i = 0; i <= maxIndex && found <= index; i++) {
    if (data.charAt(i) == separator || i == maxIndex) {
      found++;
      strIndex[0] = strIndex[1] + 1;
      strIndex[1] = (i == maxIndex) ? i + 1 : i;
    }
  }
  return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

curious, what is a KNX bus?

quoting Wikipedia
KNX is an open standard (see EN 50090, ISO/IEC 14543) for commercial and residential building automation. KNX devices can manage lighting, blinds and shutters, HVAC, security systems, energy management, audio video, white goods, displays, remote control, etc. KNX evolved from three earlier standards; the European Home Systems Protocol (EHS), BatiBUS, and the European Installation Bus (EIB or Instabus).

It can use twisted pair (in a tree, line or star topology), powerline, RF, or IP links. On this network, the devices form distributed applications and tight interaction is possible. This is implemented via interworking models with standardised datapoint types and objects, modelling logical device channels.

What statements do you expect to be executed if you clean up your respuesta just after printing?

Hi @crisljtc_89 ,

the main issue has already been pointed out in post #7 by @b707:

You clear the string before it can be evaluated.

However also this construction seems to be prone to error:

 String respuesta="";
  while (Serial2.available() > 0) {
    char receivedChar = Serial2.read();
    if (receivedChar == '\n') {
      Serial.println(respuesta);
      delay(1000);     // Print the received message in the Serial monitor
      respuesta = "";  // Reset the received message
    } else {
      respuesta += receivedChar;  // Append characters to the received message
    }
  }

Just assume that some characters on Serial2 are delayed. Serial2.available() would be 0 and the sketch would leave the while() loop with an inconsistent message and in the next loop it would clear the string, read the rest of the message and probably have trouble to synchronize again.

A solution could be to

  • set respuesta = "" as you do here just before the while() loop
  • use a second String variable to collect the Serial input (e.g. call it String tempString;)
  • set repuesta = tempString and clear tempString if a \n was received

String tempString = "";

void loop(){
 // ...
  String respuesta = "";
  while (Serial2.available() > 0) {
    char receivedChar = Serial2.read();
    if (receivedChar == '\n') {
      respuesta = tempString;
      tempString = "";
      Serial.println(respuesta);
      delay(1000);     // Print the received message in the Serial monitor
    } else {
      tempString += receivedChar;  // Append characters to the received message
    }
  }
// ...

Now a (hopefully) valid message, at least closed by '\n' will be available from after the while()-loop until the sketch reaches the while() loop again OR respuesta will be an empty string.
Not tested but should work ...

Please do not post pictures of code, use code tags

Here is the easiest way to tidy up the code and add the code tags

Start by tidying up your code by using Tools/Auto Format in the IDE to make it easier to read. Then use Edit/Copy for Forum and paste what was copied in a new reply. Code tags will have been added to the code to make it easy to read in the forum thus making it easier to provide help.

Ok thanks, sorry

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"
#include <Keypad.h>
#include <KnxTpUart.h>
#include <stdio.h>
#include <stdlib.h>
#include "DHT.h"
#if defined(ARDUINO) && ARDUINO >= 100
#define printByte(args) write(args);
#else
#define printByte(args) print(args, BYTE);
#endif

int estado_luz_salon = 0;
int estado_luz_dormitorio = 0;
//Variables KNX
KnxTpUart knx(&Serial1, "1.1.30");
//Variables RTC
uint8_t clock[8] = { 0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0 };
RTC_DS3231 RTC;
//Variables LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
String diasSemana[7] = { "DOM", "LUN", "MART", "MIER", "JUEV", "VIER",
                         "SAB" };
//Variables Teclado Matricial
const byte filas = 4;
const byte columnas = 4;
const byte pinesColumnas[filas] = { 5, 4, 3, 2 };
const byte pinesFilas[columnas] = { 9, 8, 7, 6 };
char formatoTeclado[filas][columnas] = {
  { '1', '2', '3', 'A' },
  { '4', '5', '6', 'B' },
  { '7', '8', '9', 'C' },
  { '*', '0', '#', 'D' }
};
Keypad teclado = Keypad(makeKeymap(formatoTeclado),
                        (byte*)pinesFilas, (byte*)pinesColumnas, filas, columnas);
//Variables Zumbador
const int zumbador = 10;
//Variables PIR
#define pinSensor 11
//Variables DHT11
const int pinDTH = 12;
DHT dht(pinDTH, DHT11);

//Variables globales
int movimiento = 0;
int intentos = 0;
int repeticionesPantalla = 0;
bool alarmaSalirActivada = false;
bool alarmaDespertarActivada = false;
void setup() {

  Serial.begin(19200);        // Inicia Serial
  pinMode(zumbador, OUTPUT);  //Establece el pin 10 de salida al que

  Wire.begin();  //Inicializa la biblioteca Wire para permitir la

  //Inicializacion del RTC
  if (!RTC.begin()) {
    while (1)
      ;
  }
  // Si se ha perdido la corriente, fijar fecha y hora de compilacion
  if (RTC.lostPower()) {
    RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  // Inicializa la pantalla LCD y luz de fondo
  lcd.init();
  lcd.backlight();

  //Inicia el sensor DHT
  dht.begin();
  //Inicia KNX
  Serial1.begin(19200, SERIAL_8E1);
  Serial2.begin(19200);

  knx.uartReset();
  //Escena Me voy
  knx.addListenGroupAddress("0/1/1");
  //Escena Dormir
  knx.addListenGroupAddress("0/1/2");
  Serial.println("Added listen group adress ");

  delay(1000);

  knx.groupRead("0/1/1");
  knx.groupRead("0/1/2");
  Serial.println("Read group address ");
}
//Se recorre de manera repetitiva y a la velocidad del procesador
void loop() {


  if (repeticionesPantalla != 5) {
    pantallaLCD();
  } else {
    pantallaTempHumedad();
  }

  //Código para la puesta de la alarma despertar
  while (alarmaDespertarActivada) {
    if (preguntarEstablecerDespertador()) {
      String hora = insertarHoraDespertar();
      esperarDespertador(hora);
    }
    alarmaDespertarActivada = false;
  }

  //Código para la puesta de la alarma al irnos de casa
  while (alarmaSalirActivada) {
    activarBuzzerPonerAlarma();

    while (movimiento == LOW) {
      pantallaLCD();
      lecturaPIR();
    }
    LCDMovimientoDetectado();
    movimiento = LOW;
  }

  if (Serial2.available()) {

    String respuesta = "";
    while (Serial2.available() > 0) {
      char receivedChar = Serial2.read();
      if (receivedChar == '\n') {
        //Serial.println(respuesta);
        delay(1000);  // Print the received message in the Serial monitor
        //respuesta = "";  // Reset the received message
      } else {
        respuesta += receivedChar;  // Append characters to the received message
      }
    }
    Serial.println(respuesta);

    //respuesta += '\0';


    if (respuesta == "/sube_persiana") {

      //persiana
      knx.groupWriteBool("2/0/0", 0);
    }

    if (respuesta == "/baja_persiana") {

      //persiana
      knx.groupWriteBool("2/0/0", 1);
    }

    if (respuesta == "/enciende_luz_dormitorio") {
      //dormitorio
      Serial.println("Here");
      bool xd = true;
      knx.groupWriteBool("1/0/1", xd);
    }

    if (respuesta == "/apaga_luz_dormitorio") {
      //dormitorio
      Serial.println(respuesta);

      knx.groupWriteBool("1/0/1", 0);
    }

    if (respuesta == "/enciende_luz_salon") {

      //salon
      knx.groupWriteBool("1/0/0", 1);
    }

    if (respuesta == "/apaga_luz_salon") {

      //salon
      knx.groupWriteBool("1/0/0", 0);
    }
  }
}

void serialEvent1() {
  KnxTpUartSerialEventType tipoEvento = knx.serialEvent();
  Serial.println("knx.serialEvent()");

  if (tipoEvento == KNX_TELEGRAM) {


    KnxTelegram* telegram = knx.getReceivedTelegram();
    KnxCommandType tipoComando = telegram->getCommand();

    if (tipoComando == KNX_COMMAND_WRITE) {

      Serial.println("Received KNX_COMMAND_WRITE");

      String grupoOrigen =
        String(0 + telegram->getTargetMainGroup()) + "/" + String(0 + telegram->getTargetMiddleGroup()) + "/" + String(0 + telegram->getTargetSubGroup());

      Serial.println("GrupoOrigen :" + grupoOrigen);

      if (grupoOrigen == "0/1/1") {
        Serial.println("Activada escena Me voy");
        alarmaSalirActivada = true;
      } else if (grupoOrigen == "0/1/2") {
        Serial.println("Activada escena Dormir");
        alarmaDespertarActivada = true;
      }
    }
  }
}


//Mostrar fecha y hora en LCD
void pantallaLCD() {

  lcd.clear();
  DateTime valorRTC = RTC.now();
  //FECHA
  lcd.setCursor(0, 0);
  lcd.print("");
  lcd.print(diasSemana[valorRTC.dayOfTheWeek()]);
  lcd.print(" ");
  lcd.print(valorRTC.day(), DEC);
  lcd.print('/');
  lcd.print(valorRTC.month(), DEC);
  lcd.print('/');
  lcd.print(valorRTC.year(), DEC);
  //HORA
  lcd.setCursor(0, 1);
  lcd.print("HORA: ");
  lcd.print(valorRTC.hour(), DEC);
  lcd.print(':');
  lcd.print(valorRTC.minute(), DEC);
  lcd.print(':');
  lcd.print(valorRTC.second(), DEC);

  delay(1000);

  repeticionesPantalla++;
}
void pantallaTempHumedad() {
  float humed = dht.readHumidity();
  float temper = dht.readTemperature();
  if (isnan(humed) || isnan(temper)) {
    Serial.println("Fallo en la lectura del sensor DHT11");
  }
  lcd.clear();
  //TEMPERATURA
  lcd.setCursor(0, 0);
  lcd.print("TIEMPO: ");
  lcd.print(temper);
  lcd.print((char)223);
  lcd.print("C");

  //HUMEDAD
  //TEMPERATURA
  lcd.setCursor(0, 1);
  lcd.print("HUMEDAD: ");
  lcd.print(humed);
  lcd.print(" %");


  delay(3000);

  repeticionesPantalla = 0;
}
//Lectura del sensor PIR
int lecturaPIR() {
  movimiento = digitalRead(pinSensor);
  return movimiento;
}
bool preguntarEstablecerDespertador() {
  char establecerAlarma;
  bool establecerBool = false;
  int establecer = 0;

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("PONER ALARMA?");
  lcd.setCursor(0, 1);
  lcd.print("A=SI B=NO");

  while (establecer != 1) {
    establecerAlarma = teclado.getKey();

    if (establecerAlarma == 'A') {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("ACTIVAR ALARMA");
      delay(3000);
      lcd.clear();
      establecerBool = true;
      establecer++;
    } else if (establecerAlarma == 'B') {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("ALARMA");
      lcd.setCursor(0, 1);
      lcd.print("NO ACTIVADA");
      delay(3000);
      lcd.clear();
      establecer++;
    }
  }
  return establecerBool;
}
String insertarHoraDespertar() {

  int i;
  lcd.setCursor(0, 0);
  lcd.print("INTRODUZCA HORA");
  String horaCompleta = "";
  char horaAlarma;
  char correcto;
  String caracterPuntos = ":";
  for (i = 0; i <= 4; i++) {

    if (i == 2) {
      lcd.setCursor(i, 1);
      lcd.print(caracterPuntos);
      horaCompleta = horaCompleta + caracterPuntos;
    } else {
      horaAlarma = teclado.waitForKey();
      lcd.setCursor(i, 1);
      lcd.print(horaAlarma);
      horaCompleta = horaCompleta + String(horaAlarma);
    }
  }

  validarHoraDespertar(horaCompleta);

  lcd.clear();
  return horaCompleta;
}
void validarHoraDespertar(String horaInsertada) {
  char horaAlarma;
  bool hora = getValidarHora(horaInsertada, 0);
  bool minutos = getValidarHora(horaInsertada, 1);
  Serial.println(String(hora));
  Serial.println(String(minutos));

  if (hora && minutos) {

    delay(2000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("CORRECTO?" + horaInsertada);
    lcd.setCursor(0, 1);
    lcd.print("A=SI B=NO C=EX");

    horaAlarma = teclado.waitForKey();

    if (horaAlarma == 'A') {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("ALARMA");
      lcd.setCursor(0, 1);
      lcd.print("ESTABLECIDA");
      delay(3000);
      lcd.clear();
    } else if (horaAlarma == 'B') {
      lcd.clear();
      insertarHoraDespertar();
    } else if (horaAlarma == 'C') {
      alarmaDespertarActivada = false;
    }
  } else {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("HORA INVALIDA");
    delay(2000);
    lcd.clear();
    insertarHoraDespertar();
  }
}
void esperarDespertador(String hora) {
  DateTime valorRTC = RTC.now();
  int horas = getValue(hora, ':', 0).toInt();
  int minutos = getValue(hora, ':', 1).toInt();
  do {
    pantallaLCD();
    valorRTC = RTC.now();
  } while (valorRTC.hour() != horas || valorRTC.minute() != minutos);

  activarBuzzerDespertador();
  activarEscenaDespertar();
  alarmaDespertarActivada = false;
}
void activarEscenaDespertar() {
  Serial.println("Activada escena Despertar");
  Serial.println("Subo persiana");
  knx.groupWrite4BitInt("2/0/0", 0);
  Serial.println("Subo enciendo luz dormitorio");
  knx.groupWriteBool("1/0/1", true);
}
//Indica si se ha detectado movimiento
void LCDMovimientoDetectado() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("INSERTE CODIGO");
  lcd.setCursor(0, 1);
  lcd.print("DESBLOQUEO");
  delay(3000);
  indicarCorrectoCodigoDesbloqueo();
}
//Indica al lcd si el código introducido es correcto
void indicarCorrectoCodigoDesbloqueo() {
  bool correcta = false;
  intentos = 0;

  while ((intentos != 3) && (correcta == false)) {
    correcta = pedirCodigoDesbloqueo();
    //Contraseña introducida es correcta
    if (correcta == true) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.println("***BIENVENIDO***");
      lcd.setCursor(0, 1);
      lcd.println("*****A CASA*****");
      delay(3000);
      intentos = 0;
      alarmaSalirActivada = false;

    }
    //Contraseña incorrecta.
    //Hasta 3 imprime mensaje de que continue.
    //En 3 suena buzzer
    else {
      lcd.clear();
      delay(1000);
      //Muchas veces equivocando
      if (intentos == 3) {
        lcd.setCursor(0, 0);
        lcd.print("****DETECTADO***");
        lcd.setCursor(0, 1);
        lcd.print("*****LADRON*****");
        delay(2000);
        activarBuzzerLadron();

      } else {
        lcd.setCursor(0, 0);
        lcd.print("CODIGO ERRONEO");
        lcd.setCursor(0, 1);
        lcd.print("VUELVE A PROBAR");
        delay(2000);
      }
    }
  }
}
//Pide al usuario el código de 4 dígitos de desbloqueo
bool pedirCodigoDesbloqueo() {
  bool correcta = false;
  int posicion = 1;
  lcd.clear();
  char digitoPass;
  int digitoCorrecto = 0;
  bool passCorrecta = false;

  //Pedir los 4 dígitos de la contraseña
  while (posicion != 5) {

    char caracter = teclado.getKey();
    if (caracter) {

      if (posicion == 1) {
        digitoPass = 'A';
        lcd.clear();
        lcd.print("*");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass,
                                                    caracter);
        posicion++;
      } else if (posicion == 2) {
        digitoPass = '3';
        lcd.clear();
        lcd.print("**");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass, caracter);
        posicion++;
      } else if (posicion == 3) {
        digitoPass = '2';
        lcd.clear();
        lcd.print("***");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass, caracter);
        posicion++;
      } else {
        digitoPass = '1';
        lcd.clear();
        lcd.print("****");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass, caracter);
        posicion++;
      }
    }
  }
  intentos++;
  if (digitoCorrecto == 4) {
    passCorrecta = true;
  }

  return passCorrecta;
}
//Comprueba si el dígito establecido en la contraseña es igual al
int comprobarCodigoDesbloqueo(char caracterEstablecido, char caracterIntroducido) {
  int digitoCorrecto = 0;

  //Compruebo si la contraseña es igual a la establecida
  if (caracterEstablecido == caracterIntroducido) {
    digitoCorrecto = 1;

  } else {
    digitoCorrecto = 0;
  }
  return digitoCorrecto;
}
void activarBuzzerLadron() {

  int contador = 0;
  while (contador != 2) {
    tone(zumbador, 50);  // Envía señal de 1Khz al zumbador
    delay(1000);
    noTone(zumbador);  // Detiene el zumbador
    delay(1000);       //Espera un segundo y vuelve a repetir el bucle
    contador++;
  }

  alarmaSalirActivada = false;
}
void activarBuzzerPonerAlarma() {

  int contador = 0;
  while (contador < 3) {
    tonoInicio();
    contador++;
  }
  contador = 0;
  while (contador < 2) {
    tonoMedio();
    contador++;
  }
  contador = 0;

  while (contador < 4) {
    tonoFinal();
    contador++;
  }
}
void tonoInicio() {
  tone(zumbador, 440);
  delay(500);
  noTone(zumbador);  // Detiene el zumbador
  delay(1500);       //Espera un segundo y vuelve a repetir el bucle
}
void tonoMedio() {
  tone(zumbador, 440);
  delay(500);
  noTone(zumbador);  // Detiene el zumbador
  delay(750);        //Espera un segundo y vuelve a repetir el bucle
}
void tonoFinal() {
  tone(zumbador, 440);
  delay(250);
  noTone(zumbador);  // Detiene el zumbador
  delay(250);        //Espera un segundo y vuelve a repetir el bucle
}
void activarBuzzerDespertador() {
  int contador = 0;
  while (contador != 1) {
    tone(zumbador, 50);  // Envía señal de 1Khz al zumbador
    delay(1000);
    noTone(zumbador);  // Detiene el zumbador
    delay(1000);       //Espera un segundo y vuelve a repetir el bucle
    contador++;
  }
  contador = 0;
}

bool getValidarHora(String datos, int index) {
  String hora = getValue(datos, ':', index);
  int datosLong = datos.length();
  char datosChar[datosLong + 1];
  bool valido = true;
  hora.toCharArray(datosChar, datosLong);
  for (int i = 0; i < datosLong; i++) {
    switch (datosChar[i]) {
      case 'A':
        return false;
        break;
      case 'B':
        return false;
        break;
      case 'C':
        return false;
        break;
      case 'D':
        return false;
        break;
      case '#':
        return false;
        break;
      case '*':
        return false;
        break;
    }
  }
  int horaInt = hora.toInt();

  if (index == 0 && ((horaInt >= 0 && horaInt <= 23))) {
    return true;
  } else if (index == 1 && ((horaInt >= 0 && horaInt <= 59))) {
    return true;
  }
}
String getValue(String data, char separator, int index) {
  int found = 0;
  int strIndex[] = { 0, -1 };
  int maxIndex = data.length() - 1;
  for (int i = 0; i <= maxIndex && found <= index; i++) {
    if (data.charAt(i) == separator || i == maxIndex) {
      found++;
      strIndex[0] = strIndex[1] + 1;
      strIndex[1] = (i == maxIndex) ? i + 1 : i;
    }
  }
  return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

"not work" said nothing about what is your problem with the code.

if you receive /enciende_luz_dormitorio, in

if (respuesta == "/enciende_luz_dormitorio") {
      //dormitorio
      Serial.println("Here");
      bool xd = true;
      knx.groupWriteBool("1/0/1", xd);
    }

No launch "Here"

Is above mean you received
"/enciende_luz_dormitorio"
or
"/enciende_luz_dormitorio, in"

?

"/enciende_luz_dormitorio" when i said in i refer the if

If you read my post #8 thoroughly you will see that just deleting the line inside the while() loop does not help to overcome synchronization issues.

Synchronization means: Always read complete messages terminated by '\n'

I tried to implement the second snippet from my postg #8 to your code from post #11; not tested but feel free to give it a try:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"
#include <Keypad.h>
#include <KnxTpUart.h>
#include <stdio.h>
#include <stdlib.h>
#include "DHT.h"
#if defined(ARDUINO) && ARDUINO >= 100
#define printByte(args) write(args);
#else
#define printByte(args) print(args, BYTE);
#endif

int estado_luz_salon = 0;
int estado_luz_dormitorio = 0;
//Variables KNX
KnxTpUart knx(&Serial1, "1.1.30");
//Variables RTC
uint8_t clock[8] = { 0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0 };
RTC_DS3231 RTC;
//Variables LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
String diasSemana[7] = { "DOM", "LUN", "MART", "MIER", "JUEV", "VIER",
                         "SAB" };
//Variables Teclado Matricial
const byte filas = 4;
const byte columnas = 4;
const byte pinesColumnas[filas] = { 5, 4, 3, 2 };
const byte pinesFilas[columnas] = { 9, 8, 7, 6 };
char formatoTeclado[filas][columnas] = {
  { '1', '2', '3', 'A' },
  { '4', '5', '6', 'B' },
  { '7', '8', '9', 'C' },
  { '*', '0', '#', 'D' }
};
Keypad teclado = Keypad(makeKeymap(formatoTeclado),
                        (byte*)pinesFilas, (byte*)pinesColumnas, filas, columnas);
//Variables Zumbador
const int zumbador = 10;
//Variables PIR
#define pinSensor 11
//Variables DHT11
const int pinDTH = 12;
DHT dht(pinDTH, DHT11);

//Variables globales
int movimiento = 0;
int intentos = 0;
int repeticionesPantalla = 0;
bool alarmaSalirActivada = false;
bool alarmaDespertarActivada = false;
String tempString = "";
String respuesta = "";

void setup() {

  Serial.begin(19200);        // Inicia Serial
  pinMode(zumbador, OUTPUT);  //Establece el pin 10 de salida al que

  Wire.begin();  //Inicializa la biblioteca Wire para permitir la

  //Inicializacion del RTC
  if (!RTC.begin()) {
    while (1)
      ;
  }
  // Si se ha perdido la corriente, fijar fecha y hora de compilacion
  if (RTC.lostPower()) {
    RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  // Inicializa la pantalla LCD y luz de fondo
  lcd.init();
  lcd.backlight();

  //Inicia el sensor DHT
  dht.begin();
  //Inicia KNX
  Serial1.begin(19200, SERIAL_8E1);
  Serial2.begin(19200);

  knx.uartReset();
  //Escena Me voy
  knx.addListenGroupAddress("0/1/1");
  //Escena Dormir
  knx.addListenGroupAddress("0/1/2");
  Serial.println("Added listen group adress ");

  delay(1000);

  knx.groupRead("0/1/1");
  knx.groupRead("0/1/2");
  Serial.println("Read group address ");
}
//Se recorre de manera repetitiva y a la velocidad del procesador
void loop() {


  if (repeticionesPantalla != 5) {
    pantallaLCD();
  } else {
    pantallaTempHumedad();
  }

  //Código para la puesta de la alarma despertar
  while (alarmaDespertarActivada) {
    if (preguntarEstablecerDespertador()) {
      String hora = insertarHoraDespertar();
      esperarDespertador(hora);
    }
    alarmaDespertarActivada = false;
  }

  //Código para la puesta de la alarma al irnos de casa
  while (alarmaSalirActivada) {
    activarBuzzerPonerAlarma();

    while (movimiento == LOW) {
      pantallaLCD();
      lecturaPIR();
    }
    LCDMovimientoDetectado();
    movimiento = LOW;
  }

  respuesta = "";
  while (Serial2.available() > 0) {
    char receivedChar = Serial2.read();
    if (receivedChar == '\n') {
      respuesta = tempString;
      tempString = "";
      Serial.println(respuesta);
      delay(1000);     // Print the received message in the Serial monitor
    } else {
      tempString += receivedChar;  // Append characters to the received message
    }
  }


    if (respuesta == "/sube_persiana") {

      //persiana
      knx.groupWriteBool("2/0/0", 0);
    }

    if (respuesta == "/baja_persiana") {

      //persiana
      knx.groupWriteBool("2/0/0", 1);
    }

    if (respuesta == "/enciende_luz_dormitorio") {
      //dormitorio
      Serial.println("Here");
      bool xd = true;
      knx.groupWriteBool("1/0/1", xd);
    }

    if (respuesta == "/apaga_luz_dormitorio") {
      //dormitorio
      Serial.println(respuesta);

      knx.groupWriteBool("1/0/1", 0);
    }

    if (respuesta == "/enciende_luz_salon") {

      //salon
      knx.groupWriteBool("1/0/0", 1);
    }

    if (respuesta == "/apaga_luz_salon") {

      //salon
      knx.groupWriteBool("1/0/0", 0);
    }
  }
}

void serialEvent1() {
  KnxTpUartSerialEventType tipoEvento = knx.serialEvent();
  Serial.println("knx.serialEvent()");

  if (tipoEvento == KNX_TELEGRAM) {


    KnxTelegram* telegram = knx.getReceivedTelegram();
    KnxCommandType tipoComando = telegram->getCommand();

    if (tipoComando == KNX_COMMAND_WRITE) {

      Serial.println("Received KNX_COMMAND_WRITE");

      String grupoOrigen =
        String(0 + telegram->getTargetMainGroup()) + "/" + String(0 + telegram->getTargetMiddleGroup()) + "/" + String(0 + telegram->getTargetSubGroup());

      Serial.println("GrupoOrigen :" + grupoOrigen);

      if (grupoOrigen == "0/1/1") {
        Serial.println("Activada escena Me voy");
        alarmaSalirActivada = true;
      } else if (grupoOrigen == "0/1/2") {
        Serial.println("Activada escena Dormir");
        alarmaDespertarActivada = true;
      }
    }
  }
}


//Mostrar fecha y hora en LCD
void pantallaLCD() {

  lcd.clear();
  DateTime valorRTC = RTC.now();
  //FECHA
  lcd.setCursor(0, 0);
  lcd.print("");
  lcd.print(diasSemana[valorRTC.dayOfTheWeek()]);
  lcd.print(" ");
  lcd.print(valorRTC.day(), DEC);
  lcd.print('/');
  lcd.print(valorRTC.month(), DEC);
  lcd.print('/');
  lcd.print(valorRTC.year(), DEC);
  //HORA
  lcd.setCursor(0, 1);
  lcd.print("HORA: ");
  lcd.print(valorRTC.hour(), DEC);
  lcd.print(':');
  lcd.print(valorRTC.minute(), DEC);
  lcd.print(':');
  lcd.print(valorRTC.second(), DEC);

  delay(1000);

  repeticionesPantalla++;
}
void pantallaTempHumedad() {
  float humed = dht.readHumidity();
  float temper = dht.readTemperature();
  if (isnan(humed) || isnan(temper)) {
    Serial.println("Fallo en la lectura del sensor DHT11");
  }
  lcd.clear();
  //TEMPERATURA
  lcd.setCursor(0, 0);
  lcd.print("TIEMPO: ");
  lcd.print(temper);
  lcd.print((char)223);
  lcd.print("C");

  //HUMEDAD
  //TEMPERATURA
  lcd.setCursor(0, 1);
  lcd.print("HUMEDAD: ");
  lcd.print(humed);
  lcd.print(" %");


  delay(3000);

  repeticionesPantalla = 0;
}
//Lectura del sensor PIR
int lecturaPIR() {
  movimiento = digitalRead(pinSensor);
  return movimiento;
}
bool preguntarEstablecerDespertador() {
  char establecerAlarma;
  bool establecerBool = false;
  int establecer = 0;

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("PONER ALARMA?");
  lcd.setCursor(0, 1);
  lcd.print("A=SI B=NO");

  while (establecer != 1) {
    establecerAlarma = teclado.getKey();

    if (establecerAlarma == 'A') {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("ACTIVAR ALARMA");
      delay(3000);
      lcd.clear();
      establecerBool = true;
      establecer++;
    } else if (establecerAlarma == 'B') {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("ALARMA");
      lcd.setCursor(0, 1);
      lcd.print("NO ACTIVADA");
      delay(3000);
      lcd.clear();
      establecer++;
    }
  }
  return establecerBool;
}
String insertarHoraDespertar() {

  int i;
  lcd.setCursor(0, 0);
  lcd.print("INTRODUZCA HORA");
  String horaCompleta = "";
  char horaAlarma;
  char correcto;
  String caracterPuntos = ":";
  for (i = 0; i <= 4; i++) {

    if (i == 2) {
      lcd.setCursor(i, 1);
      lcd.print(caracterPuntos);
      horaCompleta = horaCompleta + caracterPuntos;
    } else {
      horaAlarma = teclado.waitForKey();
      lcd.setCursor(i, 1);
      lcd.print(horaAlarma);
      horaCompleta = horaCompleta + String(horaAlarma);
    }
  }

  validarHoraDespertar(horaCompleta);

  lcd.clear();
  return horaCompleta;
}
void validarHoraDespertar(String horaInsertada) {
  char horaAlarma;
  bool hora = getValidarHora(horaInsertada, 0);
  bool minutos = getValidarHora(horaInsertada, 1);
  Serial.println(String(hora));
  Serial.println(String(minutos));

  if (hora && minutos) {

    delay(2000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("CORRECTO?" + horaInsertada);
    lcd.setCursor(0, 1);
    lcd.print("A=SI B=NO C=EX");

    horaAlarma = teclado.waitForKey();

    if (horaAlarma == 'A') {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("ALARMA");
      lcd.setCursor(0, 1);
      lcd.print("ESTABLECIDA");
      delay(3000);
      lcd.clear();
    } else if (horaAlarma == 'B') {
      lcd.clear();
      insertarHoraDespertar();
    } else if (horaAlarma == 'C') {
      alarmaDespertarActivada = false;
    }
  } else {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("HORA INVALIDA");
    delay(2000);
    lcd.clear();
    insertarHoraDespertar();
  }
}
void esperarDespertador(String hora) {
  DateTime valorRTC = RTC.now();
  int horas = getValue(hora, ':', 0).toInt();
  int minutos = getValue(hora, ':', 1).toInt();
  do {
    pantallaLCD();
    valorRTC = RTC.now();
  } while (valorRTC.hour() != horas || valorRTC.minute() != minutos);

  activarBuzzerDespertador();
  activarEscenaDespertar();
  alarmaDespertarActivada = false;
}
void activarEscenaDespertar() {
  Serial.println("Activada escena Despertar");
  Serial.println("Subo persiana");
  knx.groupWrite4BitInt("2/0/0", 0);
  Serial.println("Subo enciendo luz dormitorio");
  knx.groupWriteBool("1/0/1", true);
}
//Indica si se ha detectado movimiento
void LCDMovimientoDetectado() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("INSERTE CODIGO");
  lcd.setCursor(0, 1);
  lcd.print("DESBLOQUEO");
  delay(3000);
  indicarCorrectoCodigoDesbloqueo();
}
//Indica al lcd si el código introducido es correcto
void indicarCorrectoCodigoDesbloqueo() {
  bool correcta = false;
  intentos = 0;

  while ((intentos != 3) && (correcta == false)) {
    correcta = pedirCodigoDesbloqueo();
    //Contraseña introducida es correcta
    if (correcta == true) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.println("***BIENVENIDO***");
      lcd.setCursor(0, 1);
      lcd.println("*****A CASA*****");
      delay(3000);
      intentos = 0;
      alarmaSalirActivada = false;

    }
    //Contraseña incorrecta.
    //Hasta 3 imprime mensaje de que continue.
    //En 3 suena buzzer
    else {
      lcd.clear();
      delay(1000);
      //Muchas veces equivocando
      if (intentos == 3) {
        lcd.setCursor(0, 0);
        lcd.print("****DETECTADO***");
        lcd.setCursor(0, 1);
        lcd.print("*****LADRON*****");
        delay(2000);
        activarBuzzerLadron();

      } else {
        lcd.setCursor(0, 0);
        lcd.print("CODIGO ERRONEO");
        lcd.setCursor(0, 1);
        lcd.print("VUELVE A PROBAR");
        delay(2000);
      }
    }
  }
}
//Pide al usuario el código de 4 dígitos de desbloqueo
bool pedirCodigoDesbloqueo() {
  bool correcta = false;
  int posicion = 1;
  lcd.clear();
  char digitoPass;
  int digitoCorrecto = 0;
  bool passCorrecta = false;

  //Pedir los 4 dígitos de la contraseña
  while (posicion != 5) {

    char caracter = teclado.getKey();
    if (caracter) {

      if (posicion == 1) {
        digitoPass = 'A';
        lcd.clear();
        lcd.print("*");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass,
                                                    caracter);
        posicion++;
      } else if (posicion == 2) {
        digitoPass = '3';
        lcd.clear();
        lcd.print("**");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass, caracter);
        posicion++;
      } else if (posicion == 3) {
        digitoPass = '2';
        lcd.clear();
        lcd.print("***");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass, caracter);
        posicion++;
      } else {
        digitoPass = '1';
        lcd.clear();
        lcd.print("****");
        digitoCorrecto += comprobarCodigoDesbloqueo(digitoPass, caracter);
        posicion++;
      }
    }
  }
  intentos++;
  if (digitoCorrecto == 4) {
    passCorrecta = true;
  }

  return passCorrecta;
}
//Comprueba si el dígito establecido en la contraseña es igual al
int comprobarCodigoDesbloqueo(char caracterEstablecido, char caracterIntroducido) {
  int digitoCorrecto = 0;

  //Compruebo si la contraseña es igual a la establecida
  if (caracterEstablecido == caracterIntroducido) {
    digitoCorrecto = 1;

  } else {
    digitoCorrecto = 0;
  }
  return digitoCorrecto;
}
void activarBuzzerLadron() {

  int contador = 0;
  while (contador != 2) {
    tone(zumbador, 50);  // Envía señal de 1Khz al zumbador
    delay(1000);
    noTone(zumbador);  // Detiene el zumbador
    delay(1000);       //Espera un segundo y vuelve a repetir el bucle
    contador++;
  }

  alarmaSalirActivada = false;
}
void activarBuzzerPonerAlarma() {

  int contador = 0;
  while (contador < 3) {
    tonoInicio();
    contador++;
  }
  contador = 0;
  while (contador < 2) {
    tonoMedio();
    contador++;
  }
  contador = 0;

  while (contador < 4) {
    tonoFinal();
    contador++;
  }
}
void tonoInicio() {
  tone(zumbador, 440);
  delay(500);
  noTone(zumbador);  // Detiene el zumbador
  delay(1500);       //Espera un segundo y vuelve a repetir el bucle
}
void tonoMedio() {
  tone(zumbador, 440);
  delay(500);
  noTone(zumbador);  // Detiene el zumbador
  delay(750);        //Espera un segundo y vuelve a repetir el bucle
}
void tonoFinal() {
  tone(zumbador, 440);
  delay(250);
  noTone(zumbador);  // Detiene el zumbador
  delay(250);        //Espera un segundo y vuelve a repetir el bucle
}
void activarBuzzerDespertador() {
  int contador = 0;
  while (contador != 1) {
    tone(zumbador, 50);  // Envía señal de 1Khz al zumbador
    delay(1000);
    noTone(zumbador);  // Detiene el zumbador
    delay(1000);       //Espera un segundo y vuelve a repetir el bucle
    contador++;
  }
  contador = 0;
}

bool getValidarHora(String datos, int index) {
  String hora = getValue(datos, ':', index);
  int datosLong = datos.length();
  char datosChar[datosLong + 1];
  bool valido = true;
  hora.toCharArray(datosChar, datosLong);
  for (int i = 0; i < datosLong; i++) {
    switch (datosChar[i]) {
      case 'A':
        return false;
        break;
      case 'B':
        return false;
        break;
      case 'C':
        return false;
        break;
      case 'D':
        return false;
        break;
      case '#':
        return false;
        break;
      case '*':
        return false;
        break;
    }
  }
  int horaInt = hora.toInt();

  if (index == 0 && ((horaInt >= 0 && horaInt <= 23))) {
    return true;
  } else if (index == 1 && ((horaInt >= 0 && horaInt <= 59))) {
    return true;
  }
}
String getValue(String data, char separator, int index) {
  int found = 0;
  int strIndex[] = { 0, -1 };
  int maxIndex = data.length() - 1;
  for (int i = 0; i <= maxIndex && found <= index; i++) {
    if (data.charAt(i) == separator || i == maxIndex) {
      found++;
      strIndex[0] = strIndex[1] + 1;
      strIndex[1] = (i == maxIndex) ? i + 1 : i;
    }
  }
  return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

Good luck!

Just to give you some insight what the problem with this code above may be, it is worth to go walk through the code "manually" step by step:

  • The while loop() will only be left if no characters available on Serial2.
  • As long as Serial2.available() > 0 the code reads each single character
  • and collects them in String repuesta unless it is a '\n'
  • If a '\n' was received the code waits for 1 second
  • If further data arrived at Serial2 within this second the while()-loop will go on adding the next characters to repuesta ...

In case that there is a time gap of more than 1 second between messages the code might work but it is not "fail-safe".

Hi! I delete / if was the problem but, seria no launch Here.

I try ==, equals, c.str()...

 if (Serial2.available()) {

    String tempString = "";
    String respuesta = "";
    while (Serial2.available() > 0) {
      char receivedChar = Serial2.read();
      if (receivedChar == '\n') {
        respuesta = tempString;
        tempString = "";
        Serial.println(respuesta);
        delay(1000);  // Print the received message in the Serial monitor
      } else {
        tempString += receivedChar;  // Append characters to the received message
      }
    }

    respuesta.remove(0, 1);
    Serial.println(respuesta);

    if (respuesta == "/sube_persiana") {

      //persiana
      knx.groupWriteBool("2/0/0", 0);
    }

    if (respuesta == "/baja_persiana") {

      //persiana
      knx.groupWriteBool("2/0/0", 1);
    }

    if (respuesta.equals("enciende_luz_dormitorio")) {
      //dormitorio
      Serial.println("Here");
      bool xd = true;
      knx.groupWriteBool("1/0/1", xd);
    }

    if (respuesta == "/apaga_luz_dormitorio") {
      //dormitorio
      Serial.println(respuesta);

      knx.groupWriteBool("1/0/1", 0);
    }

    if (respuesta == "/enciende_luz_salon") {

      //salon
      knx.groupWriteBool("1/0/0", 1);
    }

    if (respuesta == "/apaga_luz_salon") {

      //salon
      knx.groupWriteBool("1/0/0", 0);
    }
  }
}

Do you really need these long indentificators?

Maybe it’s worth using, for example, room codes? For example, dormitory is code 1, and baja_persiana is code 33?

After all, this is a computer program; using names that are understandable to humans is completely unnecessary.

The longer your messages, the more likely it is that they will not be received completely in one turn of the loop.

I know but look

String xddd = "/enciende_luz_dormitorio";
    Serial.println(respuesta.length());
    Serial.println(xddd.length());

13:39:26.050 -> /enciende_luz_dormitorio

13:39:27.077 -> 25

13:39:27.077 -> 24

Maybe one character invisible?

try this

char c = respuesta[respuesta.length() -1];
Serial.print("Charcode of the last char in respuesta: ");
Serial.println((uint8_t)c);