Same program from Arduino Uno R4 Wifi on Arduino Mega 2560

Hello,

I'm trying to change from Arduino Uno R4 Wifi to an Arduino Mega 2560, as i need the extra serial ports for a sonar which is working only on hardware serial, and the same program that runs on Uno is not working on Mega, although i made the same connections on Serial, meaning RX0 and TX0.

The program requests data from Pixhawk flight controller, thru Serial, by sending a heartbeat message and receiving the data requested, in this particular program i am requesting unix time, latitude, longitude, elevation, roll, pitch, yaw, which are being received correctly as i'm connected to the Pixhawk with Mission Planner and reading the values (same in the planner as in what i'm receiving as in the uploaded screenshot, mind you I was inside and the unix time and position are not being correct).

This screenshot is from the Mega

Below you can see the code:

/*  MAVLInk_DroneLights
    by Juan Pedro López
*/
// In case we need a second serial port for debugging
#define SOFT_SERIAL_DEBUGGING   // Comment this line if no serial debugging is needed
#ifdef SOFT_SERIAL_DEBUGGING

// Library to use serial debugging with a second board
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include "SoftwareSerial.h"
#include "ping1d.h"
#include <Int64String.h>


#define RxPin0 1
#define TxPin0 0



int request = 0;
int receive = 0;

const int chipSelect = 53;
float distantaMetri;

SoftwareSerial pxSerial = SoftwareSerial(RxPin0, TxPin0);  // RX, TX || UNO - PX4

#endif

#include "mavlink.h"
//#include "common/mavlink_msg_request_data_stream.h"
static const uint8_t ledPin = 13;

// Mavlink variables
unsigned long previousMillisMAVLink = 0;     // will store last time MAVLink was transmitted and listened
unsigned long next_interval_MAVLink = 100;  // next interval to count
const int num_hbs = 10;                      // # of heartbeats to wait before activating STREAMS from Pixhawk. 60 = one minute.
int num_hbs_pasados = num_hbs;

float mesajRoll;
float mesajPitch;
float mesajYaw;

int32_t gpsLat;
int32_t gpsLong;
int32_t gpsElev;
uint8_t gpsSolution;

uint64_t timeUNIX;

String dataString = "";
String timeUNIXstring = "";

void setup() {

pinMode(RxPin0, INPUT);
pinMode(TxPin0, OUTPUT);

  // MAVLink interface start
  // Serial.begin(57600);

  // [DEB] Soft serial port start
  Serial.begin(115200);
  pxSerial.begin(115200);
  Serial.println("MAVLink starting.");

  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
/*if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1)
      ;
  }
*/
  Serial.println("card initialized.");
  //inceput scrie capat fisier~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  File dataFile = SD.open("sonar.txt", FILE_WRITE);
  dataFile.println("unix_time,lat,long,elev,roll,pitch,yaw,distanta");
  dataFile.close();
  //sfarsit scrie capat fisier~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // sfarsit setari card SD ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// PANA AICI E OK MOMENTAN
}

void loop() {



  String dataString = "";

  // MAVLink
  /* The default UART header for your MCU */
  int sysid = 1;                   ///< ID 20 for this airplane. 1 PX, 255 ground station
  int compid = 158;                ///< The component sending the message
  int type = MAV_TYPE_QUADROTOR;   ///< This system is an airplane / fixed wing

  // Define the system type, in this case an airplane -> on-board controller
  // uint8_t system_type = MAV_TYPE_FIXED_WING;
  uint8_t system_type = MAV_TYPE_GENERIC;
  uint8_t autopilot_type = MAV_AUTOPILOT_INVALID;

  uint8_t system_mode = MAV_MODE_PREFLIGHT; ///< Booting up
  uint32_t custom_mode = 0;                 ///< Custom mode, can be defined by user/adopter
  uint8_t system_state = MAV_STATE_STANDBY; ///< System ready for flight
  // Initialize the required buffers
  mavlink_message_t msg;
  uint8_t buf[MAVLINK_MAX_PACKET_LEN];

  // Pack the message
  //mavlink_msg_heartbeat_pack(sysid,compid, &msg, type, autopilot_type, system_mode, custom_mode, system_state);
  mavlink_msg_heartbeat_pack(1, 0, &msg, type, autopilot_type, system_mode, custom_mode, system_state);

  // Copy the message to the send buffer
  uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);

  // Send the message with the standard UART send function
  // uart0_send might be named differently depending on
  // the individual microcontroller / library in use.
  unsigned long currentMillisMAVLink = millis();
  if (currentMillisMAVLink - previousMillisMAVLink >= next_interval_MAVLink) {
    previousMillisMAVLink = currentMillisMAVLink;

#ifdef SOFT_SERIAL_DEBUGGING
    pxSerial.write(buf, len);
  //  Serial.println("Ardu HB");
#else
    Serial.write(buf, len);
#endif

    //Mav_Request_Data();
    num_hbs_pasados++;

  }

  // Check reception buffer

