sinanjj 发表于 2011-8-18 14:40

linux/windows兼容串口代码 serial.py

本帖最后由 sinanjj 于 2011-8-18 14:41 编辑

今天整理资料. 一些存了的代码发上来吧.

估计以后不会再用了.#! /usr/bin/python
# apt-get install python-serial
import sys
import serial
import time

for i in range(256):      #scan for available ports
      try:
                #ser = serial.Serial(i, 115200, timeout=1)
                ser = serial.Serial(i, 115200)
                break
      except:
                if i == 255:
                        print 'there is no serial port exist'
                        sys.exit(0)
                pass
print ser.portstr
ser.setRTS(0)
ser.setDTR(0)
file_ir = open('ir_data.txt', 'w')
cmd_len = 0      # one cmd length 1s == 20000/8 == 2500
while 1:
      buf_ser = ser.read(20)
      if buf_ser == "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00":
                if (cmd_len >0) and (cmd_len < 2500):
                        pass
                elif cmd_len == 2500:
                        cmd_len = 0
                        continue
                else:
                        continue
      print " ".join(map(lambda c: "%02X" %ord(c), buf_ser))
      file_ir.write(",".join(map(lambda c: "0x%02X" %ord(c), buf_ser)) + ",")
      file_ir.flush()
      cmd_len = cmd_len + 20




看得懂的朋友自己拿走. 看不懂的朋友自己查. 实在看不懂我也没办法. 不解释.

sinanjj 发表于 2011-12-21 09:08

accessing serial ports
        check the system's serial port
$ dmesg | grep tty
        Serial Port Files
+------------+------------+--------------+
| Port 1   | Port 2   | usb2serial   |
| /dev/ttyS0 | /dev/ttyS1 | /dev/ttyUSB0 |
+------------+------------+--------------+
To access a serial port you simply open the corresponding device file.
# chmod a+rw /dev/ttyS0

                codes for a serial port
#! /usr/bin/python
# -*- coding: utf-8 -*-
# apt-get install python-serial
import sys
import serial
for i in range(256):        #scan for available ports
        try:
                ser = serial.Serial(i, 115200, timeout=1)
                break
        except:
                if i == 255:
                        print 'there is no serial port exist'
                        sys.exit(0)
                pass
print ser.portstr
ser.setRTS(0)
ser.setDTR(0)
file_ser = open('ser_data.txt', 'w')
while 1:
        ser.write("\x00\x01\x02\x03\x04\x05")
        buf_ser = ser.read(11)
        print " ".join(map(lambda c: "%02X" %ord(c), buf_ser))
        file_ser.write(",".join(map(lambda c: "0x%02X" %ord(c), buf_ser)) + ",")
        file_ser.flush()

haolaishi 发表于 2011-12-21 16:42

学习

renmin520 发表于 2012-1-24 16:37

学习
页: [1]
查看完整版本: linux/windows兼容串口代码 serial.py