简体   繁体   English

C# 来自 UART 如何将读取的数据分成字节?

[英]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. SerialPort已经返回字节读取并返回字节。 ReadExisting converts those bytes to a string using the SerialPort.Encoding . ReadExisting使用SerialPort.Encoding将这些字节转换为字符串。 To get the raw bytes use Read or ReadByte instead:要获取原始字节,请改用ReadReadByte

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.如果要将字节显示或写入控制台,则必须使用Encoding.GetString显式将字节转换为字符串。 :

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

Be careful though.不过要小心。

The default for SerialPort.Encoding is ASCIIEncoding, the 7-bit US-ASCII encoding. SerialPort.Encoding的默认值为 ASCIIEncoding,即 7 位 US-ASCII 编码。 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.如果端口返回非 US-ASCII 文本,您必须找到正确的编码并使用它。 On a POS this would mangle non-English product names.在 POS 上,这会破坏非英文产品名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# 中的 WebSockets:当字节不是预期的字节时,如何读取数据帧? - WebSockets in C#: How do I read a data frame when the bytes are not what they're expected to be? 你如何从 c# 中的已知偏移量中读取 4、6、8 个字节? - How do you read 4, 6, 8 bytes from a known offset in c#? C#-我一次应该从FileStream读取多少个字节? - C# - How many bytes should I read from a FileStream at one time? C# 开始/结束接收 - 如何读取大数据? - C# Begin/EndReceive - how do I read large data? 如何使用带有c#的OpenXML Format SDK从具有格式的单词中读取数据? - How do I read data from a word with format using the OpenXML Format SDK with c#? 如何从c#中由多行组成的数据中读取单行? - How do I read single lines from data consisting of multiple lines in c#? 如何使用 firesharp nuget package 从 firebase 读取数据? - How do I read data from firebase using firesharp nuget package in C#? 如何从SQLDataReader到C#变量读取Rowversion或时间戳记SQL Server数据类型 - How Do I Read A Rowversion or Timestamp SQL Server Data Type From a SQLDataReader to a C# Variable 如何从C#文件中读取这4种特定的十六进制数据? - How do I read this 4 specific hex data from a file in C#? C#如何在插入SQL Server数据库后立即读取数据? - C# How do I read data from an SQL Server database as soon as it is inserted?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM