源代码:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Threading;

namespace 串口通信

{

public partial class frmMain : Form

{

public frmMain()

{

InitializeComponent();

}

public int iPort = 1; //1,2,3,4

public int iRate = 9600; //1200,2400,4800,9600

public byte bSize = 8; //8 bits

public byte bParity = 0; // 0-4=no,odd,even,mark,space

public byte bStopBits = 1; // 0,1,2 = 1, 1.5, 2

public int iTimeout = 1000;

public myCom com = new myCom();

public byte[] recb;

public int nub = 0;

//打开串口

public bool openCom()

{

try {

if (com.Opened)

{

com.Close();

com.Open();

}

else

{

com.Open();

}

return true;

}catch(Exception ex)

{

MessageBox.Show(ex.Message);

return false;

}

}

//显示包信息

public string disPackage(byte[] reb)

{

string temp = "";

foreach (byte b in reb)

temp += b.ToString("X2") + " ";

return temp;

}

//去掉字符数组中的空格

public string delSpace(string input)

{

string output = "";

for(int i=0;i

{

if(input!=' ')

output += input;

}

return output;

}

//发送数据包

public void sendPackage(byte[] bb)

{

int sendNum = 0;

try

{

sendNum = com.Write(bb);

Thread.Sleep(50);

this.txtShow.AppendText("\r\n发送数据:"+disPackage(bb));

recb = com.Read(50);

this.txtShow.AppendText("\r\n接收到数据:" + disPackage(recb));

}catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

//提取发送的数据包

public byte[] sendDB()

{

string temp = delSpace(this.txtSend.Text.Trim());

byte[] strTemp = new byte[50];

int j = 0;

try

{

for (int i = 0; i < temp.Length; i = i + 2, j++)

strTemp[j] = Convert.ToByte(temp.Substring(i, 2), 16);

}catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

byte[] send = new byte[j];

Array.Copy(strTemp, send, j);

return send;

}

//点击发送按钮发送数据

private void button4_Click(object sender, EventArgs e)

{

if (this.txtSend.Text == "")

{

MessageBox.Show("发送数据为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

return;

}

if (com.Opened)

{

byte[] temp = sendDB();

sendPackage(temp);

}

else

{

MessageBox.Show("串口已经关闭!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

return;

}

}

//程序开启,串口初始化

private void Form1_Load(object sender, EventArgs e)

{

this.timer1.Enabled = true;

this.cboRate.SelectedIndex =5;

this.cboPortNo.SelectedIndex=0;

this.cboByteSize.SelectedIndex=3;

this.cboStopByte.SelectedIndex=1;

this.cboParity.SelectedIndex=0;

com.PortNum = iPort;

com.BaudRate = iRate;

com.ByteSize = bSize;

com.Parity = bParity;

com.StopBits = bStopBits;

com.ReadTimeout = iTimeout;

if(this.openCom())

{

this.txtShow.AppendText("串口初始化成功!...");

}else{

this.txtShow.AppendText("串口初始化失败!");

}

}

//保存配置

private void button1_Click(object sender, EventArgs e)

{

switch (this.cboPortNo.SelectedIndex)

{

case 0:

iPort = 1;

break;

case 1:

iPort = 2;

break;

case 2:

iPort = 3;

break;

case 3:

iPort = 4;

break;

}

//MessageBox.Show(iPort.ToString());

switch (this.cboParity.SelectedIndex)

{

case 0:

bParity = 0;

break;

case 1:

bParity = 1;

break;

case 2:

bParity = 2;

break;

case 3:

bParity = 3;

break;

case 4:

bParity = 4;

break;

}

//MessageBox.Show(bParity.ToString());

switch (this.cboStopByte.SelectedIndex)

{

case 0:

bStopBits =0;

break;

case 1:

bStopBits = 1;

break;

case 2:

bStopBits = 2;

break;

}

//MessageBox.Show(bParity.ToString());

com.PortNum = Convert.ToInt16(iPort);

com.BaudRate = Convert.ToInt16(this.cboRate.Text);

com.ByteSize = Convert.ToByte(this.cboByteSize.Text,10);

com.Parity = Convert.ToByte(bParity);

com.StopBits = Convert.ToByte(bStopBits);

if(this.openCom())

{

this.txtShow.AppendText("\r\n串口参数设置成功!...");

}else

{

this.txtShow.AppendText("\r\n串口参数设置失败!");

}

}

private void button3_Click(object sender, EventArgs e)

{

this.Dispose();

}

private void button5_Click(object sender, EventArgs e)

{

this.txtSend.Text = string.Empty;

// this.textBox2.Text = "";

}

//打开关闭按钮

private void button2_Click(object sender, EventArgs e)

{

if (this.btnCloseCom.Text == "关闭串口")

{

this.btnCloseCom.Text = "打开串口";

this.txtShow.AppendText("\r\n串口被关闭!");

this.cboPortNo.Enabled = true;

com.Close();

}

else

{

this.btnCloseCom.Text = "关闭串口";

this.txtShow.AppendText("\r\n串口成功开启!...");

this.cboPortNo.Enabled = false;

com.Open();

}

}

//打开关于窗口

private void button2_Click_1(object sender, EventArgs e)

{

frmAbout frm = new frmAbout();

frm.Show();

}

private void btnClearShow_Click(object sender, EventArgs e)

{

this.txtShow.Text = "";

}

private void timer1_Tick(object sender, EventArgs e)

{

this.TsslDate.Text = DateTime.Now.ToString();

this.TsslWeek.Text = DateTime.Now.ToString("dddd");

}

private void button1_Click_1(object sender, EventArgs e)

{

Help.ShowHelp(this, Application.StartupPath + "\\Readme.chm");

}

}

}

本程序需要用到一个C++写的dll,功能是帮助初始化串口。(该dll文件已经放在bin\debug目录下)

以下是串口通信类:

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;

using System.Configuration;

namespace 串口通信

{

public  class myCom

{

public myCom()

{

}

public int PortNum; //1,2,3,4

public int BaudRate; //1200,2400,4800,9600

public byte ByteSize; //8 bits

public byte Parity; // 0-4=no,odd,even,mark,space

public byte StopBits; // 0,1,2 = 1, 1.5, 2

public int ReadTimeout; //10

//comm port win32 file handle

private int hComm = -1;

public bool Opened = false;

//win32 api constants

private const uint GENERIC_READ = 0x80000000;

private const uint GENERIC_WRITE = 0x40000000;

private const int OPEN_EXISTING = 3;

private const int INVALID_HANDLE_VALUE = -1;

[StructLayout(LayoutKind.Sequential)]

private struct DCB

{

//taken from c struct in platform sdk

public int DCBlength;           // sizeof(DCB)

public int BaudRate;            // current baud rate

public int fBinary;          // binary mode, no EOF check

public int fParity;          // enable parity checking

public int fOutxCtsFlow;      // CTS output flow control

public int fOutxDsrFlow;      // DSR output flow control

public int fDtrControl;       // DTR flow control type

public int fDsrSensitivity;   // DSR sensitivity

public int fTXContinueOnXoff; // XOFF continues Tx

public int fOutX;          // XON/XOFF out flow control

public int fInX;           // XON/XOFF in flow control

public int fErrorChar;     // enable error replacement

public int fNull;          // enable null stripping

public int fRtsControl;     // RTS flow control

public int fAbortOnError;   // abort on error

public int fDummy2;        // reserved

public ushort wReserved;          // not currently used

public ushort XonLim;             // transmit XON threshold

public ushort XoffLim;            // transmit XOFF threshold

public byte ByteSize;           // number of bits/byte, 4-8

public byte Parity;             // 0-4=no,odd,even,mark,space

public byte StopBits;           // 0,1,2 = 1, 1.5, 2

public char XonChar;            // Tx and Rx XON character

public char XoffChar;           // Tx and Rx XOFF character

public char ErrorChar;          // error replacement character

public char EofChar;            // end of input character

public char EvtChar;            // received event character

public ushort wReserved1;         // reserved; do not use

}

[StructLayout(LayoutKind.Sequential)]

private struct COMMTIMEOUTS

{

public int ReadIntervalTimeout;

public int ReadTotalTimeoutMultiplier;

public int ReadTotalTimeoutConstant;

public int WriteTotalTimeoutMultiplier;

public int WriteTotalTimeoutConstant;

}

[StructLayout(LayoutKind.Sequential)]

private struct OVERLAPPED

{

public int  Internal;

public int  InternalHigh;

public int  Offset;

public int  OffsetHigh;

public int hEvent;

}

[DllImport("kernel32.dll")]

private static extern int CreateFile(

string lpFileName,                         // file name

uint dwDesiredAccess,                      // access mode

int dwShareMode,                          // share mode

int lpSecurityAttributes, // SD

int dwCreationDisposition,                // how to create

int dwFlagsAndAttributes,                 // file attributes

int hTemplateFile                        // handle to template file

);

[DllImport("kernel32.dll")]

private static extern bool GetCommState(

int hFile,  // handle to communications device

ref DCB lpDCB    // device-control block

);

[DllImport("kernel32.dll")]

private static extern bool BuildCommDCB(

string lpDef,  // device-control string

ref DCB lpDCB     // device-control block

);

[DllImport("kernel32.dll")]

private static extern bool SetCommState(

int hFile,  // handle to communications device

ref DCB lpDCB    // device-control block

);

[DllImport("kernel32.dll")]

private static extern bool GetCommTimeouts(

int hFile,                  // handle to comm device

ref COMMTIMEOUTS lpCommTimeouts  // time-out values

);

[DllImport("kernel32.dll")]

private static extern bool SetCommTimeouts(

int hFile,                  // handle to comm device

ref COMMTIMEOUTS lpCommTimeouts  // time-out values

);

[DllImport("kernel32.dll")]

private static extern bool ReadFile(

int hFile,                // handle to file

byte[] lpBuffer,             // data buffer

int nNumberOfBytesToRead,  // number of bytes to read

ref int lpNumberOfBytesRead, // number of bytes read

ref OVERLAPPED lpOverlapped    // overlapped buffer

);

[DllImport("kernel32.dll")]

private static extern bool WriteFile(

int hFile,                    // handle to file

byte[] lpBuffer,                // data buffer

int nNumberOfBytesToWrite,     // number of bytes to write

ref int lpNumberOfBytesWritten,  // number of bytes written

ref OVERLAPPED lpOverlapped        // overlapped buffer

);

[DllImport("kernel32.dll")]

private static extern bool CloseHandle(

int hObject   // handle to object

);

[DllImport("Comm.dll")]

public static extern void Init_Comm();

public void Open()

{

Init_Comm();

DCB dcbCommPort = new DCB();

COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

// OPEN THE COMM PORT.

hComm = CreateFile("COM" + PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);

// IF THE PORT CANNOT BE OPENED, BAIL OUT.

if(hComm == INVALID_HANDLE_VALUE)

{

throw(new ApplicationException("Comm Port Can Not Be Opened"));

}

// SET THE COMM TIMEOUTS.

GetCommTimeouts(hComm,ref ctoCommPort);

ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;

ctoCommPort.ReadTotalTimeoutMultiplier = 0;

ctoCommPort.WriteTotalTimeoutMultiplier = 0;

ctoCommPort.WriteTotalTimeoutConstant = 0;

SetCommTimeouts(hComm,ref ctoCommPort);

// SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.

// THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.

// IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER

// THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.

// ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.

dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);

GetCommState(hComm, ref dcbCommPort);

dcbCommPort.BaudRate=BaudRate;

dcbCommPort.Parity=Parity;

dcbCommPort.ByteSize=ByteSize;

dcbCommPort.StopBits=StopBits;

SetCommState(hComm, ref dcbCommPort);

Opened = true;

}

public void Close()

{

if (hComm!=INVALID_HANDLE_VALUE)

{

CloseHandle(hComm);

Opened=false;

}

}

public byte[] Read(int NumBytes)

{

byte[] BufBytes;

byte[] OutBytes;

BufBytes = new byte[NumBytes];

if (hComm!=INVALID_HANDLE_VALUE)

{

OVERLAPPED ovlCommPort = new OVERLAPPED();

int BytesRead=0;

ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);

OutBytes = new byte[BytesRead];

Array.Copy(BufBytes,OutBytes,BytesRead);

}

else

{

throw(new ApplicationException("Comm Port Not Open"));

}

return OutBytes;

}

public int Write(byte[] WriteBytes)

{

int BytesWritten = 0;

if (hComm!=INVALID_HANDLE_VALUE)

{

OVERLAPPED ovlCommPort = new OVERLAPPED();

WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);

}

else

{

throw(new ApplicationException("Comm Port Not Open"));

}

return BytesWritten;

}

}

}

投影串口测试程序_【原创】串口通信测试程序相关推荐

