'pyserial'에 해당되는 글 1건

  1. 2020.10.18 Arduino serial communication with Python - 아두이노 시리얼 통신 2
반응형

파이썬 모듈인 pySerial을 이용해 간단히 아두이노와 시리얼 통신을 할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
char state;
 
void setup() {
  // put your setup code here, to run once:
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  Serial.println("Arduino ready.");
}
 
void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available())
  {
    state = Serial.read();
    while (Serial.available())
    {
      Serial.read();  // 첫 번째 문자만 입력받고 나머지는 버린다.
    }
    
    if (state == '0')
    {
      digitalWrite(LED_BUILTIN, LOW);
      Serial.println("LED OFF");
    } else
    {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.println("LED ON");
    }
  }
 
  delay(100);
}


위 소스를 컴파일 하고 아두이노에 업로드 한다. 시리얼 모니터를 통해서도 Builtin LED를 제어할 수 있다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import serial
import time
import sys
 
try:
    ser = serial.Serial('COM5'9600, timeout = 1)
    time.sleep(1)
except:
    print("Device can not be found or can not be configured.")
    sys.exit(0)
 
if (ser.readable()):
    print(ser.readline().decode(), end =''# 아두이노 준비 상태 확인.
    # 아두이노에서 Serial.println("Arduino ready"); 명령으로 데이터를 보내기 때문에
    # Serial 통신으로 읽어온 데이터에는 줄바꿈 문자(\r\n)가 이미 포함되어 있다.
    # Serial.print("Arduino ready");으로 바꾸면 end = ''가 필요 없다. 
 
while (True):
    print("\n0: Off, 1: On, q(Q): Quit\nChoose: ", end = '')    
    state = input()
 
    if state == 'q' or state == 'Q':
        break
    elif state == '0':
        ser.write(b'0')
        print(ser.readline().decode(), end = '')
    else:
        ser.write(b'1')
        print(ser.readline().decode(), end = '')
 
    time.sleep(0.1)
 
ser.close()


Windows에서 위 소스를 실행하면 연결된 아두이노의 Builtin LED를 제어할 수 있다.

※ 참고: https://pythonhosted.org/pyserial/




이 프로그램과 Arduino IDE의 시리얼 모니터를 동시에 실행시킬 수는 없다.


반응형
Posted by J-sean
: