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;
}
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[] { };
openFileDialog1.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
openFileDialog1.Filter = "bin文件(*.bin)|*.bin";
openFileDialog1.Multiselect = false;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileStream fileStream = new FileStream(openFileDialog1.FileName, FileMode.Open);
BinaryReader br = new BinaryReader(fileStream, Encoding.UTF8);
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;
}
time_now = "_IAP_UPDATE_" + System.DateTime.Now.ToString("G").Replace("/", "_").Replace(" ", "_").Replace(":", "_") + ".";
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");
br.Close();
fileStream.Close();
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();
openFileDialog1.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
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);
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)
{
try
{
StringBuilder str = new StringBuilder();
openFileDialog1.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
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);
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;
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);
}
}