1-C# 数据转换

C# 数据转换

1.byte转int16

temp[0] = rec[8];
temp[1] = rec[7];
textBox27.Text = BitConverter.ToInt16(temp, 0).ToString("D");

2.int字符串转byte

byte[] temp = BitConverter.GetBytes(Convert.ToInt16(textBox28.Text));
send2[7] = temp[1];
send2[8] = temp[0];

3.byte转float

byte[] rec = new byte[4];
rec[0] = OX3F;
rec[1] = OXBA;
rec[2] = OX6A;
rec[3] = OXA0;
float a = BitConverter.ToSingle(rec, 0);

4.float字符串转byte

float value = (float)Convert.ToDouble(textBox9.Text.ToString());//
byte[] bytes = BitConverter.GetBytes(value);
send2[7] = bytes[0];
send2[8] = bytes[1];
send2[9] = bytes[2];
send2[10] = bytes[3];

5.byte数组转字符串

byte[] rec = new byte[serialPort1.BytesToRead];
serialPort1.Read(rec, 0, rec.Length);
textBox30.Text = System.Text.Encoding.GetEncoding("gb2312").GetString(rec);

6.毫秒延时函数

private void Delay(double delayTime)
{
    DateTime now = DateTime.Now;
    double s;
    do
    {
        TimeSpan spand = DateTime.Now - now;
        s = spand.Milliseconds;
        Application.DoEvents();
    } while (s < delayTime);
}

7.4byte转int函数

public int ConvertTo32(byte la, byte lb, byte lc, byte ld)
{
    int value;
    value = (int)(((la & 0xFF) << 24) + ((lb & 0xFF) << 16) + ((lc & 0xFF) << 8) + ((ld & 0xFF) << 0));
    return value;
}

8.累加和数据校验

private byte Check_Sum(byte[] arr)
{
    int sum = 0;
    for (int i = 0; i < arr.Length - 1; i++)
    {
        sum += arr[i];
    }
    return (byte)(sum % 256);
}

9.CRC数据校验

public ushort Check_CRC16(byte[] data, int length)
{
    int len = length;
    ushort crc_value = 0xFFFF;

    for (int i = 0; i < len; i++)
    {
        crc_value ^= (ushort)data[i];
        for (int j = 8; j != 0; j--)
        {
            if ((crc_value & 0x0001) != 0)
            {
                crc_value >>= 1;
                crc_value ^= 0xA001;
            }
            else
            {
                crc_value >>= 1;
            }
        }
    }
    return crc_value;//= (ushort)(((crc_value & 0x00ff) << 8) | ((crc_value & 0xff00) >> 8));
}

10.接收串口数据

private void ReceiveFromMCU()
{
    try
    {
        if (serialPort1.IsOpen)
        {
            byte[] rec = new byte[serialPort1.BytesToRead];
            serialPort1.Read(rec, 0, rec.Length);

            string str = "";

            for (int i = 0; i < rec.Length; i++)
            {
                str = str + rec[i].ToString("X2") + " ";
            }
            textrecvive.Text = str;
        }
        else
        {
            MessageBox.Show("串口未开启!", "Error", MessageBoxButtons.OK);
            timer1.Stop();
            serialPort1.Close();
        }
    }
    catch (Exception ex)
    {
        timer1.Stop();
    }
}

11.发送串口数据

private void SendtoMCU(byte[] send)
{
    if (serialPort1.IsOpen)
    {
        string str = "";

        for (int i = 0; i < send.Length; i++)
        {
            str = str + send[i].ToString("X2") + " ";
        }
        textsend.Text = str;
        serialPort1.Write(send, 0, send.Length);
    }
    else
    {
        MessageBox.Show("串口未开启", "Error", MessageBoxButtons.OK);
        timer1.Stop();
    }
}

12.搜索串口并添加只下拉框

private void button1_Click(object sender, EventArgs e)
{

    string[] ArryPort = System.IO.Ports.SerialPort.GetPortNames();

    comboBox1.Items.Clear();

    for (int i = 0; i < ArryPort.Length; i++)
    {
        comboBox1.Items.Add(ArryPort[i]);
    }
}

13.打开串口

