⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rs232.java

📁 本源码给出了在jbuilder下实现串口通信,并且如何使用
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.comm.*;

public class RS232 extends Frame implements ActionListener, 
  WindowListener, ItemListener, SerialPortEventListener {

  Frame Fs;
  Choice comPort;
  TextField byteField;
  Button sendBytes;
  Button sendHex;
  Button selectFile; 
  Button quit; 
  Button clear; 
  Button getFile;
  Panel p1, p2, p3;
  TextArea tArea; 
  TextArea tArea2; 
  Label bytesSent;
  Label byteCount;
  Label bytesReceived;
  Label byteCount2;
  int cnt2;
  String fileName;
  String filePath;
  String portSelected;
  String s1;
 
  Enumeration portList;
  CommPortIdentifier portId;
  String messageString = "Hello, world!\n";
  SerialPort serialPort;
  // Stream for displaying bytes on screen
  OutputStream outputStream;
  // Stream for writing bytes to a file
  OutputStream outputStream2;
  boolean gettingFile;
  InputStream inputStream;
  File readFile;
  InputStream fin;
  boolean portOpen = false;
  // Send HEX values - Java interprets HEX notation as integers, 
  // so they must be cast to bytes
  byte[] byteCommand = {(byte)0xff, (byte)0xfe, (byte)0xfd, 
                        (byte)0xfc, (byte)0xfb, (byte)0xfa};

  public RS232() {
  
    super("Send and Read bytes via RS232 Serial Port"); 
    Fs = new Frame(); 
    //setLayout(new FlowLayout(FlowLayout.CENTER,15,15));

    // NORTH Panel

    comPort = new Choice();
    // add items to comPort list
    comPort.add("Select Port");
    comPort.add("COM1");
    comPort.add("COM2");
    comPort.add("COM3");
    comPort.add("COM4");
    //portSelected = "- Select Port -";
    portSelected = "Select Port";
    p1 = new Panel();
    p1.add(comPort);
    // register choice to receive item events
    comPort.addItemListener(this);
    byteField = new TextField("Enter Data");
    p1.add(byteField);
    sendBytes = new Button("Send Bytes");
    p1.add(sendBytes);
    sendBytes.addActionListener(this);
    add(p1, BorderLayout.NORTH);
    sendHex = new Button("Send Hex");
    p1.add(sendHex);
    sendHex.addActionListener(this);
    add(p1, BorderLayout.NORTH);
    selectFile = new Button("Send File");
    p1.add(selectFile);
    selectFile.addActionListener(this);
    add(p1, BorderLayout.NORTH);

    // CENTER Panel

    p2 = new Panel(new GridLayout(1,2));
    tArea = new TextArea(5,58);
    p2.add(tArea);
    tArea.setText("");
    tArea2 = new TextArea(5,58);
    p2.add(tArea2);
    tArea2.setText("");
    add(p2, BorderLayout.CENTER);


    // SOUTH Panel

    p3 = new Panel();
    bytesSent =new Label("Bytes out: ");
    p3.add(bytesSent);
    byteCount = new Label("0      ");
    p3.add(byteCount);
    getFile = new Button("Get File");
    p3.add(getFile);
    getFile.addActionListener(this);
    clear = new Button("Clear");
    p3.add(clear);
    clear.addActionListener(this);
    quit = new Button("Quit");
    p3.add(quit);
    quit.addActionListener(this);
    bytesReceived =new Label("Bytes in: ");
    p3.add(bytesReceived);
    byteCount2 =new Label("0      ");
    p3.add(byteCount2);
    add(p3, BorderLayout.SOUTH);

    cnt2 = 0;

    setBackground(Color.white);
    setFont(new Font("Monospaced", 1, 16));
    //setBounds(50,50,550,325);
    setBounds(50,50,680,375);
    setVisible(true);
    addWindowListener(this);

  }

  public void actionPerformed(ActionEvent evt) {

    String command;
    command=evt.getActionCommand();

    if (command.equals("Send Bytes")) {
      if (portOpen) {
        sendBytes();
        return;
      }
      doComms();
    }

    if (command.equals("Send Hex")) {
      if (portOpen) {
        sendHex();
        return;
      }
      doComms();
    }

    if (command.equals("Send File")) {
      if (portOpen) {
        sendFile();
        return;
      }
      doComms();
    }

    if (command.equals("Get File")) {
      // if we have just received a file close the output stream 
      if (gettingFile) {
        gettingFile = false;
        try{
          outputStream2.close();
          } catch (IOException e){}
      }
      if (portOpen) {        
        dialogBox("SAVE");
        if (!fileName.equals("nullnull")) {
          gettingFile = true;
          try{
            outputStream2 = new FileOutputStream(fileName);
          } catch (IOException e){}
          tArea2.append("Listening for " + fileName + "...\n");
          cnt2 = 0;
          byteCount2.setText(""+ cnt2);
        }
        else
          tArea2.append("No file name entered.\n");
        return;
      }
      doComms();
    }

    if (command.equals("Clear")) {
      byteField.setText("");
      tArea.setText("");
      tArea2.setText("");
      byteCount.setText("");
      byteCount2.setText("");
      cnt2 = 0;
      if (gettingFile) {
        gettingFile = false;
        try{
          outputStream2.close();
          } catch (IOException e){}
      }
    }

    if (command.equals("Quit")) {
      System.exit(0);
    }
  }

  public void windowClosing(WindowEvent evt) {
    Frame f = (Frame)evt.getSource(); 
    f.dispose();
    // Free the console (eg,MSDOS Prompt, Unix Shell)
    System.exit(0);
  }
  public void windowClosed(WindowEvent evt) {};
  public void windowOpened(WindowEvent evt) {}
  public void windowIconified(WindowEvent evt) {}
  public void windowDeiconified(WindowEvent evt) {}
  public void windowActivated(WindowEvent evt) {}
  public void windowDeactivated(WindowEvent evt) {}

  public void itemStateChanged(ItemEvent ie) {
    if (portOpen) {
      tArea.append(" To change port, Quit program and restart\n");
      comPort.select(portSelected);
      repaint();
      return;
    }
    portSelected = comPort.getSelectedItem();
    if (!portSelected.equals("Select Port"))
      tArea.append(" " + portSelected + " selected.\n");
    doComms();
  }

  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:
      case SerialPortEvent.DATA_AVAILABLE:
        int b=0;
        try {
          while (inputStream.available() > 0) {
            b = inputStream.read();
            byteCount2.setText(""+ ++cnt2);

            if (gettingFile) {
              outputStream2.write(b);
            }
            else {
               if (!Character.isISOControl((char)b)) 
                 s1 = " " + String.valueOf((char)b) + "\t";
               else
                 s1 = "  \t";
                 s1 = s1 + padLeft(String.valueOf(b), 3, " ") + "\t";
                 s1 = s1 + padLeft(Integer.toBinaryString(b), 8, "0") + "  ";
                 s1 = s1 + padLeft(Integer.toHexString(b).toUpperCase(), 2, " ") + "\n";
                 tArea2.append(s1);
            }
          } // End while
        } // End try
        catch (IOException e) {}
        break;
      
    } // End switch
  } // End serialEvent()

  public void doComms() {
    if (portSelected.equals("Select Port")) { 
      tArea.append(" No port selected.\n");
      return;
    }
    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        if (portId.getName().equals(portSelected)) {
          try { serialPort = (SerialPort)
            portId.open("FileSendApp", 2000);
          } catch (PortInUseException e) {
              tArea.append(e + "\n");
              tArea.append("Try another port.\n");
              System.out.println(e);
              return;
            }
                 
          // Create an OutputStream to send bytes down serial port

          try {
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {}

          // Create an InputStream to receive bytes from serial port

          try {
            inputStream = serialPort.getInputStream();
          } catch (IOException e) {}

          //System.out.println("serialPort.getInputStream(): null");}
	  try {
            serialPort.addEventListener(this);
	  } catch (TooManyListenersException e) {}

          // Omit this and the listener ignores data received!
          serialPort.notifyOnDataAvailable(true);

          // Set the baud rate, number of data bits, stop bit and parity
  
          try {
            serialPort.setSerialPortParams(9600,
            SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1,
            SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {}

          portOpen = true;
         
        }
      }
    }
  }

  public void sendBytes() {
    int cnt=0;
    byte[] sBytes = byteField.getText().getBytes();
    tArea.append(" Sending " + sBytes.length + " bytes ...\n");
    tArea.append(" Char\tDec\tBinary   Hex\n");
    /*****
      try {
        outputStream.write(byteCommand);
      } catch (IOException e) {}
    ******/
    for (int i = 0; i < sBytes.length; i++) {
      int b = sBytes[i];
      byteCount.setText(""+ ++cnt);
      try {
        outputStream.write(sBytes[i]);
      } catch (IOException e) {}
      s1 = " " + String.valueOf((char)b) + "\t";
      s1 = s1 + padLeft(String.valueOf(b), 3, " ") + "\t";
      s1 = s1 + padLeft(Integer.toBinaryString(b), 8, "0") + "  ";
      s1 = s1 + padLeft(Integer.toHexString(b).toUpperCase(), 2, " ") + "\n";
      tArea.append(s1);
    }
  }

  public void sendHex() {
    int cnt=0;
    tArea.append(" Sending 255 bytes ...\n");
    tArea.append(" Char\tDec\tBinary   Hex\n");

    for (int i = 0; i < 256; i++) {
      byteCount.setText(""+ ++cnt);
      try {
        outputStream.write(i);
      } catch (IOException e) {}
      if (!Character.isISOControl((char)i)) 
        s1 = " " + String.valueOf((char)i) + "\t";
      else
        s1 = "  \t";
      s1 = s1 + padLeft(String.valueOf(i), 3, " ") + "\t";
      s1 = s1 + padLeft(Integer.toBinaryString(i), 8, "0") + "  ";
      s1 = s1 + padLeft(Integer.toHexString(i).toUpperCase(), 2, " ") + "\n";
      tArea.append(s1);
    }

  }

  public void sendFile() {
    // We've found a port - now select a file to send
    dialogBox("LOAD");

    if (fileName.equals("nullnull")) {
      tArea.append("No file selected.\n");
      return;
    }

    // Create a File object from the file selected
                    
    readFile = new File(fileName);

    // Check if file exists
    File newFile = new File(fileName);
    if (!newFile.exists()) {      
      tArea.append("No file selected.\n");
      return;
    }               
    tArea.append(fileName + " selected. File size: " + newFile.length() + " bytes.\n");
    // Create a FileInputStream to read bytes from the File

    try {
      fin = new FileInputStream(readFile);
    } catch (FileNotFoundException e) {}

    try {
      int b,cnt=0;
      while ((b = fin.read()) != -1) {
        byteCount.setText(""+ ++cnt);
        outputStream.write(b);
      }      
      //outputStream.write(messageString.getBytes());
      byteCount.setText(""+cnt);
      tArea.append("Finished sending: "+fileName+" - "+cnt + " bytes sent.\n");
    } catch (IOException e) {}
  }

  public void dialogBox(String mode) {

    FileDialog fd=null;
    if (portSelected.equals("Select Port")) { 
      tArea.append("No port selected.\n");
      return;
    }
    //FileDialog fd = new FileDialog(Fs, "Select a File");
    if (mode.equals("LOAD"))
      fd = new FileDialog(Fs, "Select a File", FileDialog.LOAD);
    else
      fd = new FileDialog(Fs, "Save File as:", FileDialog.SAVE);
    fd.setVisible(true);
    fileName = fd.getFile();
    // Find the path of the file
    filePath = fd.getDirectory();
    fileName = filePath + fileName;
   
  }

  String padLeft(String s, int i, String str) {
    for(; s.length() < i; s = str + s);
      return s;
  }

  public static void main(String args[]) {
    RS232 sendRead = new RS232();
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -