Send data via USB using STX ETC LRC framing (SerialPort object) - c#

I am trying to write a simple Forms app to send data over a USB port to a listening terminal device. I have been told that I need to send the data using STX ETX LRC framing but I have no idea what that means. I am a software tester for our company and not familiar with data transmissions via usb. Is there anyone who can help me with this? This is my current forms code:
private void sendRequestButton_Click(object sender, EventArgs e)
{
try
{
_serialPort = new SerialPort
{
PortName = portsDropdown.Text,
BaudRate = 19200,//connectionTypeDropdown.Text.Equals(Usb) ? 115200 : 19200,
DataBits = 8,
Parity = Parity.None,
StopBits = StopBits.One,
};
_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
_serialPort.Open();
_serialPort.Write(requestTextbox.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, #"Caught Exception:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
_serialPort.Close();
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
var serialPort = (SerialPort)sender;
_response = serialPort.ReadExisting();
Debug.Print(_response);
}

Here's what I used for connecting through the serial port in C#. This is in WPF so you'll have to make some adjustments.
using System;
using System.IO.Ports;
using System.Windows;
using System.Windows.Input;
namespace SerialTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private SerialPort port = new SerialPort();
int intBaud = 0;
string strComport = "";
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
string[] ports = SerialPort.GetPortNames();
cbCom.ItemsSource = ports;
}
private void StartUp()
{
int intbaud;
if (int.TryParse(cbBaud.SelectionBoxItem.ToString(), out intbaud))
{
intBaud = intbaud;
strComport = cbCom.SelectedItem.ToString();
SerialStart();
}
else
{
MessageBox.Show("Enter a valid Baudrate");
}
}
private void SerialStart()
{
try
{
port.BaudRate = int.Parse(cbBaud.SelectionBoxItem.ToString());
port.DataBits = 8;
port.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "One");
port.Parity = (Parity)Enum.Parse(typeof(Parity), "None");
port.PortName = cbCom.SelectedItem.ToString();
port.DataReceived += new SerialDataReceivedEventHandler(SerialReceive);
port.Handshake = Handshake.None;
if (port.IsOpen) port.Close();
port.Open();
}
catch (Exception ex)
{
txtTerm.AppendText(ex.ToString());
}
}
public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
private void Log(LogMsgType msgtype, string msg)
{
try
{
txtTerm.Dispatcher.Invoke(new EventHandler(delegate
{
txtTerm.AppendText(msg);
}));
}
catch (Exception ex)
{
ex.ToString();
}
}
private void SerialReceive(object sender, SerialDataReceivedEventArgs e)
{
if (!port.IsOpen) return;
string data = port.ReadExisting();
this.Dispatcher.Invoke(() =>
{
txtTerm.AppendText(data);
txtTerm.ScrollToEnd();
});
}
private void txtInput_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return && port.IsOpen)
{
try
{
port.WriteLine(txtInput.Text + "\r\n");
}
catch (Exception ex)
{
this.Dispatcher.Invoke(() =>
{
txtTerm.AppendText(ex.ToString()); ;
});
}
this.Dispatcher.Invoke(() =>
{
txtTerm.AppendText(txtInput.Text + "\n");
txtInput.Text = "";
});
}
}
}
}
Edit
Looks like for STX and ETC you have to also convert the characters to bytes
https://www.codeproject.com/questions/1107562/sending-ascii-control-stx-and-etx-in-csharp

Related

Display a updating list of items on Windows Form using C#

I read a MAC addresses from serial monitor and then i need to put them in the list. My problem is that only the first incoming address (string) is stored in the list. I also need the same addresses (string) not to be stored in the list more than once. I use listbox to view the items in the list. Thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace SerialMonitor2
{
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data;
List<string> MacList = new List<string>();
public int cnt = 0;
public Form1()
{
InitializeComponent();
}
private void stop_btn_Click(object sender, EventArgs e)
{
try
{
myport.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message,"Error");
}
}
private void start_btn_Click(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 115200;
myport.PortName = port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_dataReceived;
try
{
myport.Open();
data_tb.Text = "";
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void myport_dataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data = myport.ReadLine();
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
if (in_data[0] == '&')
{
string[] arr = in_data.Split('#');
string MAC = arr[0];
string temperature = arr[3];
textBox1.Text = MAC;
textBox2.Text = temperature;
MacList.Add(MAC);
listBox1.DataSource = MacList;
}
data_tb.AppendText(in_data + "\n");
}
private void port_name_tb_TextChanged(object sender, EventArgs e)
{
}
}
}
/// Try this
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data;
List<string> MacList = new List<string>();
public int cnt = 0;
public Form1()
{
InitializeComponent();
}
private void stop_btn_Click(object sender, EventArgs e)
{
try
{
myport.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message,"Error");
}
}
private void start_btn_Click(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 115200;
myport.PortName = port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_dataReceived;
try
{
myport.Open();
data_tb.Text = "";
string[] arr = in_data.Split('#');
string MAC = arr[0];
if !MacList.Contains(MAC))
MacList.Add(MAC);
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void myport_dataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data = myport.ReadLine();
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
if (in_data[0] == '&')
{
string[] arr = in_data.Split('#');
string MAC = arr[0];
string temperature = arr[3];
textBox1.Text = MAC;
textBox2.Text = temperature;
// MacList.Add(MAC);
listBox1.DataSource = MacList;
}
data_tb.AppendText(in_data + "\n");
}
}

