Languages/java

[Java] RS232 통신 예제

ten415 2022. 5. 6. 00:04
728x90
반응형

1. 개발 환경설정

윈도우에서 Java로 RS232통신을 하려면 우선 RXTXcomm.jar 와 dll이 필요하다 

각 운영체제별로 설치파일은 아래파일 사용하면된다 

64bit.zip
0.11MB
32bit.zip
0.11MB

이걸 그냥 개인 프로젝트에서 Build Path에 넣고 사용하는거보다 Java가 설치된 폴더의 lib 폴더와 bin 폴더에 각각 파일을 넣어주는 작업이 필요하다. 

어디는 jar 넣고 어디는 dll 넣고 하라는데 걍 구찮으니 둘다 넣어줌 (이상없음)

jre의 lib>ext 폴더
jre 의 bin

혹시나 개발하다 에러나면 jdk 하위에도 넣어주면 된다

jdk 하위 bin , lib

위 처럼 넣어주면 개발하는 과정에서 문제는 발생하지 않는다. 

2. java 기본 코드 

  일단 시작은 CO2 센서에서 발생시키는 RS232 데이터를 받아서 신호처리하는 경우이다. 

  RS232 to USB Cable 을 사용해서 노트북 USB에 연결해주면된다. 

  기본코드는 아래처럼 사용한다. 

  아래 기본코드는 시리얼로 수신된 데이터가 

  

   {........}

 

   처럼 '{' 로시작해서 '}' 로 마무리 된다는 전제하에 만들어진 코드이다.

   ASCII로만 데이터가 들어오면 모르겠는데, 주로 Hex 데이터가 많이 사용된다.

  아래 프로그램으로 데이터를 받아보고 특정 문자를 추출해서 센서별로 매뉴얼에 맞는 값을 사용하면 본인 입맛에 맞는 프로그램을 만들 수 있다. 

  실제로 아래 골격을 활용해서 24/7 online 장비에 사용 중 이다. 

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort; 
public class SensorSerialComm 
{
    public  Thread thIN;
    public  Thread thOUT;
    public  CommPort commPort ;
    
    //생성자
    public SensorSerialComm()
    {
        super();
    }
    
