Python เป็นภาษาหนึ่งในการเขียนโปรแกรม ที่ผมว่าน่าจะครอบจักรวาลเลยก็ว่าได้
นอกจากจะเขียนง่ายแล้วยังทำได้เกือยทุกอย่าง อย่าตอนนี้ที่จะลองใช้กัน พอดีต้องเขียนโปรแกรม
เพื่อติดต่อกับ Serial Port หรือ Com Port นั่นเอง จริง ๆ อาจมีหลายภาษาที่ทำได้เหมือนกัน
แต่เราจะมาลองเขียนด้วย Python บน Windows กันครับ (จริง ๆ Linux ก็น่าจะได้เหมือนกัน)
โปรแกรมที่ต้องใช้
1. Python 2.5 เป็นตัวแปลภาษาของ python ครับ ดาวน์โหลดได้จาก http://www.python.org/download/ [1]
2. PyWin32 เป็น extension สำหรับการติดต่อบน Windows ดาวน์โหลดได้จาก http://sourceforge.net/projects/pywin32/ [2]
3. PySerial เป็น extension สำหรับติดต่อกับ Serial Port พระเอกของเราในครั้งนี้ครับ ดาวน์โหลดได้จาก http://sourceforge.net/projects/pyserial/ [3]
เมื่อ โหลดมาแล้ว เราก็มาลองทดสอบกัน โดยที่ http://pyserial.sourceforge.net/ [4] ก็มีตัวอย่างให้ครับ
#!C:/Python25/python.exe
import serial
ser = serial.Serial(0) # เปิดพอร์ต serial พอร์ต 0 หรือพอร์ตแรก
print ser.isOpen()
ser.close()
เมื่อลองรันดู ผมที่ได้คือ
>> True
หมายถึงพอร์ตเปิดแล้ว
ยังมีคำสั่งอื่น ๆ ให้ใช้อีกมากมายครับ เช่น
setRTS(level=1) #set RTS line to specified logic level
setDTR(level=1) #set DTR line to specified logic level
getCTS() #return the state of the CTS line
getDSR() #return the state of the DSR line
getRI() #return the state of the RI line
getCD() #return the state of the CD line
สำหรับผม ใช้คำสั่ง setRTS() เพื่อกำหนดให้วงจรปิดเปิดไปทำงาน ตอนนี้ถือว่าใช้ได้เลยทีเดียว ง่ายและรวดเร็ว
ส่วน Front-End ก็อาจจะใช้ PyGTK ก็ได้ครับ
Links
[1] http://www.python.org/download/
[2] http://sourceforge.net/projects/pywin32/
[3] http://sourceforge.net/projects/pyserial/
[4] http://pyserial.sourceforge.net/
[5] https://sake.in.th/tags/sitetags/programming
[6] https://sake.in.th/category/sitetags/python
[7] https://sake.in.th/tags/sitetags/serial-port