断开传感器并将传感器结果转换为C#上的距离测量仪

时间:2018-02-26 03:01:57

标签: c#

我在这方面遇到两个问题,请帮我查一下。我正在尝试使用C#开发RS-422传感器程序。

所有数据都显示在文本区域中,但我想要以米为单位的数据,我搜索了很多关于这个但我找不到任何解决方案。如果您有任何想法以仪表形式转换传感器默认数据,请给我一些解决方案。

另一个问题是我想用断开连接按钮断开传感器,但我的代码无法断开连接。请帮我解决这个问题。

这是我的代码:

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 System.Diagnostics;
using System.IO.Ports;

namespace WindowsFormsApp9
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label3.Text = DateTime.Now.ToLongDateString();
            label4.Text = DateTime.Now.ToLongTimeString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SerialPort aSerialPort = new SerialPort("COM4");
            aSerialPort.BaudRate = 19200;
            aSerialPort.DataBits = 7;
            aSerialPort.Parity = Parity.Even;
            aSerialPort.StopBits = StopBits.One;
            aSerialPort.DataReceived += new SerialDataReceivedEventHandler(serialDataReceivedEventHandler);
            button1.Enabled = false;
            button2.Enabled = true;

            if (aSerialPort.IsOpen == false)
            {
                aSerialPort.Open();
            }
        }

        private void serialDataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sData = sender as SerialPort;
            string recvData = sData.ReadLine();

            serialData.Invoke((MethodInvoker)delegate { serialData.AppendText("受け取った :" + recvData); });
            double data;
            bool result = Double.TryParse(recvData, out data);
        }

        private void serialData_TextChanged(object sender, EventArgs e)
        {
            serialData.SelectionStart = serialData.Text.Length;
            serialData.ScrollToCaret();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SerialPort aSerialPort = new SerialPort("COM4");
            button1.Enabled = true;
            button2.Enabled = false;

            if (aSerialPort.IsOpen == true)
            {
                aSerialPort.Close();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label4.Text = DateTime.Now.ToLongTimeString();
            timer1.Start();
        }
    }
}

0 个答案:

没有答案