PDA

View Full Version : مشکل در ارسال داده های hex به پورت سریال



sajjad23
یک شنبه 13 بهمن 1392, 11:50 صبح
خب من باید یه سری کد hex به مثلا این شکل (00 23 11 15 00) رو برای پورت ارسال کنم . -البته بدون فاصله-
توی نت بهترین راههی که پیدا کردم ساختن آرایه ای از بایت بود و عدها رو تک تک بفرستم که جواب نداد ... (http://www.codeproject.com/Questions/236017/Correct-Way-to-write-Hex-Values-to-Serial-port-thi)


پیشاپیش ممنون

sajjad23
یک شنبه 13 بهمن 1392, 15:00 عصر
خب قربون این خارجیا برم که چه سریع جواب میدن با این کد حل شد ... میگذارمش تا اگه کسی مشکل مشابه داشت کمک کنه..
private void SendData()
{
if (CurrentDataMode == DataMode.Text)
{
// Send the user's text straight out the port
comport.Write(txtSendData.Text);

// Show in the terminal window the user's text
Log(LogMsgType.Outgoing, txtSendData.Text + "\n");
}
else
{
try
{
// Convert the user's string of hex digits (ex: B4 CA E2) to a byte array
byte[] data = HexStringToByteArray(txtSendData.Text);

// Send the binary data out the port
comport.Write(data, 0, data.Length);

// Show the hex digits on in the terminal window
Log(LogMsgType.Outgoing, ByteArrayToHexString(data) + "\n");
}
catch (FormatException)
{
// Inform the user if the hex string was not properly formatted
Log(LogMsgType.Error, "Not properly formatted hex string: " + txtSendData.Text + "\n");
}
}
در هر حال ممنون ..
ویرایش :
اینو یادم رفت بذارم ...:)

private byte[] HexStringToByteArray(string s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}

کد بالایی تبدیل تکست به هکس و زیری تبدیل هگز به تکست

private string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();
}