Receive data from two hardware serial ports

Hello, I am new to this platform, I wanted to ask a question, I am doing a project, in which I have two mega arduinos, which are connected serially, one as a master and the other as a slave, (Rx---19, Tx --18), the slave is sending information to the master, but I want to implement a sensor to an arduino mega (master) through another serial port (Rx---15, Tx---14), and my question is if I can receive data at the same time from the two serial ports, I want the information from the two serial ports to be seen in the serial window, so that I can later print them on an LCD.

Is it possible to do this, or is it not possible?

I appreciate your help in advance.

Strictly saying - no, because the Mega has only one core and can do only one thing in time.
But it seems to me that it is acceptable for your task if you read these ports one by one

Yes, it is possible, but you need to keep in mind Arduino doesn't have multithreading, and hardware buffers are limited to 1 byte (but there's a 64 bytes software buffer, internally updated via ISR). So any "the same time" isn't "same time" actually, but they're very quickly handled by Mega: except for very exceptional environment (e.g. high speed serial communications together with some hard interrupt handling/disabling) you can assume a "parallel" communication.

Thank you very much for answering, but if it is possible to do this, even if it is not exactly "at the same time", how could it be done, I would appreciate it if you can help me with this

Sinse pins 18 &19 belongs to Serial1 and pins 14 &15 to Serial3, so

char x = Serial1.read();  // read a byte from Serial1
...
char y = Serial3.read(); // read a byte from Serial3

1. A suggested hardware setup in Fig-1.


Figure-1:

2. Control Codes for Fig-1.
(1) Read data from MEGA-2 for 5-sec and show on SM1.
(2) Read data from Sensor for next 5-sec and show on SM1.
(3) Repeat from Step-(1).

Sorry, I do not receive anything with that code provided

Thanks for your help, I also have the hardware connected. but the code, I do not understand how to do it exactly.

Try the following sketch to read data by MEGA-1 from MEGA-2 and show on SM1.
Code for MEGA-1:

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial.println("Receiveing data from MEGA-2.");
}

void loop()
{
  byte n = Serial1.available();
  if (n != 0)
  {
    char y = Serial1.read();
    Serial.print(y);
  }
}

Code for MEGA-2:

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

void loop()
{
  Serial1.println("Hello!");
  delay(1000);
}

Check that the SM1 of MEGA-1 shows the message "Hello!" at 1-sec interval.

1 Like

thanks for the code, but my query was if I could process data in two hardware serial ports of an arduino mega (it is receiving information from another arduino mega by serial port), I also want to implement a sensor by serial port.

but when reading these two serial ports, I get errors, to be able to see it in the serial window.

please show your code and detail error output of compile process.

Please post your codes and the connection diagram among your devices.

Are sketches of post #39 working?

Well, this image shown below is the data that I am sending from the mega (slave) to the mega (master); in the mega master I receive that data, but when connecting another serial port in the arduino (master), for the distance sensor, I have errors. I want to obtain the data from the distance sensor in addition to the data that can be seen in the image.


I also upload the code to receive data and the programming of the distance sensor type LIAR

#include<Wire.h>




