MAVLink and Arduino: step by step

did you solve the problem?

Do you have the complete code for requesting data from the flight controller? I am new here so I struggle here.

I think you can find it this page. But what I’m wondering about is control motors with pixhawk.

Controlling individual motors over MAVLink? For some servo outputs you can set them using a MAVLink command. For others you would need to use Lua scripting on board the autopilot. That allows for setting any servo output to any value for a specific amount of time. It just depends on what you need to do.

1 Like

Hi @Perun_Kiyev,
From what you asked in your direct message, it sounds like you are successfully issuing the ARM command over MAVLink to your AutoPilot, but it sounds like you may not be entering AUTO flight mode as well?
My understanding (and I may be wrong) is that you need to ARM your AP, then put it in the AUTO flight mode and then it will start any previous loaded Mission.
But you also need to make sure that there is nothing stopping your AP from going into AUTO mode, for example no GPS fix etc.
I also read once that you can set your ArduPilot to automatically go into AUTO mode, but I’m not sure how that’s done.
If you use my test program GitHub - pauljeffress/Pulsar-MAVLink-Tester (or parts of it) on a suitable Arduino, you can monitor what happens when you try to change the flight mode to AUTO. If there is something blocking it, you will see an error response in the STATUSTEXT saying “Flight mode change failed”.
Here is what it looks like when I ARM and then try to AUTO my AP which is inside and not able to get a GPS fix at the moment.

14:59:33.940 > MSG RCVD - magic:254 seq:224 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:65 DISarmed Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3
14:59:33.941 > MSG RCVD - magic:254 seq:225 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:65 DISarmed Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3
14:59:33.941 > MSG RCVD - magic:254 seq:226 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:65 DISarmed Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3
14:59:33.942 > MSG RCVD - magic:254 seq:227 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:65 DISarmed Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3
14:59:33.942 > MSG RCVD - magic:254 seq:228 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:65 DISarmed Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3
14:59:33.943 > MSG RCVD - magic:254 seq:229 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:65 DISarmed Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3
14:59:33.943 > MSG RCVD - magic:254 seq:230 sysid:1 compid:1 msgid#:77=COMMAND_ACK command:400 result:0
14:59:33.944 > MSG RCVD - magic:254 seq:231 sysid:1 compid:1 msgid#:253=STATUSTEXT severity:6 text:Throttle armed
14:59:33.945 > MSG RCVD - magic:254 seq:232 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:193 !!ARMED!! Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3
14:59:33.945 > MSG RCVD - magic:254 seq:233 sysid:1 compid:1 msgid#:111=TIMESYNC - undecoded
14:59:33.945 > MSG RCVD - magic:254 seq:234 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:193 !!ARMED!! Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3
14:59:33.945 > MSG RCVD - magic:254 seq:235 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:193 !!ARMED!! Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3
14:59:33.966 > mavlink_receive() - WARNING - MSG(s) missed from sysID:1,compID:1 according to seq nums!
14:59:33.966 > MSG RCVD - magic:254 seq:240 sysid:1 compid:1 msgid#:77=COMMAND_ACK command:176 result:4
14:59:33.976 > MSG RCVD - magic:254 seq:241 sysid:1 compid:1 msgid#:253=STATUSTEXT severity:4 text:Flight mode change failed
14:59:34.827 > MSG RCVD - magic:254 seq:242 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:193 !!ARMED!! Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3
14:59:34.891 > MSG RCVD - magic:254 seq:243 sysid:1 compid:1 msgid#:22=PARAM_VALUE param_id:STAT_RUNTIME param_value:10251307.00 param_type:6 param_count893 param_index65535
14:59:35.827 > MSG RCVD - magic:254 seq:244 sysid:1 compid:1 msgid#:0=HEARTBEAT Type:11 APclass:3 BaseMode:193 !!ARMED!! Custom/Flightmode:0 MANUAL SysStat:5 MavVer:3

Hello guys,
thank you for the tutorial it is very useful for me to start mavlink with Arduino. I want to ask about my project related to this topic, so I use Arduino UNO R3 to stream the data. for the wiring, i use RX and TX pin in Arduino and connect it to Telemetry2 port in pixhawk.

I can get the data as you can see in the serial monitor but it is not the same as in the mission planner.

I really confused about what kind of data my Arduino gets from pixhawk, maybe you can give me some insight about this.

Additionally, I use cube orange and here3 GPS also this is my code on Github:

cheers,
Figo

Hi @insan_terdidik,

