private static Encoding _encoding = System.Text.Encoding.GetEncoding("GBK");
private static SerialPort serialPort = null;
int btl = 9600;
private void button1_Click(object sender, EventArgs e)
{
string s = rTextBox_send.Text.Trim();
byte[] bytes = Encodes(s);
byte[] bytes2 = new byte[bytes.Length + 6];
bytes2[0] = 0xfd;
//数据长度
int nlen = bytes.Length + 3;
bytes2[1] = (byte)(nlen >> 8 & 0xff); ;
bytes2[2] = (byte)(nlen & 0xff);
//控制命令
bytes2[3] = 0x01;//播放语音
//高5位为背景音乐,后面的为字符编码 0表示为gb2312
int nbackmusic = trackBar_beijingyy.Value * 8 + 1;
bytes2[4] = (byte)(nbackmusic & 0xff); ;//播放语音
for (int i = 0; i < bytes.Length; i++)
{
bytes2[5 + i] = bytes[i];
}
//crc 计算
byte b1 = CRC8(bytes2);
bytes2[5 + bytes.Length] = b1;
//
SendByte(bytes2);
DispOut(bytes2);
}
private void DispOut(byte[] bytes)
{
string s = "";
for (int i = 0; i < bytes.Length; i++)
{
string stmp = Convert.ToString(bytes[i], 16).ToUpper();
if (stmp.Length == 1)
{
stmp = "0" + stmp;
}
s += stmp + " ";
}
rTextBox_result.Text = s;
}
private static byte[] Encodes(string s)
{
// Encode the string.
byte[] bytes = _encoding.GetBytes(s);
return bytes;
}
public static byte CRC8(byte[] buffer)
{
byte crc = 0;
if (buffer.Length > 0)
{
crc = buffer[0];
}
for (int j = 1;
j < buffer.Length - 1; j++)
{
crc ^= buffer[j];
}
return crc;
}
private void SendTxt(string hc)
{
byte[] bInfo = ASCIIEncoding.Default.GetBytes(hc);
SendByte(bInfo);
}
private void SendByte(byte[] bInfo)
{
try
{
if (serialPort == null)
{
string COMNAME = comboBox1.SelectedItem.ToString();// comboBox1.SelectedText;
serialPort = new SerialPort(COMNAME, btl);
serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
serialPort.ReadTimeout = 500; serialPort.WriteTimeout = 500;
serialPort.Open();
}
serialPort.Write(bInfo, 0, bInfo.Length);
}
catch (Exception ee)
{
MessageBox.Show("串口异常");
}
}