Bananapi-Arduino serial communication - HowTo (headless, no USB)

Shared by MrGlasspoole

maybe it helps somebody… You need a Logic Level Converter because most Arduinos work with 5 Volt and the Banana with 3.3 Volt! Something like this: https://www.sparkfun.com/products/12009

Connections (Banana <> Converter Low<> Converter High <> Arduino Mega Serial1): Pin 1 <> LV <> HV <> 5V Pin 24 <> GND <> GND <> GND Pin 22 (RX) <> LV1 <> HV1 <> D18 (TX1) Pin 23 (TX) <> LV2 <> HV2 <> D19 (RX1)

Arduino Code:

void setup() {

  Serial.begin(9600); // Open serial communications and wait for port to open
    while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial1.begin(115200); // Open serial communications and wait for port to open
    while (!Serial1) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

}

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\n': // Ignore new-lines
        break;
      case '\r': // Return on CR
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  // No end of line has been found, so return -1.
  return -1;
}

void loop() {
  
    // Do something here that prints:
    Serial1.print("myButtonIsPressed");
    Serial1.print('\n');
  
  static char buffer[80];
  if (readline(Serial1.read(), buffer, 80) > 0) {
    Serial.print("Serial received: >");
    Serial.print(buffer);
    Serial.println("<");
  }

}

Banana Python example with PySerial:

import serial
import threading
import time

CRLF = '\r\n'

def log(msg):
    print "[",datetime.datetime.now(), "] ", msg
   
def read_serial():

    global last_received
    buffer = ''
    try:
        ser = serial.Serial('/dev/ttyS2', baudrate=115200, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE, timeout=None)
        log("Serial successfully connected to port %r." % ser.port)
    except Exception as e:
        log("Serial error opening port: " + str(e))
        exit()
    # Reset Arduino
    ser.setDTR(False) # set reset signal 
    time.sleep(2)     # wait two seconds - Arduino needs some time to reset
    ser.flushInput()  # toss data already received
    ser.setDTR(True)  # remove reset signal - Arduino will restart
    try:
        while True:
            if '\n' in buffer:
                pass # skip if a line already in buffer
            else:
                buffer = buffer + ser.read(1).decode("utf-8")  # this will block until one more char or timeout
            buffer = buffer + ser.read(ser.inWaiting()).decode("utf-8")
            lines = buffer.split('\n') # Guaranteed to have at least 2 entries
            last_received = lines[-2]
            buffer = lines[-1]
            log("Serial received: " + last_received)
            if (last_received == "myButtonIsPressed"):
                # Do something here if the button on the Arduino is pressed
                ser.write("I got it!" + CRLF) # Sends back a message to the Arduino and shows it in the Arduino Serial Monitor
            else:
                log("nothing to work with")
                
    except Exception as e:
        log("Serial error communicating...: " + str(e))
        ser.close()
        raise
    ser.close()
              
serialThread = threading.Thread(target = read_serial)
#serialThread.daemon = True
serialThread.start()

link: http://www.lemaker.org/thread-7167-1-7.html