随着工业互联的发展,扫码枪在很多场合都有所应用,超市、商场以及一些智能工厂。今天主要讲如何通过C#实现与新大陆扫码枪(OY10)进行通信,对于扫码枪的配置,这里就不多说了,结合说明书就可以实现。这里值得注意的是,如果安装驱动后,电脑设备管理器中看不到COM口,可能需要扫一个条形码来设置一下,具体参考说明书通讯配置章节。

   首先贴下界面,基于Winform开发,主要就是正常的串口通信,涉及的技术包括UI界面设计+串口通信知识+参数配置处理+委托更新界面,涵盖了一个小系统必备的一些知识。

    

    再来贴一些源码,首先贴个核心串口类的编写:

 using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace NewLand
{
public delegate void ShowMsgDelegate(string info); public class NewLandSerial
{ //定义串口类对象
private SerialPort MyCom;
//定义接收字节数组
byte[] bData = new byte[];
byte mReceiveByte;
int mReceiveByteCount = ;
public ShowMsgDelegate myShowInfo; public NewLandSerial()
{
MyCom = new SerialPort(); } #region 打开关闭串口方法
/// <summary>
/// 打开串口方法【9600 N 8 1】
/// </summary>
/// <param name="iBaudRate">波特率</param>
/// <param name="iPortNo">端口号</param>
/// <param name="iDataBits">数据位</param>
/// <param name="iParity">校验位</param>
/// <param name="iStopBits">停止位</param>
/// <returns></returns>
public bool OpenMyComm(int iBaudRate, string iPortNo, int iDataBits, Parity iParity, StopBits iStopBits)
{
try
{
//关闭已打开串口
if (MyCom.IsOpen)
{
MyCom.Close();
}
//设置串口属性
MyCom.BaudRate = iBaudRate;
MyCom.PortName = iPortNo;
MyCom.DataBits = iDataBits;
MyCom.Parity = iParity;
MyCom.StopBits = iStopBits;
MyCom.ReceivedBytesThreshold = ;
MyCom.DataReceived += MyCom_DataReceived; MyCom.Open();
return true;
}
catch
{
return false;
}
} private void MyCom_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
mReceiveByteCount = ;
while (MyCom.BytesToRead > )
{
mReceiveByte = (byte)MyCom.ReadByte();
bData[mReceiveByteCount] = mReceiveByte;
mReceiveByteCount += ;
if (mReceiveByteCount >= )
{
mReceiveByteCount = ;
//清除输入缓存区
MyCom.DiscardInBuffer();
return;
}
}
if (mReceiveByteCount > )
{
myShowInfo(Encoding.ASCII.GetString(GetByteArray(bData, , mReceiveByteCount)));
} } /// <summary>
/// 自定义截取字节数组
/// </summary>
/// <param name="byteArr"></param>
/// <param name="start"></param>
/// <param name="length"></param>
/// <returns></returns>
private byte[] GetByteArray(byte[] byteArr, int start, int length)
{
byte[] Res = new byte[length];
if (byteArr != null && byteArr.Length >= length)
{
for (int i = ; i < length; i++)
{
Res[i] = byteArr[i + start];
} }
return Res;
} /// <summary>
/// 关闭串口方法
/// </summary>
/// <returns></returns>
public bool ClosePort()
{
if (MyCom.IsOpen)
{
MyCom.Close();
return true;
}
else
{
return false;
} }
#endregion }
}

NewLandSerial

    再者就是界面的调用,直接看代码:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace NewLand
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
this.Load += FrmMain_Load; } private void FrmMain_Load(object sender, EventArgs e)
{
this.btn_DisConn.Enabled = false;
} private void txt_Info_DoubleClick(object sender, EventArgs e)
{
this.txt_Info.Clear();
} NewLandSerial myNewLand; private void btn_Connect_Click(object sender, EventArgs e)
{
string Port= ConfigurationManager.AppSettings["Port"].ToString(); myNewLand = new NewLandSerial();
myNewLand.myShowInfo += ShowInfo; if (myNewLand.OpenMyComm(, Port, , Parity.None, StopBits.One))
{
MessageBox.Show("连接成功!", "建立连接");
this.btn_Connect.Enabled = false;
this.btn_DisConn.Enabled = true;
}
else
{
MessageBox.Show("连接失败!", "建立连接");
}
} private void ShowInfo(string info)
{
Invoke(new Action(() =>
{
this.txt_Info.AppendText(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + info + Environment.NewLine);
}));
} private void btn_DisConn_Click(object sender, EventArgs e)
{
if (myNewLand.ClosePort())
{
MessageBox.Show("断开连接成功!", "断开连接");
this.btn_Connect.Enabled = true;
this.btn_DisConn.Enabled = false;
}
else
{
MessageBox.Show("断开连接失败!", "断开连接");
}
} private void btn_ParaSet_Click(object sender, EventArgs e)
{
new FrmParaSet().ShowDialog();
}
}
}

FrmMain

    最后是参数配置,通过App.Config实现:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace NewLand
{
public partial class FrmParaSet : Form
{
public FrmParaSet()
{
InitializeComponent();
this.Load += FrmParaSet_Load;
} private void FrmParaSet_Load(object sender, EventArgs e)
{
for (int i = ; i < ; i++)
{
this.cmb_Port.Items.Add("COM" + i.ToString());
} this.cmb_Port.Text = ConfigurationManager.AppSettings["Port"].ToString();
} private void btn_Set_Click(object sender, EventArgs e)
{
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //首先打开配置文件
cfa.AppSettings.Settings["Port"].Value = this.cmb_Port.Text;
cfa.Save(); //保存配置文件
ConfigurationManager.RefreshSection("appSettings"); //刷新配置文件
this.Close();
}
}
}