  1. espflashdownloadtool连接串口失败_关于串口下载问题和超时

    串口下载适用于mini.精英.战舰.探索者.阿波罗429 不适用于阿波罗767,H743,号令者1052 保证板子在独立供电状态下,电源灯处于亮灯状态下, USB线接板子上USB_232, RXD 和 ...

  2. ch340串口驱动_关于串口下载问题和超时

    串口下载适用于mini.精英.战舰.探索者.阿波罗429 不适用于阿波罗767,H743,号令者1052 保证板子在独立供电状态下,电源灯处于亮灯状态下, USB线接板子上USB_232, RXD 和 ...

  3. 投影串口测试程序_关于串口控制投影机的操作方法的几个步骤

    关于串口控制投影机的操作方法的几个步骤 1.将中控接上电源,连好控制面板 2.将中控主机串口(RS232)接口与电脑主机COM口连接好 3.将中控系统随机的光盘放入电脑中,打开"串口写码程序 ...

  4. 读取串口数据_自定义串口通信的相关问题整理

    串口通信是常见的通信方式,串口接口是大部分工控器件标配的通信接口.在项目开发的过程中,也经常遇到进行串口通信的处理.这里就串口通信的部分问题分享给大家. 1.TTL.RS232.RS422.RS458 ...

  5. python串口编程_- python串口编程实例

