XBee-Ardiono Communication TX,RX

hello forum

I have a big problem Arduino-XBee.

One of my code for xbee/arduino is to control a relay and another one to control voltage and current sensors.
The problem is the following:
When the code of the relay TX,RX communication connections is as follows:

*RELAY
++EMOSIR++
XBee==Arduino
RX==RX
TX==TX

++RECEIVER++
XBee==Arduino
RX==TX
TX==RX

When loading the code of the sonsores is the following,

SENSORS*
++SENSOR ++
XBee==Arduino
RX==RX
TX==TX

++RECEIVER++
XBee==Arduino
RX==RX
TX==TX

The problem is that when joining the programs they don't work together, I would like to make the programs work together.
I upload the cogio in case anyone has a solution.

//////SENSOR/////////

int dato;

#include <Wire.h>

   /* 1 BLOQUE General */

    int decimalPrecision = 2;                     /*lugares decimales para todos los valores que se muestran en el monitor en serie*/
    
    /* 1.1 VOLTAJE 1 */
    
    int VoltageAnalogInputPin = A0;             /*Qué pin medir el valor del voltaje*/ 
    float voltageSampleRead  = 0;               /*Leer el valor de una muestra en analógico, incluido voltageOffset1*/
    float voltageLastSample  = 0;               /*Contar el tiempo de cada muestra. Técnicamente se toma 1 milisegundo 1 muestra*/
    float voltageSampleSum   = 0;               /*Acumulación de lecturas de muestra*/
    float voltageSampleCount = 0;               /*Contar el número de muestra*/
    float voltageMean ;                         /*Calcular el valor promedio de todas las muestras, en valores analógicos*/
    float RMSVoltageMean ;                      /*Calcular el valor promedio de todas las muestras, en valores analogicos*/
    float adjustRMSVoltageMean;
    float FinalRMSVoltage;                      /*Valor de tensión final con valor de compensación*/


    
    /* 1.1 - VOLTAJE 1 */
    
          float voltageOffset1 =0.00 ;          /*Para compensar la desviación y la precisión. Compensa cualquier corriente falsa cuando no funciona ninguna corriente*/
                                                                                                                                                       
          float voltageOffset2 = 0.00;          /*Valor demasiado compensado debido a un error de cálculo del cuadrado y la raíz cuadrada*/
          


    /* 1.1 CORRIENTE 1 */

    int currentOffset1  = 0;                      /* introducir valor de compensación*/
    int currentOffset2  = -2;                     /* introducir valor de compensación*/
    int CurrentAnalogInputPin = A8;               /* Qué pin medira el valor actual*/
    float mVperAmpValue = 100;                     /* Se utiliza el módulo de corriente ACS712: para el módulo de 5A clave en 185, para el módulo de 20A clave en 100, para el módulo de 30A clave en 66*/
                                                  /* Si usa un transformador de corriente de "efecto Hall", ingrese el valor usando esta fórmula: mVperAmp = rango de voltaje máximo (en milivoltios) / corriente nominal de CT*/
                                                  /* Por ejemplo, un transformador de corriente de efecto Hall de 20 A clasificado en 20 A, 2,5 V +/- 0,625 V, mV por amperio será 625 mV / 20 A = 31,25 mV/A*/
    float currentSampleRead  = 0;                 /* Para leer el valor de una muestra */
    float currentLastSample  = 0;                 /* Para contar el tiempo de cada muestra. Técnicamente se toma 1 milisegundo 1 muestra*/
    float currentSampleSum   = 0;                 /* Acumulación de lecturas de muestra */
    float currentSampleCount = 0;                 /* Para contar el número de muestra */
    float currentMean ;                           /* Para calcular el valor promedio de todas las muestras*/ 
    float RMSCurrentMean =0 ;                     /* Square roof de currentMean*/
    float FinalRMSCurrent ;                       /* La lectura actual RMS final*/

    /* 1.2 - VOLTAJE 2 */
    
    int VoltageAnalogInputPin2 = A2;             /*Qué pin medir el valor del voltaje*/ 
    float voltageSampleRead2  = 0;               /*Leer el valor de una muestra en analógico, incluido voltageOffset1*/
    float voltageLastSample2  = 0;               /*Contar el tiempo de cada muestra. Técnicamente se toma 1 milisegundo 1 muestra*/
    float voltageSampleSum2   = 0;               /*Acumulación de lecturas de muestra*/
    float voltageSampleCount2 = 0;               /*Contar el número de muestra*/
    float voltageMean2 ;                         /*Calcular el valor promedio de todas las muestras, en valores analógicos*/
    float RMSVoltageMean2 ;                      /*Calcular el valor promedio de todas las muestras, en valores analogicos*/
    float adjustRMSVoltageMean2;
    float FinalRMSVoltage2;                      /*Valor de tensión final con valor de compensación*/

void setup() /*Códigos para ejecutar una vez en monitor serie */

{

    /* 2 BLOQUE Monitor serie */
    
    Serial.begin(9600);                           /* Para mostrar lecturas en Serial Monitor a velocidades de 9600 baudios */
    pinMode(A15,OUTPUT);


    Wire.begin();
    Wire.beginTransmission(0x68);
    Wire.write(0x68);
    Wire.write(0x00);
    Wire.endTransmission(true);

}

/* 3 BLOQUE Calculo de corriente */

