`
灵雨飘零
  • 浏览: 34963 次
  • 性别: Icon_minigender_1
  • 来自: 唐山
文章分类
社区版块
存档分类
最新评论

【原创】串口通信测试程序

 
阅读更多

1.jpg.jpg

源代码:

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<input.Length;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 串口通信
{
publicclass 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 intInternal;
public intInternalHigh;
public intOffset;
public intOffsetHigh;
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. **通信测试**:连接到目标设备,发送预设的测试数据,观察返回的响应,判断通信是否正常。 2. **故障排查**:如果设备无法正常工作,可以使用串口助手发送已知正确的命令,以确定问题是否在于通信层面。 3. **...

    VC++串口通信20个经典源码

    vc++ 开放的串口通讯程序,经测试特别好用.rar vc++实现串口通信的聊天程序,可供有关爱好者学习-.rar VC++实现串口通信,觉得好的人顶详细介绍串口通信.rar VC++实现串口通讯的完整编程,并且实现各种数据的转换...

    VC++串口通信20个经典源码合集

    vc++ 开放的串口通讯程序,经测试特别好用.rar VC++串口编程 不需使用Active控件实现.rar VC++串口编程教学源码,串口学习的好东西.rar VC++串口通信源代码,用与两台机器间的串口通信,内含串口通信类.zip vc++串口...

    完整版原创STM32F103串口IAP升级程序(小部分基本代码借鉴,包含测试app和完整IAP)

    这个“完整版原创STM32F103串口IAP升级程序”集合了开发者的核心创新和部分参考自其他来源的代码,为用户提供了一套完整的解决方案,包括测试应用程序和完整的IAP流程。 STM32是意法半导体公司(STMicroelectronics...

    原创_NEC单片机模拟串口程序源代码

    根据给定的信息,本文将详细解析“原创_NEC单片机模拟串口程序源代码”的核心知识点,包括NEC单片机模拟串口的基本原理、程序设计思路以及具体实现细节。 ### NEC单片机模拟串口的基本原理 NEC单片机在某些型号中...

    原创的串口工具(VB)

    【标题】"原创的串口工具(VB)" 是一个基于Visual Basic(VB)开发的串行通信工具,专为单片机学习者和开发者设计。这个工具提供了串口通信的基本功能,帮助用户与单片机进行数据交互,是VB编程学习和实践的一个实例...

    VC 串口监听工具 不占用串口

    这种工具通常允许用户查看串行端口的数据传输,而不会干扰到其他正在使用该串口的程序。 在描述中提到的“原创为俄国人”,暗示这个工具可能由俄罗斯的程序员开发。它被发现于另一个网站,这表明它可能是一个开源...

    原创LabVIEW与汇川绝对值伺服电机驱动器串口通讯控制指令封装

    本主题聚焦于“原创LabVIEW与汇川绝对值伺服电机驱动器串口通讯控制指令封装”,它涉及到如何利用LabVIEW编程语言与汇川绝对值伺服电机驱动器通过串行接口进行高效、可靠的通信。 LabVIEW(Laboratory Virtual ...

    【[Python原创]】Python控制串口发送指令

    在Python编程语言中,串口通信(Serial Communication)是一种常用的技术,它允许设备之间通过串行数据线进行双向通信。本篇文章将详细讲解如何使用Python控制串口发送指令,以及如何进行测试。 首先,我们需要引入...

    vb与OMRON plc 串口通信

    本程序原创, 使用vb6.0开发, 使用fins通信协议,非网上的试用版,或淘宝卖家的连接,希望大家多多指教,共同学习进步!内部包含 vb源码 可执行文件 fins协议 及说明!无需plc程序,CP1H测试通过,请支持原创!

    23-本站原创 PC与单片机双向通讯智能温控程序

    双向通信可能通过串行通信协议如UART、SPI或I2C实现,这些协议允许PC和单片机之间以较低的速率交换数据。 在压缩包内的文件名未给出具体细节,但可以推测可能包含以下内容: 1. **源代码**:VB代码可能包含用户界面...

    原创VB控制继电器实验_单片机_VB源码单片机_

    这个电路包括51单片机的串行接口、电源部分、继电器驱动电路以及必要的保护电路。确保电路设计符合电气安全标准,能够稳定可靠地工作。 6. **软件设计**:VB程序设计需要考虑人机交互界面,如按钮、指示灯等控件,...

    针对mini2440的GPS程序(大部分GPS类型,自己写的,测试过)

    "自己写的"意味着程序是原创的,并且经过了作者的个人调试和测试,确保其功能性和稳定性。 **描述** "我自己根据mini2440的UART模块的特性及需要,对GPS进行移植及改进,用的是C语言,通俗易懂!" 这里说明了作者是...

    51单片机c源码390-原创VB上位机控制LED灯程序

    51单片机通常包含CPU、RAM、ROM、定时器/计数器、并行端口以及串行通信接口等功能模块。 ### 二、C语言在51单片机中的应用 #### 1. C语言的特点: - **高级语言**:相比汇编语言而言,C语言更接近自然语言,易于...

    protel99se原创电路图PCB图 串行点阵LCD 20181128

    串行点阵LCD通常用于显示字母、数字或其他简单图形,它们通过串行接口与微控制器通信,减少了所需的I/O引脚数量,节省了硬件资源。 标签“lcd 电路”进一步强调了设计的核心是与LCD相关的电路部分。LCD(Liquid ...

    用SerialPort编写的串口调试助手和V2.2完全一样.rar

    通过阅读源码,我们可以学习到如何使用C++或者C#进行串口通信的实践,了解串口调试工具的设计思路,这对于开发自己的串口应用程序或者进行硬件调试是非常有帮助的。 总的来说,这个串口调试助手是一个实用的开发...

    简易PC虚拟串口示波器(VC++整个工程源码)

    简易PC虚拟串口示波器是一款基于VC++开发的应用程序,它允许用户通过串行端口接收模拟或数字信号,并将其显示为示波器形式的数据波形。这个项目对于学习串口通信、数字信号处理以及可视化技术具有很高的教育价值。在...

    51单片机源码程序-原创VB串口继电器控制实验.zip

    《51单片机源码程序-原创VB串口继电器控制实验》是一个关于嵌入式系统设计的项目,主要涉及51系列单片机、VB编程语言以及串口通信和继电器控制技术。在这个实验中,开发者使用了51单片机作为核心处理器,并通过...

    avr例程经典

    学习这些例程,开发者可以掌握如何初始化和配置AVR的串口、如何设置中断、如何处理中断事件,以及如何进行有效的串口通信测试。这对于任何希望在AVR平台上进行串行通信应用开发的人来说,都是宝贵的参考资料。通过...

    串口工具及CRC计算数据分析编码转换

    串口,也称为串行接口,是计算机硬件的一种通信接口,用于设备间的低速数据传输。它以比特流的形式发送和接收数据,常用于连接单片机、模块或者调试设备。 首先,我们要理解串口的基本概念。串口通信通常基于RS-232...

Global site tag (gtag.js) - Google Analytics