Communicating between Pi + Navigator and Arduino UART

Thanks for all your help @tony-white,

Now that Ive got some time working with Lua scripts under my belt I had a few questions.

Ive worked out a quick and simple serial connection test. I have a serial connection from serial 4 to a arduino nano setup running a simple blinky script where the navigator sends a high signal (asci 76 ‘H’ and the low ‘L’ 72) to the nano and the nanos LED blinks every second.

On boot, it seems that any Lua script I create only runs for about 5 seconds before sending a const 255 high signal without end. I can fix this by restarting autopilot and the blinky code will run find with the odd 255 high signal mixed in between the intended 76 and 72 signals. Do you know why lua scripts might not work properly on cold boot and why I get the occasional Junk signal?

I have serial 4 set to 9600 and scripting

Lua:

local port = serial:find_serial(0)
if not port then
  gcs:send_text(0, “Lua: no scripting serial found”)
  return
end

– Match Arduino baud
port:begin(9600)
port:set_flow_control(0)

local state = false   – false → L, true → H

function send_hi_lo()
  local byte_to_send
  local char_label

  if state then
    byte_to_send = string.byte(“H”)  – 72
    char_label   = “H”
  else
    byte_to_send = string.byte(“L”)  – 76
    char_label   = “L”
  end

  port:write(byte_to_send)  – NOW a number, not a string
  state = not state

  gcs:send_text(0, “Lua sent: " .. char_label .. " (” .. byte_to_send .. “)”)

  return send_hi_lo, 1000  – run again in 1 second
end

return send_hi_lo, 1000

Arduino:

#include <SoftwareSerial.h>

const uint8_t NAV_RX_PIN = 2;  // From Navigator TX
const uint8_t NAV_TX_PIN = 3;  // (not used yet)

SoftwareSerial navSerial(NAV_RX_PIN, NAV_TX_PIN);  // RX, TX

void setup() {
  pinMode(13, OUTPUT);

  Serial.begin(9600);      // USB debug
  navSerial.begin(9600);   // Must match Lua
  navSerial.listen();

  Serial.println(“Nano: waiting for Navigator bytes…”);
}

void loop() {
  while (navSerial.available()) {
    char c = navSerial.read();
    int code = (int)c & 0xFF;   // force to 0–255

    Serial.print("Byte: ");
    Serial.print(code);
    Serial.print("  char: '");
    Serial.print((code >= 32 && code <= 126) ? c : '.');  
    Serial.println("'");

    // LED control only on clean H/L
    if (c == 'H') {
      digitalWrite(13, HIGH);
    } else if (c == 'L') {
      digitalWrite(13, LOW);
    }

  }
}