private void button2_Click(object sender, EventArgs e)//打开串口
{
    if (button2.Text == "启用端口")
    {
        try
        {
            serialPort1.PortName = comboBox1.Text;
            serialPort1.Open();
            button2.BackColor = System.Drawing.Color.Red;
            serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
        }
        catch
        {
            System.Media.SystemSounds.Beep.Play();
            MessageBox.Show("端口打开失败", "错误");
        }
    }
    else
    {
        try
        {
            timer1.Stop();
            serialPort1.Close();
            button2.BackColor = System.Drawing.Color.Green;
        }
        catch
        {
            System.Media.SystemSounds.Beep.Play();
            MessageBox.Show("关闭串口失败", "错误");
        }
    }
}

13.BIN文件末尾加上校验

FileStream fileStream;
BinaryReader br;
BinaryWriter bw;
int file_len;//文件大小
int file_num_of_packets;
UInt16 file_crc;
private void button3_Click(object sender, EventArgs e)//校验固件与生成固件
{
    string bin_str = "";
    string new_file_path;
    string time_now;
    byte[] bin_text = new byte[8];
    ushort crc16;
    int temp1_int;
    byte[] binchar = new byte[] { };//得到文件字节
    //打开文件类
    //OpenFileDialog dialog = new OpenFileDialog();
    //使用当前目录作为初始目录
    openFileDialog1.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
    //文件过滤,仅打开bin
    openFileDialog1.Filter = "bin文件(*.bin)|*.bin";
    //关闭选择多文件
    openFileDialog1.Multiselect = false;
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        //文件流类//用于文件的读写与关闭//来自于System.IO 
        FileStream fileStream = new FileStream(openFileDialog1.FileName, FileMode.Open);
        //读二进制文件类
        BinaryReader br = new BinaryReader(fileStream, Encoding.UTF8);
        //获取bin文件长度
        file_len = (int)fileStream.Length;
        //得到所有字节
        binchar = br.ReadBytes(file_len);
        //检查固件是否为真正的固件,否则提示报错。
        temp1_int = ConvertTo32(binchar[3], binchar[2], binchar[1], binchar[0]);
        if ((temp1_int & 0xFFF00000) != 0x20400000)
        {
            MessageBox.Show("固件信息栈地址有误,请重新选取", "错误提示");
            br.Close();
            fileStream.Close();
            return;
        }
        temp1_int = ConvertTo32(binchar[7], binchar[6], binchar[5], binchar[4]);
        if ((temp1_int & 0xFFFF0000) != 0x00420000)
        {
            MessageBox.Show("固件信息复位函数有误,请重新选取", "错误提示");
            br.Close();
            fileStream.Close();
            return;
        }
        //复制BIN文件到新文件。
        time_now = "_IAP_UPDATE_" + System.DateTime.Now.ToString("G").Replace("/", "_").Replace(" ", "_").Replace(":", "_") + ".";
        //label16.Text= openFileDialog1.FileName;
        new_file_path = openFileDialog1.FileName.Replace(".", time_now);
        File.Copy(openFileDialog1.FileName, new_file_path);
        label16.Text = "生成" + new_file_path;
        //显示文件名称
        textBox1.Text = openFileDialog1.FileName;
        foreach (byte j in binchar)
        {
            bin_str += "0x" + j.ToString("X2") + " ";
        }
        textBox4.Text = bin_str;
        textBox2.Text = "0x" + file_len.ToString("X2");
        crc16 = Check_CRC16(binchar, file_len);
        textBox3.Text = "0x" + crc16.ToString("X");
        //关闭 BinaryReader 对象和基础流
        br.Close();
        fileStream.Close();
        //文件流类//用于文件的读写与关闭//来自于System.IO 
        FileStream myStream = new FileStream(new_file_path, FileMode.Append, FileAccess.Write);
        //写二进制文件类
        BinaryWriter bw = new BinaryWriter(myStream);
        bin_text[0] = 0;
        bin_text[1] = 1;
        bin_text[2] = (byte)(crc16 >> 8);
        bin_text[3] = (byte)(crc16 >> 0);
        bin_text[4] = (byte)(file_len >> 24);
        bin_text[5] = (byte)(file_len >> 16);
        bin_text[6] = (byte)(file_len >> 8);
        bin_text[7] = (byte)(file_len >> 0);
        //写字节到文件
        bw.Write(bin_text);
        //关闭数据流与文件
        bw.Close();
        myStream.Close();
        //提示成功
        MessageBox.Show(new_file_path, "升级固件名称路径如下");
    }
}