comm_receive();

//Serial.println(timeUNIX);
//Serial.println(gpsLat);
//Serial.println(gpsLong);
//Serial.println(gpsElev);
//Serial.println(gpsSolution);
//Serial.println(mesajRoll,10);
//Serial.println(mesajPitch,10);
//Serial.println(mesajYaw,10);

timeUNIXstring = int64String(timeUNIX);
 
 dataString = timeUNIXstring + "," + String(gpsLat) + "," + String(gpsLong) + "," + String(gpsElev) + ","  + String(mesajRoll,10) + "," + String(mesajPitch,10) + "," + String(mesajYaw,10) + ","; // + String(distantaMetri);

Serial.println(dataString);


if (gpsSolution > 3) {
// INCEPUT PARTE DE SCRIS PE CARD SD
 // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("sonar.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("Eroare fisier sonar.txt");
  }
  // SFARSIT PARTE DE SCRIS PE CARD SD
  // Toggle the LED to show that the program is running
  digitalWrite(ledPin, !digitalRead(ledPin));
}
  delay(100);
} // SFARSIT LOOP

void Mav_Request_Data()
{

  request = request + 1;

  mavlink_message_t msg;
  uint8_t buf[MAVLINK_MAX_PACKET_LEN];


  // STREAMS that can be requested
  /*
     Definitions are in common.h: enum MAV_DATA_STREAM

     MAV_DATA_STREAM_ALL=0, // Enable all data streams
     MAV_DATA_STREAM_RAW_SENSORS=1, /* Enable IMU_RAW, GPS_RAW, GPS_STATUS packets.
     MAV_DATA_STREAM_EXTENDED_STATUS=2, /* Enable GPS_STATUS, CONTROL_STATUS, AUX_STATUS
     MAV_DATA_STREAM_RC_CHANNELS=3, /* Enable RC_CHANNELS_SCALED, RC_CHANNELS_RAW, SERVO_OUTPUT_RAW
     MAV_DATA_STREAM_RAW_CONTROLLER=4, /* Enable ATTITUDE_CONTROLLER_OUTPUT, POSITION_CONTROLLER_OUTPUT, NAV_CONTROLLER_OUTPUT.
     MAV_DATA_STREAM_POSITION=6, /* Enable LOCAL_POSITION, GLOBAL_POSITION/GLOBAL_POSITION_INT messages.
     MAV_DATA_STREAM_EXTRA1=10, /* Dependent on the autopilot
     MAV_DATA_STREAM_EXTRA2=11, /* Dependent on the autopilot
     MAV_DATA_STREAM_EXTRA3=12, /* Dependent on the autopilot
     MAV_DATA_STREAM_ENUM_END=13,

     Data in PixHawk available in:
      - Battery, amperage and voltage (SYS_STATUS) in MAV_DATA_STREAM_EXTENDED_STATUS
      - Gyro info (IMU_SCALED) in MAV_DATA_STREAM_EXTRA1
  */

  // To be setup according to the needed information to be requested from the Pixhawk
  const int  maxStreams = 3;
  const uint8_t MAVStreams[maxStreams] = {MAV_DATA_STREAM_EXTENDED_STATUS, MAV_DATA_STREAM_POSITION, MAV_DATA_STREAM_EXTRA1};
  const uint16_t MAVRates[maxStreams] = {0x10, 0x10, 0x10};


  for (int i = 0; i < maxStreams; i++) {
    mavlink_msg_request_data_stream_pack(2, 200, &msg, 1, 0, MAVStreams[i], MAVRates[i], 1);
    uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
#ifdef SOFT_SERIAL_DEBUGGING
    pxSerial.write(buf, len);
#else
    Serial.write(buf, len);
#endif
  }

}