    python读取串口信息#e# 4.python简单程序读取串口信息的方法 具体分析如下: 这段代码需要调用serial模块,通过while循环不断读取串口数据 5.Python简单串口收发GUI界面 ...

  6. STM32 USART1 USART2 UASRT3 UART4 UART5串口通信测试程序

    STM32 USART1 USART2 UASRT3 UART4 UART5串口通信测试程序 (2014-02-11 20:09:19) 转载▼ 分类: 单片机.嵌入系统 // 5个串口均可工作,已经 ...

  7. 变频器怎么设置_如何利用串口调试软件与变频器通信?

     西门子博途的全套视频教程下载!  西门子S7-1500内部培训PPT下载! 每一个做工控的都必须要会利用串口调试软件来和我们的外围设备来做通讯测试.今天我们就来学习怎么用串口调试软件控制台达的这款变 ...

  8. android 串口调试工具_树莓派通用串口通信实验

    一.介绍 对于树莓派 3B+来说,他的UART功能有三种:1.内部蓝牙使用:2.控制终端使用:3.与其他设备进行串口通信. 在树莓派USB TO TTL模块实验中学习了通过串口对树莓派进行控制台控制, ...

  9. msp430g2553串口通信_软件串口

    msp430g2553通过定时器A和软件代码配合可以形成串口,即软件串口.当然msp430g2553也有硬件串口,内部有自己完整的uart模块. 内部的uart参考:msp430g2533USCI_A ...

