0

I implemented a code that maintains Serial communications to different ports.

However, the same code is working perfectly with USB port /dev/ttyUSB0, but not working on port /dev/ttyAMA0 (This port is operating if I use PI4J library)

Baud rates :

/dev/ttyAMA0 - 115200
/dev/ttyUSB0 - 9600

I'm running on a raspberry pi 3B with Java 9

What I am missing here?

This is my code:

public class JSerialComm extends BaseSerial
{
    private SerialPort serial = null;
    private Object recLock = new Object();
    
    public JSerialComm()
    {
        super();
    }
    @Override
    protected boolean checkIsClosed()
    {
        return this.serial == null || !this.serial.isOpen();
    }

    @Override
    protected void registerToSerialEventListener()
    {
        
        this.serial.addDataListener(new SerialPortPacketListener()
        {

            @Override
            public void serialEvent(SerialPortEvent event)
            {
                try
                {
                    synchronized (recLock)
                    {
                        if(event.getSerialPort().bytesAvailable()>=getPacketSize())
                        {
                            final byte[] newData = new byte[getPacketSize()];
                            event.getSerialPort().readBytes(newData, getPacketSize());
                            
                            notifyHandlers(newData);
                        }
                    }
                }
                catch(Exception e)
                {
                }
            }

            @Override
            public int getListeningEvents()
            {
                return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
            }

            @Override
            public int getPacketSize()
            {
                return MindoLifeJSerialComm.this.getPacketSize();
            }
        });
    }

    @Override
    protected int sendByteToSerial(byte[] input) throws Exception
    {       
        return sendByteToSerial(input,input.length);
    }

    @Override
    protected void openPort(String portName, int baudRate) throws Exception
    {       
        for (SerialPort port : SerialPort.getCommPorts())
        {
            if (portName.toLowerCase().endsWith(port.getSystemPortName().toLowerCase()))
            {
                serial = port;
            }
        }
        
        if(serial == null)
        {
            throw new Exception("Couldn't find port " + portName );
        }
        
        serial.setBaudRate(baudRate);
        serial.setComPortTimeouts(SerialPort.TIMEOUT_NONBLOCKING, 0, 0);
        serial.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        serial.setParity(SerialPort.NO_PARITY);
        serial.setNumStopBits(SerialPort.ONE_STOP_BIT);
        
        if (!serial.openPort())
        {
            
            throw new Exception("Couldn't open port " + portName + " opened with baud " + baudRate);
        }
    }
    @Override
    protected int sendByteToSerial(byte[] input, int length) throws Exception {
        int res = serial.writeBytes(input, length);
        // TODO:flush
        return res;
    }
    @Override
    protected void closePort() {
        this.serial.closePort();
        
    }
}

Base class:

public abstract class BaseSerial
{
    HasSerialMessageHandler handler;
    
    private Object recLock = new Object();
    private int packetSize = 1;
    private String portName;

    protected final void notifyHandlers(byte[] newData)
    {
        if (handler != null)
        {
            handler.incoming(newData);
        }
    }
    
    private Object writeLock = new Object();

    public int write(byte[] input) throws Exception
    {
        return write(input, -1);
    }

    public int write(byte[] input, int length) throws Exception
    {
        int res = sendByteToSerial(input,length);       
        
        return res;
    }

    public void addListener(final HasSerialMessageHandler handler) throws TooManyListenersException
    {
        this.handler = handler;
        registerToSerialEventListener();
    }

    public boolean isClosed()
    {
        return checkIsClosed();
    }

    public void open(String portName, int baudRate) throws Exception
    {
        this.portName = portName;
        openPort(portName, baudRate);
        Thread.sleep(1000);
    }

    public int getPacketSize()
    {
        return packetSize;
    }

    public void setPacketSize(int packetSize)
    {
        this.packetSize = packetSize;
    }

    public void close()
    {
         closePort();
    }
    
    public String getPortName() 
    {
        return portName;
    }

    protected abstract boolean checkIsClosed();
    protected abstract void registerToSerialEventListener();

    protected abstract void openPort(String portName, int baudRate) throws Exception;

    protected abstract int sendByteToSerial(byte[] input) throws Exception;
    protected abstract int sendByteToSerial(byte[] input, int length) throws Exception;
    protected abstract void closePort();
}

Init and Usage (For both ports):

public class Main
{
        public static void main(String[] args)
        {
            BaseSerial serial = new JSerialComm ();
            serial.setPacketSize(14);
            
            serial.addListener(new HasSerialMessageHandler() {
            
            @Override
            public void incoming(final byte[] message)
            {               
                if (message.length > 0)
                {           
                    sysout(message);                    
                }               
            }
            
            serial.open("/dev/ttyAMA0", 115200);
        });
        }
}

My /etc/inittab is set as the following:

1:2345:respawn:/sbin/getty --noclear 38400 tty1
2:23:respawn:/sbin/getty 38400 tty2
3:23:respawn:/sbin/getty 38400 tty3
4:23:respawn:/sbin/getty 38400 tty4
5:23:respawn:/sbin/getty 38400 tty5
6:23:respawn:/sbin/getty 38400 tty6

# Example how to put a getty on a serial line (for a terminal)
#
#T0:23:respawn:/sbin/getty -L ttyS0 9600 vt100
#T1:23:respawn:/sbin/getty -L ttyS1 9600 vt100

# Example how to put a getty on a modem line.
#
#T3:23:respawn:/sbin/mgetty -x0 -s 57600 ttyS3


#Spawn a getty on Raspberry Pi serial line
#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
Rami Khawaly
  • 126
  • 3
  • 14
  • Perhaps this article? [How can I set the UART speed?](https://raspberrypi.stackexchange.com/q/1094) – kunif Oct 26 '21 at 16:57
  • It's not a matter of UART, I had to mention that it works with PI4J in both AMA and USB. – Rami Khawaly Oct 27 '21 at 05:14
  • I mentioned that it might be a problem with the config file(/boot/cmdline.txt, /etc/inittab) in the answer to that article. Does that mean there is no problem? – kunif Oct 27 '21 at 05:19
  • I just updated the original post with my inittab configuration for your reference – Rami Khawaly Oct 27 '21 at 05:29
  • Is the corresponding line of ttyAMA0 commented out and invalid in the presented /etc/inittab? It would be better to check it together with other information in the article answer introduced. – kunif Oct 27 '21 at 05:46
  • Do not use the inittab to perform basic configuration of a serial terminal. That's for setting up a terminal for logging into the system. Each program that opens the serial terminal should configure all termios settings (and not just the baudrate) to what ever it requires. Inspect the files in **/proc/tty/driver/** for statistics on the serial terminals. – sawdust Oct 27 '21 at 23:23
  • Which more settings I need to configure? As you see in my code, I configure all needed settings (Which I'm aware of, Pairity, stop bit and so ). I'm almost sure that it's not a matter of rpi configuration as it works smoothly with PI4J library.. however I'm trying all the advice here, still with no success – Rami Khawaly Oct 28 '21 at 05:31
  • *"Not working"* is a conclusion rather than a description of observed symptoms. *"I'm trying all the advice here, still with no success"* -- A sweeping generalization that lacks any details. Did you bother to look at /proc/tty/driver/ at all? – sawdust Oct 29 '21 at 05:37

0 Answers0