16,240
社区成员
发帖
与我相关
我的任务
分享
#include<synserialcomm.h>
using namespace std;
int main(int argc, char*argv[])
{
SynSerialComm *myport = new SynSerialComm();
myport->start();
while(1);
delete myport;
return 0;
}
#include<synserialcomm.h>
using namespace std;
static portinfo_t portinfo;
int serial_fd;
char databuffer[20];
int datalen;
SynSerialComm::SynSerialComm()
{
portinfo = {
'0', // print prompt after receiving
38400, // baudrate: 115200
'8', // databit 8
'0', // debug: off
'0', // echo off
'2', // flow control: software
'0', // default tt: SAC0
'0', // parity: none
'1', // stopbit: 1
0 // reserved
};
this->moveToThread(this);
}
void SynSerialComm::run()
{
open_serial();
while(1)
{
string sendstr;
cin>>sendstr;
send_setial(sendstr);
}
close_serial();
}
void SynSerialComm::open_serial()
{
serial_fd=PortOpen(&portinfo);
if(serial_fd<0)
{
perror("Error:open serial port error");
//exit(1);
}
PortSet(serial_fd,&portinfo);
QSocketNotifier *notifier=new QSocketNotifier(serial_fd,QSocketNotifier::Read,this);
connect(notifier,SIGNAL(activated(int)),this,SLOT(read_serial()));
}
void SynSerialComm::close_serial()
{
PortClose(serial_fd);
}
void SynSerialComm::send_setial(string sendstr)
{
char *psendchar = new char[sendstr.length()];
strcpy(psendchar, sendstr.c_str());
PortSend(serial_fd,psendchar,sendstr.length());
}
void SynSerialComm::read_serial()
{
datalen=PortRecv(serial_fd,databuffer,10,38400);
databuffer[datalen] = '\0';
cout << databuffer << endl;
}
#ifndef SYNSERIALCOMM_H
#define SYNSERIALCOMM_H
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <linux/fs.h>
#include <errno.h>
#include <string.h>
#include <termio.h>
#include<QSocketNotifier>
#include<qdebug.h>
#include "mqz_thread.h"
#include<iostream>
#include<serialport.h>
using namespace std;
class SynSerialComm : public QThread
{
Q_OBJECT
public:
public:
SynSerialComm();
~SynSerialComm(){}
void open_serial();
void close_serial();
void send_setial(string sendstr);
virtual void run();
private slots:
void read_serial();
};
#endif // SYNSERIALCOMM_H