How to receive and send data from Serial Ports in Visual Studio(Using C#)

I am trying to set up a serial com interface that will send and receive data in the Windows Forms App with C#. I can confirm that I am sending and receiving data from the ports with the help of a virtual serial port driver app since it also shows the number of bytes sent and received. However, the text box doesn't display the received messages. There no reported errors.
-------The Code---------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace FormAppAuto
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
buttonDisconnect.Enabled = false;
buttonSend.Enabled = false;
foreach (var serialPort in SerialPort.GetPortNames())
{
comboBoxSerialPorts.Items.Add(serialPort);
}
comboBoxSerialPorts.SelectedIndex = 0;
}
private void buttonConnect_Click(object sender, EventArgs e)
{
serialPort1.PortName = comboBoxSerialPorts.Text;
serialPort1.BaudRate = 115200;
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
serialPort1.DataBits = 8;
try
{
serialPort1.Open();
}
catch (Exception ex)
{
MessageBox.Show($"Seri port bağlantısı yapılamadı\n Hata : {ex.Message}", "Problem", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (serialPort1.IsOpen)
{
buttonConnect.Enabled = false;
buttonDisconnect.Enabled = true;
buttonSend.Enabled = true;
}
}
private void buttonDisconnect_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonConnect.Enabled = true;
buttonDisconnect.Enabled = false;
buttonSend.Enabled = false;
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Write(textBoxMyMessage.Text);
textBoxMyMessage.Clear();
}
}
public delegate void dataShow(String s);
public void writeText(String s)
{
textBoxMessages.Text += s;
}
//private void serialPort1_DataReceived(object sender, SerialDataReceivedEventHandler e)
//{
// String dataIn = serialPort1.ReadExisting();
//textBoxMessages.Text += gelenVeri;
// textBoxMessages.Invoke(new dataShow(writeText), dataIn);
// }
private void DatareceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
String indata = sp.ReadExisting();
Console.WriteLine("Data Received");
Console.Write(indata);
textBoxMessages.Text += indata;
}
}
}

How to add textalign and timestamp to a chat