void comm_receive() {

  receive = receive + 1;

  mavlink_message_t msg;
  mavlink_status_t status;

  #ifdef SOFT_SERIAL_DEBUGGING
  while(pxSerial.available()>0) {
    uint8_t c = pxSerial.read();
#else
  while(Serial.available()>0) {
    uint8_t c = Serial.read();
#endif

    // Try to get a new message
    if (mavlink_parse_char(MAVLINK_COMM_0, c, &msg, &status)) {

      // Handle message
      switch (msg.msgid) {
        case MAVLINK_MSG_ID_HEARTBEAT:  // #0: Heartbeat
          {
            // E.g. read GCS heartbeat and go into
            // comm lost mode if timer times out
          }
          break;
        
        case MAVLINK_MSG_ID_ATTITUDE:  // #30
          {
            /* Message decoding: PRIMITIVE
                  mavlink_msg_attitude_decode(const mavlink_message_t* msg, mavlink_attitude_t* attitude)
            */
            mavlink_attitude_t attitude;
            mavlink_msg_attitude_decode(&msg, &attitude);
            mesajRoll = attitude.roll;
            mesajPitch = attitude.pitch;
            mesajYaw = attitude.yaw;
          }
          break;

          case MAVLINK_MSG_ID_GPS_RAW_INT:  // #30
          {
            /* Message decoding: PRIMITIVE
                  mavlink_msg_attitude_decode(const mavlink_message_t* msg, mavlink_attitude_t* attitude)
            */
            mavlink_gps_raw_int_t gps_raw_int;
            mavlink_msg_gps_raw_int_decode(&msg, &gps_raw_int);
              gpsLat = gps_raw_int.lat; // seteaza variabila globala cu latitudine GPS Pixhawk
              gpsLong = gps_raw_int.lon; // seteaza variabila globala cu longitudine GPS Pixhawk 
              gpsElev = gps_raw_int.alt; // seteaza variabila globala cu altitudine GPS Pixhawk
              gpsSolution = gps_raw_int.satellites_visible; // seteaza variabila globala cu numar sateliti
          }

          break;

          case MAVLINK_MSG_ID_SYSTEM_TIME:  // #30
          {

            mavlink_system_time_t system_time;
            mavlink_msg_system_time_decode(&msg, &system_time);
            timeUNIX = system_time.time_unix_usec; // seteaza variabila globala cu timp unix 
          }

          break;

      }
    }
  }
}

The code above is stitched together from MAVLInk_DroneLights by Juan Pedro López and the SDcard library (which is commented as i keep switching between boards to see if something changes)

I tried to change from Serial0 to Serial1, Serial2, together with changing the cables on their respective pins and changing where there is Serial.write(), Serial.available() and Serial.read() to Serial1.write(), Serial1.available() and Serial1.read() ....

I don't know what exactly i'm missing.

Please be kind to me as i only started with Arduino, and implicitly C language only a month ago. I have some programming experience with Vlisp.

Thank you.

How many serial ports do you need?

Do not run software serial on pins 0 & 1, those are hardware serial pins (Serial on the Mega, Serial1 on the R4).

Hello,

I need 2 serial ports, 1 for Pixhawk and 1 for the Ping sonar (is not implemented in the code yet).

As it goes about Software serial, that is used for debugging, as i understand from the code. I tried to remove software serial from the code on the Uno, and it doesn't work anymore.

The uploaded code works on Uno as is (with Software serial on pins 0 and 1).

As soon as i upload the same code to Mega is giving me only 0 across the row.

You cannot run software serial on pins 0 & 1 on a Mega, those are used for Serial, which is connectef to the serial-to-usb converter. On the R4 those pins are hardware serial port Serial1, so can be used for software serial when Serial1 is not in use, but does not make much sense to do so.

Removed the software serial, and now it doesn't run on R4 either.

Regarding the R4 ports, from reading about Serial, is that is not available for reading when is connected to PC, and i need to see data coming in.

Commented the code related to software serial (did i missed something?)

/*  MAVLInk_DroneLights
    by Juan Pedro López
*/
// In case we need a second serial port for debugging
//#define SOFT_SERIAL_DEBUGGING   // Comment this line if no serial debugging is needed
//#ifdef SOFT_SERIAL_DEBUGGING

// Library to use serial debugging with a second board
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include "SoftwareSerial.h"
#include "ping1d.h"
#include <Int64String.h>


#define RxPin0 1
#define TxPin0 0



int request = 0;
int receive = 0;

const int chipSelect = 53;
float distantaMetri;

//SoftwareSerial pxSerial = SoftwareSerial(RxPin0, TxPin0);  // RX, TX || UNO - PX4

//#endif

#include "mavlink.h"
//#include "common/mavlink_msg_request_data_stream.h"
static const uint8_t ledPin = 13;

// Mavlink variables
unsigned long previousMillisMAVLink = 0;     // will store last time MAVLink was transmitted and listened
unsigned long next_interval_MAVLink = 100;  // next interval to count
const int num_hbs = 10;                      // # of heartbeats to wait before activating STREAMS from Pixhawk. 60 = one minute.
int num_hbs_pasados = num_hbs;

float mesajRoll;
float mesajPitch;
float mesajYaw;

int32_t gpsLat;
int32_t gpsLong;
int32_t gpsElev;
uint8_t gpsSolution;

uint64_t timeUNIX;

String dataString = "";
String timeUNIXstring = "";

void setup() {

pinMode(RxPin0, INPUT);
pinMode(TxPin0, OUTPUT);

  // MAVLink interface start
  // Serial.begin(57600);

  // [DEB] Soft serial port start
  Serial.begin(115200);
//  pxSerial.begin(115200);
  Serial.println("MAVLink starting.");

  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
/*if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1)
      ;
  }
*/
  Serial.println("card initialized.");
  //inceput scrie capat fisier~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  File dataFile = SD.open("sonar.txt", FILE_WRITE);
  dataFile.println("unix_time,lat,long,elev,roll,pitch,yaw,distanta");
  dataFile.close();
  //sfarsit scrie capat fisier~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // sfarsit setari card SD ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// PANA AICI E OK MOMENTAN
}

void loop() {



  String dataString = "";

  // MAVLink
  /* The default UART header for your MCU */
  int sysid = 1;                   ///< ID 20 for this airplane. 1 PX, 255 ground station
  int compid = 158;                ///< The component sending the message
  int type = MAV_TYPE_QUADROTOR;   ///< This system is an airplane / fixed wing

  // Define the system type, in this case an airplane -> on-board controller
  // uint8_t system_type = MAV_TYPE_FIXED_WING;
  uint8_t system_type = MAV_TYPE_GENERIC;
  uint8_t autopilot_type = MAV_AUTOPILOT_INVALID;

  uint8_t system_mode = MAV_MODE_PREFLIGHT; ///< Booting up
  uint32_t custom_mode = 0;                 ///< Custom mode, can be defined by user/adopter
  uint8_t system_state = MAV_STATE_STANDBY; ///< System ready for flight
  // Initialize the required buffers
  mavlink_message_t msg;
  uint8_t buf[MAVLINK_MAX_PACKET_LEN];

  // Pack the message
  //mavlink_msg_heartbeat_pack(sysid,compid, &msg, type, autopilot_type, system_mode, custom_mode, system_state);
  mavlink_msg_heartbeat_pack(1, 0, &msg, type, autopilot_type, system_mode, custom_mode, system_state);

  // Copy the message to the send buffer
  uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);

  // Send the message with the standard UART send function
  // uart0_send might be named differently depending on
  // the individual microcontroller / library in use.
  unsigned long currentMillisMAVLink = millis();
  if (currentMillisMAVLink - previousMillisMAVLink >= next_interval_MAVLink) {
    previousMillisMAVLink = currentMillisMAVLink;

//#ifdef SOFT_SERIAL_DEBUGGING
//    pxSerial.write(buf, len);
  //  Serial.println("Ardu HB");
//
    Serial.write(buf, len);
//#endif

    //Mav_Request_Data();
    num_hbs_pasados++;

  }

  // Check reception buffer

comm_receive();

//Serial.println(timeUNIX);
//Serial.println(gpsLat);
//Serial.println(gpsLong);
//Serial.println(gpsElev);
//Serial.println(gpsSolution);
//Serial.println(mesajRoll,10);
//Serial.println(mesajPitch,10);
//Serial.println(mesajYaw,10);

timeUNIXstring = int64String(timeUNIX);
 
 dataString = timeUNIXstring + "," + String(gpsLat) + "," + String(gpsLong) + "," + String(gpsElev) + ","  + String(mesajRoll,10) + "," + String(mesajPitch,10) + "," + String(mesajYaw,10) + ","; // + String(distantaMetri);

Serial.println(dataString);


if (gpsSolution > 3) {
// INCEPUT PARTE DE SCRIS PE CARD SD
 // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("sonar.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("Eroare fisier sonar.txt");
  }
  // SFARSIT PARTE DE SCRIS PE CARD SD
  // Toggle the LED to show that the program is running
  digitalWrite(ledPin, !digitalRead(ledPin));
}
  delay(100);
} // SFARSIT LOOP

