日期:2014-05-16 浏览次数:21035 次
//主程序
#include "CSerial.h"
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
CSerial::CSerial serial;
serial.OpenPort("/dev/ttySAC0", 115200, 8, 1, 'N');//报错!!
while(1);
return 0;
}
/*自定义串口类
* CSerial.h
*
* Created on: 2010-7-20
* Author: yzm
*/
#ifndef CSERIAL_H_
#define CSERIAL_H_
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> /*文件控制定义*/
#include <termios.h> /*PPSIX 终端控制定义*/
#include <errno.h> /*错误号定义*/
#include <string.h>
#include <string>
#include "CCriticalSection.h"
using namespace std;
#define BUFFER_LENGTH 1024
namespace CSerial {
class CSerial
{
private:
string m_PortName;
int m_baudrate;
int m_databits;
int m_stopbits;
char m_parity;
//通讯线程标识符ID
pthread_t m_thread;
CCriticalSection mutex;
// 串口数据接收线程
static void* ReceiveThreadFunc( void* lparam );
public:
CSerial();
virtual ~CSerial();
// 已打开的串口文件描述符
int m_fd;
int m_DatLen;
unsigned char DatBuf[BUFFER_LENGTH];
int m_ExitThreadFlag;
// 按照指定的串口参数打开串口,并创建串口接收线程
int OpenPort( string PortName, int baudrate, int databits, int stopbits, char parity );
// 关闭串口并释放相关资源
int ClosePort( );
// 向串口写数据
int WritePort( unsigned char* Buf, int len );
// 接收串口数据处理函数
virtual int PackagePro( unsigned char* Buf, int len );
private:
void set_speed(int fd, int speed);
int set_Parity(int fd,int databits,int stopbits,int parity);
};
}
#endif /* CSERIAL_H_ */
/*
* CSerial.cpp
*
* Created on: 2010-7-20
* Author: yzm
*/
#include "CSerial.h"
#include <sys/select.h>
#include <sys/time.h>
#include <stdlib.h>
#include <unistd.h> /*Unix 标准函数定义*/
namespace CSerial {
int speed_arr[] = {B115200,B38400, B19200, B9600, B4800, B2400, B1200, B300, B38400,
B19200, B9600, B4800, B2400, B1200, B300, };
int name_arr[] = {115200,38400, 19200, 9600, 4800, 2400, 1200, 300, 38400, 19200,
9600, 4800, 2400, 1200, 300, };
string BYTE2HEX(unsigned char* buffer,int nSize)
{
char buf[1024];
memset(buf,0,1024);
int len = 0;
for(int i = 0;i < nSize;i++)
{
int tmp = sprintf(buf + len,"%02x ",buffer);
len += tmp;
}
string str(buf);
return str;
}
CSerial::CSerial()
{
m_ExitThreadFlag = false;
m_PortName = "/dev/ttyS0";
m_baudrate = 2400;
m_databits = 8;
m_stopbits = 1;
m_parity = 'e';
}
CSerial::~CSerial()
{
ClosePort( );
}
int CSerial::OpenPort(string PortName, int baudrate, int databits,
int stopbits, char parity) {
/*以读写方式打开串口*/
m_fd = open(PortName.data(), O_RDWR);
if (-1 == m_fd) {
/* 不能打开串口一*/
perror(" 提示错误!");
return -1;
} else {
m_Po