블루투스로 주기적으로 데이터를 전송하는 장비에서

시리얼로 데이터를 읽어오기 위한 테스트 코드

 

 

import serial
import binascii

 

ser = serial.Serial('/dev/ttyUSB1', 38400, timeout=1)
ser.timeout = None
t = ''
c = 0 

 

while 1:
    x = ser.read()
    t = t + x
    c = c + 1
    if  ord(x) == 13 : # 0x0d :
        print binascii.hexlify(t)
        print "%d\n" % (c)
        t = ''
        c = 0

 

시리얼라이브러리는 pySerial을 사용했다.

http://pyserial.readthedocs.org/en/latest/pyserial.html

 

몇가지 사항만 참고적으로 설명해 둔다.

 

리눅스에서 시리얼포트 확인방법은

/dev

라는 디렉토리를 검색해보면 된다.

USB 장비일 경우 위의 코드와 같이

 

/dev/ttyUSB0

부터 시작하는 장치파일이 생성된다.

 

이 코드에서는 두번째 USB포트를 38400 보오율로 오픈하도록 되어있다.

(실제 설정은 디폴트 값이 적용되어 38400,N,8,1 로 적용된다.)

 

ser.timeout 을 None으로 설정해서

블럭킹 모드로 동작하도록 한다.

 

  • timeout = None: wait forever / until requested number of bytes are received

  • timeout = 0: non-blocking mode, return immediately in any case, returning zero or more, up to the requested number of bytes
  • timeout = x: set timeout to x seconds (float allowed) returns immediately when the requested number of bytes are available, otherwise wait until the timeout expires and return all bytes that were received until then.
  •  

    read 함수를 통해 1바이트씩 읽어온다.

    read함수에 파라미터를 설정하면 해당 바이트만큼 읽어오도록 된다.

     

    read(size=1)


    Parameters:
    size – Number of bytes to read.
    Returns:
    Bytes read from the port.
    Return type:
    bytes

    Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.

     

    읽어온 바이트가 13(0x0d)가 되면 하나의 패킷 종료지점으로 보고 프린트하고 새로운 패킷을 기다린다.

     

    이때 읽어온 바이트를 10진수로 비교하기 위해 변환함수 ord를 사용한다.

     

    Posted by 휘프노스
    ,