I'm learning to code and I'm currently making a server and a client with two-way communication. Is there a way to make the received message appear on the left side of the textbox and the sent message on the right side of the textbox just like in a real chat service. Is there also a way to add the timestamp, when the message was received and when it was sent?
I will attach all the code that I have written and images of the client and server windows.
Server
Client
Server code:
namespace Full_Chatt_Server
{
public partial class Form1 : Form
{
TcpListener listener;
TcpClient klient;
int port;
public Form1()
{
InitializeComponent();
}
private void btnStartServer_Click(object sender, EventArgs e)
{
btnTaEmot.Enabled = false;
port = int.Parse(tbxPort.Text);
try
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
StartAccepting();
}
public async void StartAccepting()
{
try
{
klient = await listener.AcceptTcpClientAsync();
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
StartReading(klient);
}
public async void StartReading(TcpClient k)
{
byte[] buffer = new byte[1024];
int n = 0;
try
{
n = await k.GetStream().ReadAsync(buffer, 0, 1024);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
tbxMessage.AppendText(Encoding.Unicode.GetString(buffer, 0, n) + "\r\n");
StartReading(k);
}
private void btnSend_Click(object sender, EventArgs e)
{
string chatt = tbxChatt.Text;
StartSending(chatt);
tbxChatt.Clear();
tbxMessage.AppendText(chatt + "\r\n");
}
public async void StartSending(string message)
{
if (klient.Connected)
{
byte[] OutStream = Encoding.Unicode.GetBytes(message);
try
{
await klient.GetStream().WriteAsync(OutStream, 0, OutStream.Length);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
}
}
}
Client code:
namespace Full_Chatt_Klient
{
public partial class Form1 : Form
{
TcpClient klient = new TcpClient();
int port;
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (!klient.Connected)
{
Connect();
}
}
public async void Connect()
{
IPAddress address = IPAddress.Parse(tbxIP.Text);
port = int.Parse(tbxPort.Text);
try
{
await klient.ConnectAsync(address, port);
StartReading(klient);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
btnSkicka.Enabled = true;
btnAnslut.Enabled = false;
}
private void btnSend_Click(object sender, EventArgs e)
{
string chatt = tbxChatt.Text;
StartSending(chatt);
tbxChatt.Clear();
tbxMessage.AppendText(chatt + "\r\n");
}
public async void StartSending(string message)
{
if (klient.Connected)
{
byte[] OutStream = Encoding.Unicode.GetBytes(message);
try
{
await klient.GetStream().WriteAsync(OutStream, 0, OutStream.Length);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
}
}
public async void StartReading(TcpClient k)
{
byte[] buffer = new byte[1024];
int n = 0;
try
{
n = await k.GetStream().ReadAsync(buffer, 0, 1024);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
tbxMessage.AppendText(Encoding.Unicode.GetString(buffer, 0, n) + "\r\n");
StartReading(k);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (klient != null)
{
klient.Close();
}
}
}
}

Open the same serial port multiple times

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.dll
Additional information: Access to the port 'COM3' is denied.
The error happens when i open the port for the second time (when i open the this form again)
using DI_120_Interface.Class;
using MetroFramework.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DI_120_Interface
{
public partial class frmAddInventoryTransItem3 : MetroForm
{
public frmAddInventoryTrans ReceivingAdd { set; get; }
public frmEditInventoryTrans ReceivingEdit { set; get; }
string inv_type2 = null, action2 = null, document2 = null;
static SerialPort _serialPort;
static INIFile settings = new INIFile("C:\\Lateco\\settings.ini");
private string weight;
public frmAddInventoryTransItem3(object parent, string action, string inv_type, string document)
{
if (inv_type == "Receiving in LAVI" && action == "add")
this.ReceivingAdd = (frmAddInventoryTrans)parent;
else if (inv_type == "Receiving in LAVI" && action == "edit")
this.ReceivingEdit = (frmEditInventoryTrans)parent;
InitializeComponent();
inv_type2 = inv_type;
action2 = action;
document2 = document;
}
private void frmAddInventoryTransItem3_Load(object sender, EventArgs e)
{
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtPLU;
string portname, baudrate, parity, databits, stopbits, handshake;
portname = settings.Read("SERIAL PORT PROPERTIES", "PORT_NAME");
baudrate = settings.Read("SERIAL PORT PROPERTIES", "BAUD_RATE");
parity = settings.Read("SERIAL PORT PROPERTIES", "PARITY");
databits = settings.Read("SERIAL PORT PROPERTIES", "DATA_BITS");
stopbits = settings.Read("SERIAL PORT PROPERTIES", "STOP_BITS");
handshake = settings.Read("SERIAL PORT PROPERTIES", "HANDSHAKE");
_serialPort = new SerialPort(); //error here
_serialPort.PortName = portname;
_serialPort.BaudRate = int.Parse(baudrate);
_serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), parity, true);
_serialPort.DataBits = int.Parse(databits);
_serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopbits, true);
_serialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
_serialPort.Open();
_serialPort.ReadTimeout = 200;
if (_serialPort.IsOpen)
{
weight = "";
txtWeight.Text = "000.000";
}
_serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
weight = _serialPort.ReadExisting();
weight = weight.Substring(0, 7);
try
{
if (this.InvokeRequired)
this.BeginInvoke(new EventHandler(DisplayText));
}
catch (ObjectDisposedException) { }
}
catch (TimeoutException) { }
}
private void txtPLU_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
this.ActiveControl = txtQty;
}
}
private void txtQty_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
this.ActiveControl = txtWeight;
}
}
private void txtWeight_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
this.ActiveControl = btnAddItem;
}
}
private void btnAddItem_Click(object sender, EventArgs e)
{
string plu_code = txtPLU.Text;
txtWarning.Text = "";
if (IsNumeric(txtQty.Text) && IsNumeric(txtWeight.Text))
{
if (Convert.ToDecimal(txtQty.Text) == 0 || Convert.ToDecimal(txtWeight.Text) == 0)
{
txtWarning.Text = "***Qty/Weight must not be equal to zero.***";
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtQty;
}
else
{
if (Functions.AddInventoryItemTempFromItemMasterUsingPLU(inv_type2, document2, plu_code, Convert.ToDecimal(txtQty.Text), Convert.ToDecimal(txtWeight.Text)))
{
txtPLU.Text = "";
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtPLU;
if (inv_type2 == "Receiving in LAVI" && action2 == "add")
this.ReceivingAdd.UpdateQtyWeightAmount();
else if (inv_type2 == "Receiving in LAVI" && action2 == "edit")
this.ReceivingEdit.UpdateQtyWeightAmount();
//this.Close();
}
else
{
txtWarning.Text = "***PLU not found.***";
txtPLU.Text = "";
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtPLU;
}
}
}
else
{
txtWarning.Text = "***Please enter numeric value/s only.***";
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtQty;
}
}
private bool IsNumeric(string s)
{
float output;
return float.TryParse(s, out output);
}
private void DisplayText(object sender, EventArgs e)
{
txtWeight.Text = weight;
}
class INIFile
{
private string filePath;
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
public INIFile(string filePath)
{
this.filePath = filePath;
}
public void Write(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, this.filePath);
}
public string Read(string section, string key)
{
StringBuilder SB = new StringBuilder(255);
int i = GetPrivateProfileString(section, key, "", SB, 255, this.filePath);
return SB.ToString();
}
public string FilePath
{
get { return this.filePath; }
set { this.filePath = value; }
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (_serialPort.IsOpen)
_serialPort.Close();
}
}
}
A possible solution to this problem could be to have the serial connection in a separate class and provide an event if you received data. Each window can then add an event handler for this event. In the following code, I tried to maintain only the parts necessary to the serial connection. I couldn't really try it on my machine, so there might be some minor problems. Also the event is very basic. It would be better to define a delegate that meets your specific needs:
public class SerialConnection
{
INIFile settings = new INIFile("C:\\Lateco\\settings.ini");
public SerialPort SerialPort { get; set; }
static SerialConnection connection= null;
public event EventHandler WeightReceived;
public static SerialConnection OpenConnection()
{
if(connection == null)
{
connection = new SerialConnection();
string portname, baudrate, parity, databits, stopbits, handshake;
portname = settings.Read("SERIAL PORT PROPERTIES", "PORT_NAME");
baudrate = settings.Read("SERIAL PORT PROPERTIES", "BAUD_RATE");
parity = settings.Read("SERIAL PORT PROPERTIES", "PARITY");
databits = settings.Read("SERIAL PORT PROPERTIES", "DATA_BITS");
stopbits = settings.Read("SERIAL PORT PROPERTIES", "STOP_BITS");
handshake = settings.Read("SERIAL PORT PROPERTIES", "HANDSHAKE");
connection.SerialPort = new SerialPort(); //error here
connection.SerialPort.PortName = portname;
connection.SerialPort.BaudRate = int.Parse(baudrate);
connection.SerialPort.Parity = (Parity)Enum.Parse(typeof(Parity), parity, true);
connection.SerialPort.DataBits = int.Parse(databits);
connection.SerialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopbits, true);
connection.SerialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
connection.SerialPort.Open();
connection.SerialPort.ReadTimeout = 200;
connection.SerialPort.DataReceived += new SerialDataReceivedEventHandler(connection.serialPort1_DataReceived);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
weight = SerialPort.ReadExisting();
weight = weight.Substring(0, 7);
WeightReceived?.Invoke(weight, new EventArgs());
}
catch (TimeoutException) { }
}
return connection;
}
public void CloseConnection()
{
if (SerialPort.IsOpen)
SerialPort.Close();
}
~SerialConnection()
{
if (SerialPort.IsOpen)
SerialPort.Close();
}
}
In the Form use it like this:
public partial class frmAddInventoryTransItem3 : MetroForm
{
public frmAddInventoryTrans ReceivingAdd { set; get; }
public frmEditInventoryTrans ReceivingEdit { set; get; }
string inv_type2 = null, action2 = null, document2 = null;
private string weight;
private SerialConnection sc = null;
private void frmAddInventoryTransItem3_Load(object sender, EventArgs e)
{
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtPLU;
sc = SerialConnection.OpenConnection();
sc.WeightReceived += new SerialDataReceivedEventHandler(WeightReceived);
}
private void WeightReceived(object weight, EventArgs e)
{
weight = weight as string;
try
{
if (this.InvokeRequired)
this.BeginInvoke(new EventHandler(DisplayText));
}
catch (ObjectDisposedException) { }
}
private void DisplayText(object sender, EventArgs e)
{
txtWeight.Text = weight;
}
}
}