void Mav_Request_Data()
{

  request = request + 1;

  mavlink_message_t msg;
  uint8_t buf[MAVLINK_MAX_PACKET_LEN];


  // STREAMS that can be requested
  /*
     Definitions are in common.h: enum MAV_DATA_STREAM

     MAV_DATA_STREAM_ALL=0, // Enable all data streams
     MAV_DATA_STREAM_RAW_SENSORS=1, /* Enable IMU_RAW, GPS_RAW, GPS_STATUS packets.
     MAV_DATA_STREAM_EXTENDED_STATUS=2, /* Enable GPS_STATUS, CONTROL_STATUS, AUX_STATUS
     MAV_DATA_STREAM_RC_CHANNELS=3, /* Enable RC_CHANNELS_SCALED, RC_CHANNELS_RAW, SERVO_OUTPUT_RAW
     MAV_DATA_STREAM_RAW_CONTROLLER=4, /* Enable ATTITUDE_CONTROLLER_OUTPUT, POSITION_CONTROLLER_OUTPUT, NAV_CONTROLLER_OUTPUT.
     MAV_DATA_STREAM_POSITION=6, /* Enable LOCAL_POSITION, GLOBAL_POSITION/GLOBAL_POSITION_INT messages.
     MAV_DATA_STREAM_EXTRA1=10, /* Dependent on the autopilot
     MAV_DATA_STREAM_EXTRA2=11, /* Dependent on the autopilot
     MAV_DATA_STREAM_EXTRA3=12, /* Dependent on the autopilot
     MAV_DATA_STREAM_ENUM_END=13,

     Data in PixHawk available in:
      - Battery, amperage and voltage (SYS_STATUS) in MAV_DATA_STREAM_EXTENDED_STATUS
      - Gyro info (IMU_SCALED) in MAV_DATA_STREAM_EXTRA1
  */

  // To be setup according to the needed information to be requested from the Pixhawk
  const int  maxStreams = 3;
  const uint8_t MAVStreams[maxStreams] = {MAV_DATA_STREAM_EXTENDED_STATUS, MAV_DATA_STREAM_POSITION, MAV_DATA_STREAM_EXTRA1};
  const uint16_t MAVRates[maxStreams] = {0x10, 0x10, 0x10};


  for (int i = 0; i < maxStreams; i++) {
    mavlink_msg_request_data_stream_pack(2, 200, &msg, 1, 0, MAVStreams[i], MAVRates[i], 1);
    uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
//#ifdef SOFT_SERIAL_DEBUGGING
//    pxSerial.write(buf, len);
//#else
    Serial.write(buf, len);
//#endif
  }

}

