Usuário com melhor resposta
Tratar dados hex recebidos pela serial

Pergunta
-
Os dados que preciso tratar chegam assim 5E07003F3F3F precisava tratar byte por byte por exemplo 5E depois 07 depois 00 e assim por diante.
Se alguém puder me ajudar em C# Ja recebo os dados tudo certinho só preciso tratar os um por um desde já agradeço.só Lembrando que os dados são hexadecimais.
- Editado Felipezip domingo, 24 de abril de 2016 23:46
Respostas
Todas as Respostas
-
Use o método System.BitConverter.GetBytes. Tem sobrecargas pra short, int, long e suas versões unsigned; retorna um array de bytes. Se os dados são do tipo string, use o método Convert.ToInt**, com o segundo argumento igual a 16:
string s = "5E07003F3F3F"; long l = Convert.ToInt64(s, 16); byte[] bytes = BitConverter.GetBytes(l);
Se os dados estiverem invertidos, use o método System.Array.Reverse no array.
-
Use o método System.BitConverter.GetBytes. Tem sobrecargas pra short, int, long e suas versões unsigned; retorna um array de bytes. Se os dados são do tipo string, use o método Convert.ToInt**, com o segundo argumento igual a 16:
string s = "5E07003F3F3F"; long l = Convert.ToInt64(s, 16); byte[] bytes = BitConverter.GetBytes(l);
Se os dados estiverem invertidos, use o método System.Array.Reverse no array.
Recebo dados serias de microcontrolador em hex assim 5E03003F3F3F preciso tratalos assim
switch (Texto[0])
{
case "5E":
textbox1.text=94;//mostra o valor do hex 5E convertido para ascii
break;
case "03":
textbox2.text=03;//mostra o valor do hex 03 convertido para ascii
break;
case "3F":
textbox2.text=63;//mostra o valor do hex 3f convertido para ascii
break;
}
-
Eu falei como converter números hexadecimais para array de bytes. Crie um switch com o valor de um item do array; em que cada case, em vez de string, tenha um byte:
case 0x5E: textBox1.Text = "94"; break;
Números constantes hexadecimais em C# devem ter o prefixo "0x".
-
Eu falei como converter números hexadecimais para array de bytes. Crie um switch com o valor de um item do array; em que cada case, em vez de string, tenha um byte:
case 0x5E: textBox1.Text = "94"; break;
Números constantes hexadecimais em C# devem ter o prefixo "0x".
Amigo tentei assim so pra ver mas nao teve efeito.
private void button1_Click(object sender, EventArgs e)
{
string s = "5E07003F3F3F";
long l = Convert.ToInt64(s, 16);
byte[] bytes = BitConverter.GetBytes(l);
switch (bytes[0])
{
case 0x5E:
textBox1.Text = "94";
break;
}
switch (bytes[1])
{
case 0x07:
textBox2.Text = "07";
break;
}
} -
A string 5E07003F3F3F é convertida para esse array:
63 63 63 00 07 94 00 00
Está ao contrário. Use o método Array.Reverse no array:
Array.Reverse(bytes);
Um long tem 8 bytes, a string tem 6. Por isso os dois zeros no final (no começo depois de chamar Array.Reverse). Então, para obter o primeiro byte da string, acesse o terceiro elemento do array: bytes[2].
-
-
-
Os dados são em hexadecimal vem de um microcontrolador via serial. vou postar trechos do código pra vc ver.
Outra coisa os dados já chegam tudo certinho como preciso 5E07003F e assim por diante.
void SerialComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
ResultadoBuffer = SerialComPort.ReadExisting();
//******************************************************************************************************
//Converte para Hexadecimal
string hex = "";
foreach (char c in ResultadoBuffer)//Mudei
{
int tmp = c;
hex += String.Format("{0:X2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
//******************************************************************************************************
FundDelegate EnviaTextBox = new FundDelegate(EscreveTXT);
EnviaTextBox.Invoke(hex);/
FundDelegate EnviaDecodificar = new FundDelegate(Decodificar);
EnviaDecodificar.Invoke(hex);
}esta parte do codigo estava testando,estava fazendo com a suas dicas.
public void Decodificar(string TxtDecoder)
{
//string s = "5E07003F3F3F3F3F";
string s = TxtDecoder;
long l = Convert.ToInt64(s, 16);
byte[] bytes = BitConverter.GetBytes(l);
byte[] revertido = bytes.Reverse().ToArray();
//Array.Reverse(bytes);
if (revertido[0] == 0x5E && revertido[1] == 0x07 && revertido[2] == 0x00 && revertido[3] == 0x3F && revertido[4] == 0x3F && revertido[5] == 0x3F)
{ textBox3.Text = "conectado"; }
switch (revertido[2])
{
case (0x07):
textBox1.Text = revertido[4].ToString();
break;
case 0x00:
textBox1.Text = revertido[4].ToString();
break;
}
switch (bytes[1])
{
case 0x5E:
textBox1.Text = "94";
break;
case 0x07:
textBox1.Text = bytes[4].ToString();
break;
}
}
-
Uma forma de resolver:
Use o método ReadByte, que retorna -1 quando o fim do stream é atingido. Encha uma List de bytes. Altere seu delegado e sua função para receberem uma List<byte>. Como o tamanho dos dados varia, esse deve ser o melhor método.
Para ler os dados da porta para a lista:
int byteALer = 0; while ((byteALer = ms.ReadByte()) != -1) { bytes.Add(Convert.ToByte(byteALer)); }
bytes é uma List<byte>; ms é o stream (porta serial).
Na função Decodificar:
public void Decodificar(List<byte> bytes) { if (bytes[0] == 0x5E && bytes[1] == 0x07 && bytes[2] == 0x00 && bytes[3] == 0x3F && bytes[4] == 0x3F && bytes[5] == 0x3F) { textBox3.Text = "conectado"; } switch (bytes[2]) { case (0x07): textBox1.Text = bytes[4].ToString(); break; case 0x00: textBox1.Text = bytes[4].ToString(); break; } switch (bytes[1]) { case 0x5E: textBox1.Text = "94"; break; case 0x07: textBox1.Text = bytes[4].ToString(); break; } }
List tem o método Reverse também, se precisar inverter.
Se pode comparar números decimais com hexadecimais em C#.
Fica mais simples comparar os dados como são e converter só quando precisa, por exemplo:
textBox1.Text = bytes[4].ToString("X");
Converte o byte para hex. pra por no textbox.
-
-
Você deve ter um delegado declarado mais ou menos assim em algum lugar no seu código:
delegate void FundDelegate (string ...);
Mude o parâmetro de string para List<byte>:
delegate void FundDelegate (List<byte> bytes);
Mude a declaração da variável ResultadoBuffer para:
List<byte> ResultadoBuffer = new List<byte>();
Comente todas as linhas do método SerialComPort_DataReceived.
Substitua por:
int byteALer = 0; while ((byteALer = SerialComPort.ReadByte()) != -1) { ResultadoBuffer.Add(Convert.ToByte(byteALer)); }
FundDelegate EnviaTextBox = new FundDelegate(EscreveTXT); EnviaTextBox.Invoke(ResultadoBuffer); FundDelegate EnviaDecodificar = new FundDelegate(Decodificar); EnviaDecodificar.Invoke(ResultadoBuffer);
E então mude como eu falei acima a função Decodificar. A função EscreveTXT vai ter que ser alterada também, pra receber uma List<byte> em vez de uma string.
- Editado Vitor dos Santos sexta-feira, 29 de abril de 2016 02:20
-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;
namespace Monitor_CCD
{
public partial class MonitorCCD : Form
{
SerialPort SerialComPort = new SerialPort();
int Contador = 0;
// string ResultadoBuffer = string.Empty;
List<byte> ResultadoBuffer = new List<byte>();
delegate void FundDelegate(List<byte> bytes);
//public delegate void FundDelegate(string a);
public MonitorCCD()
{
InitializeComponent();
//SerialComPort.DataReceived += new SerialDataReceivedEventHandler(SerialComPort_DataReceived);
//textBox3.Text = "HCU";
}
void SerialComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//ResultadoBuffer = SerialComPort.ReadExisting();
//******************************************************************************************************
//Converte para Hexadecimal
string hex = "";
foreach (char c in ResultadoBuffer)//Mudei
{
int tmp = c;
hex += String.Format("{0:X2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
//******************************************************************************************************
int byteALer = 0;
while ((byteALer = SerialComPort.ReadByte()) != -1)
{
ResultadoBuffer.Add(Convert.ToByte(byteALer));
}
//FundDelegate EnviaTextBox = new FundDelegate(EscreveTXT);
//EnviaTextBox.Invoke(hex);//Mudei envia para a funcao EscreveTXT
//FundDelegate EnviaDecodificar = new FundDelegate(Decodificar);
//EnviaDecodificar.Invoke(hex);//Mudei envia para a funcao decodificar
}
public void EscreveTXT(string a)
{
if (this.txtRecepcao.InvokeRequired)
{
//FundDelegate d = new FundDelegate(EscreveTXT);
//this.Invoke(d, new object[] { a});
}
else
{
this.txtRecepcao.Text += a;
}
}
private void TerminalSerial_Load(object sender, EventArgs e)
{
#region Configuração Serial do Terminal
String[] ListCom = SerialPort.GetPortNames();
string NameCom;
int x = 0;
for (int i = 0; i < ListCom.Length; i++)
{
NameCom = ListCom[i];
cbxComPort.Items.Add(NameCom);
if (NameCom == "COM3")
{
x = i;
}
}
if (ListCom.Length > 0)
cbxComPort.SelectedIndex = x;
#endregion
#region Carrega valores de BaudRate no ComboBox
Int32[] BaudRateValores = { 100,300,600,1200,2400,4800,7812,9600,14400,19200,
38400,56000,57600,115200,128000,256000
};
int x1 = 0;
for (int i = 0; i < BaudRateValores.Length; i++)
{
cbxBaudRate.Items.Add(BaudRateValores[i].ToString());
if (BaudRateValores[i] == 9600)
{
x1 = i;
}
}
cbxBaudRate.SelectedIndex = x1;
#endregion
#region Carrega valores DataBits no ComboBox
cbxDataBits.Items.Add("5"); //indice 0
cbxDataBits.Items.Add("6");
cbxDataBits.Items.Add("7");
cbxDataBits.Items.Add("8"); //indice 3
cbxDataBits.SelectedIndex = 3;
#endregion
#region carrega valores de Paridade no comboBox
foreach (string s in Enum.GetNames(typeof(Parity)))
{
cbxParidade.Items.Add(s);
}
cbxParidade.SelectedIndex = 0;
#endregion
#region Carrega Valores de StopBits no ComboBox
foreach (string s in Enum.GetNames(typeof(StopBits)))
{
cbxStopBit.Items.Add(s);
}
cbxStopBit.SelectedIndex = 1;
#endregion
#region Carrega valores de HandShake no comboBox
foreach(string s in Enum.GetNames(typeof(Handshake)))
{
cbxHandshake.Items.Add(s);
}
cbxHandshake.SelectedIndex = 0;
#endregion
#region Carrega valores do BufferSize no comboBox
cbxBufferSize.Items.Add("1024");
cbxBufferSize.Items.Add("2048");
cbxBufferSize.Items.Add("8192");
cbxBufferSize.Items.Add("16384");
cbxBufferSize.SelectedIndex = 0;
#endregion
btnDesconectar.Enabled = false;
}
private void btnConectar_Click(object sender, EventArgs e)
{
SerialComPort.PortName = cbxComPort.Text;
SerialComPort.BaudRate = Int32.Parse(cbxBaudRate.Text);
SerialComPort.DataBits = Int32.Parse(cbxDataBits.Text);
SerialComPort.Parity = (Parity)cbxParidade.SelectedIndex;
SerialComPort.StopBits = (StopBits)cbxStopBit.SelectedIndex;
SerialComPort.Handshake = (Handshake)cbxHandshake.SelectedIndex;
SerialComPort.WriteTimeout = 500;
SerialComPort.ReadTimeout = 500;
System.Text.ASCIIEncoding AsCII = new System.Text.ASCIIEncoding();
SerialComPort.Encoding = AsCII;
try
{
SerialComPort.Open();
lblStatusConexao.Text = "CONECTADO";
lblStatusConexao.BackColor = Color.DarkGreen;
btnDesconectar.Enabled = true;
btnConectar.Enabled = false;
gBoxConfiguracao.Enabled = false;
//TimerRecepcao.Enabled = true;
}
catch
{
MessageBox.Show("Não foi possível abrir a porta COM selecionada");
}
}
private void btnDesconectar_Click(object sender, EventArgs e)
{
try
{
textBox1.Text = "0";
while (SerialComPort.BytesToWrite > 0) ;
SerialComPort.Dispose(); //fecha a porta e libera o recurso da memória
SerialComPort.Close(); //fecha a porta COM
TimerRecepcao.Enabled = false;
btnDesconectar.Enabled = false;
btnConectar.Enabled = true;
lblStatusConexao.Text = "DESCONECTADO";
lblStatusConexao.BackColor = Color.DarkRed;
gBoxConfiguracao.Enabled = true;
}
catch
{
MessageBox.Show("Não foi possível fechar a porta COM selecionada");
}
}
//verifica se a porta COM esta aberta ou fechada
public bool isOpen
{
get
{
return SerialComPort.IsOpen;
}
}
private void ApagarTxTTransmissao_Click(object sender, EventArgs e)
{
txtTransmissao.Text = "";
}
private void btnApagarTXTRecepcao_Click(object sender, EventArgs e)
{
txtRecepcao.Text = "";
}
string TextoRecepcao;
private void TimerRecepcao_Tick(object sender, EventArgs e)
{
if (isOpen)
{
try
{
TextoRecepcao = SerialComPort.ReadExisting();
}
catch(Exception w)
{
MessageBox.Show(w.ToString());
}
}
}
public void Decodificar(string TxtDecoder)
{
//string s = "5E07003F3F3F3F3F"; Com Esta strig funciona.
string s = TxtDecoder;
long l = Convert.ToInt64(s, 16);
byte[] bytes = BitConverter.GetBytes(l);
byte[] revertido = bytes.Reverse().ToArray();
if (revertido[0] == 0x5E && revertido[1] == 0x07 && revertido[2] == 0x00 && revertido[3] == 0x3F && revertido[4] == 0x3F && revertido[5] == 0x3F)
{
textBox3.Text = "CONECTADO";
textBox3.BackColor = Color.DarkGreen;
}
else
{
textBox3.Text = "Desconectado";
textBox3.BackColor = Color.Red;
}
switch (bytes[2])
{
case (0x07):
textBox1.Text = bytes[4].ToString();
break;
case 0x00:
textBox1.Text = bytes[4].ToString();
break;
}
switch (bytes[1])
{
case 0x5E:
textBox1.Text = "94";
break;
case 0x07:
textBox1.Text = bytes[4].ToString();
break;
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
Contador=Contador+1;
textBox1.Text = Contador.ToString();
if (isOpen)
{
try
{
byte[] x = {0x1E,0x43};
SerialComPort.Write(x,0,2);
Thread.Sleep(500);
button1.Enabled = true;
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button3_Click(object sender, EventArgs e)
{
if (isOpen)
{
try
{
byte[] x = { 0x1E, 0x03 };
SerialComPort.Write(x, 0, 2);
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
Contador = Contador - 1;
textBox1.Text = Contador.ToString();
if (isOpen)
{
try
{
byte[] x = { 0x1E, 0x23 };
SerialComPort.Write(x, 0, 2);
Thread.Sleep(500);
button2.Enabled = true;
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button4_Click(object sender, EventArgs e)
{
if (isOpen)
{
try
{
byte[] x = { 0x1E, 0x63 };
SerialComPort.Write(x, 0, 2);
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button5_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text = "0";
// byte[] x = { 0x5E, 0x07, 0x00, 0x3F, 0x3F, 0x3F };
// SerialComPort.Write(x, 0, 7);
if (isOpen)
{
try
{
byte[] x ={ 0x5E, 0x07, 0x00, 0x3F, 0x3F, 0x3F };
// byte[] x = { 0x3F, 0x3F, 0x1A, 0x6F };
SerialComPort.Write(x, 0, 6);
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button6_Click(object sender, EventArgs e)
{
if (isOpen)
{
try
{
byte[] x = { 0x3F, 0x3F, 0x1A, 0x6F };
SerialComPort.Write(x, 0, 4);
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button7_Click(object sender, EventArgs e)
{
if (isOpen)
{
try
{
// 12 23 1B 00 10 3F 23 33 03 35 3F 00 3F
byte[] x = {0x12, 0x23, 0x1B, 0x00, 0x10, 0x3F, 0x23, 0x33, 0x03, 0x35, 0x3F, 0x00, 0x3F };
SerialComPort.Write(x, 0, 13);
}
catch
{
MessageBox.Show("ERRO");
}
}
}
}
}
-
Amigo não consegui fazer funcionar se puder me ajudar segue código que consegui fazer.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;
namespace Monitor_CCD
{
public partial class MonitorCCD : Form
{
SerialPort SerialComPort = new SerialPort();
int Contador = 0;
// string ResultadoBuffer = string.Empty;
List<byte> ResultadoBuffer = new List<byte>();
delegate void FundDelegate(List<byte> bytes);
//public delegate void FundDelegate(string a);
public MonitorCCD()
{
InitializeComponent();
//SerialComPort.DataReceived += new SerialDataReceivedEventHandler(SerialComPort_DataReceived);
//textBox3.Text = "HCU";
}
void SerialComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//ResultadoBuffer = SerialComPort.ReadExisting();
//******************************************************************************************************
//Converte para Hexadecimal
string hex = "";
foreach (char c in ResultadoBuffer)//Mudei
{
int tmp = c;
hex += String.Format("{0:X2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
//******************************************************************************************************
int byteALer = 0;
while ((byteALer = SerialComPort.ReadByte()) != -1)
{
ResultadoBuffer.Add(Convert.ToByte(byteALer));
}
//FundDelegate EnviaTextBox = new FundDelegate(EscreveTXT);
//EnviaTextBox.Invoke(hex);//Mudei envia para a funcao EscreveTXT
//FundDelegate EnviaDecodificar = new FundDelegate(Decodificar);
//EnviaDecodificar.Invoke(hex);//Mudei envia para a funcao decodificar
}
public void EscreveTXT(string a)
{
if (this.txtRecepcao.InvokeRequired)
{
//FundDelegate d = new FundDelegate(EscreveTXT);
//this.Invoke(d, new object[] { a});
}
else
{
this.txtRecepcao.Text += a;
}
}
private void TerminalSerial_Load(object sender, EventArgs e)
{
#region Configuração Serial do Terminal
String[] ListCom = SerialPort.GetPortNames();
string NameCom;
int x = 0;
for (int i = 0; i < ListCom.Length; i++)
{
NameCom = ListCom[i];
cbxComPort.Items.Add(NameCom);
if (NameCom == "COM3")
{
x = i;
}
}
if (ListCom.Length > 0)
cbxComPort.SelectedIndex = x;
#endregion
#region Carrega valores de BaudRate no ComboBox
Int32[] BaudRateValores = { 100,300,600,1200,2400,4800,7812,9600,14400,19200,
38400,56000,57600,115200,128000,256000
};
int x1 = 0;
for (int i = 0; i < BaudRateValores.Length; i++)
{
cbxBaudRate.Items.Add(BaudRateValores[i].ToString());
if (BaudRateValores[i] == 9600)
{
x1 = i;
}
}
cbxBaudRate.SelectedIndex = x1;
#endregion
#region Carrega valores DataBits no ComboBox
cbxDataBits.Items.Add("5"); //indice 0
cbxDataBits.Items.Add("6");
cbxDataBits.Items.Add("7");
cbxDataBits.Items.Add("8"); //indice 3
cbxDataBits.SelectedIndex = 3;
#endregion
#region carrega valores de Paridade no comboBox
foreach (string s in Enum.GetNames(typeof(Parity)))
{
cbxParidade.Items.Add(s);
}
cbxParidade.SelectedIndex = 0;
#endregion
#region Carrega Valores de StopBits no ComboBox
foreach (string s in Enum.GetNames(typeof(StopBits)))
{
cbxStopBit.Items.Add(s);
}
cbxStopBit.SelectedIndex = 1;
#endregion
#region Carrega valores de HandShake no comboBox
foreach(string s in Enum.GetNames(typeof(Handshake)))
{
cbxHandshake.Items.Add(s);
}
cbxHandshake.SelectedIndex = 0;
#endregion
#region Carrega valores do BufferSize no comboBox
cbxBufferSize.Items.Add("1024");
cbxBufferSize.Items.Add("2048");
cbxBufferSize.Items.Add("8192");
cbxBufferSize.Items.Add("16384");
cbxBufferSize.SelectedIndex = 0;
#endregion
btnDesconectar.Enabled = false;
}
private void btnConectar_Click(object sender, EventArgs e)
{
SerialComPort.PortName = cbxComPort.Text;
SerialComPort.BaudRate = Int32.Parse(cbxBaudRate.Text);
SerialComPort.DataBits = Int32.Parse(cbxDataBits.Text);
SerialComPort.Parity = (Parity)cbxParidade.SelectedIndex;
SerialComPort.StopBits = (StopBits)cbxStopBit.SelectedIndex;
SerialComPort.Handshake = (Handshake)cbxHandshake.SelectedIndex;
SerialComPort.WriteTimeout = 500;
SerialComPort.ReadTimeout = 500;
System.Text.ASCIIEncoding AsCII = new System.Text.ASCIIEncoding();
SerialComPort.Encoding = AsCII;
try
{
SerialComPort.Open();
lblStatusConexao.Text = "CONECTADO";
lblStatusConexao.BackColor = Color.DarkGreen;
btnDesconectar.Enabled = true;
btnConectar.Enabled = false;
gBoxConfiguracao.Enabled = false;
//TimerRecepcao.Enabled = true;
}
catch
{
MessageBox.Show("Não foi possível abrir a porta COM selecionada");
}
}
private void btnDesconectar_Click(object sender, EventArgs e)
{
try
{
textBox1.Text = "0";
while (SerialComPort.BytesToWrite > 0) ;
SerialComPort.Dispose(); //fecha a porta e libera o recurso da memória
SerialComPort.Close(); //fecha a porta COM
TimerRecepcao.Enabled = false;
btnDesconectar.Enabled = false;
btnConectar.Enabled = true;
lblStatusConexao.Text = "DESCONECTADO";
lblStatusConexao.BackColor = Color.DarkRed;
gBoxConfiguracao.Enabled = true;
}
catch
{
MessageBox.Show("Não foi possível fechar a porta COM selecionada");
}
}
//verifica se a porta COM esta aberta ou fechada
public bool isOpen
{
get
{
return SerialComPort.IsOpen;
}
}
private void ApagarTxTTransmissao_Click(object sender, EventArgs e)
{
txtTransmissao.Text = "";
}
private void btnApagarTXTRecepcao_Click(object sender, EventArgs e)
{
txtRecepcao.Text = "";
}
string TextoRecepcao;
private void TimerRecepcao_Tick(object sender, EventArgs e)
{
if (isOpen)
{
try
{
TextoRecepcao = SerialComPort.ReadExisting();
}
catch(Exception w)
{
MessageBox.Show(w.ToString());
}
}
}
public void Decodificar(string TxtDecoder)
{
//string s = "5E07003F3F3F3F3F"; Com Esta strig funciona.
string s = TxtDecoder;
long l = Convert.ToInt64(s, 16);
byte[] bytes = BitConverter.GetBytes(l);
byte[] revertido = bytes.Reverse().ToArray();
if (revertido[0] == 0x5E && revertido[1] == 0x07 && revertido[2] == 0x00 && revertido[3] == 0x3F && revertido[4] == 0x3F && revertido[5] == 0x3F)
{
textBox3.Text = "CONECTADO";
textBox3.BackColor = Color.DarkGreen;
}
else
{
textBox3.Text = "Desconectado";
textBox3.BackColor = Color.Red;
}
switch (bytes[2])
{
case (0x07):
textBox1.Text = bytes[4].ToString();
break;
case 0x00:
textBox1.Text = bytes[4].ToString();
break;
}
switch (bytes[1])
{
case 0x5E:
textBox1.Text = "94";
break;
case 0x07:
textBox1.Text = bytes[4].ToString();
break;
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
Contador=Contador+1;
textBox1.Text = Contador.ToString();
if (isOpen)
{
try
{
byte[] x = {0x1E,0x43};
SerialComPort.Write(x,0,2);
Thread.Sleep(500);
button1.Enabled = true;
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button3_Click(object sender, EventArgs e)
{
if (isOpen)
{
try
{
byte[] x = { 0x1E, 0x03 };
SerialComPort.Write(x, 0, 2);
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
Contador = Contador - 1;
textBox1.Text = Contador.ToString();
if (isOpen)
{
try
{
byte[] x = { 0x1E, 0x23 };
SerialComPort.Write(x, 0, 2);
Thread.Sleep(500);
button2.Enabled = true;
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button4_Click(object sender, EventArgs e)
{
if (isOpen)
{
try
{
byte[] x = { 0x1E, 0x63 };
SerialComPort.Write(x, 0, 2);
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button5_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text = "0";
// byte[] x = { 0x5E, 0x07, 0x00, 0x3F, 0x3F, 0x3F };
// SerialComPort.Write(x, 0, 7);
if (isOpen)
{
try
{
byte[] x ={ 0x5E, 0x07, 0x00, 0x3F, 0x3F, 0x3F };
// byte[] x = { 0x3F, 0x3F, 0x1A, 0x6F };
SerialComPort.Write(x, 0, 6);
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button6_Click(object sender, EventArgs e)
{
if (isOpen)
{
try
{
byte[] x = { 0x3F, 0x3F, 0x1A, 0x6F };
SerialComPort.Write(x, 0, 4);
}
catch
{
MessageBox.Show("ERRO");
}
}
}
private void button7_Click(object sender, EventArgs e)
{
if (isOpen)
{
try
{
// 12 23 1B 00 10 3F 23 33 03 35 3F 00 3F
byte[] x = {0x12, 0x23, 0x1B, 0x00, 0x10, 0x3F, 0x23, 0x33, 0x03, 0x35, 0x3F, 0x00, 0x3F };
SerialComPort.Write(x, 0, 13);
}
catch
{
MessageBox.Show("ERRO");
}
}
}
}
}
-
-
Assim que sugeri mudar:
void SerialComPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { int byteALer = 0; while ((byteALer = SerialComPort.ReadByte()) != -1) { ResultadoBuffer.Add(Convert.ToByte(byteALer)); } FundDelegate EnviaTextBox = new FundDelegate(EscreveTXT); EnviaTextBox.Invoke(ResultadoBuffer); FundDelegate EnviaDecodificar = new FundDelegate(Decodificar); EnviaDecodificar.Invoke(ResultadoBuffer); } public void EscreveTXT (List<byte> bytes) { if (this.txtRecepcao.InvokeRequired) { FundDelegate d = new FundDelegate (EscreveTXT); this.Invoke (d, new object[] { bytes }); } else { string s = string.Empty; foreach (byte item in bytes) { s += item.ToString(); } this.txtRecepcao.Text += s; } } public void Decodificar (List<byte> bytes) { if (bytes[0] == 0x5E && bytes[1] == 0x07 && bytes[2] == 0x00 && bytes[3] == 0x3F && bytes[4] == 0x3F && bytes[5] == 0x3F) { textBox3.Text = "conectado"; } switch (bytes[2]) { case (0x07): textBox1.Text = bytes[4].ToString("X"); break; case 0x00: textBox1.Text = bytes[4].ToString("X"); break; } switch (bytes[1]) { case 0x5E: textBox1.Text = "94"; break; case 0x07: textBox1.Text = bytes[4].ToString("X"); break; } }
O resto do que importa parece estar bem.
Na função SerialComPort_DataReceived, a parte de converter o que é lido para uma string de dados hexadecimais não é necessária porque os dados estão sendo lidos como uma lista de bytes, que é passada para as funções EscreveTXT e Decodificar. Essas duas recebem uma List<byte> em vez de string; veja as mudanças que fiz na função EscreveTXT. Nela, os dados que chegam são convertidos para string para pôr no textbox.
A função Decodificar já recebe uma lista de bytes como parametro, não precisa converter.
Se os dados do stream (porta serial) estiverem na ordem em que são lidos aqui:
if (bytes[0] == 0x5E && bytes[1] == 0x07 && bytes[2] == 0x00 && bytes[3] == 0x3F && bytes[4] == 0x3F && bytes[5] == 0x3F)
Então não precisa invertê-los, porque eles são lidos na ordem em que estão.
Na função Decodificar eu converti o byte para string no formato hexadecimal:
textBox1.Text = bytes[4].ToString("X");
É a única parte em que precisa fazer isso.
-
-
Que erro?
Tente setar as propriedades DtrEnable e RtsEnable da SerialPort para true.
porta.DtrEnable = true;
porta.RtsEnable = true;- Editado Vitor dos Santos quarta-feira, 4 de maio de 2016 06:31
-
Amigo consegui fazer tudo funcionar so preciso de uma ajuda para converter este valor.
case 0x43:
BeginInvoke((MethodInvoker)(() => { textBox1.Text = txtDecoder[1].ToString(); }));
break;
Teria que aparecer o valor de 0x43 que seria decimal 67 mas aparece a letra C.
vou tentando aqui se tiver a solucao me ajuda obrigado. -