串口编程

串口连接界面
串口连接界面

主要控件

SerialPort 表示串行端口资源
打开串口
  private void buttonOpenCOM_Click(object sender, EventArgs e)
        {
            // 串口已打开,此时需要关闭
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                this.toolStripStatusLabel1.Text = "已关闭串口" + serialPort1.PortName.ToString();
                buttonOpenCOM.Text = "打开";
                return;
            }
            // 否则打开串口
            else
            {
                serialPort1.PortName = comboBoxCOMList.Text;
                InitSerialPort();

                try
                {
                    serialPort1.Open();
                    this.toolStripStatusLabel1.Text = "已打开串口" + serialPort1.PortName.ToString();
                    buttonOpenCOM.Text = "关闭";
                }
                catch (Exception ex)
                {
                    this.toolStripStatusLabel1.Text = "打开串口失败,原因:" + ex.Message;
                    return;
                }
            }
        }
自动获取串口列表并显示
 private void ServiceForm_Load(object sender, EventArgs e)
        {
            // [TODO] 自动获取串口列表并显示到comboBoxCOMList中
            string[] ArryPort = SerialPort.GetPortNames();
            comboBoxCOMList.Items.Clear();
            for (int i = 0; i < ArryPort.Length; i++)
            {
                comboBoxCOMList.Items.Add(ArryPort[i]);
            }
        }
初始化串口
 private void InitSerialPort()
        {
            // [TODO] 设置串口参数
            serialPort1.PortName = comboBoxCOMList.Text;
            serialPort1.BaudRate = 115200;
            serialPort1.DataBits = 8;
            serialPort1.Parity = Parity.None;
        }
写入卡片
private void bt_Register_Click(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)
            {
                this.toolStripStatusLabel1.Text = "请先打开串口";
                return;
            }

            //this.toolStripStatusLabel1.Text = "未找到有效的卡";

            // '666'填充为'00000666'
            string stuffId = this.tb_EmployeeId.Text.PadLeft(8, '0');
            // '00000666'转变成'66060000'
            stuffId = ISO15693CardHandler.CovertEndian(stuffId);

            // 检查输入数据的错误
            // ISO15693为32位,4字节,8字符
            if (stuffId.Length != 8)
            {
                MessageBox.Show("请输入4字节的16进制数据!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // 检查16进制字符错误
            if (!ISO15693CardHandler.CheckValidHexBytes(stuffId))
            {
                MessageBox.Show("写入数据的16进制格式错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
插入打卡记录并显示打卡成功
 String connStr = ConfigurationManager.ConnectionStrings["Attendance system"].ConnectionString;
            SqlConnection sqlConn = new SqlConnection(connStr);
            try
            {
                // 连接数据库
                sqlConn.Open();

                // 构造命令
                String sqlStr = "insert into  record(employee_id, date, time, machine_id) VALUES(@Employee_id, @date,@time, @machine_id)";
                
                SqlCommand cmd = new SqlCommand(sqlStr, sqlConn);

                // SQL字符串参数赋值
                cmd.Parameters.Add(new SqlParameter("@employee_id", stuffId));
                cmd.Parameters.Add(new SqlParameter("@date", DateTime.Now.ToString("yyyy - MM - dd").ToString()));
                cmd.Parameters.Add(new SqlParameter("@time", DateTime.Now.ToString("HH: mm:ss").ToString()));
                cmd.Parameters.Add(new SqlParameter("@machine_id", '1'));


                // 将命令发送给数据库
                int res = cmd.ExecuteNonQuery();

                // 根据返回值判断是否插入成功
                if (res != 0)
                {
                    MessageBox.Show("打卡成功");
                }
                else
                {
                    MessageBox.Show("打卡失败");
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show("访问数据库错误:" + exp.Message);
            }
            finally
            {
                sqlConn.Close();
            }
            

        }

你可能感兴趣的:(串口编程)