  10. c语言树莓派串口通信_树莓派串口通信

    树莓派的串口默认为串口终端调试使用,如要正常使用串口则需要修改树莓派设置.关闭串口终端调试功能后则不能再通过串口登陆访问树莓派,需从新开启后才能通过串口控制树莓派. 一.设置串口 要使用这个串口,必须 ...

最新文章

  1. Revit初学者完整指南 The Complete Revit Guide for Beginners
  2. lvs-keepalived
  3. APUE-文件和目录(八)文件时间
  4. python3.7.2安装教程-CentOS 7安装Python教程
  5. IOS开发--深拷贝与浅拷贝(mutableCopy与Copy)详解
  6. win10下vs2015编译的程序如何运行在win7等系统(无需安装Redistributable)
  7. 如何正确刷题计算机考研,2020考研:4个方法教你数学如何正确刷题!
  8. 解决RabbitMQ消息丢失问题和保证消息可靠性
  9. boost::minimum_degree_ordering用法的测试程序
  10. iOS设计模式 - 享元
  11. 百度OCR文字识别API使用心得 com.baidu.ocr.sdk.exception.SDKError[283604]
  12. pytorch —— 池化、线性、激活函数层
  13. qt 判断路径非英文符号与非英文字符_Qt中,软件多语言国际化翻译的方法与步骤...
  14. apk 反编译工具的使用
  15. 【求最大公共子串长度】
  16. 最好用的 7 款 Vue 3 富文本编辑器
  17. 服务器网络连接详细信息,Windows10怎么样查看网络连接详细信息
  18. pdf文档怎样转换成word文档?2022pdf转word软件推荐
  19. ApacheCN C# 译文集 20211124 更新
  20. p1633[进制应用]砝码称重

热门文章

  1. 技术06期:测试系统软件需要重视哪几点?
  2. 详解|工业机器人内部机构详解
  3. 收藏 | 各种 Optimizer 梯度下降优化算法回顾和总结
  4. 高翔Slambook第七讲代码解读(2d-2d位姿估计)
  5. extern与头文件(*.h)的区别和联系
  6. Shell特殊变量含义
  7. MOOON-server新消息处理接口
  8. mac开启sshserver
  9. php自动导入,PHP自动导入类
  10. python语言只采用解释一种翻译方式对吗_python-guide翻译