本程序采用简单的同步串行通信,分为几个阶段:

1、打开串口

2、配置串口

3、设置串口输入输出缓存区大小

4、设置串口读写超时(若不设置超时,读写时会等待读写函数返回)

5、发送字符串(每次发送前清空发送缓存区)

6、接收字符(每次接收前清空接收缓存区)

7、关闭串口

bmLightComm.h

 1 #pragma once
 2 #include "stdio.h"
 3 #include "stdbool.h"
 4 #include "windows.h"
 5 #include "tchar.h"
 6
 7 class bmLightComm
 8 {
 9 public:
10     bmLightComm();
11     ~bmLightComm();
12     bool openPort(const char* portNum);
13     bool setupPort(DWORD baudrate, BYTE bytesize, BYTE stopbits, DWORD fparity, BYTE parity);
14     bool setBufferAreaSize(DWORD inQueue, DWORD outQueue);
15     bool setComTimeout(DWORD readinttim, DWORD readToltimM, DWORD readToltimC,DWORD writeToltimM, DWORD writeToltimC);
16     bool purgePort(DWORD flags);
17     bool closePort();
18
19     bool sendBuff(const char* datas, unsigned int len);
20     char readBuff();
21
22 private:
23     HANDLE mCom;
24 };

bmLightComm.cpp

  1 #include "bmLightComm.h"
  2 #include <iostream>
  3
  4
  5 bmLightComm::bmLightComm()
  6 {
  7 }
  8
  9
 10 bmLightComm::~bmLightComm()
 11 {
 12 }
 13
 14 bool bmLightComm::openPort(const char* portNum)
 15 {
 16     printf("open the com %s\n", portNum);
 17
 18     mCom = CreateFileA(portNum, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
 19     std::cout << GetLastError() << std::endl;
 20     if (mCom == INVALID_HANDLE_VALUE)
 21     {
 22         printf("failed to open com %s %d\n", portNum,  GetLastError());
 23         return false;
 24     }
 25     else
 26     {
 27         printf("cam %s opened\n", portNum);
 28         return true;
 29     }
 30 }
 31
 32 bool bmLightComm::setupPort(DWORD baudrate, BYTE bytesize, BYTE stopbits, DWORD fparity, BYTE parity)
 33 {
 34     printf("set up port\n");
 35
 36     DCB mDcb;
 37     if (!GetCommState(mCom, &mDcb))
 38     {
 39         printf("get com state failed %d\n", GetLastError());
 40         return false;
 41     }
 42
 43     mDcb.BaudRate = baudrate;
 44     mDcb.fParity = fparity;
 45     mDcb.Parity = parity;
 46     mDcb.StopBits = stopbits;
 47     mDcb.ByteSize = bytesize;
 48
 49     if (!SetCommState(mCom, &mDcb))
 50     {
 51         printf("failed to set up com state %d\n", GetLastError());
 52         return false;
 53     }
 54     else
 55     {
 56         printf("com set up complete\n");
 57         return true;
 58     }
 59 }
 60
 61 bool bmLightComm::setBufferAreaSize(DWORD inQueue, DWORD outQueue)
 62 {
 63     if (!SetupComm(mCom, inQueue, outQueue))
 64     {
 65         printf("failed to set the buffer size %d\n", GetLastError());
 66         return false;
 67     }
 68     else
 69     {
 70         printf("com set buffer size complete\n");
 71         return true;
 72     }
 73 }
 74
 75 bool bmLightComm::setComTimeout(DWORD readinttim, DWORD readToltimM, DWORD readToltimC, DWORD writeToltimM, DWORD writeToltimC)
 76 {
 77     COMMTIMEOUTS TimeOuts;
 78     TimeOuts.ReadIntervalTimeout = readinttim;
 79     TimeOuts.ReadTotalTimeoutMultiplier = readToltimM;
 80     TimeOuts.ReadTotalTimeoutConstant = readToltimC;
 81     TimeOuts.WriteTotalTimeoutMultiplier = writeToltimM;
 82     TimeOuts.WriteTotalTimeoutConstant = writeToltimC;
 83
 84     if (!SetCommTimeouts(mCom,&TimeOuts))
 85     {
 86         printf("failed to set time out %d\n", GetLastError());
 87         return false;
 88     }
 89     else
 90     {
 91         printf("set time out complete\n");
 92         return true;
 93     }
 94 }
 95
 96 bool bmLightComm::purgePort(DWORD flags)
 97 {
 98     //PURGE_TXCLEAR,清空发送缓冲区;PURGE_RXCLEAR,清空接收缓冲区;
 99     if (!PurgeComm(mCom, flags))
100     {
101         printf("failed to purge com %d\n", GetLastError());
102         return false;
103     }
104     else
105     {
106         printf("purge com complete\n");
107         return true;
108     }
109 }
110
111 bool bmLightComm::closePort()
112 {
113     this->purgePort(PURGE_TXCLEAR | PURGE_RXCLEAR);
114
115     if (!CloseHandle(mCom))
116     {
117         printf("failed to close port %d\n", GetLastError());
118         return false;
119     }
120     else
121     {
122         printf("close port complete\n");
123         return true;
124     }
125 }
126
127 bool bmLightComm::sendBuff(const char* datas, unsigned int len)
128 {
129     this->purgePort(PURGE_TXCLEAR);
130
131     DWORD pWrite;
132     if (!WriteFile(mCom, datas, sizeof(const char)*len, &pWrite, NULL))
133     {
134         printf("failed to write buff %d\n", GetLastError());
135         return false;
136     }
137     else
138     {
139         printf("write buff complete\n");
140         return true;
141     }
142 }
143
144 char bmLightComm::readBuff()
145 {
146     this->purgePort(PURGE_RXCLEAR);
147
148     char buffl;
149     DWORD pRead;
150     if (!ReadFile(mCom, &buffl, sizeof(buffl), &pRead, NULL))
151     {
152         printf("failed to read buff %d\n", GetLastError());
153         return '\0';
154     }
155     else
156     {
157         printf("read buff complete\n");
158         return buffl;
159     }
160 }

bmLightManage.h

 1 #pragma once
 2 #ifndef BMLIGHTMANAGE_h
 3 #define BMLIGHTMANAGE_H
 4
 5 #include "bmLightComm.h"
 6 #include <string>
 7 #include <strstream>
 8 #include <iostream>
 9 #include <vector>
10
11 typedef struct LightSetting
12 {
13     int deviceID;  //0~2
14     int channelID;   //0~3
15     bool turn;
16     int bright;
17
18     LightSetting(int dID, int cID, bool tID, int bID)
19     {
20         deviceID = dID;
21         channelID = cID;
22         turn = tID;
23         bright = bID;
24     }
25 }LightSetting;
26
27 class bmLightControl
28 {
29 public:
30     bmLightControl();
31     ~bmLightControl();
32     void Init(const char* portNum);
33     void setBright(LightSetting ligtemp);
34     void sendBright();
35
36 private:
37     bmLightComm mCtrl;
38     std::string ch[4];
39 };
40
41 class bmLightManage
42 {
43 public:
44     bmLightManage();
45     ~bmLightManage();
46     void Init(const char* portNum0, const char* portNum1, const char* portNum2);
47     void setBright(std::vector<LightSetting> ligtemp);
48
49 private:
50     bmLightControl mCon[3];
51 };
52
53
54 #endif

bmLightManage.cpp

 1 #include "bmLightManage.h"
 2
 3 bmLightControl::bmLightControl()
 4 {
 5     ch[0] = ch[1] = ch[2] = ch[3] = "000F";
 6 }
 7
 8 bmLightControl::~bmLightControl()
 9 {
10     mCtrl.closePort();
11 }
12
13 void bmLightControl::Init(const char* portNum)
14 {
15     mCtrl.openPort(portNum);
16     mCtrl.setupPort(19200, 8, ONESTOPBIT, FALSE, NOPARITY);
17     mCtrl.setBufferAreaSize(1024, 1024);
18     //mCtrl.setComTimeout(5, 5, 5, 5, 5);
19 }
20
21 void bmLightControl::setBright(LightSetting ligtemp)
22 {
23     std::strstream ss;
24     std::string str;
25     ss << ligtemp.bright;
26     ss >> str;
27     if (str.length() == 1)
28     {
29         str = "00" + str;
30     }
31     else if (str.length() == 2)
32     {
33         str = "0" + str;
34     }
35
36     ch[ligtemp.channelID] = str + (ligtemp.turn ? "T" : "F");
37 }
38
39 void bmLightControl::sendBright()
40 {
41     std::string all = "S" + ch[0] + ch[1] + ch[2] + ch[3] + "C#";
42     mCtrl.sendBuff(all.c_str(), all.length() + 1);
43
44     std::cout << mCtrl.readBuff() << std::endl;
45 }
46
47 bmLightManage::bmLightManage()
48 {
49 }
50
51
52 bmLightManage::~bmLightManage()
53 {
54 }
55
56 void bmLightManage::Init(const char* portNum0, const char* portNum1, const char* portNum2)
57 {
58     mCon[0].Init(portNum0);
59     mCon[1].Init(portNum1);
60     mCon[2].Init(portNum2);
61 }
62
63 void bmLightManage::setBright(std::vector<LightSetting> ligtemp)
64 {
65     for (int i = 0; i < ligtemp.size(); i++)
66     {
67         mCon[ligtemp[i].deviceID].setBright(ligtemp[i]);
68     }
69
70     for (int i = 0; i < 3; i++)
71     {
72         mCon[i].sendBright();
73     }
74 }

qttestcomm.h

 1 #ifndef QTTESTCOMM_H
 2 #define QTTESTCOMM_H
 3
 4 #include <QtWidgets/QWidget>
 5 #include "ui_qttestcomm.h"
 6 #include "bmLightManage.h"
 7 #include <QSlider>
 8 #include <QVBoxLayout>
 9 #include <QDebug>
10
11 class qttestcomm : public QWidget
12 {
13     Q_OBJECT
14
15 public:
16     qttestcomm(QWidget *parent = 0);
17     ~qttestcomm();
18
19 private:
20     Ui::qttestcommClass ui;
21     QSlider mslider;
22     bmLightManage m;
23
24     public slots:
25     void slot1(int va);
26 };
27
28 #endif // QTTESTCOMM_H

qttestcomm.cpp

 1 #include "qttestcomm.h"
 2
 3 qttestcomm::qttestcomm(QWidget *parent)
 4     : QWidget(parent)
 5 {
 6     ui.setupUi(this);
 7
 8     mslider.setMinimum(0);
 9     mslider.setMaximum(255);
10     QVBoxLayout *lay1 = new QVBoxLayout;
11     lay1->addWidget(&mslider);
12     this->setLayout(lay1);
13     m.Init("COM1","COM2","COM3");
14
15     connect(&mslider, SIGNAL(valueChanged(int)), this, SLOT(slot1(int)));
16 }
17
18 qttestcomm::~qttestcomm()
19 {
20
21 }
22
23 void qttestcomm::slot1(int va)
24 {
25     qDebug() << va;
26     mslider.setToolTip(QString::number(va));
27
28     std::vector<LightSetting> ll;
29     ll.push_back(LightSetting(0, 0, true, va));
30     ll.push_back(LightSetting(0, 1, true, va));
31     ll.push_back(LightSetting(1, 0, true, va));
32     ll.push_back(LightSetting(1, 1, true, va));
33     ll.push_back(LightSetting(1, 2, true, va));
34     ll.push_back(LightSetting(1, 3, true, va));
35     ll.push_back(LightSetting(2, 0, true, va));
36     ll.push_back(LightSetting(2, 1, true, va));
37     ll.push_back(LightSetting(2, 2, true, va));
38     ll.push_back(LightSetting(2, 3, true, va));
39
40     m.setBright(ll);
41 }

main.cpp

 1 #include "qttestcomm.h"
 2 #include <QtWidgets/QApplication>
 3
 4 int main(int argc, char *argv[])
 5 {
 6     QApplication a(argc, argv);
 7     qttestcomm w;
 8     w.show();
 9     return a.exec();
10 }

第一次写串口通信程序,特此记录

参考:http://www.cnblogs.com/zahxz/archive/2012/12/24/2830535.html

附一个比较全面的串口通信程序:http://blog.csdn.net/wujian53/article/details/4090554

转载于:https://www.cnblogs.com/Jace-Lee/p/6187892.html

简单的串口通信程序控制光源相关推荐

  1. avr模拟串口通讯c语言,AVR简单的串口通信程序

    本例子是学习AVR的串口通信时候编写的一个简单的串口通信的程序,运行的时候先向串口发送一个数据0x12,然后等待接收,当PC机发送一个数据到单片机,单片机就对这个数据进行加1处理,然后发回到PC机显示 ...

  2. 【嵌入式小白学习】--在STM32开发板上实现简单的串口通信

    嵌入式小白学习--在STM32开发板上实现简单的串口通信 这里写目录标题 嵌入式小白学习--在STM32开发板上实现简单的串口通信 Part1. STM32环境的搭建 Part2. 编写代码 Part ...

  3. 32、树莓派的简单测试串口通信和超声波模块测距

    基本思想:随手记录一下众灵科技树莓派的测试串口通信和超声波模块,其镜像还是很nice,基本的库都给你安装了,比较大 链接:https://pan.baidu.com/s/11tMdoRh3bHmcYz ...

  4. VS2013基于对话框的MFC串口通信简单案例教程

    本例程是在VS2013环境下,使用MFC做的是一个简单的串口通信程序. 虚拟的串口软件工具下载地址:https://pan.baidu.com/s/1D-oddZk3Z_ioXBUpXE7ksw 密码 ...

  5. qt linux 串口eventdriven,详解 Qt 串口通信程序全程图文 (1)

    Qt 串口通信程序全程图文 是本文介绍的内容,在Qt中并没有特定的串口控制类,现在大部分人使用的是第三方写的qextserialport类,我们这里也是使用的该类.我们可以去 http://sourc ...

  6. 详解 Qt 串口通信程序全程图文 (1)

    Qt 串口通信程序全程图文 是本文介绍的内容,在Qt中并没有特定的串口控制类,现在大部分人使用的是第三方写的qextserialport类,我们这里也是使用的该类.我们可以去 http://sourc ...

  7. QT中串口通信程序(转)

    (说明:我们的编程环境是windows xp下,在Qt Creator中进行,如果在Linux下或直接用源码编写,程序稍有不同,请自己改动.) 在Qt中并没有特定的串口控制类,现在大部分人使用的是第三 ...

  8. 【转】Qt编写串口通信程序全程图文讲解

    Qt编写串口通信程序全程图文讲解 本文章原创于www.yafeilinux.com 转载请注明出处. (说明:我们的编程环境是windows xp下,在Qt Creator中进行,如果在Linux下或 ...

  9. STC89C52单片机串口通信以及代码演示

    目录 串口介绍 硬件电路 电平标准 常见通讯接口比较 51单片机的UART 串口参数及时序图 串口通信流程图 串口相关寄存器 波特率的计算方法 中断模式以及寄存器的配置 数据显示模式 代码示例(串口与 ...

最新文章

  1. Windows10为什么自带Linux,一直没有发现原来 Win10 内置了一个 Linux
  2. 比特币现金支持者为BCH引入了各种新概念
  3. 48万!百度推出全球最便宜RoboTaxi,赚钱能力2倍于人类网约车
  4. 使用Cloud application Studio在C4C UI里创建下拉列表(dropdown list)
  5. php tp5 redis的使用(亲测)
  6. Burst trie(爆炸式字典树)解读
  7. arm linux读cpu id,基于ARM架构的芯片获取CPU信息(cpuID)的多种方法
  8. mysql交给spring管理_Mysql事务结合spring管理
  9. oracle如何调试sql,调试oracle与调试sql server存储过程
  10. oracle函数大全指数运算,Oracle 基础语句 函数大全(字符串函数,数学函数,日期函数,逻辑运算函数......
  11. 我经常逛的技术网站,个个经典
  12. python 字典的函数
  13. 用vue实时监听多个用户扫描二维码
  14. 中美线规线径对照表(详细版)
  15. 一体机扫描文档FTP搭建全程
  16. 北京市海外学人中心《北京市留学人员工作居住证》攻略
  17. Photon教程——Photon的获取
  18. const const
  19. java分词支持拼音_java 支持分词的高性能拼音转换工具,速度是 pinyin4j
  20. 怎样的金融IT公司才算好公司

热门文章

  1. 无聊之作:Karry解数独程序
  2. 钦州学院毕业有计算机二级要求吗,钦州学院本科相关表格和要求.doc
  3. X.509数字证书的结构与解析
  4. 基于Thinkphp开发的独立版本后台主流约拍小程序约拍券约拍发布约拍分享得券约拍平台源码源生前后端源码可以二开适合摄影师或者模特运营的小程序平台
  5. 摩杜云出席2021亚太CDN峰会,荣获“融合CDN创新奖”
  6. android 蓝牙opp流程,Android BluetoothProfile之OPP(蓝牙文件分享流程)
  7. HTML用乘法函数,excel乘法函数-这两个乘积函数技巧,办公时特别实用,但擅长的人不多...
  8. 如何进行工时测定?什么工时测定软件比较准确?
  9. OPENAIPLUS账号申请
  10. Intel联合Waymo研发自动驾驶技术,在处理器及互联网芯片上展开合作