In comm_receive() you are not decoding the heartbeat msg, before you print its contents.
Just after the line

mavlink_heartbeat_t variabel;

You need to add the heartbeat version of this command

mavlink_msg_gps_raw_int_decode (&msg, &datagps);

Like you do for your GPS msg.

That should help with correctly receiving the MAVLink Heartbeats for a start.

Let us know how you go. :slight_smile:

Cheers,
Paul

mavlink_msg_heartbeat_decode(&msg, &variabel);

thanks, paul for the advice, The heartbeat data is now same as in mavlink inspector. Unfortunately, the GPS raw data is still not same as in the mission planner, here is the figure.


additionally, I added

mavlink_msg_heartbeat_decode(&msg, &variabel);

into my code

Cool, good progress.

Looking at your code I think the problem with the GPS decode is just a simple missing a

break;

statement just before your

case MAVLINK_MSG_ID_GPS_RAW_INT:

line.

hey, thank you for the tutorial it was very helpful,
bet i didnt secceed to connect between the arduino aand the pixhawk.
if someone can help me in private or in here it would be great because i need to be done with my project in about two weeks.

1 Like

Thanks for all of that information ;keep learning

Hello there,

I am also new to mavlink and I also want to get data from pixhawk just like you,
if you succeeded in getting the data please help me out.

Hello there,

I am also trying to get data from pixhawk, but I am stuck, I do not know what to do now will you please share the code or which header files you are using. I am using arduino due to get data.

Everybody that followed the steps described, got data into the arduino. Read the steps again

2 Likes

Hi there @Huzaifa_Ahmed, can you tell us what you have done and what isn’t working? Can you share your code with us perhaps and then we can help :slight_smile:
Cheers,
Paul

This is the code

#include <PixhawkArduinoMAVLink.h>
#include “common/mavlink_msg_log_data.h”
#include “common/mavlink_msg_attitude.h”
#include “common/mavlink_msg_request_data_stream.h”
#include “common/mavlink_msg_param_request_list.h”
#include “common/mavlink_msg_hil_state.h”

#define MAVLINK_MSG_ID_ATTITUDE 30
#define MAVLINK_MSG_ID_HIL_STATE 90

int val;
float volt;
int pack;
char cstr[33];
int leds_modo = 1;
int leds_status = 0;
int t1;

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

void setup() {
// put your setup code here, to run once:

Serial.begin(57600);
Serial.println(“Arduino is go!”);

}

void loop() {
// put your main code here, to run repeatedly:
int sysid = 1;
int compid = 158;
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_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;
mavlink_message_t msg1;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
uint8_t param_type = 9;
uint16_t param_count = 2;
uint16_t param_index = 1;

//misc test
int32_t lat = 0;
int32_t lon = 0;
//xacc will be test
int16_t yacc = 0;
int16_t zacc = 0;
int16_t xgy = 0;
int16_t ygy = 0;
int16_t zgy = 0;
int16_t xmag = 0;
int16_t ymag = 0;
int16_t zmag = 0;

val = analogRead(A0);
volt = (val * 5.00)/1023.00;
pack = volt * 100;
itoa(pack, cstr, 10);

//CURRENT CONFIGURATION: BOTH HEARTBEAT AND PARAM_VALUE

Serial.println(cstr);
mavlink_msg_heartbeat_pack(1,0, &msg, type, autopilot_type, system_mode, custom_mode, system_state);
mavlink_msg_param_value_pack(1,0, &msg, “Voltage”, volt, param_type, param_count, param_index);
mavlink_msg_log_data_pack(1,0,&msg,volt, 0,0,0);
mavlink_msg_raw_imu_pack(1,0,&msg, t1,pack,yacc,zacc,xgy,ygy,zgy,xmag,ymag,zmag);

mavlink_msg_heartbeat_pack(255,0, &msg, type, autopilot_type, system_mode, custom_mode, system_state);
mavlink_msg_param_value_pack(1,0, &msg, “Voltage”, volt, param_type, param_count, param_index);
mavlink_msg_log_data_pack(1,155,&msg1,volt,0,0,0);
mavlink_msg_raw_imu_pack(1,0,&msg, t1,pack,yacc,zacc,xgy,ygy,zgy,xmag,ymag,zmag);

uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
uint16_t len1 = mavlink_msg_to_send_buffer(buf, &msg1);

unsigned long currentMillisMAVLink = millis();
if (currentMillisMAVLink - previousMillisMAVLink >= next_interval_MAVLink) {
// Timing variables

Serial.write(buf, len);
Serial.write(buf, len1);
Serial.println("heart confirmed...");

}

mavlink_msg_heartbeat_pack(255,0, &msg, type, autopilot_type, system_mode, custom_mode, system_state);
mavlink_msg_param_value_pack(1,0, &msg, “Voltage”, volt, param_type, param_count, param_index);
mavlink_msg_log_data_pack(255,0,&msg,volt, 0,0,0);
mavlink_msg_raw_imu_pack(1,0,&msg, t1,pack,yacc,zacc,xgy,ygy,zgy,xmag,ymag,zmag);

comm_receive();
Mav_Request_Data();

delay(1000);

}