FrmParamSet

    如果大家还有什么不明白的地方,可以关注一下微信公众号:dotNet工控上位机

基于C#实现与新大陆扫码枪通信的更多相关文章

  1. JAVA基础知识之网络编程——-基于NIO的非阻塞Socket通信

    阻塞IO与非阻塞IO 通常情况下的Socket都是阻塞式的, 程序的输入输出都会让当前线程进入阻塞状态, 因此服务器需要为每一个客户端都创建一个线程. 从JAVA1.4开始引入了NIO API, NI ...

  2. APP Inventor 基于网络微服务器的即时通信APP

    APP Inventor 基于网络微服务器的即时通信APP 一.总结 一句话总结:(超低配版的QQ,逃~) 1.APP Inventor是什么? google 傻瓜式 编程 手机 app App In ...

  3. 基于NIOS II的双端口CAN通信回环测试

    基于NIOS II的双端口CAN通信回环测试 小梅哥编写,未经授权,严禁用于任何商业用途 说明:本稿件为初稿,如果大家在使用的过程中有什么疑问或者补充,或者需要本文中所述工程源文件,欢迎以邮件形式发送 ...

  4. 基于XMPP协议的Android即时通信系

    以前做过一个基于XMPP协议的聊天社交软件,总结了一下.发出来. 设计基于开源的XMPP即时通信协议,采用C/S体系结构,通过GPRS无线网络用TCP协议连接到服务器,以架设开源的Openfn'e服务 ...

  5. Prism for WPF再探(基于Prism事件的模块间通信)

    上篇博文链接 Prism for WPF初探(构建简单的模块化开发框架) 一.简单介绍: 在上一篇博文中初步搭建了Prism框架的各个模块,但那只是搭建了一个空壳,里面的内容基本是空的,在这一篇我将实 ...

  6. 基于ZYNQ的双核启动与通信问题解决

    1    处理器间的通信 为AMP 设计创建应用之前,您需要考虑应用如何进行通信(如有需要).最简单的方法是使用片上存储器.Zynq SoC 配备256KB 的片上SRAM,可从以下四个源地址进行访问 ...

  7. 基于Tcp协议的简单Socket通信实例(JAVA)

    好久没写博客了,前段时间忙于做项目,耽误了些时间,今天开始继续写起~ 今天来讲下关于Socket通信的简单应用,关于什么是Socket以及一些网络编程的基础,这里就不提了,只记录最简单易懂实用的东西. ...

  8. Java实例练习——基于UDP协议的多客户端通信

    昨天学习了UDP协议通信,然后就想着做一个基于UDP的多客户端通信(一对多),但是半天没做出来,今天早上在参考了很多代码以后,修改了自己的代码,然后运行成功,在这里分享以下代码,也说一下自己的认识误区 ...

  9. 基于TCP 协议的socket 简单通信

    DNS 服务器:域名解析 socket 套接字 : ​ socket 是处于应用层与传输层之间的抽象层,也是一组操作起来非常简单的接口(接受数据),此接口接受数据之后,交由操作系统 为什么存在 soc ...

随机推荐

  1. 在Ubuntu18.04上安装Nvidia驱动

    拿到了一台新机子,带显卡的那种,当然是各种倒腾了!于是我又一天装了三遍机子来进行各种尝试熟悉配置啥的. 所以首先是在裸机上安装Nvidia驱动. 环境:Ubuntu18.04 刚安装完系统,当然是把软 ...

  2. 图的深度优先遍历(DFS)和广度优先遍历(BFS)算法分析

    1. 深度优先遍历 深度优先遍历(Depth First Search)的主要思想是: 1.首先以一个未被访问过的顶点作为起始顶点,沿当前顶点的边走到未访问过的顶点: 2.当没有未访问过的顶点时,则回 ...

  3. iTerm2 + oh my zsh +agnoster

    安装iTerm2 iTerm2官方下载地址 http://www.iterm2.com/downloads.html 安装Oh My Bash 1.通过cat /etc/shells命令可以查看当前系 ...

  4. php 的生命周期

    1.PHP的运行模式: PHP两种运行模式是WEB模式.CLI模式.无论哪种模式,PHP工作原理都是一样的,作为一种SAPI运行. 1.当我们在终端敲入php这个命令的时候,它使用的是CLI. 它就像 ...

  5. mac安装mysql数据库及配置环境变量

    mac安装mysql数据库及配置环境变量 mac安装mysql数据库及配置环境变量 原文文链接:https://blog.csdn.net/qq_36004521/article/details/80 ...

  6. JAVA踩坑录

    以前踩了很多坑,大多忘了.现在踩了坑,想起了一定记下来. 1. 字符串分割,这种工具类,首次使用一定要先看一眼,不然跳坑 commons-lang StringUtils.split分割时会去掉空串: ...

  7. features its own

    Gulp.js features its own built-in watch() method - no external plugin required ---- However, the Arn ...

  8. nginx虚拟机无法访问解决

    .重要:修改配置文件使用虚拟机,否则怎么配置都不生效,添加如下用户 [root@host---- html]# ll /etc/nginx/nginx.conf -rw-r--r-- root roo ...

  9. CentOS修改主机名称

    centos6 或者centos7修改主机名称的方式 centos6 修改主机名 [root@centos6 ~]$ hostname # 查看当前的hostnmae centos6.com [roo ...

  10. matlab boundaries和fchcode函数无法执行的解决办法 未定义与 'double' 类型的输入参数相对应的函数 'boundaries'

    在测试代码时发现,自己的matlab无法执行Freeman链码函数: boundaries和fchcode函数都无法正常运行: 需要在自己的工作目录中添加如下函数: boundaries   fchc ...