Reputation: 219
I have been trying to send and read commands using the serial port COM4 which is already configured using this code, it is connected to a bill acceptor device
im using an event to suscribe whenever the device sends an answer however when debbuging i found out that it never actually reaches the event nor subscribes to it , i have been reading the whole week how to solve this with no luck,
Even if i happen to put the "read port" lines right after the "write port lines" and the program gets to the
ptSerial.Read(RxMensaje, 0, 5);
line the program just frezzes and i have to stop it hopefully someone here can help me oput
public partial class Form1 : Form
{
public SerialDataReceivedEventHandler DataReceivedDelegate;
public Form1()
{
InitializeComponent();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
DataReceivedDelegate = new SerialDataReceivedEventHandler(DataReceivedHandler);
//SerialPort sp = (SerialPort)sender;
//string indata = sp.ReadExisting();
byte[] RxMensaje = new byte[5];
ptSerial.Read(RxMensaje, 0, 5);
rtbDevice.Text = Encoding.ASCII.GetString(RxMensaje, 0, 5);
// rtbDevice.Text = indata;
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
Open(sender, e);
}
catch (Exception ex)
{
lblSalida.Text = ex.Message;
}
}
private void Open(object sender, EventArgs e)
{
ptSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
ptSerial.Open();
lblSalida.Text = "Puerto COM4 Abierto";
}
private void btnSend_Click(object sender, EventArgs e)
{
if (ptSerial.IsOpen)
{
byte[] TxMensaje = new byte[5] { 0x02, 0x00, 0x01, 0xFE, 0xFF }; //CCtalk
ptSerial.Write(TxMensaje, 0, 5);
rtbHost.Text = "2 0 1 254 255 Enviado";
//byte[] RxMensaje = new byte[5];
//ptSerial.Read(RxMensaje, 0, 5);
//rtbDevice.Text = Encoding.ASCII.GetString(RxMensaje, 0, 5);
ptSerial.Close();
lblSalida.Text = "Bytes Enviados Pto Cerrado";
}
else
{
lblSalida.Text = "Puerto Cerrado";
}
}
private void btnCerrar_Click(object sender, EventArgs e)
{
if (ptSerial.IsOpen)
{
ptSerial.Close();
lblSalida.Text = "Puerto COM4 Cerrado";
}
else
{
lblSalida.Text = "No ocurrio nada :(";
}
}
}
Upvotes: 1
Views: 310
Reputation: 710
I don't see the full definition of the serial port (e.g. where do you bind to "COM4"). Very important the baud rate is set properly else the device won't synchronize correctly with your application and no event will generate.
See http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx
_serialPort = new SerialPort(); // Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
Upvotes: 1