简体   繁体   中英

C# from UART How do I separate the data I read into bytes?

I will be glad if you tell me what I need to edit on the code. I want to separate the data I receive byte by byte, how do I do it?

namespace _1993
{
    public partial class Form1 : Form
    {
        string[] ports = SerialPort.GetPortNames(); //Port Numaralarını ports isimli diziye atıyoruz.
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            foreach (string port in ports)
            {
                comboBox1.Items.Add(port); // Port isimlerini combobox1'de gösteriyoruz.
                comboBox1.SelectedIndex = 0;
            }
            comboBox2.Items.Add("2400");  // Baudrate'leri kendimiz combobox2'ye giriyoruz.
            comboBox2.Items.Add("4800");
            comboBox2.Items.Add("9600");
            comboBox2.Items.Add("19200");
            comboBox2.Items.Add("115200");
            comboBox2.SelectedIndex = 2;

            label3.Text = "Bağlantı Kapalı";   //Bu esnada bağlantı yok.
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            
             // Form kapandığında Seri Port Kapatılmış Olacak.
            if (serialPort1.IsOpen == true)
            {
                serialPort1.Close();
            }

            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                string sonuc = serialPort1.ReadExisting();//Serial.print kodu ile gelen analog veriyi alıyoruz,string formatında sonuc'a atıyoruz
                
                if (sonuc != "")
                {
                    label1.Text = sonuc + ""; //Labele yazdırıyoruz. 
                    listBox1.Items.Add(sonuc); //labele yazdırdığını listboxa ekle
                    byte[] ba = Encoding.Default.GetBytes(sonuc);
                    var hexString = BitConverter.ToString(ba);
                    

                    if (ba[0] == 0XFF)
                    {
                        Console.WriteLine(ba);
                    }
                    else
                    {
                        Console.WriteLine("hatalı");
                    }


                    //Console.WriteLine(ba[0]);
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message); // basarısız olursa hata verecek.
                timer1.Stop();
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {

            timer1.Start(); //250 ms olarak ayarladım timer'ı.
            if (serialPort1.IsOpen == false)
            {
                if (comboBox1.Text == "")
                    return;
                serialPort1.PortName = comboBox1.Text;  // combobox1'e zaten port isimlerini aktarmıştık.
                serialPort1.BaudRate = Convert.ToInt16(comboBox2.Text); //Seri Haberleşme baudrate'i combobox2 'de seçilene göre belirliyoruz.
                try
                {
                    serialPort1.Open(); //Haberleşme için port açılıyor
                    label3.ForeColor = Color.Green;
                    label3.Text = "Bağlantı Açık";


                }
                catch (Exception hata)
                {
                    MessageBox.Show("Hata:" + hata.Message);
                }
            }
            else
            {
                label3.Text = "Bağlantı kurulu !!!";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //BAĞLANTIYI KES BUTONU
            timer1.Stop();
            if (serialPort1.IsOpen == true)
            {
                serialPort1.Close();
                label3.ForeColor = Color.Red;
                label3.Text = "Bağlantı Kapalı";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add(label1.Text); //Okunan veri listbox'a atılıyor

        }

        private void button4_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear(); // listbox temizleniyor.
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

SerialPort already returns bytes reads and returns bytes. ReadExisting converts those bytes to a string using the SerialPort.Encoding . To get the raw bytes use Read or ReadByte instead:

var buffer=byte[1024];
var read=port.Read(buffer,0,buffer.Length);
if (read>0 && buffer[0] == 0XFF)
{
....
}

You'll have to convert the bytes to a string explicitly using Encoding.GetString if you want to display the or write them to the console. :

var str=SerialPort.Encoding.GetString(buffer,0,read);

Be careful though.

The default for SerialPort.Encoding is ASCIIEncoding, the 7-bit US-ASCII encoding. This will mangle all non-Latin characters. If the port returnes non-US-ASCII text you'll have to find the proper encoding and use it. On a POS this would mangle non-English product names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM