Serial Communication Gi A Python Và Arduino

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

PYTHON: SERIAL COMMUNICATION GIỮA LAPTOP VÀ ARDUINO

1. Code Python:

import serial
import time
arduino = serial.Serial(port='COM7', baudrate=9600, timeout=.1)

while True:
arduino.write(b'32767')
time.sleep(0.01)
S1 = arduino.readline()
time.sleep(0.01)
S2=S1.decode()
if S2!='':
S3 = int(S2)
print(S3+1)
print("Ket thuc")

arduino.readline(): đọc trọn vẹn 1 dòng, kết thúc khi gặp xuống dòng.
2. Code Arduino:
int giaTri;
void setup() {
Serial.begin(9600);
Serial.setTimeout(10);
}

void loop() {
while (!Serial.available());
giaTri=Serial.readString().toInt();
Serial.println(giaTri);

Giá trị lớn nhất của biến Int trong Arduino là 32767.
Serial.println(giaTri): ghi giá trị xong rồi xuống dòng.

You might also like