由于最近接触到承重传感器,起初基于Python开发串口通信,在QT中通过process调用Python的串口程序,结果发现效果不是太好。最后转手在Qt中直接使用Qt的串口接口,达到了理想的效果。
Python接口
在python中需要使用pyserial接口,可以通过下面连接进行下载,主要系统环境为python2.7 X86.
http://download.csdn.net/detail/lovelyaiq/9857117
from __future__ import division
import serial
import time
import serial.tools.list_ports
import os
port_list = list(serial.tools.list_ports.comports())
if len(port_list) <= 0:
os.system('echo %s' %("The Serial port can't find!"))
else:
for i,port in enumerate(port_list):
os.system('echo %s' %port[0])
class Serial_prot():
def __init__(self):
try:
self.ser = serial.Serial('COM5',9600,timeout=0.1)#串口初始化
except serial.SerialException:
os.system('echo Can not open the serial %s' %('com5'))
def hexShow(self,argv):
result = ''
hLen = len(argv)
for i in xrange(hLen):
hvol = ord(argv[i])
hhex = '%02x'%hvol
result += hhex
os.system('echo %s' %str(int(result[6:14],16)/1000))
def set_zero(self):
#reset zero
self.ser.write('\x01\x10\x00\x00\x00\x02\x04\x00\x00\x00\x00\xF3\xAF')#串口写数据
time.sleep(1)
def run(self):
while True:
self.ser.write('\x01\x03\x00\x00\x00\x02\xC4\x0B')
time.sleep(0.3)
self.hexShow(self.ser.readline())
def close(self):
self.ser.close()
#flag=sys.argv[1]
def main():
sers=Serial_prot()
sers.run()
if __name__ == '__main__':
main()
上述的代码中,使用os.system进行输出信息,而不用print输出,因为print输出的信息,在Qt的Qprocess::readAllStandardOutput()无法捕捉的信息。
Qt接口
1、需要在".pro"文件中加入“QT += serialport“,否则会报错。
2、头文件是必不可少的。
#include <QtSerialPort/QSerialPort>
3、串口初试化。
QSerialPort serial;
serial.setPortName("COM5"); //设置COM口
serial.setBaudRate(QSerialPort::Baud9600,QSerialPort::AllDirections);//设置波特率和读写方向
serial.setDataBits(QSerialPort::Data8); //数据位为8位
serial.setFlowControl(QSerialPort::NoFlowControl);//无流控制
serial.setParity(QSerialPort::NoParity); //无校验位
serial.setStopBits(QSerialPort::OneStop); //一位停止位
serial.close(); //先关串口,再打开,可以保证串口不被其它函数占用。
4、需要定时读取或写入程序,初始化一个定时器,并定义信号与槽。
QTimer *timer_serial;
timer_serial =new QTimer();
connect (timer_serial,SIGNAL(timeout()),this,SLOT(process_read_weight_fun()));
5、启动定时器打开串口。
if(timer_serial->isActive ()==false){
serial.open(QIODevice::ReadWrite);
timer_serial->start (30);
}
6、读写串口
//读取传感器中的数据
void MainWindow::process_read_weight_fun()
{
bool ok;
const unsigned char s[8]={0x01,0x03,0x00,0x00,0x00,0x02,0xC4,0x0B};
serial.write ((char*)s,8);//以ASCII码的形式通过串口发送出去。
serial.waitForBytesWritten (300);
QByteArray temp=serial.read(10);//在缓冲区中读一个byte
serial.waitForReadyRead (100);
float weight=temp.toHex ().left (14).right (8).toInt (&ok,16)/1000.;
para_weight_show->setText (QString::number(weight, 'f',2)+" Kg");
}
至此,python和Qt接口的串口操作完毕,大家如有不懂,应该多参考Qt或python关于串口的API,里面介绍还是比较详细的。