void comm_receive() {

  receive = receive + 1;

  mavlink_message_t msg;
  mavlink_status_t status;

//  #ifdef SOFT_SERIAL_DEBUGGING
//  while(pxSerial.available()>0) {
//    uint8_t c = pxSerial.read();
//#else
  while(Serial.available()>0) {
    uint8_t c = Serial.read();
//#endif

    // Try to get a new message
    if (mavlink_parse_char(MAVLINK_COMM_0, c, &msg, &status)) {

      // Handle message
      switch (msg.msgid) {
        case MAVLINK_MSG_ID_HEARTBEAT:  // #0: Heartbeat
          {
            // E.g. read GCS heartbeat and go into
            // comm lost mode if timer times out
          }
          break;
        
        case MAVLINK_MSG_ID_ATTITUDE:  // #30
          {
            /* Message decoding: PRIMITIVE
                  mavlink_msg_attitude_decode(const mavlink_message_t* msg, mavlink_attitude_t* attitude)
            */
            mavlink_attitude_t attitude;
            mavlink_msg_attitude_decode(&msg, &attitude);
            mesajRoll = attitude.roll;
            mesajPitch = attitude.pitch;
            mesajYaw = attitude.yaw;
          }
          break;

          case MAVLINK_MSG_ID_GPS_RAW_INT:  // #30
          {
            /* Message decoding: PRIMITIVE
                  mavlink_msg_attitude_decode(const mavlink_message_t* msg, mavlink_attitude_t* attitude)
            */
            mavlink_gps_raw_int_t gps_raw_int;
            mavlink_msg_gps_raw_int_decode(&msg, &gps_raw_int);
              gpsLat = gps_raw_int.lat; // seteaza variabila globala cu latitudine GPS Pixhawk
              gpsLong = gps_raw_int.lon; // seteaza variabila globala cu longitudine GPS Pixhawk 
              gpsElev = gps_raw_int.alt; // seteaza variabila globala cu altitudine GPS Pixhawk
              gpsSolution = gps_raw_int.satellites_visible; // seteaza variabila globala cu numar sateliti
          }

          break;

          case MAVLINK_MSG_ID_SYSTEM_TIME:  // #30
          {

            mavlink_system_time_t system_time;
            mavlink_msg_system_time_decode(&msg, &system_time);
            timeUNIX = system_time.time_unix_usec; // seteaza variabila globala cu timp unix 
          }

          break;

      }
    }
  }
}

I only have the Pixhawk controller attached to pins 0 and 1, no other device connected to the R4.
RX, TX and GND wires connected.
This works with the uploaded code (with software serial enabled), and doesn't without it.

Doesn't work, as in doesn't print to serial monitor the expected values, only 0,0,0,0...

Regarding pxSerial, i will make the changes and get back, thank you.

Hello,

Included the line '#define pxSerial Serial1', and commented the line with SoftwareSerial pxSerial = SoftwareSerial(RxPin0, TxPin0); // RX, TX || UNO - PX4, with the result printed in the serial monitor 0,0,0,0... same thing that happens on the Mega
If i leave the software serial it prints expected values, but only on the R4

On the Mega, did you change the wiring from pin 0 & 1 to pin 18 (TX1) & pin 19 (RX1)?

Yes, i did it, that's Serial1, no?

Correct, pins 18 & 19 on the Mega are Serial1.

Be careful that you get the Tx and Rx lines correct, in your code using SoftwareSerial on the R4, you have the Tx and Rx pins swapped from how they are used for hardware Serial1 on that board.

