Using eclipse and java how to read the data from the pcb board with a serial cable, because the data of the pcb board arrive via cable in binary format. How to save the data that will be displayed in the compiler?
Someone help me please.
Below is the code I am writing to do this, but it does not detect any port when I plug in the serial cable
import gnu.io.*;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TooManyListenersException;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) {
boolean portFound = false;
String defaultPort ="COM 1" ;
if (args.length > 0) {
defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port: "+defaultPort);
portFound = true;
SimpleRead reader = new SimpleRead();
}
}
}
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}
}
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print("The Read Bytes from SerialPort are");
System.out.write(readBuffer);
System.out.println();
}
System.out.print(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
}
Log Result:
port COM 1 not found.
The port names don't have spaces in them. Try changing:
String defaultPort ="COM 1" ;
to:
String defaultPort ="COM1" ;
Related
i couldn't find any article upon "place call using java with a HSDPA Dongle" on google. i have done port initialization but don't know what to do for placing call.
1) i am using Huawei Dongle.
2) I have found error "NO CARRIER".
3) i am using the following code to detect port or modem and trying to place call but its giving me "NO CARRIER" error ! what mistake i am doing here kindly help me please
import java.io.*;
import java.util.*;
import gnu.io.*;
import java.io.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.apache.log4j.chainsaw.Main;
import sun.audio.*;
public class GSMConnect implements SerialPortEventListener,
CommPortOwnershipListener {
private static String comPort = "COM6"; // This COM Port must be connect with GSM Modem or your mobile phone
private String messageString = "";
private CommPortIdentifier portId = null;
private Enumeration portList;
private InputStream inputStream = null;
private OutputStream outputStream = null;
private SerialPort serialPort;
String readBufferTrial = "";
/** Creates a new instance of GSMConnect */
public GSMConnect(String comm) {
this.comPort = comm;
}
public boolean init() {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(comPort)) {
System.out.println("Got PortName");
return true;
}
}
}
return false;
}
public void checkStatus() {
send("AT+CREG?\r\n");
}
public void dial(String phoneNumber) {
try {
//dial to this phone number
messageString = "ATD" + phoneNumber + ";\r\n";
outputStream.write(messageString.getBytes());
System.out.println("Called ");
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String cmd) {
try {
outputStream.write(cmd.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String phoneNumber, String message) {
char quotes ='"';
send("AT+CMGS="+quotes + phoneNumber +quotes+ "\r\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// send("AT+CMGS=\""+ phoneNumber +"\"\r\n");
send(message + '\032');
System.out.println("Message Sent");
}
public void hangup() {
send("ATH\r\n");
}
public void welcomeMessage(){
// open the sound file as a Java input stream
String gongFile = "C:\\Users\\SACHIN\\Desktop\\7001110.mp3";
InputStream in;
try {
in = new FileInputStream(gongFile);
// create an audiostream from the inputstream
// AudioStream audioStream = new AudioStream(in);
// play the audio clip with the audioplayer class
// AudioPlayer.player.start(audioStream);
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream(gongFile));
clip.open(inputStream);
clip.start();
} catch (IOException | UnsupportedAudioFileException | LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void connect() throws NullPointerException {
if (portId != null) {
try {
portId.addPortOwnershipListener(this);
serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
} catch (PortInUseException | UnsupportedCommOperationException e) {
e.printStackTrace();
}
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
/** These are the events we want to know about*/
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.notifyOnRingIndicator(true);
} catch (TooManyListenersException e) {
e.printStackTrace();
}
//Register to home network of sim card
send("ATZ\r\n");
} else {
throw new NullPointerException("COM Port not found!!");
}
}
public void serialEvent(SerialPortEvent serialPortEvent) {
switch (serialPortEvent.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
System.out.println("Ringing");
/*try {
Thread.sleep(5000);
send("ATA");
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
break;
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[2048];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print(numBytes);
if((readBuffer.toString()).contains("RING")){
System.out.println("Enter Inside if RING Loop");
welcomeMessage();
}
}
//readBufferTrial=readBufferTria;//+new String(readBuffer)+new Date();
//print response message
System.out.print(new String(readBuffer));
} catch (IOException e) {
}
break;
}
}
public void outCommand(){
System.out.print(readBufferTrial);
}
public void ownershipChange(int type) {
switch (type) {
case CommPortOwnershipListener.PORT_UNOWNED:
System.out.println(portId.getName() + ": PORT_UNOWNED");
break;
case CommPortOwnershipListener.PORT_OWNED:
System.out.println(portId.getName() + ": PORT_OWNED");
break;
case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
System.out.println(portId.getName() + ": PORT_INUSED");
break;
}
}
public void closePort(){
serialPort.close();
}
public static void main(String args[]) {
GSMConnect gsm = new GSMConnect(comPort);
if (gsm.init()) {
try {
System.out.println("Initialization Success");
gsm.connect();
Thread.sleep(5000);
gsm.checkStatus();
Thread.sleep(5000);
System.out.println("Before Auto Answer");
gsm.send("ATS0=1");
Thread.sleep(1000);
gsm.dial("87SSSXXX9105");
// Thread.sleep(1000);
// gsm.welcomeMessage();
// Thread.sleep(1000);
// gsm.welcomeMessage();// for turning on Echo ATE1&W
Thread.sleep(20000);
gsm.hangup();
Thread.sleep(1000);
gsm.closePort();
gsm.outCommand();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Can't init this card");
}
}
}
First you have to check if your HSDPA dongle really supports calls. A lot of HSDPA sticks only support SMS and data.
If it does and you have e.g. a virtual serial port you can connect from your Java program to it using e.g. Java RXTX and send AT-Commands like ATDT01234567 (dial 01234567) to the stick.
I saw that there are a lot of question with the serial i/o operation so i decided to share a snippet of my code in which i read serial data from a serial port with the RXTX library.
This class read wait when there are data on the serial port and printed it.The class also save data in a String named data which can be obtained from another class
import java.io.*;
import java.util.*;
import javax.comm.*;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static String data = "";
public static String getData() {
return data;
}
public static void setData(String data) {
SimpleRead.data = data;
}
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {
// if (portId.getName().equals("/dev/term/a")) {
SimpleRead reader = new SimpleRead();
}
}
}
}
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {System.out.println(e);}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {System.out.println(e);}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {System.out.println(e);}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {System.out.println(e);}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {System.out.println(e);}
}
public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
String data1="";
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
data1=data1+(String) numBytes;
}
setData(data1)
System.out.print(new String(readBuffer));
} catch (IOException e) {System.out.println(e);}
break;
}
}
}
The code for readig data from the serial port into another class
SimpleRead simpleRead=new SimpleRead;
String finalData="";
simpleRead.run();
finalData=simpleRead.getData()
I have an XBee-PRO S1 on Arduino Uno R3 which acts like a transmitter to send data to another XBee which is acting like a receiver to turn on the LEDs connected to it. Here is what I'm doing:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;
public class NewClass implements SerialPortEventListener {
SerialPort serialPort;
OutputStream out;
private static final String PORT_NAME = "COM10"; //(XBee Transmitter)
private BufferedReader input;
private static final int TIME_OUT = 2000;
private static final int DATA_RATE = 9600;
// End of input chars
//private static final byte EOIC = 3;
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, find an instance of serial port as set in PORT_NAME.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
if (currPortId.getName().equals(PORT_NAME)) {
portId = currPortId;
}
}
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);
// Open the input stream
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.setEndOfInputChar((byte) 3);
}
catch (PortInUseException | UnsupportedCommOperationException | IOException | TooManyListenersException 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 {
char inputLine;
//dat = new ArrayList<Character>();
if (input.ready()) {
inputLine = (char) input.read();
Thread.sleep(1500);
sendChar();
}
}
catch (Exception e) {
System.err.println(e.toString());
System.out.println("Error reading");
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public synchronized void sendChar() {
try {
Thread.sleep(1500);
out = serialPort.getOutputStream();
System.out.println("out is not null");
for (int i = 0; i <= 900; i++) {
Thread.sleep(1500);
out.write((char) 'A');
out.flush();
System.out.println(i+") written-> A"); //For debugging
}
}
catch (InterruptedException | IOException e) {
}
}
public synchronized void cRead(char data) {
if (data != ' ') {
System.out.print(data);
//getTimestamp();
}
}
public static void main(String[] args) throws Exception {
NewClass main = new NewClass();
main.initialize();
Thread t = new Thread() {
#Override
public void run() {
//The following line will keep this application alive for 12 hours,
//waiting for events to occur and responding to them (printing
//incoming messages to console).
try {
Thread.sleep(43200000);
}
catch (InterruptedException ie) {
}
}
};
t.start();
System.out.println("Started");
}
}
One problem with this code is that, when I get some incoming signal at the COM port then only the sendChar() is called which is due to the condition if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE). Also the data is not being sent. I don't know what other event types are there because of lack of proper documentation.
What I want is to send data to Arduino without receiving anything. What am I doing wrong or missing?
i am using net beans 7 ide and java 6 to develop my java projects. i used the following coding to read value from serial port :
import java.io.*;
import java.util.*;
import javax.comm.*;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
JOptionPane.showMessageDialog(null, "portList :"+portList.hasMoreElements());
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM3")) {
// if (portId.getName().equals("/dev/term/a")) {
SimpleRead reader = new SimpleRead();
}
}
}
}
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {System.out.println(e);}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {System.out.println(e);}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {System.out.println(e);}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {System.out.println(e);}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {System.out.println(e);}
}
public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
System.out.print(new String(readBuffer));
} catch (IOException e) {System.out.println(e);}
break;
}
}
}
When i execute from netbeans, JOptionPane showing "portList : true"
but when i double click on the jar file and tried to run, JOptionPane showing " portList : false"
Why there is different output trying to execute same java code
I have two computers running this code:
import java.io.*;
import java.util.*;
import gnu.io.*;
public class Deb implements SerialPortEventListener, Runnable{
public static final int TIMEOUTSECONDS = 30;
public static final int BAUD = 9600;
static String telefono;
static Boolean llamar = false;
CommPortIdentifier cpiModem = null;
SerialPort modem;
BufferedReader is;
PrintStream os;
Thread hiloMarcado;
int nConnects = 0;
boolean flag = false;
String line;
public static void main(String argv[]) throws PortInUseException, UnsupportedCommOperationException, IOException, InterruptedException, TooManyListenersException {
if (argv.length>0) {
telefono = argv[0];
llamar = true;
}
new Deb();
}
public Deb() throws PortInUseException, UnsupportedCommOperationException, IOException, InterruptedException, TooManyListenersException{
Enumeration pList = CommPortIdentifier.getPortIdentifiers();
while (pList.hasMoreElements()) {
CommPortIdentifier cpi = (CommPortIdentifier)pList.nextElement();
if (cpi.getPortType()==CommPortIdentifier.PORT_SERIAL) {
SerialPort puertoSerie = (SerialPort) cpi.open("DEB", TIMEOUTSECONDS * 1000);
puertoSerie.setSerialPortParams(BAUD, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
puertoSerie.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN & SerialPort.FLOWCONTROL_RTSCTS_OUT);
BufferedReader is = new BufferedReader(new InputStreamReader(puertoSerie.getInputStream()));
PrintStream os = new PrintStream(puertoSerie.getOutputStream(), true);
os.println("AT");
Thread.sleep(TIMEOUTSECONDS * 50);
if (!is.ready()) {
System.out.println("No hay un modem en " + cpi.getName());
} else {
System.out.println("Hay un modem en " + cpi.getName());
cpiModem = cpi;
}
puertoSerie.close();
}
}
modem = (SerialPort) cpiModem.open("DEBita", TIMEOUTSECONDS * 1000);
modem.setSerialPortParams(BAUD, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
modem.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN & SerialPort.FLOWCONTROL_RTSCTS_OUT);
is = new BufferedReader(new InputStreamReader(modem.getInputStream()));
os = new PrintStream(modem.getOutputStream(), true);
modem.addEventListener(this);
modem.notifyOnDataAvailable(true);
modem.notifyOnCarrierDetect(true);
modem.notifyOnBreakInterrupt(true);
modem.notifyOnCTS(true);
modem.notifyOnDSR(true);
modem.notifyOnFramingError(true);
modem.notifyOnOutputEmpty(true);
modem.notifyOnOverrunError(true);
modem.notifyOnParityError(true);
modem.notifyOnRingIndicator(true);
/*System.out.println(is.read());*/
if (llamar) {
hiloMarcado = new Thread(this);
hiloMarcado.start();
}
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.DSR:
System.out.println("Data Set Ready.");
break;
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
System.out.println("Ignored event");
break;
case SerialPortEvent.BI:
System.out.println("Break Interrupt");
break;
case SerialPortEvent.CTS:
System.out.println("Clear to send");
break;
case SerialPortEvent.RI:
System.out.println("Pick up the receiver.");
if( event.getNewValue() )
{
System.out.println("Ring Indicator On");
}
else
{
System.out.println("Ring Indicator Off");
}
break;
case SerialPortEvent.CD:
if (event.getNewValue()) {
System.out.println("Connected");
nConnects = nConnects + 1;
} else {
System.out.println("Disconnected");
}
break;
case SerialPortEvent.DATA_AVAILABLE:
handleData();
break;
}
}
public void run() {
while (true) {
if (nConnects == 0) {
try {
if (!modem.isCD()) {
System.err.println("Estamos llamando ...");
os.println("ATDT" + telefono);
}
Thread.sleep(TIMEOUTSECONDS * 2000);
} catch (Exception ex) {
System.err.println("Failed to write message");
}
}
}
}
public void handleData() {
try {
int avail = modem.getInputStream().available();
byte[] response = new byte[avail];
StringBuffer strbuf = new StringBuffer();
modem.getInputStream().read(response, 0, avail);
if (!flag) {
modem.getInputStream().read(response, 0, avail);
for (int i = 0; i < avail; i++) {
Thread.sleep(5);
os.write((char) response[i]);
System.out.print((char) response[i]);
}
}
} catch (IOException ie1) {
System.out.println("File " + ie1);
} catch (InterruptedException in) {
System.out.println("Interrupt " + in);
}
}
}
It isn't the final version, I'm only seeing how it works. The thing is that when I use this code to dial to a phone number, for example, my mobile phone, it works, but it doesn't work the other way round; that is, calling from my number and acting the programme as a listener. I tried also with 2 computers, neither of them get the calls from the other end. Am I doing something wrong? I would appreciate any help.
AT-compatible modems should send a “RING” over the data line to notify you of an incoming ring event. Maybe you could listen for that?