void loop()
{
if(Serial.available()>0)
{
dato=Serial.read();
if(dato == 'Y')
{
digitalWrite(A15,HIGH);}
if(dato=='Z')
{
digitalWrite(A15,LOW);
}
}
Wire.beginTransmission(0x68);
Wire.write(0x41);
Wire.endTransmission(false);
Wire.requestFrom(0x68,2,true);

    /* 3.1- AC Voltage Measurement */
    if(micros() >= voltageLastSample + 3000 )                                                                      /*cada 0,2 milisegundos tomando 1 lectura*/
      {
        voltageSampleRead = (analogRead(VoltageAnalogInputPin)- 512)+ voltageOffset1;                             /* lea el valor de muestra, incluido el valor de compensación*/
        voltageSampleSum = voltageSampleSum + sq(voltageSampleRead) ;                                             /* acumular valores analógicos totales para cada lectura de muestra*/
        
        voltageSampleCount = voltageSampleCount + 1;                                                              /* para pasar al siguiente conteo siguiente*/
        voltageLastSample = micros() ;                                                                            /*restablecer el tiempo de nuevo para que el próximo ciclo pueda comenzar*/
      }
    
    if(voltageSampleCount == 3000)                                                                                /* después de 4000 cuentas o 800 milisegundos (0,8 segundos), haga el cálculo y muestre el valor*/
      {
        voltageMean = voltageSampleSum/voltageSampleCount;                                                        /* calcular el valor promedio de todas las lecturas de muestra tomadas*/
        RMSVoltageMean = (sqrt(voltageMean))*1.5;                                                                 /*El valor X 1.5 significa la relación hacia la amplificación del módulo*/     
        adjustRMSVoltageMean = RMSVoltageMean + voltageOffset2;                                                   /* raíz cuadrada del valor promedio, incluido el valor de compensación*/                                                                                                                                                     /* square root of the average value*/                                                                                                             
        FinalRMSVoltage = RMSVoltageMean + voltageOffset2;                                                        /* este es el voltaje RMS final*/
        if(FinalRMSVoltage <= 2.5)                                                                                /* para eliminar cualquier posible valor fantasma*/
        {FinalRMSVoltage = 0;}
        Serial.print("Voltaje 1 RMS: ");
        Serial.print(FinalRMSVoltage,decimalPrecision);
        Serial.println(" V1 ");
        voltageSampleSum =0;                                                                                      /* Restablecer los valores de muestra acumulados para el siguiente ciclo */
        voltageSampleCount=0;                                                                                     /* Restablecer el número de muestras para el siguiente ciclo*/
      }
      
    /* 3.1 CALCULO CORRIENTE UNO */
    
    if(millis() >= currentLastSample + 1)                                                     /* Cada 1 milisegundo tomando 1 lectura */
      {
        currentSampleRead = analogRead(CurrentAnalogInputPin)-512 + currentOffset1;           /* Leer el valor de la muestra */
        currentSampleSum = currentSampleSum + sq(currentSampleRead) ;                         /* Acumular valor con lecturas de muestra anteriores*/
        currentSampleCount = currentSampleCount + 1;                                          /* Para pasar al siguiente conteo siguiente */
        currentLastSample = millis();                                                         /* Para restablecer el tiempo nuevamente para que el próximo ciclo pueda comenzar de nuevo*/ 
      }
    
    if(currentSampleCount == 6001)                                                            /* Después de 1000 cuentas o 1000 milisegundos (1 segundo), haga el cálculo y muestre el valor*/
      {       
        currentMean = currentSampleSum/currentSampleCount;                                    /* Calcular el valor promedio de todas las lecturas de muestra tomadas*/
        RMSCurrentMean = sqrt(currentMean)+currentOffset2 ;                                   /* Raíz cuadrada del valor promedio*/
        FinalRMSCurrent = (((RMSCurrentMean /1024) *5000) /mVperAmpValue);                    /* Calcula el valor RMS de la corriente final*/


        currentSampleSum =0;                                                                  /* Para restablecer los valores de muestra acumulados para el siguiente ciclo */
        currentSampleCount=0;                                                                 /* para restablecer el número de muestras para el próximo ciclo */

        Serial.print("Corriente 1: ");
        Serial.print(FinalRMSCurrent,decimalPrecision);
        Serial.println(" A1  ");
      }

}

/////RECEPTOR///////

char data;
String entradaSerial = ""; // a String to hold incoming data
bool entradaCompleta = false; // whether the string is complete

void setup() {
Serial.begin(9600);
pinMode(A15, OUTPUT);

}

void loop() {

if (entradaCompleta) {
if (entradaSerial == "Y /n") {
digitalWrite(A15, LOW);

}

else if (entradaSerial == "Z /n") {
  digitalWrite(A15, HIGH);
  
}

    entradaSerial = "";
entradaCompleta = false; 

}
if(Serial.available()>0){
data = Serial.read();
Serial.print(data);
}

}

could you reformat your code using code tags </> so it is readable
upload a schemtic showing the wiring

I will give you a hint. When you talk and somebody else is talking communication does not happen. If you talk and the other person listens it goes very well. Serial communications are like that in electronics. A transmitter (TX) can send data all day and unless a receiver (RX) is there nothing will be communicated. TX goes to RX and RX goes to TX any other way does not work. Post a schematic, not a frizzy picture of what you have wired showing all power and ground connections including power supplies. Also post links to "Technical information" on the hardware items. This will get you your answer much faster and help us see what you have.


with this emitter only the sensors work, for the relay to work I have to invert the orange and purple wires of the receiver

can you give details of the specific XBee module, e.g. link to website?
did you do a simple test with just the XBees communicating with each other?

you appear to be using Mega pins 0 (RX0) and 1(TX0) to communicate with the XBee modules
why not use one of the Mega hardware serial ports, e.g. e.g.Serial1 pins 18 and 19
this leaves RX0 and TX0 free to communicate with the IDE serial monitor?

I cannot read your frizzy picture!