Already tried and reversed the Tx and Rx, same result in the serial monitor 0,0,0,0...

Something else to try. On the Mega, change the pins used for SoftwareSerial so that they are not on pins 0 & 1.

Note the following:

Tried with Serial3 on Mega, that are pins 14 and 15, modifying the Serial.available, Serial.read and Serial.write to Serial3..., together with Serial3.begin(115200), leaving the SoftwareSerial as is. I modified #define RxPin0 14 and #define TxPin0 15 as those are the ones which Software Serial uses thru SoftwareSerial pxSerial = SoftwareSerial(RxPin0, TxPin0); // RX, TX || UNO - PX4
Edit: same result 0,0,0,0...

I will probably try going further with the R4, as it reads the needed data, and activate the 3rd serial according to: https://forum.arduino.cc/t/third-serial-port-on-uno-r4-serial2/1177436, so that Serial is left to connect PC, Serial1 is for the Pixhawk (as it works), leave software serial (as it works), and use Serial2 from the post in the link, to connect the Sonar (hopefully it will work).

I'll revive the post if, what i plan to do doesn't work.

Thank you all so far.

I managed to activate the Serial2 on the R4, connected the Pixhawk to A4 and A5 pins, left the SerialSoftware active, and it works.

I'm inclined to believe that the board is at fault, as I've tried all Serial ports on the Mega and none work with what you guys recommended.

Edit: i tested the Mega with the simple led blink and it works, but for some reason it doesn't run the code which runs on the R4 (with the modifications for the pins)

This is the code for the R4, which runs on Serial2:

/*  MAVLInk_DroneLights
    by Juan Pedro López
*/
// In case we need a second serial port for debugging
#define SOFT_SERIAL_DEBUGGING   // Comment this line if no serial debugging is needed
#ifdef SOFT_SERIAL_DEBUGGING

// Library to use serial debugging with a second board
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include "SoftwareSerial.h"
#include "ping1d.h"
#include <Int64String.h>


#define RxPin0 1
#define TxPin0 0

#define UART2_TX_PIN (18u)  // Pin A4
#define UART2_RX_PIN (19u)  // Pin A5



int request = 0;
int receive = 0;

const int chipSelect = 53;
float distantaMetri;

SoftwareSerial pxSerial = SoftwareSerial(UART2_TX_PIN, UART2_RX_PIN);  // RX, TX || UNO - PX4

#endif

#include "mavlink.h"
//#include "common/mavlink_msg_request_data_stream.h"
static const uint8_t ledPin = 13;

// Mavlink variables
unsigned long previousMillisMAVLink = 0;     // will store last time MAVLink was transmitted and listened
unsigned long next_interval_MAVLink = 100;  // next interval to count
const int num_hbs = 10;                      // # of heartbeats to wait before activating STREAMS from Pixhawk. 60 = one minute.
int num_hbs_pasados = num_hbs;

float mesajRoll;
float mesajPitch;
float mesajYaw;

int32_t gpsLat;
int32_t gpsLong;
int32_t gpsElev;
uint8_t gpsSolution;

uint64_t timeUNIX;

String dataString = "";
String timeUNIXstring = "";

void setup() {

pinMode(RxPin0, INPUT);
pinMode(TxPin0, OUTPUT);

pinMode(UART2_TX_PIN, INPUT);
pinMode(UART2_RX_PIN, OUTPUT);

  // MAVLink interface start
  // Serial.begin(57600);

  // [DEB] Soft serial port start
  Serial.begin(115200);
  Serial2.begin(115200);
  pxSerial.begin(115200);
  Serial.println("MAVLink starting.");

  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
/*if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1)
      ;
  }
*/
  Serial.println("card initialized.");
  //inceput scrie capat fisier~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  File dataFile = SD.open("sonar.txt", FILE_WRITE);
  dataFile.println("unix_time,lat,long,elev,roll,pitch,yaw,distanta");
  dataFile.close();
  //sfarsit scrie capat fisier~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // sfarsit setari card SD ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// PANA AICI E OK MOMENTAN
}

