-
Read from rs232??
Please help me with this code:
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;
namespace Terminal
{
public partial class MainForm : Form
{
byte[] Receive_Buffer;
int a;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
serialPort1.Open();
serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived);
text1.Text = System.Text.ASCIIEncoding.ASCII.GetString(Receive_Buffer);
}
private void serialPort1_DataReceived (object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
a=serialPort1.Read(Receive_Buffer, 0, 1);
}
private void but_r_file_Click(object sender, EventArgs e)
{
}
private void but_s_file_Click(object sender, EventArgs e)
{
}
/// ////////////
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Write(text2.Text);
text1.Text = text1.Text + Environment.NewLine + text2.Text;
}
private void but_ers_Click(object sender, EventArgs e)
{
text1.Text = "";
}
}
}
///////////////////////////
-
Re: Read from rs232??
Use [CODE] tags :) It makes the code so much more readable. I notice that in your Form.Load event handler you're using Receive_Buffer without initializing it first. You probably want to initialize and read something into Receive_Buffer before you try to convert it to a string. Also, if you specify a newline character for the SerialPort.Newline property you can simply call the SerialPort.ReadLine() method and it will read a line of text from the port and return a string. No encoding conversion necessary on your part :D
-
Re: Read from rs232??
Do you have a code example? tutorial? thanks
-
Re: Read from rs232??
This is a reference to the SerialPort class on the MSDN:
http://msdn.microsoft.com/en-us/libr...erialport.aspx
And here is a tutorial for reading data using serial ports in C#:
http://www.codeproject.com/KB/cs/ser...unication.aspx
It's pretty simple really. You configure the port using the SerialPort constructor, open it, then handle the DataReceived event. In that event handler, you read the port using either Read() or ReadLine() and process the data.
You don't even have to handle the DataReceived event. You can simply poll the port to see if there is data to read and if there is, read it. But in a Windows forms app like yours, you will probably want to use the DataReceived event. Makes it a little easier :)