Serial Communication in UserCode.cpp

Dear community,

I’m trying to send a Mavlink message from UserCode.cpp to a connected microcontroller via one of the Serial ports.

I succeeded so far that my microcontroller is visible in Missionplanner, see picture:

So the Serial options, baudrate etc… should be correct. I can also confirm the exchange with Mavlink messages when connecting this microcontroller with another one. ==> I can send and receive message on the microcontroller side.

What gives me headache is the UserCode.cpp. I can confirm that my loops (I use SuperSlow and Medium) are active. I use

gcs().send_text(MAV_SEVERITY_CRITICAL, “CUSTOM AP3”);

and I can also confirm that I can see these messages in Missionplanner. What doesn’t work is Serial communication and I don’t understand why. I was even able to get it run with my FC when flashing the UART_test example, but not from UserCode.cpp. What I have tried:

in void Copter::userhook_init():

 hal.serial(1)->begin(115200);
 hal.serial(2)->begin(115200);
 hal.serial(4)->begin(115200);

then in void Copter::userhook_MediumLoop()

mavlink_msg_rc_channels_override_encode(MAV_SYSTEM_ID, MAV_COMP_ID_USER2, &mvl_tx_message, &msgData);
uint8_t mavlink_message_buffer[MAVLINK_MAX_PACKET_LEN];
uint16_t mavlink_message_length = mavlink_msg_to_send_buffer(mavlink_message_buffer, &mvl_tx_message);  // move message to serial send buffer
hal.serial(4)->write(mavlink_message_buffer, mavlink_message_length); // I tried all ports 1-4 but I dont receive anything on the microcontroller side.

Alternatively, I tried:

comm_send_buffer(MAVLINK_COMM_0, buffer, mavlink_message_length);

instead. But there’s still no communication. What am I missing? It appears like Serial is blocked or simply not available in UserCode.cpp.

Any advice?