Arduino Uno in Proteus send � character - java

I'm writing a java program to read data from COM3 port. Data sent by Arduino [1]: https://imgur.com/a/MiNfTZN
But in Java Program (I'm using JSSC) it return � character. If I use RXTX, it return java.io.IOException: Underlying input stream returned zero bytes. I wonder how I can fix it?
This is my code
Using JSSC:
public class SerialTestJSSC {
private static SerialPort serialPort;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// выбор порта
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("Hurrah!!!");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
System.out.println("Received response from port: " + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
Using RXTX
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"COM3", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private static BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
public void initialize() {
// the next line is for Raspberry Pi and
// gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
//System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* Handle an event on the serial port. Read the data and print it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println("System "+inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public static void main(String[] args) throws Exception {
SerialTest main = new SerialTest();
main.initialize();
Thread t=new Thread() {
public void run() {
try {
Thread.sleep(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}}

Related

Java and XON XOFF serial print

I m build a java code to use xon xoff protocol to print a fiscal document with cash register Custom K3. This is the setting of this cash register.
This is the code about DriverPrinterSeriale.java
package prove;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.mcsolution.common.LoggerFactory.MyLog4J;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
public class DriverPrinterSeriale {
private SerialPort serialPort;
private OutputStream outStream;
private InputStream inStream;
public static MyLog4J log;
public DriverPrinterSeriale(String portaCOM){
log = new MyLog4J();
try {
this.connect(portaCOM);
} catch (IOException e) {
log.logStackTrace(e);
}
}
public void apriCassetto(){
try {
outStream = serialPort.getOutputStream();
//inStream = serialPort.getInputStream();
//log.information("output acquisito ");
String messageString = "a";
outStream.write(messageString.getBytes());
log.information("cassetto aperto");
} catch (Exception e) {
log.logStackTrace(e);
}
}
public void provaScontrino(String codiceDaInviare){
try {
outStream = serialPort.getOutputStream();
//inStream = serialPort.getInputStream();
log.information("output acquisito ora provo a stampare uno scontrino");
//String messageString = "j";
//outStream.write(messageString.getBytes());
//messageString = "'PANTALONE'10H1R";
//outStream.write(messageString.getBytes());
//String messageString = "\"MAGLIA. 1\"100H1R";
outStream.write(codiceDaInviare.getBytes());
//messageString = "1T";
//outStream.write(messageString.getBytes());
//messageString = "J";
//outStream.write(messageString.getBytes());
log.information("scontrino stampato ora apro il cassetto");
//apriCassetto();
} catch (Exception e) {
log.logStackTrace(e);
}
}
public void connect(String portName) throws IOException {
try {
// Obtain a CommPortIdentifier object for the port you want to open
CommPortIdentifier portId =
CommPortIdentifier.getPortIdentifier(portName);
log.information("apro porta seriale");
//System.out.println("apro porta seriale");
// Get
serialPort =
(SerialPort) portId.open("Demo application", 5000);
// Set the parameters of the connection.
setSerialPortParameters();
log.information("settaggio porta terminato");
} catch (NoSuchPortException e) {
log.logStackTrace(e);
throw new IOException(e.getMessage());
} catch (PortInUseException e) {
log.logStackTrace(e);
throw new IOException(e.getMessage());
} catch (IOException e) {
log.logStackTrace(e);
serialPort.close();
throw e;
}
}
/**
* Get the serial port input stream
* #return The serial port input stream
*/
public InputStream getSerialInputStream() {
return inStream;
}
/**
* Get the serial port output stream
* #return The serial port output stream
*/
public OutputStream getSerialOutputStream() {
return outStream;
}
/**
* Sets the serial port parameters
*/
private void setSerialPortParameters() throws IOException {
int baudRate = 19200; // 57600bps
//int baudRate = 38400; // 57600bps
try {
// Set serial port to 57600bps-8N1..my favourite
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE
);
log.information("settaggio porta iniziato");
serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
log.information("settaggio porta eseguito");
} catch (UnsupportedCommOperationException ex) {
log.logStackTrace(ex);
throw new IOException("Unsupported serial port parameter");
}
}
}
This is the code to print a fiscal document:
driverSeriale = new DriverPrinterSeriale("COM3");
String rigaDaStampare = "\"Pippo"+
"\"10"+"*1"+"H1R";
driverSeriale.provaScontrino(rigaDaStampare);
I have no error but I m not able to print fiscal document. nothing comes out of the cash register
I found a copy of your printer manual located here. Page 40 lists the printer parameters supported. From your description, it seems like there is a mismatch of parameters. First, I would try setting it to something other than CUSTOM XON-XOFF and see if the printer will work with hardware flow control. That shouldn't be a problem with today's equipment and may make this work out of the box.
If you can't change to hardware flow control, then I think you need to set flowcontrol in your serial port. Here is a link to Java documentation on setFlowControlMode. From the current configuration, it appears you might want to logical or include both FLOWCONTROL_XONXOFF_IN and FLOWCONTROL_XONXOFF_OUT.

Reading data from embedded controller using COM port

we are receiving data from controller using terminal software and as well as also java program ..
but think is that we get proper data on terminal software but java program can not show like terminal .. actually data come in ASCII and we convert to HEX terminal application show proper data but java program can not show terminal data.....
java program data
import java.io.*; // IOException
import java.util.*; // Scanner
import jssc.*;
/**
*
* #author Emiliarge
*/
public class ComPortSendReceive1 {
private static SerialPort serialPort;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// выбор порта
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("Hurrah!!!");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
for (char ch : receivedData.toCharArray()) {
System.out.format("%H ", ch);
} // prints "31 32 2E 30 31 33 "
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
}

Wait all byte (JSSC)

I'm trying to read a String from my Sara g350 module. I'm using a serial port comunication. The code that I use is this one:
private static SerialPort serialPort;
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// OPEN PORT
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("AT+CMEE=2");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
System.out.println("Received response from port: " + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
}
The Problem is that i read only the eco response and not all String.
I send "AT+CMEE=2" and the response could be:
AT+CMEE=2
OK
Can anyone help me? Thank you!

Exception ( java.io.IOException: Underlying input stream returned zero bytes ) while reading from Input Stream Serial Port Java

I am trying to read Input-Stream from Serial Port but getting an exception "java.io.IOException: Underlying input stream returned zero bytes"
Here is the code :
package communication;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import org.apache.commons.io.IOUtils;
public class Serial_0306 implements SerialPortEventListener {
public SerialPort serialPort;
private static final String PORT_NAMES[] = {
"COM3", // Windows
};
enter code herepublic static BufferedReader input;
public static OutputStream output;
public static InputStream inputStream;
public static final int TIME_OUT = 2000;
public static final int DATA_RATE = 9600;
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
inputStream = serialPort.getInputStream();
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8); // Exception over here
System.out.println("Result ::" + result);
output = serialPort.getOutputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
#Override
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
System.out.println("Result in Serial Event::" + result);
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
public static synchronized void writeData(String data) {
System.out.println("Sent: " + data);
try {
output.write(data.getBytes());
System.out.println("Received DATA BYTES");
} catch (Exception e) {
System.out.println("could not write to port");
}
}
public static void main(String[] args) throws Exception {
Serial_0306 main = new Serial_0306();
main.initialize();
Thread t = new Thread() {
public void run() {
//the following line will keep this app alive for 1000 seconds,
//waiting for events to occur and responding to them (printing incoming messages to console).
try {
Thread.sleep(1500);
writeData("CP");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
};
t.start();
System.out.println("Started");
}
}
**OUTPUT :
Stable Library
Native lib Version = RXTX-2.1-7
Java lib Version = RXTX-2.1-7
Started
java.io.IOException: Underlying input stream returned zero bytes
Sent: CP
could not write to port**
My actual need is to get input Stream from Serial Port and convert it to String.
But for testing purpose I am myself sending output stream and trying to read the same..But whenever I try to read input Stream I get the Exception.
Is my code correct? What else I need to do to get proper Input Stream and convert it to String.

How to add an EventListener to a thread - Java

I've created a Java thread that reads data through serial port. The main parts of the code is given below:
public class dthread implements Runnable{
public dthread(CommPortIdentifier portId)implements SerialPortEventListener {
try {
serialPort = (SerialPort) portId.open(this.getClass().getName(),TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {System.err.println(e.toString());}
}
public void serialEvent(SerialPortEvent oEvent){
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
String inputLine =null;
try {
// String inputLine=null;
if (input.ready()) {
inputLine = input.readLine();
System.out.println(inputLine);
}
} catch (Exception e) {System.err.println(e.toString());}
}
}
public void run() {}
}
portId - contains commportidentifier info. about the connected COM port; from another class.
public dthread(CommPortIdentifier portId)implements SerialPortEventListener { clearly, this is wrong. How should I implement SerialPortEvent in my code?

Categories