void Mav_Request_Data()
{
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 = 2;
const uint8_t MAVStreams[maxStreams] = {MAV_DATA_STREAM_EXTENDED_STATUS, MAV_DATA_STREAM_EXTRA1};
const uint16_t MAVRates[maxStreams] = {0x02,0x05};

for (int i=0; i < maxStreams; i++) {
/*
mavlink_msg_request_data_stream_pack(system_id, component_id,
&msg,
target_system, target_component,
MAV_DATA_STREAM_POSITION, 10000000, 1);

 mavlink_msg_request_data_stream_pack(uint8_t system_id, uint8_t component_id, 
    mavlink_message_t* msg,
    uint8_t target_system, uint8_t target_component, uint8_t req_stream_id, 
    uint16_t req_message_rate, uint8_t start_stop)
 */
 
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);
Serial.write(buf, len);
Serial.println("data stream active");

}
}

void comm_receive() {
mavlink_message_t msg;
mavlink_status_t status;
int leds_modo = 0;
int t;

while(Serial.available()>0) {
uint8_t c = Serial.read();

// 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_SYS_STATUS:  // #1: SYS_STATUS
      {
        /* Message decoding: PRIMITIVE
         *    mavlink_msg_sys_status_decode(const mavlink_message_t* msg, mavlink_sys_status_t* sys_status)
         */
        //mavlink_message_t* msg;
        mavlink_sys_status_t sys_status;
        mavlink_msg_sys_status_decode(&msg, &sys_status);
      }
      break;

    case MAVLINK_MSG_ID_PARAM_VALUE:  // #22: PARAM_VALUE
      {
        /* Message decoding: PRIMITIVE
         *    mavlink_msg_param_value_decode(const mavlink_message_t* msg, mavlink_param_value_t* param_value)
         */
        //mavlink_message_t* msg;
        mavlink_param_value_t param_value;
        mavlink_msg_param_value_decode(&msg, &param_value);
        
        char* id = param_value.param_id;
        float val = param_value.param_value;
        uint16_t count = param_value.param_count;
        uint16_t ind = param_value.param_index;
        uint8_t typ = param_value.param_type;
        Serial.println("Paramter info-------------");
        Serial.print("ID: "); Serial.println(id);
        Serial.print("value: "); Serial.println(val);
        Serial.print("count: "); Serial.println(count);
        Serial.print("index: "); Serial.println(ind);
        Serial.print("type: "); Serial.println(typ);
        Serial.println();
        Serial.println();
        
        
      }
      break;

    case MAVLINK_MSG_ID_RAW_IMU:  // #27: RAW_IMU
      {
        /* Message decoding: PRIMITIVE
         *    static inline void mavlink_msg_raw_imu_decode(const mavlink_message_t* msg, mavlink_raw_imu_t* raw_imu)
         */
        mavlink_raw_imu_t raw_imu;
        mavlink_msg_raw_imu_decode(&msg, &raw_imu);
      }
      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);

        if(attitude.roll>1) leds_modo = 0;
        else if(attitude.roll<-1) leds_modo = 2;
        else leds_modo=1;
        t = attitude.time_boot_ms;
      }
      break;

    
   default:
      break;
  }
}

}
}

On Pixhawk I am using Telem2 and it is connected with pin 1 and 0 of Arduino due

Hi @Huzaifa_Ahmed,
Ok, there is a bit that you need to fix in your code.
Code Tidy Up
You need to move some of your code from loop() up into setup() or even place it before setup when it is something like a global variable. It makes your code more readable and also good practice. Any code that only needs to run once, should be in setup().
For example, all of this code should be moved from loop() to be above setup() and used as global.