void loop() {



  String dataString = "";

  // MAVLink
  /* The default UART header for your MCU */
  int sysid = 1;                   ///< ID 20 for this airplane. 1 PX, 255 ground station
  int compid = 158;                ///< The component sending the message
  int type = MAV_TYPE_QUADROTOR;   ///< This system is an airplane / fixed wing

  // Define the system type, in this case an airplane -> on-board controller
  // uint8_t system_type = MAV_TYPE_FIXED_WING;
  uint8_t system_type = MAV_TYPE_GENERIC;
  uint8_t autopilot_type = MAV_AUTOPILOT_INVALID;

  uint8_t system_mode = MAV_MODE_PREFLIGHT; ///< Booting up
  uint32_t custom_mode = 0;                 ///< Custom mode, can be defined by user/adopter
  uint8_t system_state = MAV_STATE_STANDBY; ///< System ready for flight
  // Initialize the required buffers
  mavlink_message_t msg;
  uint8_t buf[MAVLINK_MAX_PACKET_LEN];

  // Pack the message
  //mavlink_msg_heartbeat_pack(sysid,compid, &msg, type, autopilot_type, system_mode, custom_mode, system_state);
  mavlink_msg_heartbeat_pack(1, 0, &msg, type, autopilot_type, system_mode, custom_mode, system_state);

  // Copy the message to the send buffer
  uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);

  // Send the message with the standard UART send function
  // uart0_send might be named differently depending on
  // the individual microcontroller / library in use.
  unsigned long currentMillisMAVLink = millis();
  if (currentMillisMAVLink - previousMillisMAVLink >= next_interval_MAVLink) {
    previousMillisMAVLink = currentMillisMAVLink;

#ifdef SOFT_SERIAL_DEBUGGING
    pxSerial.write(buf, len);
  //  Serial.println("Ardu HB");
#else
    Serial2.write(buf, len);
#endif

    //Mav_Request_Data();
    num_hbs_pasados++;

  }

  // Check reception buffer

comm_receive();

//Serial.println(timeUNIX);
//Serial.println(gpsLat);
//Serial.println(gpsLong);
//Serial.println(gpsElev);
//Serial.println(gpsSolution);
//Serial.println(mesajRoll,10);
//Serial.println(mesajPitch,10);
//Serial.println(mesajYaw,10);

timeUNIXstring = int64String(timeUNIX);
 
 dataString = timeUNIXstring + "," + String(gpsLat) + "," + String(gpsLong) + "," + String(gpsElev) + ","  + String(mesajRoll,10) + "," + String(mesajPitch,10) + "," + String(mesajYaw,10) + ","; // + String(distantaMetri);

Serial.println(dataString);
if (gpsSolution > 3) {
// INCEPUT PARTE DE SCRIS PE CARD SD
 // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("sonar.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("Eroare fisier sonar.txt");
  }
  // SFARSIT PARTE DE SCRIS PE CARD SD
  // Toggle the LED to show that the program is running
  digitalWrite(ledPin, !digitalRead(ledPin));
}
  delay(200);

} // SFARSIT LOOP

void Mav_Request_Data()
{

  request = request + 1;

  mavlink_message_t msg;
  uint8_t buf[MAVLINK_MAX_PACKET_LEN];


  // STREAMS that can be requested
  /*
     Definitions are in common.h: enum MAV_DATA_STREAM

     MAV_DATA_STREAM_ALL=0, // Enable all data streams
     MAV_DATA_STREAM_RAW_SENSORS=1, /* Enable IMU_RAW, GPS_RAW, GPS_STATUS packets.
     MAV_DATA_STREAM_EXTENDED_STATUS=2, /* Enable GPS_STATUS, CONTROL_STATUS, AUX_STATUS
     MAV_DATA_STREAM_RC_CHANNELS=3, /* Enable RC_CHANNELS_SCALED, RC_CHANNELS_RAW, SERVO_OUTPUT_RAW
     MAV_DATA_STREAM_RAW_CONTROLLER=4, /* Enable ATTITUDE_CONTROLLER_OUTPUT, POSITION_CONTROLLER_OUTPUT, NAV_CONTROLLER_OUTPUT.
     MAV_DATA_STREAM_POSITION=6, /* Enable LOCAL_POSITION, GLOBAL_POSITION/GLOBAL_POSITION_INT messages.
     MAV_DATA_STREAM_EXTRA1=10, /* Dependent on the autopilot
     MAV_DATA_STREAM_EXTRA2=11, /* Dependent on the autopilot
     MAV_DATA_STREAM_EXTRA3=12, /* Dependent on the autopilot
     MAV_DATA_STREAM_ENUM_END=13,

     Data in PixHawk available in:
      - Battery, amperage and voltage (SYS_STATUS) in MAV_DATA_STREAM_EXTENDED_STATUS
      - Gyro info (IMU_SCALED) in MAV_DATA_STREAM_EXTRA1
  */

  // To be setup according to the needed information to be requested from the Pixhawk
  const int  maxStreams = 3;
  const uint8_t MAVStreams[maxStreams] = {MAV_DATA_STREAM_EXTENDED_STATUS, MAV_DATA_STREAM_POSITION, MAV_DATA_STREAM_EXTRA1};
  const uint16_t MAVRates[maxStreams] = {0x10, 0x10, 0x10};


  for (int i = 0; i < maxStreams; i++) {
    mavlink_msg_request_data_stream_pack(2, 200, &msg, 1, 0, MAVStreams[i], MAVRates[i], 1);
    uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
#ifdef SOFT_SERIAL_DEBUGGING
    pxSerial.write(buf, len);
#else
    Serial2.write(buf, len);
#endif
  }

}