void getTFminiData(int* distance, int* strength) { //sensor distance TF mini Plus
  static char i = 0;
  char j = 0;
  int checksum = 0; 
  static int rx[9];
  if(Serial1.available()) {  
    rx[i] = Serial1.read();
    if(rx[0] != 0x59) {
      i = 0;
    } else if(i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if(i == 8) {
      for(j = 0; j < 8; j++) {
        checksum += rx[j];
      }
      if(rx[8] == (checksum % 256)) {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    } else {
      i++;
    } 
  }  
}


void setup() { 
  // Inicializar el LCD
  Serial.begin(115200);
  Serial3.begin(115200);
  Serial1.begin(115200);
   
  }
  
void loop() {
  
if (Serial3.available()){ //receive data from the arduino (slave)
    
     char as=Serial3.read();
  

    Serial.print(as);
      delay(5000);}
     int distance = 0;
  int strength = 0;

  getTFminiData(&distance, &strength);
  while(!distance) {
    getTFminiData(&distance, &strength);
    if(distance) {
    
      Serial.print(distance);
     delay(5000);
Serial.println();
      
    
}
      }
     
       
   


}

 
 
 

You said that your sensor is connected to pins 14 &15 - so to the Serial3, but in the code you try to read from Serial1
And please show what the error do you receive when try to read the sensor

I only receive the value of the sensor, but not the information coming from the other serial port.
is connected on port one currently, was trying the other ports

Sometimes clear description helps to understand the problem and then the solution becomes easier.

1. Let us call MEGA-1 (Sender) and NOT Master with which you have the distance sensor (type: LIAR?) is connected via Serial3 Port.

2. Let us call MEGA-2 (Receiver) and NOT Slave with which your Temp-Humidity-Aceler Sensor is connected. Is it I2C type sensor?

3. MEGA-1 and MEGA-2 are connected together via Serial1 Port. Is it correct?

4. Connect Only the distance sensor with MEGA-1 and check that it is working. Please, post the sketch and the output result shown on the Serial Monitor of MEGA-1.

5. Connect Temp-Hum-Aceler Sensor with MEGA-2. Connect MEGA-2 with MEGA-1. Check that they are working. Please, post the sketches for both MEGA-1 and MEGA-2 and also the output result on the Serial Monitor of MEGA-1.

  1. actually mega-1, a distance sensor is connected, type LIAR, that is, infrared, it is connected through the Serial3 port
  2. correct mega-2 is connected to an acceleration, luminosity, temperature-humidity sensor, these sensors are connected by I2C, and one is digital.
  3. Effectively Mega -1 and mega-2 are connected by serial port, but through a radio frequency module.
  4. is the sensor working correctly

void getTFminiData(int* distance, int* strength) {
  static char i = 0;
  char j = 0;
  int checksum = 0; 
  static int rx[9];
  if(Serial3.available()) {  
    rx[i] = Serial3.read();
    if(rx[0] != 0x59) {
      i = 0;
    } else if(i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if(i == 8) {
      for(j = 0; j < 8; j++) {
        checksum += rx[j];
      }
      if(rx[8] == (checksum % 256)) {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    } else {
      i++;
    } 
  }  
}

void setup() {
  Serial.begin(115200); 
  Serial3.begin(115200);
  
  //Serial1.begin(115200);
}

void loop() {
  int distance = 0;
  int strength = 0;

  getTFminiData(&distance, &strength);
  while(!distance) {
    getTFminiData(&distance, &strength);
    if(distance) {
      Serial.print(distance);
       //Serial1.print(distance);
      Serial.print("cm\t");
      Serial.print("strength: ");
      Serial.println(strength);
      
    delay(2000);
    }
  
    }
    }





  1. they are working correctly. mega 2 receives data from mega 1

mega 2----sensor temperature, accelera

#include<Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
int ADXLAddress= 0x53;
int Sensorluz= 0x23;
Adafruit_ADXL345_Unified accel=Adafruit_ADXL345_Unified();

#include <dht.h>
dht DHT;
#define DHT11_PIN 8

void setup() {
  
Serial.begin(115200);
if(!accel.begin()){
Serial.println("sensor inactive");
while(1);

}

sensor.begin();
}
void loop() {
 DHT.read11(DHT11_PIN);

  //TEMPER//
//temperatura para *
Serial.print("temperature ");
  Serial.println(DHT.temperature);
  


  //HUM//idity

   Serial.print("humidity ");
  Serial.println(DHT.humidity);
 
 
  delay(1000);
  
 
 

sensors_event_t event;
 accel.getEvent (&event);
Serial.print("Aceler ");
  Serial.println(event.acceleration.x); 
  

  delay(1000);
}

mega 1 ----sketch to receive data from mega -1

#include<Wire.h>


void setup() { 

  Serial.begin(9600);
  Serial3.begin(9600);
  
   
  }
  
void loop() {
  if (Serial3.available()){
    
     char as=Serial3.read();
   

    Serial.print(as);
   
  

 }

when connecting the two serial ports, that is
a connection port between arduinos
another connection port with the distance sensor
presents the error

1. Establish communication between MEGA-1, MEGA-2, and Temp-Hum-Aceler Sensor.

2. Upload the following sketch in MEGA-2. Your sketch is augmented with the codes to send data to MEGA-1 using Serial1 Port.
Sketch-1

#include<Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
int ADXLAddress = 0x53;
int Sensorluz = 0x23;
Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified();

#include <dht.h>
dht DHT;
#define DHT11_PIN 8

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  if (!accel.begin())
  {
    Serial.println("sensor inactive");
    while (1);
  }

  sensor.begin();
}

void loop()
{
  DHT.read11(DHT11_PIN);
  Serial.print("temperature ");
  float temp = DHT.temperature;
  Serial.println(temp, 2);

  Serial.print("humidity ");
  float hum = DHT.humidity;
  Serial.println(hum, 2);

  delay(1000);

  sensors_event_t event;
  accel.getEvent (&event);
  Serial.print("Aceler ");
  float aceler = event.acceleration.x;
  Serial.println(aceler, 2);
  //-------------------------------------
  Serial1.print(temp, 2);
  Serial1.print(',');
  Serial1.print(hum, 2);
  Serial1.print(',');
  Serial1.print(aceler, 2);
  Serial1.print('\n');
  delay(1000);
}

3. Upload the following sketch in MEGA-1 to receive Tem-Hum-Aceler data from MEGA-2 using Serial1 Port and show on it Serial Monitor.
Sketch-2

char myData[30] = {0};

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
}

void loop()
{
  byte n = Serial1.available();
  if ( n != 0)
  {
    byte m = Serial1.readBytesUntil('\n', myData, 30);
    myData[m] = '\0'; //null-byte is added
    Serial.println(myData);
    memset(myData, 0x00, 30);  //array reset to 0s
    Serial.println("=============================");
  }
}

4. Press RESET buttons of both MEGA.
5. Check that MEGA-1 shows Tem-Hum-Aceler data as they are coming from MEGA-1. Post the screen shot of MEGA-1.

6. After that I will show you how to combine distance codes with the codes/Sketch-2 that receives data from MEGA-1. Try the following combined sketch by uploading it into MEGA-1.
Sketch-3

void processA(); //forward declaration
void processB();

char myData[30] = {0};

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  Serial3.begin(115200);
}

void loop()
{
  processA();  //collect data from mEGA_1 and show
  delay(2000);
  Serial.println("==============================");
  processB();  //collect data from distance sensor and show
  delay(2000);
  Serial.println("==============================");
}

void processA()
{
  byte n = Serial1.available();
  if ( n != 0)
  {
    byte m = Serial1.readBytesUntil('\n', myData, 30);
    myData[m] = '\0'; //null-byte is added
    Serial.println(myData);
    memset(myData, 0x00, 30);  //array reset to 0s
  }
}

void processB()
{
  int distance = 0;
  int strength = 0;

  getTFminiData(&distance, &strength);
  while (!distance)
  {
    getTFminiData(&distance, &strength);
    if (distance)
    {
      Serial.print(distance);
      Serial.print("cm\t");
      Serial.print("strength: ");
      Serial.println(strength);
    }
  }
}

void getTFminiData(int* distance, int* strength)
{
  static char i = 0;
  char j = 0;
  int checksum = 0;
  static int rx[9];

  if (Serial3.available())
  {
    rx[i] = Serial3.read();
    if (rx[0] != 0x59)
    {
      i = 0;
    }
    else if (i == 1 && rx[1] != 0x59)
    {
      i = 0;
    }
    else if (i == 8)
    {
      for (j = 0; j < 8; j++)
      {
        checksum += rx[j];
      }
      if (rx[8] == (checksum % 256))
      {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    }
    else
    {
      i++;
    }
  }
}

All the points I have made, and all the numerals that you have described to me work very well. except for the last "6", in which the information is already received from both the arduino mega 2, and also the information from the distance sensor. But at first it starts to work fine, but then I start to lose data, and there start to be certain mixtures of numbers and letters, I suppose that instead of doing "delay" you should do "millis", or you don't recommend me.

But thank you very much, from the bottom of my heart, thank you for your time spent and for helping me with my project.

Have you tried using millis() function to insert delay? Is the issue sorted out?
Try the following sketch where I have used TC1 to generate time delay on interrupt basis instead of millis().

void processA(); //forward declaration
void processB();

char myData[30] = {0};
volatile bool runTimeIsOver = false;
volatile int irqCounter = 0;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  Serial3.begin(115200);
  //-------------------------
  TCCR1A = 0x00;
  TCCR1B = 0x00;
  TCNT1 = 3036;  //for 4-sec time dealt with 1024 prescaler
  TCCR1B = 0x05;
  bitSet(TIMSK1, TOIE1);
}

void loop()
{
  processA();  //collect 4 data frame in 4-sec from MEGA-1 and show
  Serial.println("==============================");
  processB();  //collect 4 data frame in 4-sec from distance sensor and show
  Serial.println("==============================");
}

void processA()
{
  while (runTimeIsOver != true)//4-sec delay
  {
    byte n = Serial1.available();
    if ( n != 0)
    {
      byte m = Serial1.readBytesUntil('\n', myData, 30);
      myData[m] = '\0'; //null-byte is added
      Serial.println(myData);
      memset(myData, 0x00, 30);  //array reset to 0s
    }
    delay(1000);
  }
  runTimeIsOver = false;
}

void processB()
{
  while (runTimeIsOver != true) //4-sec delay
  {
    int distance = 0;
    int strength = 0;
    getTFminiData(&distance, &strength);
    while (!distance)
    {
      getTFminiData(&distance, &strength);
      if (distance)
      {
        Serial.print(distance);
        Serial.print("cm\t");
        Serial.print("strength: ");
        Serial.println(strength);
        delay(1000);
      }
    }
  }
  runTimeIsOver = false;
}

void getTFminiData(int* distance, int* strength)
{
  static char i = 0;
  char j = 0;
  int checksum = 0;
  static int rx[9];

  if (Serial3.available())
  {
    rx[i] = Serial3.read();
    if (rx[0] != 0x59)
    {
      i = 0;
    }
    else if (i == 1 && rx[1] != 0x59)
    {
      i = 0;
    }
    else if (i == 8)
    {
      for (j = 0; j < 8; j++)
      {
        checksum += rx[j];
      }
      if (rx[8] == (checksum % 256))
      {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    }
    else
    {
      i++;
    }
  }
}

ISR(TIMER1_OVF_vect)
{
  TCNT1 = 3036; //4-sec time delay parameter
  irqCounter++;
  if (irqCounter == 1)//4-sec delay
  {
    runTimeIsOver = true;
    irqCounter = 0;
  }
}