C# WINFORM接RS232的磅秤机,显示磅秤机的秤出重量

 

这案子是为了减少秤重人员人工填写错误重量

所以用C#的WINFORM将磅秤机所秤出的重量直接读入程式的TEXTBOX中

难度不高

但是有几个关键点要先解决

 

1-磅秤机要有输出秤出的重量的功能,使用RS232或网路上传都可以

2-如果是用RS232的话,接收的电脑也要有RS232的接头,要买RS232转USB的转接头

https://ecshweb.pchome.com.tw/search/v3.3/?q=rs232%E8%BD%89usb

3-C#程式中用Thread、delegate去开启执行绪来读入磅秤机输出秤出的重量

4-RS232的SerialPort有固定参数要设定,最重要是 PortName 要设定对接到真正的COM

程式如下:

 private void Frm_Load(object sender, EventArgs e)
 	{
      	Btnconnect();
 	}
 
  public void Btnconnect()
        {
            serialPortIn = new SerialPort();
          
            serialPortIn.PortName ="COM1";       
            serialPortIn.BaudRate = 9600;
            serialPortIn.Parity = Parity.None;
            serialPortIn.DataBits = 8;
            serialPortIn.StopBits = StopBits.One;

           

            if (!serialPortIn.IsOpen)
            {
                try
                {
                   
                    serialPortIn.Open();

                }
                catch (Exception ee)
                {

                    MessageBox.Show(@"ERROR:" + ee);
                }


            }


            if (serialPortIn.IsOpen)
            {
                ReadSerialData();
               
            }

        }

        private void ReadSerialData()
        {
            ReadSerialDataThread = new Thread(ReadSerial);
            ReadSerialDataThread.Start();
        }

        private void ReadSerial()
        {
            while (serialPortIn.IsOpen)
            {
                try
                {
                    readseroaldata = serialPortIn.ReadLine();
                    ShowSerialData(readseroaldata);
                }
                catch (Exception)
                {


                }


                Thread.Sleep(20);
            }
        }

        public delegate void ShowSerialDatadelegate(string r);
        private void ShowSerialData(string s)
        {
            DateTime now = DateTime.Now;
            string pattern = @"[-+]?\d*\.?\d+";
            string datacon = "";
            
            if (textBox.InvokeRequired)
            {
                ShowSerialDatadelegate SSDD = ShowSerialData;
                Invoke(SSDD, s);
            }
            else
            {
                MatchCollection matches = Regex.Matches(s, pattern);
                foreach (Match match in matches)
                {
                    datacon += match.Value;
                }

                textBox.Text = datacon;            

            }
        }
 
        

 

 

自我LV~