int sysid = 1;
int compid = 158;
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_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;
mavlink_message_t msg1;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
uint8_t param_type = 9;
uint16_t param_count = 2;
uint16_t param_index = 1;

//misc test
int32_t lat = 0;
int32_t lon = 0;
//xacc will be test
int16_t yacc = 0;
int16_t zacc = 0;
int16_t xgy = 0;
int16_t ygy = 0;
int16_t zgy = 0;
int16_t xmag = 0;
int16_t ymag = 0;
int16_t zmag = 0;

Arduino to Autopilot Issues
On your DUE, pins D0 and D1 are connected to the USB port on the DUE, that’s how the Serial Monitor talks to the DUE. So you should not also connect them to your AutoPilot. You need to use one of the other Serial ports on the DUE, like TX1/RX1.
You then need to initialise this port in setup()
Serial1.begin(57600); // Initialise the Serial port that's connected to the AutoPilot.
Then you need to use Serial1, not Serial, to TX and RX with the AutoPilot.
For example where you have

Serial.write(buf, len);
Serial.write(buf, len1);

You need to change that to

Serial1.write(buf, len);
Serial1.write(buf, len1);

So that you are transmitting (TX) to the AutoPilot over Serial1.

Also in comm_receive() you also need to use Serial1 to read (RX) data from the AutoPilot

while(Serial1.available()>0) {
uint8_t c = Serial1.read();

That would be a great start. I haven’t looked at the rest of your code in detail, but that should help you progress.
Good luck,
Paul

Also, you can take a look at some sample code I put together earlier, that might help you.

I am still not getting the data.

the code is

#include <PixhawkArduinoMAVLink.h>
#include “common/mavlink_msg_log_data.h”
#include “common/mavlink_msg_attitude.h”
#include “common/mavlink_msg_request_data_stream.h”
#include “common/mavlink_msg_param_request_list.h”
#include “common/mavlink_msg_hil_state.h”
#include “common/mavlink_msg_data_stream.h”

#define MAVLINK_MSG_ID_ATTITUDE 30
#define MAVLINK_MSG_ID_HIL_STATE 90

int val;
float volt;
int pack;
char cstr[33];
int leds_modo = 1;
int leds_status = 0;
int t1;

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

int sysid = 1;
int compid = 158;
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_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;
mavlink_message_t msg1;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
uint8_t param_type = 9;
uint16_t param_count = 2;
uint16_t param_index = 1;

//misc test
int32_t lat = 0;
int32_t lon = 0;
//xacc will be test
int16_t yacc = 0;
int16_t zacc = 0;
int16_t xgy = 0;
int16_t ygy = 0;
int16_t zgy = 0;
int16_t xmag = 0;
int16_t ymag = 0;
int16_t zmag = 0;

void setup() {
// put your setup code here, to run once:

Serial.begin(57600);
Serial1.begin(57600);
Serial.println(“Arduino is go!”);

}

void loop() {
// put your main code here, to run repeatedly:

val = analogRead(A0);
volt = (val * 5.00) / 1023.00;
pack = volt * 100;
itoa(pack, cstr, 10);

//CURRENT CONFIGURATION: BOTH HEARTBEAT AND PARAM_VALUE

Serial.println(cstr);
mavlink_msg_heartbeat_pack(1, 0, &msg, type, autopilot_type, system_mode, custom_mode, system_state);
mavlink_msg_param_value_pack(1, 0, &msg, “Voltage”, volt, param_type, param_count, param_index);
mavlink_msg_log_data_pack(1, 0, &msg, volt, 0, 0, 0);
mavlink_msg_raw_imu_pack(1, 0, &msg, t1, pack, yacc, zacc, xgy, ygy, zgy, xmag, ymag, zmag);

mavlink_msg_heartbeat_pack(255, 0, &msg, type, autopilot_type, system_mode, custom_mode, system_state);
mavlink_msg_param_value_pack(1, 0, &msg, “Voltage”, volt, param_type, param_count, param_index);
mavlink_msg_log_data_pack(1, 155, &msg1, volt, 0, 0, 0);
mavlink_msg_raw_imu_pack(1, 0, &msg, t1, pack, yacc, zacc, xgy, ygy, zgy, xmag, ymag, zmag);

uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
uint16_t len1 = mavlink_msg_to_send_buffer(buf, &msg1);

unsigned long currentMillisMAVLink = millis();
if (currentMillisMAVLink - previousMillisMAVLink >= next_interval_MAVLink) {
// Timing variables

Serial1.write(buf, len);
Serial1.write(buf, len1);
Serial.println("heart confirmed...");

}

mavlink_msg_heartbeat_pack(255, 0, &msg, type, autopilot_type, system_mode, custom_mode, system_state);
mavlink_msg_param_value_pack(1, 0, &msg, “Voltage”, volt, param_type, param_count, param_index);
mavlink_msg_log_data_pack(255, 0, &msg, volt, 0, 0, 0);
mavlink_msg_raw_imu_pack(1, 0, &msg, t1, pack, yacc, zacc, xgy, ygy, zgy, xmag, ymag, zmag);

comm_receive();
Mav_Request_Data();

delay(1000);

}

void Mav_Request_Data()
{
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 = 2;
const uint8_t MAVStreams[maxStreams] = {MAV_DATA_STREAM_EXTENDED_STATUS, MAV_DATA_STREAM_EXTRA1};
const uint16_t MAVRates[maxStreams] = {0x02, 0x05};

for (int i = 0; i < maxStreams; i++) {
/*
mavlink_msg_request_data_stream_pack(system_id, component_id,
&msg,
target_system, target_component,
MAV_DATA_STREAM_POSITION, 10000000, 1);

  mavlink_msg_request_data_stream_pack(uint8_t system_id, uint8_t component_id,
    mavlink_message_t* msg,
    uint8_t target_system, uint8_t target_component, uint8_t req_stream_id,
    uint16_t req_message_rate, uint8_t start_stop)
*/

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);
Serial1.write(buf, len);
Serial.println("data stream active");

}
}

