(macOS)[python] pyserial을 이용한 Arduino UNO R3 제어 with vscode - 2/2
Intro
OS : MacOS, Monterey, v12.6
HW : Arduino UNO R3 board
SW : Visual Studio Code, so-called vscode
python : 3.10.7
arduino board setting with vscode in macOS
python library pyserial을 이용한 arduino serial 통신
1. Arduino Board Setting & Error Solutions
2. Arduino : Initialize, Serial, Verify, Upload
1편이 이어서.....
# 2번에서 Arduino Board Setting : Manager, Config, Serial, Build, Verify, Upload 완료되면 3번 skip 4번으로
# 2번 setting 완료 후 아래 참고
3. Arduino: Initialize
# arduino: initialize -> sketch.ino -> select board type
# Serial, Verify, Upload 까지...
py_ard_ini_project 폴더 생성 후 project 폴더를 연다.
command+shift+p : >Arduino: Initialize
py_ard_ini_project.ino : project 폴더명과 동일하게 스케치(.ino) 파일 생성
select board type : arduino Uno
Arduino Initialize 완료
Arduino: Select Serial Port
command+shift+p : >Arduino: Select Serial Port
3번째 usbmodem... 선택
하단 상태바(파란줄) : serial port 연결 확인
Arduino: Open Serial Monitor
command+shift+p : >Arduino: Open Serial Monitor
또는 하단 상태바(파란줄) 플러그버튼 클릭
# Arduino UNO R3 : baudrate 9600
하단 상태바(파란줄) : 9600(baudrate) 연결 확인
py_ard_ini_project.ino
// 초기값 설정 : inled의 13은 내장LED 번호, sw는 문자열로 표시
int inled = 13;
char sw = '1';
void setup() {
// Serial.METHOD 형식, begin은 사용, 9600은 baud rate, pinMode 설정
Serial.begin(9600);
pinMode(inled, OUTPUT);
// 동작 설명, Serial.println은 줄바꿈 포함
Serial.println("Default number is declared by sw = '1' ");
Serial.println(" '1' is Blink Mode every second for 5 times");
Serial.println(" '2' is turning on for 5 seconds");
Serial.println(" '0' is turned off & Serial shutdown");
Serial.println(" Others are jsut turned off but Serial port on");
}
void loop() {
// Serial.available은 serail 통신을 수신한 값으로 초기값이 0
// 전송창에 signal이 입력되면 Serial.available은 1을 가지며 loop를 돈다.
if(Serial.available() == 0){
Serial.println("Ready to input number");
// Serial input이 없을 때, 즉 Serial.available이 0일때 멈춤
while(!Serial.available());
Serial.println("");
}
// Serial.available이 0보다 크다는 건 입력값이 있을 때 다음 조건문을 실행하겠다는 의미
if(Serial.available()>0){
// if(sw가 1일때), 전송창에 입력되는 값을 sw에 저장
sw = Serial.read();
if(sw == '1'){
//if(조건){}else if(조건){}else{} 형태로 else는 if, else if외의 조건
//if 안에 for 조건문, 반복 변수 i 선언, for(초기값; 조건식; 증감식) 형태로 표시
int i;
Serial.println("Blink Mode every a second");
for(i=1; i<=5; i++){
Serial.print(" i = : ");
Serial.println(i);
digitalWrite(inled, HIGH);
Serial.println("inled is on");
delay(1000);
digitalWrite(inled, LOW);
Serial.println("inled is off");
delay(1000);
}
Serial.println("----- Blink Mode End -----");
Serial.println("");
}
else if(sw == '2'){
int j;
Serial.println("inled is Turning on for 5 seconds");
digitalWrite(inled, HIGH);
for(j=1; j<=5; j++){
Serial.print(" j = : ");
Serial.print(j);
Serial.println(" sec");
delay(1000);
}
Serial.println("----- Turn on Mode End -----");
Serial.println("");
digitalWrite(inled, LOW);
}
else if(sw == '0'){
Serial.println("Turn off & Serial shutdown");
digitalWrite(inled, LOW);
// Serial.end() 실행 후 전송창에 입력된 값을 통신하지 않음
Serial.end();
}
else{
digitalWrite(inled, LOW);
}
}
}
Arduino sketch code verify
command+shift+p : >Arduino: Verify
또는 우측 상단 아이콘(Arduino: Verify) 버튼 클릭
-출력-
[Starting] Verifying sketch 'py_ard_ini_project.ino'
Please see the build logs in output path: /Users/jiwonlee/persona/py_ard_ini_project/build
IntelliSense configuration already up to date. To manually rebuild your IntelliSense configuration run "Cmd+Alt+I"
[Done] Verifying sketch 'py_ard_ini_project.ino'
Arduino sketch code upload
command+shift+p : >Arduino: Upload
4. Arduino 내장 LED 제어 및 동작 확인
py_ard_ini_project/py_ard_control.py
import serial
serial_port = '/dev/tty.usbmodem142101'
serial_baudrate = 9600
# serial_baudrate = 115200
ard = serial.Serial(serial_port,serial_baudrate)
while(1):
if ard.readable():
# ard.readline() : Serial Monitor 내용을 한 줄씩 읽어온다.
smo = ard.readline()
# ard.decode() : readline을 decoding
msg = smo.decode()[:len(smo)-1]
# Arduino Serial Monitor 처럼 print
print(msg)
# 필자 코딩 구성 상 마지막 message check를 위함
pmsg = msg.strip()[0:5]
if pmsg == 'Ready':
print('input sw = ', end=' ')
sw = input()
print(sw)
# ard.write()를 이용해 Arduino Serial Monitor 전송창 입력값 전달
ard.write(sw.encode())
if sw == '0':
ard.close()
break
하단 터미널에서 1,2,0 입력하여 실행 확인
재시작은 arduino sketch file(.ino) upload 후 python 실행