CSerialPort.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #ifndef _SERIAL_H
  2. #define _SERIAL_H
  3. #include <string>
  4. #include <Windows.h>
  5. #include <cstddef>
  6. #include <cstdlib>
  7. #include <cassert>
  8. typedef unsigned long ulong;
  9. typedef unsigned char uchar;
  10. class CSerialPort
  11. {
  12. public:
  13. CSerialPort(
  14. std::wstring portNum, // 串口号
  15. DWORD baudRate = 9600, // 波特率
  16. BYTE byteSize = 8, // 数据位
  17. BYTE parityBit = NOPARITY, // 检验位
  18. BYTE stopBit = ONESTOPBIT // 停止位
  19. );
  20. ~CSerialPort();
  21. public:
  22. bool openComm(); // 打开串口
  23. void closeComm(); // 关闭串口
  24. bool writeToComm(BYTE data[], DWORD dwLegnth); // 发送数据
  25. bool readFromComm(char buffer[], DWORD dwLength); // 读取数据
  26. private:
  27. HANDLE m_hComm; // 通信设备
  28. std::wstring m_portNum; // 串口号
  29. DWORD m_dwBaudRate; // 波特率
  30. BYTE m_byteSize; // 数据位
  31. BYTE m_parityBit; // 校验位
  32. BYTE m_stopBit; // 停止位
  33. bool m_bOpen; // 串口开关标志
  34. private:
  35. enum BufferSize
  36. {
  37. MIN_BUFFER_SIZE = 256,
  38. BUFFER_SIZE = 512,
  39. MAX_BUFFER_SIZE = 1024
  40. };
  41. // 设置串口号
  42. void setPortNum(const std::wstring &portNum)
  43. {
  44. this->m_portNum = portNum;
  45. }
  46. // 设置波特率
  47. void setBaudRate(const ulong baudRate)
  48. {
  49. this->m_dwBaudRate = baudRate;
  50. }
  51. // 设置数据位
  52. void setByteSize(const uchar byteSize)
  53. {
  54. this->m_byteSize = byteSize;
  55. }
  56. // 设置检验位
  57. void setParityBit(const uchar parityBit)
  58. {
  59. this->m_parityBit = parityBit;
  60. }
  61. // 设置停止位
  62. void setStopBit(const uchar stopBit)
  63. {
  64. this->m_stopBit = stopBit;
  65. }
  66. // 获取串口号
  67. std::wstring getPortNum() { return m_portNum; }
  68. // 获取波特率
  69. ulong getBaudRate() { return m_dwBaudRate; }
  70. // 获取数据位
  71. uchar getByteSize() { return m_byteSize; }
  72. // 获取检验位
  73. uchar getParityBit() { return m_parityBit; }
  74. // 获取停止位
  75. uchar getStopBit() { return m_stopBit; }
  76. };
  77. #endif // _SERIAL_H