개발/파이썬(PYTHON)

[PYTHON] Serial Port 통신

보안인 2020. 12. 14. 13:51
반응형

이번 포스팅 내용은 파이썬에서 serial 통신을 하는 내용이다.

 

먼저 추가해줘야 할 모듈이 두개 있다. 

C:\..\Python\Python38-32\python.exe "D:/develop/python/ Python_test/Education/day1.py"

Traceback (most recent call last):

  File "D:/develop/python/ Python_test/Education/day1.py", line 2, in <module>

    import serial

ModuleNotFoundError: No module named 'serial'

 

Process finished with exit code 1

 

pip 를 통해 serial 모듈 설치 완료!!

D:\develop\python\ Python_test\mysite>pip install serial

Collecting serial

  Using cached serial-0.0.97-py2.py3-none-any.whl (40 kB)

Requirement already satisfied: pyyaml>=3.13 in c:\..\python\python38-32\lib\site-packages (from serial) (5.3.1)

Requirement already satisfied: iso8601>=0.1.12 in c:\..\python\python38-32\lib\site-packages (from serial) (0.1.13)

Requirement already satisfied: future>=0.17.1 in c:\..\python\python38-32\lib\site-packages (from serial) (0.18.2)

Installing collected packages: serial

Successfully installed serial-0.0.97

 

시리얼 포트 연결을 위해 아래와 같이 시리얼 디스크립터를 로드한다. 

ser = serial.Serial(port='COM3', baudrate=115200, parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)

 

그럼 아래와 같이 serial 모듈에 'Serial' attribute 를 추가 설치!!

C:\..\Python\Python38-32\python.exe "D:/develop/python/ Python_test/Education/day1.py"

Traceback (most recent call last):

  File "D:/develop/python/ Python_test/Education/day1.py", line 6, in <module>

    ser = serial.Serial(port='COM3', baudrate=115200, parity=serial.PARITY_NONE,

AttributeError: module 'serial' has no attribute 'Serial'

 

Process finished with exit code 1

 

pip 를 통해 'pyserial' 패키지를 설치하여 Serial attribute 를 사용할 수 있다. 

D:\develop\python\ Python_test\mysite>pip install pyserial

Collecting pyserial

  Downloading pyserial-3.5-py2.py3-none-any.whl (90 kB)

     |████████████████████████████████| 90 kB 803 kB/s

Installing collected packages: pyserial

Successfully installed pyserial-3.5

 

D:\develop\python\ Python_test\mysite>

 

목적이 serial 포트로 input 되는 데이터를 그대로 출력하는 코드는 간단한다.

코드 공유하면 아래와 같다.

Serial 함수 호출 시, port, baudrate, parity 비트, stopbits, bytesize 를 정의해주면 된다. 

 

우선 프로그래밍 하기 전 데이터를 확인하기 위해서는 하이퍼터미널이나  테라텀(TeraTerm)을 활용할 수 있다. 

import serial

ser = serial.Serial(port='COM3', baudrate=115200, parity=serial.PARITY_NONE,
                    stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
if ser.readable():
    res = ser.readline()
    print(res.decode()[:len(res) - 1])

 

대부분의 경우, 위의 코드로 serial 포트로 들어오는 데이터를 활용할 수 있겠지만, 

 

하지만 저자의 경우는 readline()으로 데이터를 읽어오면 일정한 구분자를 통해서 들어오는 데이터를 잘라서 활용할 수 없어서, byte 단위로 데이터를 받아서 처리해야만 했다. 

buffer=""
while True:
   oneByte = f.read(1)
   if oneByte == b"\r":    #byte단위로 read, 구분자 '\r'
       break
   else:
       buffer += oneByte.decode()

print (buffer.strip())

 

다음 포스팅에서는 이렇게 받아들인 데이터로 matplotlib.pyplot를 통한 차트 생성 포스팅 예정이다.

반응형