C#收集SMD零件计数器数料机
工厂为了提高效率有的场景下会使用数料机来完成高效重复的工作,原理就是通过转盘转动计算转动距离,间距不等来实现计数。常用的SMD零件计数器 通讯有串口方式,通过指令发送获取当前计数,打印按钮触发也会发送打印信息到PC,上位可以根据指令获取进行库存抵扣,并触发打印。
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TestTool.Utility;
using TestTool.Utility.LoggerHelper;
namespace SMDCountApp
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
CommonRedisHelper.InitRedis(AppConfig.Config.RedisUrl);
List<string> intervals = new List<string>();
// 初始化间距
for (var i = 2; i < 50; i += 2)
{
intervals.Add(i.ToString());
}
CbxInterval.DataSource = intervals;
CbxInterval.Text = "4";
BtnRun_Click_1(null,null);
}
private void InitSerialport() {
var log = GlobalConstant.ServiceProvider.GetService<TPLLogger>();
try
{
var interval = CbxInterval.Text.ToInt();
if (string.IsNullOrEmpty(AppConfig.Config.ComPort))
{
AppConfig.Config.ComPort = SerialPortHelper.GetSerialPortList().Last();
}
// CbxCheck.SelectedIndex = 0;
serialPortHelper = new SerialPortHelper(AppConfig.Config.ComPort, 9600, SerialParity.None, 8, StopBit.One);
serialPortHelper.Connect();
serialPortHelper.DataReceiveAction = (data) =>
{
int value = data.ToInt();
value = value + AppConfig.Config.AddCount;
// 换算规则 4mm为基础项目 ,2mm*2
var ratio = Convert.ToDouble(interval);
var v1 = ratio / 2;
var finalCount = value / v1 * 2;
this.Invoke(() =>
{
this.LTime.Text = DateTime.Now.ToString();
this.TxtCount.Text = finalCount.ToInt().ToString();
});
// 保存Redis
if (string.IsNullOrEmpty(AppConfig.Config.SaveRedisKey) == false)
{
CommonRedisHelper.StringSet(AppConfig.Config.SaveRedisKey, value);
}
};
}
catch (Exception ex) {
log.InsertAsync(new LogModel()
{
LogMessage = $"打开串口{AppConfig.Config.ComPort} 异常 {ex.ToString()}"
}) ;
}
}
int defaultNum = 4;
SerialPortHelper serialPortHelper;
private void BtnRun_Click_1(object sender, EventArgs e)
{
try
{
if (!isOpen)
{
InitSerialport();
Task.Run(async () =>
{
var log = GlobalConstant.ServiceProvider.GetService<TPLLogger>();
while (isOpen)
{
try
{
if (serialPortHelper == null || !serialPortHelper.IsConnected())
{
InitSerialport();
}
serialPortHelper.Send("smdread\r\n");
}
catch (Exception ex)
{
log.InsertAsync(new LogModel()
{
LogMessage = "读取异常:" + ex.Message,
});
await Task.Delay(500);
}
await Task.Delay(AppConfig.Config.ReadInterval);
}
});
}
else
{
serialPortHelper.Disconnect();
}
ChangeButtonState();
}
catch (Exception ex)
{
MessageBox.Show($"异常:{ex.ToString()}");
}
}
bool isOpen = false;
private void ChangeButtonState()
{
isOpen = !isOpen;
BtnRun.Text = isOpen ? "关闭" : "打开";
this.Text = isOpen ? "零件计数器(读取中)" : "零件计数器(已停止)";
}
}
}