Transmitting data with RS422 in .NET

I'm trying to make a simple application to test the RS422 communications with another computer. Using the RS232 interfaces this program is working smoothly, but with the RS422 is not working, as there is one computer that can't send. To complex the scenario a little bit more, I can communicate through RS422 using a HyperTerminal.
Here is the code:
public partial class MainForm : Form
{
private SerialPort m_port;
public MainForm()
{
InitializeComponent();
m_list.Items.AddRange(SerialPort.GetPortNames());
m_port = new SerialPort();
m_port.BaudRate = 9600;
m_port.DataBits = 8;
m_port.Parity = Parity.None;
m_port.StopBits = StopBits.One;
m_port.Handshake = Handshake.None;
m_port.Encoding = new ASCIIEncoding();
m_port.ReceivedBytesThreshold = 1;
m_port.DataReceived += DataReceivedEvent;
}
~MainForm()
{
if (m_port != null)
m_port.Close();
}
private void openClick(object sender, EventArgs e)
{
m_port.Close();
m_port.PortName = (string)m_list.SelectedItem;
try
{
m_port.Open();
m_buttonSend.Enabled = true;
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void ButtonSendClick(object sender, EventArgs e)
{
m_port.WriteLine(m_testBox.Text);
}
private void DataReceivedEvent(object sender, SerialDataReceivedEventArgs args)
{
Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
m_receivedText.Text += m_port.ReadLine();
}
}
Any help or experience with this technology is appreciated. Thanks!
EDIT
There is a lot of differences between the trace with Portmon of Hyperterminal and the .NET component. There is one of the lines that got my attention as it reefers to the wait mask of the port interruption IOCTL_SERIAL_SET_WAIT_MASK.
With HyperTerminal:
IOCTL_SERIAL_SET_WAIT_MASK Serial0 SUCCESS Mask: RLSD ERR
With the .NET SerialPort component
IOCTL_SERIAL_SET_WAIT_MASK Serial0 SUCCESS Mask: RXCHAR RXFLAG CTS DSR RLSD BRK ERR RING
Anybody knows how to change the mask from the component? This is getting deep...
Finally there was a problem in the initialitation and another one with the blocking ReadLine call. RTS and DTS must be enabled.
Here is the code
using System;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;
namespace ComPlay
{
public partial class MainForm : Form
{
private SerialPort m_port;
private byte [] m_buffer = new byte[10];
public MainForm()
{
InitializeComponent();
m_list.Items.AddRange(SerialPort.GetPortNames());
m_list.SelectedIndex = 0;
m_port = new SerialPort(SerialPort.GetPortNames()[0],9600,Parity.None,8,StopBits.One);
m_port.Handshake = Handshake.None;
m_port.RtsEnable = true;
m_port.DtrEnable = true;
m_port.DataReceived += DataReceivedEvent;
m_port.PinChanged += PinChangedEvent;
}
~MainForm()
{
if (m_port != null)
m_port.Close();
}
private void openClick(object sender, EventArgs e)
{
if (m_port.IsOpen)
m_port.Close();
m_port.PortName = (string)m_list.SelectedItem;
try
{
m_port.Open();
m_buttonSend.Enabled = true;
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void ButtonSendClick(object sender, EventArgs e)
{
byte [] r_bytes = Encoding.ASCII.GetBytes(m_testBox.Text);
m_port.Write(r_bytes,0,r_bytes.Length);
}
private void DataReceivedEvent(object sender, SerialDataReceivedEventArgs args)
{
Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
m_port.Read(m_buffer, 0, m_buffer.Length);
m_receivedText.Text += Encoding.ASCII.GetString(m_buffer);
}
private void PinChangedEvent(object sender, SerialPinChangedEventArgs args)
{
}
}
}
The important thing to begin transmitting was to change this
IOCTL_SERIAL_SET_HANDFLOW Serial1 SUCCESS Shake:80000000 Replace:80000040 XonLimit:1024 XoffLimit:1024
to this
IOCTL_SERIAL_SET_HANDFLOW Serial1 SUCCESS Shake:80000001 Replace:80000040 XonLimit:1024 XoffLimit:1024
activating RTS and DTR.

Categories