-
아두이노와 자바의 시리얼 통신(아두이노에서 자바로 0과 1을 전송)Arduino/Java Serial통신 2020. 11. 19. 18:27
자바에서 시리얼 통신을 설정하지 않았다면 아래의 글을 참고하자.
designatedroom87.tistory.com/315
아두이노에서 자바로 0과 1을 번갈아 가면서 데이터를 송신시키고 자바에서 수신을 해보자.
여기서, 자바에서 Thread의 개념을 이용해야 한다.
즉, 데이터를 수신 하거나 송신을 할 때 Thread의 개념을 이용하는 것이다.
우선 데이터를 수신하고 송신하는 클래스를 만들어보자.
이름은 각 각 SerialRead와 SerialWrite이다.
SerialRead클래스에서는 데이터를 수신하는 역할을 한다.
DataProc 클래스는 나중에 보자. 단순히 수신한 데이터를 출력하는 기능을 한다.
SerialRead.java
더보기import java.io.IOException; import java.io.InputStream; // 값을 읽는 클래스로, 이는 Thread로 구현해야 한다. public class SerialRead implements Runnable { InputStream in; public SerialRead(InputStream in){this.in = in;} @Override public void run() { byte[] buffer = new byte[1024]; int len = -1; try { // buffer에 저장하고나서, 그 길이를 반환한다. while ((len = this.in.read(buffer)) > -1) { // System.out.println(new String(buffer,0,len)); // new DataProc(new String(buffer,0,len)); String s = new String(buffer,0,len); if (len != 0) new DataProc(s); } } catch (IOException e) {e.printStackTrace();} } }
자바의 콘솔 입력 창의 입력 내용을 아두이노로 송신하는 클래스이다.
콘솔 창에 입력이 되었으면 외부로 내보낸다.
밖으로 out.write를 한다. 여기서는 반복분이 없다.
SerialWrite.java
더보기import java.io.IOException; import java.io.OutputStream; public class SerialWrite implements Runnable { OutputStream out; public SerialWrite(OutputStream out) {this.out = out;} @Override public void run() { int c = 0; try { while ((c = System.in.read()) > -1) { out.write(c); } } catch (IOException e) {e.printStackTrace();} } }
DataProc.java
더보기public class DataProc { String recvData; public DataProc(String recvData) { this.recvData = recvData; Print(); } public void Print() { System.out.println("DataProc : "+recvData); } }
Serial.java
앞의 기본설정 Serial.java내용에서 수정을 하면 된다.
읽기와 내보기는 스레드를 통해 구현 된다.
(new Thread(new SerialRead(in))).start();
new Thread(new SerialWrite(out)).start();더보기import java.io.InputStream; import java.io.OutputStream; import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; public class Serial { void connect(String port) { CommPort commPort = null; SerialPort serialPort = null; try { CommPortIdentifier com = CommPortIdentifier.getPortIdentifier(port); // com포트를 확인하는 작업 if (com.isCurrentlyOwned()) System.out.println("Error : "+port +"포트를 사용중입니다."); // 포트가 열려있으면 else { commPort = com.open(this.getClass().getName(),2000); // 획득한 포트를 객체가 사용할 수 있는지 여부 확인 if (commPort instanceof SerialPort) // commPort가 SerialPort로 사용할 수 있는지 확인 { serialPort = (SerialPort)commPort; // 정상적으로 포트를 사용할 수 있을 경우 // 포트에 필요한 정보를 입력해 준다. serialPort.setSerialPortParams( 9600, // 바운드레이트 SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // 오류제어 비트 } System.out.println("comport성공"); InputStream in = serialPort.getInputStream(); OutputStream out = serialPort.getOutputStream(); (new Thread(new SerialRead(in))).start(); new Thread(new SerialWrite(out)).start(); } } // end try catch(Exception e) {} } }
반드시 포트번호를 확인하도록 한다.
포트 번호는 다를 수 있다.
Main.java
더보기public class Main { public static void main(String[] args) { try { (new Serial()).connect("COM6"); } catch(Exception e) { e.printStackTrace(); } } }
그리고 마지막으로, 아두이노의 소스 파일이다.
반드시, 아두이노의 툴에서 아래와 같이 포트번호를 확인하자.
그리고 시리얼 통신 시에는 println함수가 아닌, write 함수를 이용해야 한다.
write 함수는 1바이트 단위로 전송하는 함수이다.
이 내용을 통틀어서 모두 write함수를 쓴다.
아두이노 소스 파일
더보기void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: Serial.write('0'); delay(1000); Serial.write('1'); delay(1000); }
또다른 아두이노 소스 파일
더보기void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: Serial.print(1); delay(200); Serial.print(0); delay(200); }
아두이노 소스 파일(아두이노에서 자바로 1과 0을 교대로 전송하고 자바에서 아두이노로 1 혹은 0을 전송)
더보기void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(13, OUTPUT); // 아두이노의 13번핀 옆에 L이라는 글자 옆에 LED가 있다. // 이 LED를 On/Off할 수 있다. } void loop() { // put your main code here, to run repeatedly: Serial.print(1); delay(200); Serial.print(0); delay(200); } // data를 받기 void serialEvent() { char c = Serial.read(); if (c == '1') digitalWrite(13, HIGH); else if (c == '0') digitalWrite(13, LOW); }
위에서 delay가 너무 작으므로, 각 각 1000으로 두도록 하자.
그리고, 만약 현재의 자바에서 프로그램이 실행 중이라면 아래와 같이 콘솔 창을 우클릭해서 Terminate/Disconnect All을 선택해서 종료를 하도록 한다.
그 이유는 포트를 사용 중이므로 아두이노에서 업로드가 되지 않는다.
그리고 나서, 아래와 같이 Remove All Terminated를 선택한다.
자바 콘솔 창에서 다음과 같은 결과를 볼 수 있다.
위의 내용을 잘 이해했다면 아래의 내용도 쉽게 이해할 수 있다.
designatedroom87.tistory.com/317
'Arduino > Java Serial통신' 카테고리의 다른 글
아두이노와 자바의 시리얼 통신(RFID) (0) 2020.12.01 아두이노의 데이터를 웹 페이지에 전송하기 (7) 2020.11.24 자바와 아두이노의 시리얼 통신(자바에서 1과 0을 전송함에따라 LED의 On/Off) (2) 2020.11.19 Java 시리얼 통신 기본 설정 (0) 2020.11.17