สิ่งที่ต้องมี
- เครื่องคอมพิวเตอร์ที่ลงโปรแกรม
- Python
- Arduino IDE - บอร์ด Arduino
- สาย USB เชื่อมต่อระหว่าง arduino กับ คอมพิวเตอร์
เขียนโปรแกรมpython
ติดตั้งแพคเกจของ python ก่อนด้วยคำสั่ง pip install pyserial
code ตัวรับ
from time import sleepimport serialtry:serialPort = serial.Serial(port = "COM3", baudrate=9600,bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)print("OK the port is opened!")while(1):if(serialPort.in_waiting > 0):serialString = serialPort.readline()captured_data = serialString.decode('Ascii')print(captured_data)sleep(1)except serial.SerialException as error:print("Failed {}".format(error))
code ตัวส่ง-ตัวรับ
code อาดูโน่ arduinofrom time import sleepimport serialtry:serialPort = serial.Serial(port = "COM3", baudrate=9600,bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)print("OK the port is opened!")while(1):txtsend = input("กรอกข้อมูลที่ต้องการส่ง : ")if(txtsend=="on"):print("")serialPort.write(txtsend.encode())serialString = serialPort.readline()captured_data = serialString.decode('Ascii')print(captured_data)sleep(1)else:print("Not Match!")if(txtsend=="exit"):exit()sleep(1)except serial.SerialException as error:print("Failed {}".format(error))
//กำหนดขา LEDไปที่ขา 2
int LED = 2;
void setup() {
//ตั้งค่า Serial 9600
Serial.begin(9600);
//กำหนดให้ LEDเป็นOUTPUT
pinMode(LED, OUTPUT);
}
void loop() {
//หน่วงเวลา 1วินาที
delay(1000);
//สร้างตัวแปร tesstr เพื่อไว้อ่านข้อมูลจาก pythonที่ส่งมา
String tesstr = Serial.readString();
//กำหนดเงื่อนไข
//ถ้า tesstr รับค่าได้ เท่ากับ onให้ทำคำสั่งด้านล่าง
if(tesstr == "on"){
Serial.println("LED : ON");
digitalWrite(LED, HIGH);
delay(1000);
digitalWrite(LED, LOW);
delay(1000);
digitalWrite(LED, HIGH);
delay(1000);
digitalWrite(LED, LOW);
delay(1000);
digitalWrite(LED, HIGH);
delay(1000);
digitalWrite(LED, LOW);
delay(1000);
}
}
0 ความคิดเห็น