14.串口发送BIN文件至单片机

        byte[] binchar1 = new byte[] { };//得到文件字节
        int file_ok = 0;
        private void button4_Click(object sender, EventArgs e)
        {
            int temp1_int;
            int temp2_int = 0;
            ushort crc16;
            int addr = 0;
            StringBuilder str = new StringBuilder();
            //打开文件类
            //OpenFileDialog dialog = new OpenFileDialog();
            //使用当前目录作为初始目录
            openFileDialog1.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
            //文件过滤,仅打开bin
            openFileDialog1.Filter = "bin文件(*.bin)|*.bin";
            //关闭选择多文件
            openFileDialog1.Multiselect = false;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                label16.Text = openFileDialog1.FileName;
                FileStream fileStream = new FileStream(openFileDialog1.FileName, FileMode.Open);
                BinaryReader br = new BinaryReader(fileStream, Encoding.UTF8);
                //获取bin文件长度
                file_len = (int)fileStream.Length;
                //得到所有字节
                binchar1 = br.ReadBytes(file_len);
                //
                temp1_int = ConvertTo32(binchar1[3], binchar1[2], binchar1[1], binchar1[0]);
                if ((temp1_int & 0xFFF00000) != 0x20400000)
                {
                    MessageBox.Show("固件信息栈地址有误,请重新选取", "错误提示");
                    br.Close();
                    fileStream.Close();
                    return;
                }
                temp1_int = ConvertTo32(binchar1[7], binchar1[6], binchar1[5], binchar1[4]);
                if ((temp1_int & 0xFFFF0000) != 0x00420000)
                {
                    MessageBox.Show("固件信息复位函数有误,请重新选取", "错误提示");
                    br.Close();
                    fileStream.Close();
                    return;
                }
                temp1_int = ConvertTo32(binchar1[file_len - 4], binchar1[file_len - 3], binchar1[file_len - 2], binchar1[file_len - 1]);
                if (temp1_int != (file_len - 8))
                {
                    MessageBox.Show("固件信息尾部数据有误,请重新选取", "错误提示");
                    br.Close();
                    fileStream.Close();
                    return;
                }
                file_ok = 1;
                //显示固件信息
                textBox2.Text = "0x" + (file_len - 8).ToString("X2") + "+8";
                crc16 = Check_CRC16(binchar1, (file_len - 8));
                textBox3.Text = "0x" + crc16.ToString("X");
                //累加每字节数组转字符串
                foreach (byte j in binchar1)
                {
                    if ((temp2_int % 16) == 0)
                    {
                        temp2_int = 0;
                        if (addr > 0) str.Append("\r\n");
                        str.Append(addr.ToString("x8") + "    ");
                        addr += 16;
                    }
                    str.Append(j.ToString("x2") + " ");
                    if (temp2_int == 7) str.Append(" ");
                    temp2_int++;
                }
                textBox4.Text = str.ToString();


            }
            else
            {
                MessageBox.Show("文件打开失败,请重新选取", "错误提示");
            }
        }

15.打开一个BIN文件并发送

byte[] binchar2 = new byte[] { };//得到文件字节
private void button58_Click(object sender, EventArgs e)//E2P数据写入
{
    try
    {
        StringBuilder str = new StringBuilder();
        //打开文件类
        //OpenFileDialog dialog = new OpenFileDialog();
        //使用当前目录作为初始目录
        openFileDialog1.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
        //文件过滤,仅打开bin
        openFileDialog1.Filter = "bin文件(*.bin)|*.bin";
        //关闭选择多文件
        openFileDialog1.Multiselect = false;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            FileStream fileStream1 = new FileStream(openFileDialog1.FileName, FileMode.Open);
            BinaryReader binr = new BinaryReader(fileStream1, Encoding.UTF8);
            //获取bin文件长度
            int file_len1 = (int)fileStream1.Length;
            //得到所有字节
            binchar2 = binr.ReadBytes(file_len1);
            byte[] send1 = new byte[file_len1 + 8];
            send1[0] = 0xEF;
            send1[1] = 0xEF;
            send1[2] = (byte)(file_len1 + 5);
            send1[3] = 0xFF;
            send1[4] = 0xE0;
            send1[5] = 0x00;
            send1[6] = 0x00;//
                            //send1[7] = 0x5A;
            Array.Copy(binchar2, 0, send1, 7, file_len1);
            send1[file_len1 + 7] = Check_Sum(send1);
            binr.Close();

            textrecvive.Text = "";
            SendtoMCU(send1);
            Delay(400);
            ReceiveFromMCU();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值