void comm_receive() {

  receive = receive + 1;

  mavlink_message_t msg;
  mavlink_status_t status;

  #ifdef SOFT_SERIAL_DEBUGGING
  while(pxSerial.available()>0) {
    uint8_t c = pxSerial.read();
#else
  while(Serial2.available()>0) {
    uint8_t c = Serial2.read();
#endif

    // Try to get a new message
    if (mavlink_parse_char(MAVLINK_COMM_0, c, &msg, &status)) {

      // Handle message
      switch (msg.msgid) {
        case MAVLINK_MSG_ID_HEARTBEAT:  // #0: Heartbeat
          {
            // E.g. read GCS heartbeat and go into
            // comm lost mode if timer times out
          }
          break;
        
        case MAVLINK_MSG_ID_ATTITUDE:  // #30
          {
            /* Message decoding: PRIMITIVE
                  mavlink_msg_attitude_decode(const mavlink_message_t* msg, mavlink_attitude_t* attitude)
            */
            mavlink_attitude_t attitude;
            mavlink_msg_attitude_decode(&msg, &attitude);
            mesajRoll = attitude.roll;
            mesajPitch = attitude.pitch;
            mesajYaw = attitude.yaw;
          }
          break;

          case MAVLINK_MSG_ID_GPS_RAW_INT:  // #30
          {
            /* Message decoding: PRIMITIVE
                  mavlink_msg_attitude_decode(const mavlink_message_t* msg, mavlink_attitude_t* attitude)
            */
            mavlink_gps_raw_int_t gps_raw_int;
            mavlink_msg_gps_raw_int_decode(&msg, &gps_raw_int);
              gpsLat = gps_raw_int.lat; // seteaza variabila globala cu latitudine GPS Pixhawk
              gpsLong = gps_raw_int.lon; // seteaza variabila globala cu longitudine GPS Pixhawk 
              gpsElev = gps_raw_int.alt; // seteaza variabila globala cu altitudine GPS Pixhawk
              gpsSolution = gps_raw_int.satellites_visible; // seteaza variabila globala cu numar sateliti
          }

          break;

          case MAVLINK_MSG_ID_SYSTEM_TIME:  // #30
          {

            mavlink_system_time_t system_time;
            mavlink_msg_system_time_decode(&msg, &system_time);
            timeUNIX = system_time.time_unix_usec; // seteaza variabila globala cu timp unix 
          }

          break;

      }
    }
  }
}

No, your code is not use Serial2. You just open yet another SoftwareSerial on UART2 pins. This is an absolutely meaningless action that shows that you don’t understand the issue.

Sorry, but your code is a mess in general. Do you understand just a line in it?

Why two SoftwareSerial.h headers?

Why pinMode on Serial pins?

Why three Serials ?

Uno R4 has a two Hardware Serials. Your code need a two UARTs. It clearly means that you don't need any SoftwareSerials at all. You need to edit your code as @Delta_G wrote in post #12. But first I recommend you take a break, sit and read a good beginner book about an Arduino programming and especially about the difference between sof and hard serials.

1 Like

The current hookup of the wires are as follows:


So, the Pixhawk is connected over Serial2 ports on the R4.

I do realize that the code is a mess, as i started with Arduino about 1 month ago, and i got bits of code deleted from the original sketch, as it was intended for flashing certain lights on a drone, based on input from the Pixhawk. Also, i do realize there are some bits which i don't need, but, so far it works for me.

2 SoftwareSerial.h, are due to the mess probably, as i combined the sketch for the sonar with this one and it remained there (sketch for the sonar was using sofwareserial), and afterwards deleted the code for the sonar

pinMode on serial pins, because that is what the sketch came with, i only added the UART2 pinModes as i changed from pin 0 and 1 to pin A4 and A5, and from my understanding i thought that is required.

3 serials for Serial.begin(115200) for PC serial monitor, Serial2.begin(115200) for Pixhawk (is where itțs connected pin A4 and pin A5) and pxSerial.begin(115200) for SoftwareSerial (sketch doesnțt work if i drop it).

I did edited the code as @Delta_G suggested and as soon as i removed the softwareserial code, sketch would give only 0,0,0,0... in the serial monitor. In the last uploaded code, it works, meaning it gives me: 0,0,0,-17000,0.0290659387,-0.0422718078,2.3743710518,
where first 0 is unixtime, second 0 is latitude, 3rd 0 is longitude and 4th 0 is elevation (this are not currently shown as i'm inside, so no gps signal, outside they do show), then i get roll, pitch and yaw (which are correct based on the readings in the Mission Planner - the program that controls the drone)

Again, I am a beginner in Arduino coding, but so far i managed to make it partially work, and although i don't understand what all the code is doing, i'm going to keep researching until i do.