void comm_receive() {
mavlink_message_t msg;
mavlink_status_t status;
int leds_modo = 0;
int t;

while (Serial.available() > 0) {
uint8_t c = Serial.read();

// 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_SYS_STATUS:  // #1: SYS_STATUS
      {
        /* Message decoding: PRIMITIVE
              mavlink_msg_sys_status_decode(const mavlink_message_t* msg, mavlink_sys_status_t* sys_status)
        */
        //mavlink_message_t* msg;
        mavlink_sys_status_t sys_status;
        mavlink_msg_sys_status_decode(&msg, &sys_status);
      }
      break;

    case MAVLINK_MSG_ID_PARAM_VALUE:  // #22: PARAM_VALUE
      {
        /* Message decoding: PRIMITIVE
              mavlink_msg_param_value_decode(const mavlink_message_t* msg, mavlink_param_value_t* param_value)
        */
        //mavlink_message_t* msg;
        mavlink_param_value_t param_value;
        mavlink_msg_param_value_decode(&msg, &param_value);

        char* id = param_value.param_id;
        float val = param_value.param_value;
        uint16_t count = param_value.param_count;
        uint16_t ind = param_value.param_index;
        uint8_t typ = param_value.param_type;
        Serial.println("Paramter info-------------");
        Serial.print("ID: "); Serial.println(id);
        Serial.print("value: "); Serial.println(val);
        Serial.print("count: "); Serial.println(count);
        Serial.print("index: "); Serial.println(ind);
        Serial.print("type: "); Serial.println(typ);
        Serial.println();
        Serial.println();
      }
      break;

    case MAVLINK_MSG_ID_RAW_IMU:  // #27: RAW_IMU
      {
        /* Message decoding: PRIMITIVE
              static inline void mavlink_msg_raw_imu_decode(const mavlink_message_t* msg, mavlink_raw_imu_t* raw_imu)
        */
        mavlink_raw_imu_t raw_imu;
        mavlink_msg_raw_imu_decode(&msg, &raw_imu);
      }
      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);

      uint32_t time_boot_ms; ///< Timestamp (milliseconds since system boot)

float roll; ///< Roll angle (rad)
float pitch; ///< Pitch angle (rad)
float yaw; ///< Yaw angle (rad)
float rollspeed; ///< Roll angular speed (rad/s)
float pitchspeed; ///< Pitch angular speed (rad/s)
float yawspeed; ///< Yaw angular speed (rad/s)
Serial.println(“Paramter info-------------”);
Serial.print("roll: "); Serial.println(roll);
Serial.print("pitch: "); Serial.println(pitch);
Serial.print("yaw: "); Serial.println(yaw);
Serial.print("rollspeed: "); Serial.println(rollspeed);
Serial.print("yawspeed: "); Serial.println(yawspeed);
Serial.println();
Serial.println();
}
break;

    default:
      break;
  }
}

}
}