I am able to write the command to RS232 but Not able to read data from SerialPort.(C#)

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
<pre class="prettyprint public frmMain()
{
InitializeComponent();

comboSerial.SelectedItem = "COM1";
comboBaudRate.SelectedItem = "9600";
comboParity.SelectedItem = "None";
comboStopBit.SelectedItem = "one";
comboData.SelectedItem = "8";
comboReadTimeOut.SelectedItem = "10";
}
// Public Members
//private MessageBasedSession mbSession;
private System.Timers.Timer timer1;
private StringBuilder recievedB = new StringBuilder();
private string recievedData;
private SerialPort sp;
int _selectedIndex;
string _text;
string indata;
delegate void SetTextCallback(string text);

private delegate void preventCrossThreading(string x);
private preventCrossThreading accessControlFromCentralThread;


// main method
public static void Main()
{
frmMain main = new frmMain();
Application.Run(main);

}
/*----------------------------------------------------------------------------------------------------

* The following function shows all the available comports in the combo-box
* when the "show" button is clicked.

------------------------------------------------------------------------------------------------------*/
private void btnShow_Click(object sender, EventArgs e)
{
// Get a list of serial port names
string[] ports = SerialPort.GetPortNames();

//Display each port name in the combobox.
foreach (string port in ports)
{
if (comboSerial.Items.Count == 0)
{
comboSerial.Items.Add(port.ToString());
}
}
}
/*----------------------------------------------------------------------------------------------------

* The following function will make connection with the selected
* comport when Connect button is clicked.

------------------------------------------------------------------------------------------------------*/
// Function starts here
private void btnConnect_Click(object sender, EventArgs e)
{
sp = new SerialPort();
sp.PortName = "COM1";
//sp.Parity = Parity.None;
sp.BaudRate = 9600;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
sp.DtrEnable = true;
sp.Handshake = Handshake.None;
sp.ReadTimeout = 10000;
sp.WriteTimeout = 10000;
sp.ReadBufferSize = 30000;
sp.WriteBufferSize = 30000;

// sp.DtrEnable = true;
//sp.RtsEnable = true;

/*
* The following commented code is for allowing user selection from combo.
* For future implementation when basic code works
*/
//SerialPort sp = new SerialPort("COM1");
//sp.BaudRate = comboBaudRate.SelectedIndex;
//string baudRate = int.Parse(sp.BaudRate);
//sp.Parity = int.Parse(comboParity.SelectedItem);
//sp.DataBits = comboData.SelectedIndex;
//sp.ReadTimeout = comboReadTimeOut.SelectedIndex;
//sp.StopBits = comboStopBit.SelectedIndex;
try
{
if (!sp.IsOpen)
sp.Open();
labelSuccess.Text = "Connected to COM1";
}
catch (Exception ex)
{
MessageBox.Show("Error opening serial port :: " + ex.Message, "Error!");
}
btnConnect.Text = "Disconnect";
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen)
serialPort1.Close();
}
/*--------------------------------------------------------------------------------------------------------------
* Following function will send(write) the Data to the comport
*--------------------------------------------------------------------------------------------------------------
*/
private void btnSend_Click(object sender, EventArgs e)
{
string command;

command = txtCommand.Text;
Debug.Print(command);
if (command == "")
{
MessageBox.Show("Please Enter a command");
txtCommand.SelectAll();
txtCommand.Focus();
}
try
{
if (sp.IsOpen)
{
MessageBox.Show(command + " sent to COM1");
Debug.Print("The commands is sent " + command);
sp.Write(command + "n");
Thread.Sleep(1000);

}
}
catch (Exception ex)
{
MessageBox.Show("Error opening serial port :: " + ex.Message, "Error!");
}


}
private void btnSendRecv_Click(object sender, EventArgs e)
{
string comm = txtCommand.Text;
string buffer;
try
{
if (sp.IsOpen)
{

//MessageBox.Show("Inside before ReadlIne");
//string message = sp.ReadLine(); // Receiving NULL
// int data = sp.ReadByte();
// MessageBox.Show((data).ToString());
// sp.Write(comm);
// Thread.Sleep(5000);
// string message = sp.ReadLine();

// int data = sp.ReadByte();

// string receivedData = data.ToString();
// MessageBox.Show(receivedData);

buffer = sp.ReadExisting();
Thread.Sleep(5000);
//string bufferChar = buffer.ToString();
MessageBox.Show(buffer);
textBoxStatus.Text = buffer;
//MessageBox.Show((data).ToString());

// MessageBox.Show(message);
// sage != String.Empty)
// {
// this.BeginInvoke(new SetTextCallback(SetText), new object[] { message });
// }


//textBoxStatus.Text = message;
}
}
catch (TimeoutException te)
{
MessageBox.Show("Error ::" + te.Message, "TimeOut!");
}
catch (Exception ex)
{
MessageBox.Show("Error opening serial port :: " + ex.Message, "Error!");
}


}[/code]
<br/>
I am trying to communicate with an instrument via RS232 serial port.
I am getting connected successfully to the port.
I can send the command to the port.
For testing : I actually opened a port on HyperTerminal of another machine and I could communicate through my program. I was able to send data from my program and receive data from HyperTerminal into my program.
However, same program wont read data from the unit I am trying to communicate with.
When I write a command on serial port and try to receive data back I am getting "blank" not even null.
I m having problems in <span style="font-size:small <span style="font-size:small btnSendRecv_Click() method.

<span style="font-size:small <span style="font-size:small


<span style="color:#0000ff; font-size:small <span style="color:#0000ff; font-size:small <span style="color:#0000ff; font-size:small private<span style="font-size:small <span style="font-size:small
<span style="color:#0000ff; font-size:small <span style="color:#0000ff; font-size:small <span style="color:#0000ff; font-size:small void<span style="font-size:small <span style="font-size:small btnSendRecv_Click(<span style="color:#0000ff; font-size:small <span style="color:#0000ff; font-size:small <span style="color:#0000ff; font-size:small object<span style="font-size:small <span style="font-size:small
sender, <span style="color:#2b91af; font-size:small <span style="color:#2b91af; font-size:small <span style="color:#2b91af; font-size:small EventArgs<span style="font-size:small <span style="font-size:small e)<span style="font-size:small <span style="font-size:small <span style="font-size:small <span style="font-size:small


View the full article
 
Back
Top