Hi,
I need to communicate through RS232 and RS485. I need to send data from RS485 and recieve same data from RS232. IC will do transmit data from RS485 to RS232. For this I wrote some sample code but I am not able to get recieved data in to textbox.I created RS232 and RS485 serial ports from components section of toolbox.
Settings for Ports: Baudrate: 57600 DataBits:8 Parity: Even
Any advice on this?
My code:
I need to communicate through RS232 and RS485. I need to send data from RS485 and recieve same data from RS232. IC will do transmit data from RS485 to RS232. For this I wrote some sample code but I am not able to get recieved data in to textbox.I created RS232 and RS485 serial ports from components section of toolbox.
Settings for Ports: Baudrate: 57600 DataBits:8 Parity: Even
Any advice on this?
My code:
public partial class Form1 : Form
{
private delegate void SetTextDeleg(string text);
string strData;
string RXString;
string data;
public Form1()
{
InitializeComponent();
Transmit.Text = "";
Recieve.Text = "";
}
private void Form1_Load(object sender, EventArgs e)
{
RS485.DataReceived += new SerialDataReceivedEventHandler(RS485_DataReceived);
}
private void RS485_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
Thread.Sleep(500);
data = RS485.ReadLine();
this.Invoke(new EventHandler(DisplayText));
}
catch (System.TimeoutException ex)
{
MessageBox.Show(ex.ToString());
}
}
private void DisplayText(object sender, EventArgs e)
{
Recieve.Enabled = true;
//Recieve.Text = data;
Recieve.AppendText(data);
}
private void btnStart_Click(object sender, EventArgs e)
{
if (Transmit.Text != "")
{
ModbusTest();
}
else
{
MessageBox.Show("Enter data to be transmitted");
}
}
public void ModbusTest()
{
try
{
if (!RS232.IsOpen && !RS485.IsOpen)
{
RS232.Open();
RS485.Open();
RS485.DataReceived += new SerialDataReceivedEventHandler(RS485_DataReceived);
}
else
{
MessageBox.Show("Unable to open the operts");
}
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
try
{
if (RS232.IsOpen && RS485.IsOpen)
{
strData = Transmit.Text;
RS232.WriteLine(strData);
RS485.DataReceived += new SerialDataReceivedEventHandler(RS485_DataReceived);
RXString = RS485.ReadExisting();
Transmit.Enabled = false;
//txtRecieve.Text = data;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form_Closing(object sender, FormClosingEventArgs e)
{
RS232.Close();
RS485.Close();
}
}