I have a network configuration as:
Arduino--Xbee--> <--Xbee-Arduino--> Java App on PC
I had burnt a code into the Sender node to send 1s continuously to the Receiver. But what i see is that even after burning a new code into the Sender to send different values, i keep getting the 1s in the receiver end and not the latest values. How do i get over this problem? Is there a way to flush the previous unwanted data?
The code that i use is from a tutorial that i found in the arduino website. Copy pasting the same below:
Receiver Code: Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM3", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private 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() {
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(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() {
//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(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}
}
I had burnt a code into the Sender node to send 1s continuously to the Receiver. But what i see is that even after burning a new code into the Sender to send different values, i keep getting the 1s in the receiver end and not the latest values.
How do i get over this problem?
You shall reflash your Arduino. Try reflashing with 2s instead of 1s, and back, you'll see it'll stop sending 1s.
Is there a way to flush the previous unwanted data?
The data itself is gone away on every unplugging of your Arduino.
It looks like your Arduino code did not get uploaded to the board, either you had a connection problem, or your new arduino code is not compiling. Have a good look at the error message the IDE compiler should be returning.
Related
What I wish to do:
Read Serial.println from my Arduino(COM3) without majoy delay in time
What my situation is:
This Java program delays roughly 20 seconds in Serial input.
This has been achieved by the Arduino IDE Serial monitor. I wanted to embed the serial monitor code into my Java application.
Following attaches useful code (This program is supposed to be ran on a computer receiving Serial.):
package arduino;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {"COM3"};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private 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 = 50000;
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=null;
if (input.ready()) {
inputLine = input.readLine();
System.out.println(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() {
//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(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}
}
Following attaches useful code supposed to ran on Arduino, involves using arcade joystick. I tested it without problems in Serial Monitor, just thought I would attach it in.
/*
The Joystick Adapter to Snake Display
Joystick connected to DIGITAL port 5 - 2
*/
//Define pins
const int joyA = 5;
const int joyB = 4;
const int joyC = 3;
const int joyD = 2;
//Begin.
void setup(){
pinMode(joyA,INPUT);
pinMode(joyB,INPUT);
pinMode(joyC,INPUT);
pinMode(joyD,INPUT);
Serial.begin(9600);
}
void loop(){
boolean a = isaxisPressed(joyA);
boolean b = isaxisPressed(joyB);
boolean c = isaxisPressed(joyC);
boolean d = isaxisPressed(joyD);
if(a){
Serial.println("A");
}else if(b){
Serial.println("B");
}else if(c){
Serial.println("C");
}else if(d){
Serial.println("D");
}else{
Serial.println("Z");
}
}
boolean isaxisPressed(int port){
pinMode(port,OUTPUT);
digitalWrite(port,HIGH);
pinMode(port,INPUT);
return !digitalRead(port);
}
I am trying to connect to my serial port "COM6", but now I cannot connect to it. I tried printing out the list of serial ports available using portId.getName(). It shows a list of serial ports available but COM6 is not showing there.
This is my Java code:
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM6")) {
//if (portId.getName().equals("/dev/term/a")) {
try {
serialPort = (SerialPort)
portId.open("Arduino", 2000);
} catch (PortInUseException e) {
System.out.println("Error1 is "+ e);
}
try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
System.out.println("Error2 is "+ e);
}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
System.out.println("Error3 is "+ e);
}
try{
byte data1 = 1;
outputStream.write(data1);
System.out.println("helo");
System.out.println(data1);
}catch(IOException e){
System.out.println("Error 3: " + e);
}
}
}
}
serialPort.close();
I have checked the COM6 in my device manager. It shows available. If I run the same com port in vb it works perfectly. Can anyone help me with this problem. Thank you.
I guess you are trying to communicate with an Arduino? If so, you have to install the Arduino IDE - there is also the RXTX library included, which is very similar to the Java Communication API.
Then you can try this code, which is very similar to yours:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyACM0", // Raspberry Pi
"/dev/ttyUSB0", // Linux
"COM3", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private 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(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() {
//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(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}
}
The code comes from the Arduino Playground, I'm not able to try it out now, but I connected an Arduino two or three months ago with this code (Windows 8, 64Bit). There are also other methods described in the post, as well as all necessary requirements (e.g. classpath variables) - check them out in your system setting.
Hope it helps.
java is not seeing the arudino on COM4 the code seems to be working
package tester;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyACM0", // Raspberry Pi
"/dev/ttyUSB0", // Linux
"COM4", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private 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(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() {
//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(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}}
seems to be working but all i get in console is
WARNING: RXTX Version mismatch
Jar version = RXTX-2.2pre1
native lib Version = RXTX-2.2pre2
Could not find COM port.
Started
i looked in to the jar version being off but rxtx asked for it in there stable release
Why are you assuming that it will be always "COM4" on windows ? Maybe try to get the com port like this (from http://www.programcreek.com/java-api-examples/index.php?api=gnu.io.CommPortIdentifier):
public static List<String> getSerialPorts(){
List<String> vp=new ArrayList<String>();
Enumeration portList=CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
CommPortIdentifier portId=(CommPortIdentifier)portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
vp.add(portId.getName());
}
}
return vp;
}
As an alternative to RxTx and the (deprecated) Java Communications API I had luck with jSerialComm
I made a dialog box with a drop down choice of 127 com ports (without the reserved) as the first thing to let the app know which COM port is in use. Then used it in the constructor for the next new class instance.
Alright, I'll try to be as clear as possible with my problem.
I'm transmitting serial data over a veeeeeeery slow radio link (using the UART-controller on the raspberry pi and a home-built radio). It's for a very specific project where the requirement is spelled long range and speed is of less importance.
The program (Radio.java) is running two threads. One thread (Receiver) receives telemetry data from another program using a TCP-socket (which is very high speed, actually 100mbit). This thread continuously saves the data it receives on the TCP-socket in an ArrayBlockingQueue (with size = 1) so that the other thread (Transmitter) can reach this data. The rate at which the Receiver-thread receives data is pretty high. Now, I want Transmitter-thread to transmit the data and when it's finished I want it to again get the latest data from Receiver-thread and transmit it again over the slow-radio-link.
So in transmitter-thread I want it to work like this:
Get latest data from Receiver-thread
Transmit data over radio link (using the serialport)
Don't do ANYTHING until the data is actually transmitted.
repeat.
Now, when I'm running the program everything regarding the Receiver-thread is working just fine. But inside the transmitter-thread the line "this.out.write(output.getBytes());" just puts everything inside the OutputStream in a couple of milliseconds, and then again does the same thing. The data has no chance in being transmitted!
I've tried the example (only using the "SerialWriter"-thread) here:
http://rxtx.qbang.org/wiki/index.php/Two_way_communcation_with_the_serial_port
And using a long "Lirum Ipsum"-text everything worked just fine transmitting in 50baud. So basically, I want the same behaviour in my program as using System.in.read > -1... (which I guess is blocking, the reason it works???).
What should I do?
2015-01-01 edit BEGIN
I've found the problem! SRobertz lead me into the right direction! The problem is actually not the writespeed to the UART-buffer. The difference between running the "TwoWayComm"-example and my own code is that I'm running a GPS connected to UART-RX-port of the Raspberry Pi. To read data from the GPS is use the "GPSD"-software (which outputs data in a JSON-format). The GPSD-software connects to the GPS with 9600baud (specifically for this GPS-unit), while I switch to 50 baud on the same port (without closing the open connection that GPSD is running)! Trying to open UART with two different baud-rates is what is messing everything up.
I've rewritten the code so that I:
Open UART on 9600 baud
Read GPS data
Close the UART
Open UART on 50 baud
Transmit telemetry data to UART
Close UART
Repeat
And now everything works like a charm...
2015-01-01 edit END
So ... here is the code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
public class RADIO {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(1);
void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier
.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
int timeout = 2000;
CommPort commPort = portIdentifier.open(this.getClass().getName(),
timeout);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(50, SerialPort.DATABITS_7,
SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
// Open outputstream to write to the serial port
OutputStream out = serialPort.getOutputStream();
(new Thread(new Receiver(queue))).start();
(new Thread(new Transmitter(out, queue))).start();
} else {
System.err.println("Error: Not serial port.");
}
}
}
public static class Receiver implements Runnable {
OutputStream out;
protected ArrayBlockingQueue<String> queue = null;
public Receiver(ArrayBlockingQueue<String> queue) {
this.queue = queue;
}
public void run() {
// Open TCP-connection
try {
ServerSocket serverSocket = new ServerSocket(1002);
Socket clientSocket = serverSocket.accept(); // Wait for the client to start up
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null) {
queue.clear();
queue.put(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static class Transmitter implements Runnable {
OutputStream out;
protected ArrayBlockingQueue<String> queue = null;
String output = "";
public Transmitter(OutputStream out, ArrayBlockingQueue<String> queue) {
this.out = out;
this.queue = queue;
}
public void run() {
try {
while (true) {
output = queue.take();
this.out.write(output.getBytes());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
(new RADIO()).connect("/dev/ttyAMA0");
} catch (Exception e) {
e.printStackTrace();
}
}
}
(a small caveat: I haven't used gnu.io on the raspberry pi)
First, to isolate the problem, I would put a fairly long sleep in the transmitter thread, after this.out.write... to verify that the problem is not waiting for the serial port to
finish the transmission.
If that works, then you can try waiting for OUTPUT_BUFFER_EMPTY, by adding a
SerialPortEventListener and setting notifyOnOutputEmpty(true), making your
SerialPortEventListener a monitor along the lines of
class ExampleMonitor implements SerialPortEventListener {
boolean condition;
public synchronized serialEvent(SerialPortEvent ev) {
condition = true;
notifyAll();
}
public synchronized void awaitCondition() throws InterruptedException {
while(!condition) wait();
condition = false;
}
and then do
myExampleMonitor.awaitCondition() instead of the sleep in the transmit thread.
See http://rxtx.qbang.org/wiki/index.php/Event_based_two_way_Communication for the inverse use of events (note that there, there is no monitor and no waiting; instead, the work is done in the listener/callback.)
I have this class called Main.java. In this the output is shown by inputLine which is a string taken serially from the com port. I want this string value to be used in some other class which is in the same default package. How do I call this string in other class? I have made a static and declared it outside the method. Now do I call in other class. When I try calling it in other class by Main.inputLine=1 then it says incomparable types.
Also I'm attaching a snapshot of the error: http://oi45.tinypic.com/2gvo5u9.jpg
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.lang.String;
import java.util.Enumeration;
public class Main implements SerialPortEventListener
{
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"COM30", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results code page independent
*/
public BufferedReader input;
/** The output stream to the port */
public 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() {
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 static String inputLine;
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
inputLine=input.readLine();
System.out.println(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 {
Main main = new Main();
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(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}
}
You're trying to compare two things and one of them is an Object (String). Use equals(Object o).
(Besides, comparison between primitives is done using ==.
You're trying to compare to an integer value. You need to wrap the integer value to a String for this to make much sense.
You want:
if(Main.inputLine.equals("1"))
{
...
}
If you are trying to assign 1 to Main.inputLine then use the following :
Main.inputLine="1"
instead of
Main.inputLine=1
And if you are comparing the String to check for 1 then use the following:
Main.inputLine.equals("1");
instead of
Main.inputLine == "1"