    //연결종료 
    public void disconnect(String portName){
    	//System.out.println("Closing: " + portName);
    	try {
            thIN.stop();
            thOUT.stop();
            commPort.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    // comport 접속부분
    public void connect ( String portName,int baudrate,int databit,int stopbit,int parity) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.err.println("Error: Port is currently in use");
        }
        else
        {
             commPort = portIdentifier.open(this.getClass().getName(),2000);
            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                if(databit == 8 && stopbit == 1 && parity == 1){
                serialPort.setSerialPortParams( baudrate,
                               SerialPort.DATABITS_8,//5678
                               SerialPort.STOPBITS_1, //1,2
                               SerialPort.PARITY_NONE);//even mark none odd space
                }else if(databit == 8 && stopbit == 2 && parity == 1){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_8,//5678
                            SerialPort.STOPBITS_2, //1,2
                            SerialPort.PARITY_NONE);//even mark none odd space
                }else if(databit == 8 && stopbit == 1 && parity == 2){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_8,//5678
                            SerialPort.STOPBITS_1, //1,2
                            SerialPort.PARITY_EVEN);//even mark none odd space
                }else if(databit == 8 && stopbit == 2 && parity == 2){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_8,//5678
                            SerialPort.STOPBITS_2, //1,2
                            SerialPort.PARITY_EVEN);//even mark none odd space
                }else if(databit == 7 && stopbit == 1 && parity == 1){
                serialPort.setSerialPortParams( baudrate,
                               SerialPort.DATABITS_7,//5678
                               SerialPort.STOPBITS_1, //1,2
                               SerialPort.PARITY_NONE);//even mark none odd space
                }else if(databit == 7 && stopbit == 2 && parity == 1){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_7,//5678
                            SerialPort.STOPBITS_2, //1,2
                            SerialPort.PARITY_NONE);//even mark none odd space
                }else if(databit == 7 && stopbit == 1 && parity == 2){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_7,//5678
                            SerialPort.STOPBITS_1, //1,2
                            SerialPort.PARITY_EVEN);//even mark none odd space
                }else if(databit == 7 && stopbit == 2 && parity == 2){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_7,//5678
                            SerialPort.STOPBITS_2, //1,2
                            SerialPort.PARITY_EVEN);//even mark none odd space
                }else if(databit == 6 && stopbit == 1 && parity == 1){
                serialPort.setSerialPortParams( baudrate,
                               SerialPort.DATABITS_6,//5678
                               SerialPort.STOPBITS_1, //1,2
                               SerialPort.PARITY_NONE);//even mark none odd space
                }else if(databit == 6 && stopbit == 2 && parity == 1){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_6,//5678
                            SerialPort.STOPBITS_2, //1,2
                            SerialPort.PARITY_NONE);//even mark none odd space
                }else if(databit == 6 && stopbit == 1 && parity == 2){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_6,//5678
                            SerialPort.STOPBITS_1, //1,2
                            SerialPort.PARITY_EVEN);//even mark none odd space
                }else if(databit == 6 && stopbit == 2 && parity == 2){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_6,//5678
                            SerialPort.STOPBITS_2, //1,2
                            SerialPort.PARITY_EVEN);//even mark none odd space
                }else if(databit == 5 && stopbit == 1 && parity == 1){
                serialPort.setSerialPortParams( baudrate,
                               SerialPort.DATABITS_5,//5678
                               SerialPort.STOPBITS_1, //1,2
                               SerialPort.PARITY_NONE);//even mark none odd space
                }else if(databit == 5 && stopbit == 2 && parity == 1){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_5,//5678
                            SerialPort.STOPBITS_2, //1,2
                            SerialPort.PARITY_NONE);//even mark none odd space
                }else if(databit == 5 && stopbit == 1 && parity == 2){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_5,//5678
                            SerialPort.STOPBITS_1, //1,2
                            SerialPort.PARITY_EVEN);//even mark none odd space
                }else if(databit == 5 && stopbit == 2 && parity == 2){
                    serialPort.setSerialPortParams( baudrate,
                            SerialPort.DATABITS_5,//5678
                            SerialPort.STOPBITS_2, //1,2
                            SerialPort.PARITY_EVEN);//even mark none odd space
                }
                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();
                thIN = null;
                thOUT = null;
                thIN  = new Thread(new SerialReader(in));
                thOUT = new Thread(new SerialWriter(out));
                thIN.start();
                thOUT.start();
            }
            else
            {
                System.err.println("Error: Only serial ports are handled by this example.");
            }
        }     
    }
    
    //시리얼데이터 수신 부분 (스레드로 별도로 처리함)
    public class SerialReader implements Runnable{
        InputStream in;
        public SerialReader(InputStream in){
            this.in = in;
        }
        public void run (){
            byte[] buffer = new byte[512];
            int len = -1;
            StringBuffer stbCompleteSentence = new StringBuffer();
             byte start = 0;
			try {
				
				//시리얼 데이터 read
				while ((len = this.in.read(buffer)) > -1) {
					System.out.println("len = " + len);
					for(int i = 0;i<len;i++){
						System.out.println("RX>" + String.format("%02X",buffer[i]));
							if("7B".equals(String.format("%02X",buffer[i])) == true){
								stbCompleteSentence.append(String.format("%02X",buffer[i]));
								start = 1;
							}else if("7D".equals(String.format("%02X",buffer[i])) == true && start == 1){
								start = 0;
								stbCompleteSentence.delete(0, stbCompleteSentence.length());
							}else if(start == 1){
								stbCompleteSentence.append(String.format("%02X",buffer[i]));
							}
					}
				}
			} catch (IOException e) {
		       e.printStackTrace();
			}          
        }
    }



    //시리얼 데이터 전송 부분 (스레드로 별도로 처리함)
    public  class SerialWriter implements Runnable 
    {
        OutputStream out;
        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }
        
        public void run ()
        {
            try
            {                
                int c = 0;
                StaticPool.ValveOpenCommand = 1;
                
                while ( StaticPool.ACIPIDSerialCommLoop ){
                	byte ARR = 0;
                	if(StaticPool.ValveOpenCommand == 1){
                    	 ARR = (byte)Short.parseShort("41", 16); //A
                	}else if(StaticPool.ValveOpenCommand == 2){
                	     ARR = (byte)Short.parseShort("42", 16); //B
                	}else if(StaticPool.ValveOpenCommand == 3){
                      	 ARR = (byte)Short.parseShort("43", 16); //C
                   	}else if(StaticPool.ValveOpenCommand == 4){
                      	 ARR = (byte)Short.parseShort("44", 16); //D
                   	}else if(StaticPool.ValveOpenCommand == 5){
                      	 ARR = (byte)Short.parseShort("45", 16); //E
                   	}else if(StaticPool.ValveOpenCommand == 6){
                      	 ARR = (byte)Short.parseShort("46", 16); //F
                   	}else if(StaticPool.ValveOpenCommand == 0){
                     	 ARR = (byte)Short.parseShort("5A", 16); //Z
                  	}
                		this.out.write(ARR);
                			this.out.flush();
                    try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                } //while
            }//try                
            //}
            catch ( IOException e )
            {
                e.printStackTrace();
            }            
        }
    }
    
    public static void main ( String[] args )
    {
        try
        {
            new SensorSerialComm().connect("COM8",9600,8,1,1);
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
728x90
반응형