2012年10月29日 星期一

Recieve Data from serial port by C sharp


        void AddRecieve(object s, EventArgs e)
        {
            textBox2.AppendText("進入!Received" + "\n");
            int count;
            int i = 0;

                 do
                {
                     count = serialPort1.BytesToRead;
                     System.Threading.Thread.Sleep(200);
                     i += 1;
                 }

                 while (i < 19);
       
            byte[] rxBuff = new byte[count];
            int[] wordss = new int[18];
            serialPort1.Read(rxBuff, 0, rxBuff.Length);

            string str = BitConverter.ToString(rxBuff);
            textBox2.AppendText(str + " i=" + i + "\n");
            System.IO.File.AppendAllText(@"WriteLines.txt", str + " i=" +i + "\n");
            string[] words = str.Split('-');
            i = 0;
            foreach (string word in words)
            {
                textBox2.AppendText(word + " ");
                wordss[i] = Convert.ToInt16(word, 16);
                i++;
            }

            // int decValue;
            textBox1.Text = wordss[1].ToString();           
                textBox3.Text = (Convert.ToSingle(wordss[3]) + (Convert.ToSingle(wordss[4])) / 10).ToString();
                textBox4.Text = (Convert.ToSingle(wordss[5]) + (Convert.ToSingle(wordss[6])) / 10).ToString();

                double xValue = (Convert.ToDouble(wordss[7]) + (Convert.ToDouble(wordss[8])) / 10.0);
                if (xValue >= 128.0)
                {
                    xValue = 128.0 - xValue;
                }
                double yValue = (Convert.ToDouble(wordss[9]) + (Convert.ToDouble(wordss[10])) / 10.0);
                if (yValue >= 128.0)
                {
                    yValue = 128.0 - yValue;
                }
                double zValue = (Convert.ToDouble(wordss[11]) + (Convert.ToDouble(wordss[12])) / 10.0);
                if (zValue >= 128.0)
                {
                    zValue = 128.0 - zValue;
                }
                textBox5.Text = String.Format("{0:0.0}", xValue);
                textBox6.Text = String.Format("{0:0.0}", yValue);
                textBox7.Text = String.Format("{0:0.0}", zValue);
                //wordss[11].ToString() + wordss[12].ToString();
                string NowTime = String.Format("{0:yyyy/M/d HH:mm:ss}", DateTime.Now);
                writeLog(NowTime, textBox3.Text, textBox4.Text, textBox5.Text, textBox6.Text, textBox7.Text);
            textBox2.AppendText("\n");
        }

沒有留言: