Arduino Serial Monitor와 Python 연결

황동준·2021년 1월 14일
1

정말 간단하다. python 파일만 수정하면 되는데, 일단 예시코드로 다음과 같이 작성했다.

import serial
import time

ser = serial.Serial('com8', 9600)
time.sleep(2)

id = 1
id = str(id)
print(id)
ser.write(id.encode())
time.sleep(10)

먼저 아두이노를 다루기 위해서는 다음과 같은 package를 설치해야 한다.
pip install pyserial
이후에 import serial을 선언하여 이 라이브러리를 이용하면 된다.
serial.Serial()에는 두가지 변수가 있는데 이는 Arduino의 Serial.begin과 같다. 그러나 python은 어디 포트에 아두이노가 연결되어 있는지 모르기 때문에,

serial.Serial(port, baudrate)
# baudrate = 9600으로 동일하게 설정
# port같은 경우 연결되어있는 포트번호를 arduino IDE의
# 메뉴 툴에 들어가서 COM#으로 이루어 진것을 입력하면 된다. (only Window)
# 윈도우가 아니면 경로를 입력하면 된다. (dev/port#)

이렇게 설정하면 Arduino IDE의 Serial Monitor대신 python으로 소통할 수 있게 되는 것이다.

주의사항 : Arduino IDE의 serial Monitor을 킨 상태로 이 코드를 실행할 수 없다. 한번에 하나의 Serial Monitor에만 연결될 수 있기 때문.
마찬가지로 python에서 serial monitor을 쓰고 있을 때는 Arduino IDE의 serial monitor을 쓸 수 없다.

그리고 ser.write, ser.read등으로 python에서 serial monitor와 통신할 수 있다. (매우 신기하다.)

이때 python에서 받은 변수 string은 type이 string으로 Arduino serial monitor에 입력될 수 없다. serial monitor

bytes type의 변수만 입력, 출력이 가능하기 때문이다.

따라서 string변수라면 string.encode()를 통해 해당 변수를 byte로 바꿔주고 넘긴다. 만약 int형이라면 string으로 바꿔주고 encode()도 해준다.

마찬가지로 command창에서 serial monitor에서 출력된 값을 보고 싶다면 decode를 해준후 print해줘야 한다.

위 코드를 실행할 경우 다음과 같이 7 segment에 1이 뜨는 것을 알 수 있었다.

또한 이를 얼굴인식 프로그램에 넣어서 인식한 얼굴의 id값을 출력하게 하였다. 적용한 방법은 다음과 같다.

ser = serial.Serial('com8', 9600)
time.sleep(2) #delay because of serial communication

...

	if (confidence < 55):
            id_num = str(id)
            id = names[id]
            in_lab_list[0] = id
            in_lab_set_compare = set(in_lab_list)
            in_lab_set_compare = in_lab_set_compare & in_lab_set
            if not in_lab_set_compare:
                ser.write(id_num.encode())
                f_write = open('lab_user.txt', 'a')
                in_lab_set.add(id)
                f_write.write(str(id) + '\n')
                f_write.close()

인식을 중복으로 하면 계속 한번 코드가 돌아가도 계속 해야 될 수도 있기 때문에, set을 이용해서 해당 부분을 처리했다. text파일은 인식한 사람 이름을 저장해 놓는 파일이다.

profile
부담없이 기록하기

0개의 댓글