Im doing serial communication in java,
my code will send, but doesn not recieve for some reason.
Help please!!!
/// including libraries
import javax.comm.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
/// Main class which handles the gui portion and connection with the Serial Port
public class CommSelect extends JFrame implements SerialPortEventListener {
/** Creates new form CommSelect */
public CommSelect() {
initComponents();
this.setResizable(false); // the main frame is set to not resizeable
disableFrame(); // other input fields are disabled , definition is given in the end
}
/// code generated by netbeans IDE for the GUI part
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
selPort = new javax.swing.JDialog();
jLabel2 = new javax.swing.JLabel();
portOptions = new javax.swing.JComboBox();
sePortButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
out_put = new javax.swing.JTextArea();
in_put = new javax.swing.JTextField();
connect = new javax.swing.JButton();
terminate = new javax.swing.JButton();
send = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
selPort.setTitle("Select the Desired Port");
selPort.getAccessibleContext().setAccessibleParent(connect);
jLabel2.setText("Select Port: ");
sePortButton.setText(" Ok ");
sePortButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
con2Port(evt);
}
});
javax.swing.GroupLayout selPortLayout = new javax.swing.GroupLayout(selPort.getContentPane());
selPort.getContentPane().setLayout(selPortLayout);
selPortLayout.setHorizontalGroup(
selPortLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(selPortLayout.createSequentialGroup()
.addGroup(selPortLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, selPortLayout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(jLabel2)
.addGap(37, 37, 37)
.addComponent(portOptions, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(sePortButton))
.addContainerGap(95, Short.MAX_VALUE))
);
selPortLayout.setVerticalGroup(
selPortLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(selPortLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(selPortLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(portOptions, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
.addComponent(sePortButton)
.addGap(32, 32, 32))
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Serial Prot Communication RS-232 ");
out_put.setColumns(20);
out_put.setRows(5);
jScrollPane1.setViewportView(out_put);
connect.setText(" Connect ");
connect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showCombBox(evt);
}
});
terminate.setText("Terminate");
terminate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closePort(evt);
}
});
send.setText("Send");
send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendData(evt);
}
});
jLabel1.setText("Enter the Data here you want to send to the microcontroller");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(in_put, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(send)
.addGap(13, 13, 13))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(terminate))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(connect))))
.addComponent(jLabel1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(23, 23, 23)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(connect, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(terminate, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(in_put, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(send))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/// event called when user clicks the send button
private void sendData(java.awt.event.ActionEvent evt) {
OutputStream outputStream;
try {
outputStream = myPort.getOutputStream(); /// getting the output stream of serial port
outputStream.write(in_put.getText().getBytes()); // sending data to the output stream
// but the data should be sent in bytes
// this is why i used .getBytes operation
// displaying the data in the area box
// concatenate the previous stream with a new stream
out_put.setText(out_put.getText() + "\n Sent Data:" + in_put.getText());
in_put.setText(""); // clear the input field
} catch (IOException e) { // alerting the user that data couldn't be sent
// by display dialog box.
JOptionPane.showMessageDialog(this,
"The Data Couldn't be sent",
"Inane error",
JOptionPane.ERROR_MESSAGE);
}
}
/// event called when user clicks the terminate button
private void closePort(java.awt.event.ActionEvent evt) {
commPort.close(); // close the port
out_put.setText(""); // empty the text area field
in_put.setText(""); // empty the input field
disableFrame(); // disabled the Frame again, definition is given in the end
}
/// event called when user clicks the ok button displayed in the Dialog box
private void con2Port(java.awt.event.ActionEvent evt) {
selPort.setVisible(false);
portName = (String) portOptions.getSelectedItem(); // getting the selection
/// getting the list of port and matching it with the user selected port
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
commId = null;
while (portList.hasMoreElements()){
commId = (CommPortIdentifier) portList.nextElement();
if (commId.getName() == portName)
break;
}
try{
commPort = commId.open("Anya",20000); // opening the port
/// casting the port in Seerial port beacuse its the sub class of Comm Port class
/// and we need to do the serial port communication only which will be in RS-232 mode
myPort = (SerialPort) commPort;
inputStream = myPort.getInputStream();
/// adding and event listerner fot the port we have acquired
/// so when the data is available on the port we can get it
/// rdData is a variable declare below and its class definition is also given below
/// when the data is available on the port an exception will be generated
/// and request will be forwarded to the SerialEvent function of the class defined below
myPort.addEventListener(this);
/// enabling the notify on data available event
myPort.notifyOnDataAvailable(true);
/// setting the parameter of the port
/// you can change the parameter as required
myPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
/// enabling the main frames buttons
enableFrame();
out_put.setText("Connected to the Port " + portName);
}catch(PortInUseException e1){ /// generated by .open function call
JOptionPane.showMessageDialog(this,
"The Selected Port Couldn't be opened",
"Inane error",
JOptionPane.ERROR_MESSAGE);
}
catch(UnsupportedCommOperationException e1) { /// generated by .setSerialPortPrams
JOptionPane.showMessageDialog(this,
"The Selected Port Couldn't be opened",
"Inane error",
JOptionPane.ERROR_MESSAGE);
}
catch(TooManyListenersException e1){ /// generated by .addEventListener
JOptionPane.showMessageDialog(this,
"You have a message from the controller",
"",
JOptionPane.ERROR_MESSAGE);
}
catch (IOException e) {}
}
/// event called when user clicks the connect button
private void showCombBox(java.awt.event.ActionEvent evt) {
portOptions.removeAllItems(); // clearing the pervious menu list in the combox
selPort.setVisible(true); // displaying the dialog box
selPort.setSize(400,150); // setting the size of dialog box
selPort.setResizable(false);
/// getting the list of available ports
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()){
CommPortIdentifier id_tmp = (CommPortIdentifier) portList.nextElement();
if (id_tmp.getPortType() == CommPortIdentifier.PORT_SERIAL){
if (id_tmp.getName() == null)
out_put.setText("Null");
else
portOptions.addItem(id_tmp.getName()); /// adding the name in the combox
}
}
portOptions.setSelectedIndex(0); /// setting the index of combox which item should it point
/// in the begining
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CommSelect().setVisible(true);
}
});
}
public void enableFrame (){
in_put.enable(true);
in_put.setBackground(Color.white);
out_put.enable(true);
out_put.setBackground(Color.white);
send.setVisible(true);
terminate.setVisible(true);
connect.setVisible(false);
}
public void disableFrame (){
in_put.enable(false);
in_put.setBackground(Color.GRAY);
out_put.enable(false);
out_put.setBackground(Color.GRAY);
send.setVisible(false);
terminate.setVisible(false);
connect.setVisible(true);
}
void serialEvent(SerialPortEvent event) {
/// getting teh input stream of the selected port due to which the
/// function is called
try {
switch(event.getEventType()) {
case SerialPortEvent.BI: // do nothing at Break Interrupt
case SerialPortEvent.OE: // do nothing at Over run Error
case SerialPortEvent.FE: // do nothing at Framing Error
case SerialPortEvent.PE: // do nothing at Parity Error
case SerialPortEvent.CD: // do nothing at Carrier Detect
case SerialPortEvent.CTS: // do nothing at Clear to Send
case SerialPortEvent.DSR: // do nothing at Dat set Ready
case SerialPortEvent.RI: // do nothing at Ring indication
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20]; // maximum no. of bytes you can get at a time
// can change it
/// keep checking teh buffer unless it gets empty
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
/// displaying the data over the text area field
out_put.setText(out_put.getText() + "\n Received Data:" + readBuffer);
}
break;
}
}catch (IOException e) {}
}
// Variables declaration - do not modify
private javax.swing.JButton connect;
private javax.swing.JTextField in_put;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea out_put;
private javax.swing.JComboBox portOptions;
private javax.swing.JButton sePortButton;
private javax.swing.JDialog selPort;
private javax.swing.JButton send;
private javax.swing.JButton terminate;
// End of variables declaration
/// variable declared for the serial port communication
CommPortIdentifier commId;
CommPort commPort;
SerialPort myPort;
String portName;
InputStream inputStream;
Thread readThread;
}

