Serialport port fault when i work with embedded system - c#

I want to create communication with Com Ports.
I can write and read any data on my computer, but when I work with embedded system, my system doesn't read data.
My code:
if (!serialPort1.IsOpen)
{
serialPort1.PortName = cbComPort.SelectedItem.ToString();
serialPort1.BaudRate = 9600;
serialPort1.Open();
serialPort1.ReadTimeout = 5000;
//serialPort1.WriteTimeout = 1500;
serialPort1.WriteLine("USB>>READ<END");
string gelenveri;
bool durum = false;
while (!durum)
{
try
{
gelenveri = serialPort1.ReadLine();
lblGelen.Text = gelenveri;
serialPort1.Close();
durum = true;
lblKarakterDeneme.Text = hextobinary(karakter_temizle(gelenveri));
veriyerlestir(lblKarakterDeneme.Text);
}
catch (TimeoutException)
{
MessageBox.Show("Veri Alınamadı");
serialPort1.Close();
}
break;
}
}

i find answer for this my question,
i canceled serialPort1.ReadLine(); and i use SerialDataReceivedEventArgs

Related

How to send hex character to serial port with C# form app?

I want to send the hex over the COM port. I have prepared code manually, but its for string sending.
This is how application looks like currently :
I need to read data from textbox and then send in hex format to COM port.
Currently I am handling the button click with the following sending code, however currently it is sending hard coded values, but I need ones taken from text field.
private void btnSendData_Click(object sender, EventArgs e) {
if (serialPort1.IsOpen) {
dataOUT = tBoxDataOut.Text;
if (sendWith == "WriteLine") {
serialPort1.WriteLine(dataOUT);
} else if (sendWith == "Write") {
serialPort1.Write(dataOUT);
}
}
}
You can read about Standard Numeric Format Strings here. Read the section "The Hexadecimal ("X") Format Specifier".
private void btnSendData_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
//dataOUT = tBoxDataOut.Text;
int intVal = Int32.Parse(tBoxDataOut.Text);
dataOUT = intVal.ToString("X");
if (sendWith == "WriteLine")
{
serialPort1.WriteLine(dataOUT);
}
else if (sendWith == "Write")
{
serialPort1.Write(dataOUT);
}
}
}
I would like to include a simple, working example. I do not have a COM port, but the com0com virtual driver works fine for this demonstration; you can download it here. I also used Putty to display the ports' received data; you can download it here.
Here's my program:
public class HexConvert
{
SerialPort mySerialPort;
public HexConvert()
{
InitPort();
}
void InitPort()
{
mySerialPort = new SerialPort("COM1");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
}
public void SendMessage()
{
try
{
string s = "15"; // "F" In Hexadecimal
int x = Int32.Parse(s);
string s2 = x.ToString("X");
if(!mySerialPort.IsOpen)
mySerialPort.Open();
mySerialPort.WriteLine(s2);
mySerialPort.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Here's my com0com utility's Configuration (I added the COM1 and COM2 pair; no other actions taken in this emulator):
Here is my Putty Configuration (Note that I used COM1 in the program, and COM2 in Putty):
And, finally, here is the output that my demo app produces:

Serial port doesn't read all data

I am reading from a serial port Rs232. I am facing a very strange problem.
The total bytes from incoming information is 37 bytes. In my computer, each time which i have interrupt in my serial port, the information is exactly 37bytes.
example abcdefghijklmnopqrstuvwxyz1234567890! and so on till 3
but in another pc, my imformation is been seperated to 8 bytes
example abcdefgh, in next interrup ijklmnop , in next interrup qrstuvwx and so on
Here is my serial port code:
public static string Rs232Weight = "0";//Αυτό είναι για να παίρνει την τιμή η ζυγαριά
public static readonly object lockWeight = new object();
private static SerialPort mySerialPort;
private void button1_Click(object sender, EventArgs e)
{
try
{
mySerialPort = new SerialPort(textBox1.Text);
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.Open();
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
catch
{
}
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
SerialPort sp = (SerialPort)sender;
lock (lockWeight)
{
string tmp = sp.ReadExisting();
ExportFile(Convert.ToString(tmp) + "|" + Convert.ToString(tmp.Length));
}
}
catch //(Exception ex)
{
// Dialogs.SingleMessage(Convert.ToString(ex), "Προειδοποίηση");
}
}

access to the port 'com8' is denied. Where's the error in this code?

i'm trying to get data from a serial device, but program is running with this error "access to the port 'com8' is denied". please give a solution.
public void PorttInit(object sender, EventArgs e)
{
SerialPort mySerialPort = new SerialPort("COM8");
try
{
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.Open();
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
catch (Exception ex)
{
mySerialPort.Close();
}
finally
{
//mySerialPort.Close();
}
}
public String data;
public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
String dataInput = sp.ReadExisting();
data = dataInput;
}
If in the IDE your serial report output windows(Serial Monitor) is open, you will face with this error. So close that window and then upload your code

Serial Communication c# terminal, changing the stop bits ruins the comunication

so I wrote a terminal in c# and I need to communicate with a kl25z microprocessor.
the application needs to support the option to choose the number of stop bits, the baud rate and the parity method.
I managed to sort it out with the baud rate but when I try to change the stop bits something goes out of sync and I cant figure out what.
the problem is that the uart is getting jibrish kind of chars instead of what I intended it to get, it does work well when I use one stop bit so I assume I just missed something in my code
I'll add the part of the code that gives me hard time:
this is only the c# part, my terminal I'm pretty sure that the problem is here
and not in the kl25z code
public Form1() {
InitializeComponent(); //init all variables
getAvailablePorts(); //fill the ports combo box with all the ports
}
void getAvailablePorts() {
String[] ports = SerialPort.GetPortNames(); //get the names of all availoable ports
comboBox1.Items.AddRange(ports); //add all the ports names to the combo box
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {
try {
SerialPort sp = (SerialPort) sender;
if (serialPort1.IsOpen & sp.IsOpen) {
string indata = sp.ReadLine();
Invoke(new Action(() => textBox1.Text = indata));
if (indata.Equals("new settings been set") ||
indata.Equals("\0new settings been set") ||
indata.Equals("new settings been set??")) {
// baud rate
Invoke(new Action(() => baud = Convert.ToInt32(comboBox3.Text)));
Invoke(new Action(() => serialPort1.BaudRate = baud));
//end bits
Invoke(new Action(() => serialPort1.StopBits = end));
}
}
} catch (System.IO.IOException error) {
return;
} catch (System.InvalidOperationException error) {
return;
}
}
//here i open the port
private void button3_Click(object sender, EventArgs e) { //start port
try { // give the micro processor the info it needs about the settings
serialPort1.Handshake = Handshake.RequestToSendXOnXOff;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
serialPort1.PortName = comboBox1.Text; //port
serialPort1.BaudRate = baud; //baud rate current
// serialPort1.Parity= parity;//parity current
serialPort1.StopBits = end; //stopBits current
serialPort1.DataBits = bits; //current
//sort strings to send
String baudString = comboBox3.Text;
String StopString = comboBox6.Text;
String bitsString = comboBox2.Text;
String parityString = comboBox4.Text;
String startString = comboBox5.Text;
serialPort1.Open(); //open port
bitsString = "8";
//send properties to klz
serialPort1.Write("prop" + "$" + baudString + "$" + StopString + "$" + bitsString + "$" + parityString + "$" + startString + "$");
if (Convert.ToInt32(comboBox6.Text) == 1) {
end = StopBits.One;
} else {
end = StopBits.Two;
}
bits = Convert.ToInt32(comboBox2.Text);
} catch (UnauthorizedAccessException) {
textBox1.Text = "Unauthorized Access";
}
try {
progressBar1.Value = 100;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
button4.Enabled = true;
textBox2.Enabled = true;
} catch (UnauthorizedAccessException) {
textBox1.Text = "Unauthorized Access";
}
}

SerialPort.Write method hanging, timeout not fired in C#

I have to write a program that writes on a serial port but sometimes the call to the Write method hangs and the WriteTimeout is never fired so my program hangs indefinitely.
Here is the port creation code:
void DetectX1BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
String[] ports = SerialPort.GetPortNames();
int i = 0;
foreach (string PortName in ports)
{
try
{
Console.WriteLine("Trying to open:" + PortName);
SerialPort port = openSerial(PortName);
Console.WriteLine("Port is open:" + PortName);
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Write("$ST+IMEI=0000\r\n");
if (IMEIFoundEvent.WaitOne(250))
{
Console.WriteLine("IMEI Found:[" + imei + "]");
if (addresses.ContainsKey(imei))
{
((BackgroundWorker)sender).ReportProgress(0, new X1Model(imei, PortName, addresses[imei]));
}
else
Console.WriteLine("imei not in file: " + imei);
}
port.Close();
}
catch (Exception ex)
{
Console.WriteLine("Erreur port " + PortName + ex.Message);
}
finally
{
i++;
((BackgroundWorker)sender).ReportProgress(i * 100 / ports.Length);
}
}
}
private SerialPort openSerial(string PortName)
{
SerialPort port = new SerialPort(PortName);
port.BaudRate = 57600;
port.DataBits = 8;
port.StopBits = StopBits.One;
port.Parity = Parity.None;
port.ReceivedBytesThreshold = 1;
port.Handshake = Handshake.None;
port.DtrEnable = true;
port.RtsEnable = true;
port.WriteTimeout = 5000;
port.ReadTimeout = 5000;
if (!port.IsOpen)
port.Open();
return port;
}
Is there anything I'm missing ?
I don't know if it's relevant but I'm using Serial To USB Adapters.
Edit: I'm using Windows XP with .Net 4.0. The line doesnt't exceed 50 characters and ends by a EOL character.
I know it's an old question, which you've probably solved by now, but there's no accepted answer yet. I was having the same issue yesterday and seem to have fixed it -- were you setting the Write Timeout?
_serialPort.WriteTimeout = 500;
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.writetimeout.aspx
You also need to set the PortName. You can get the list of ports from GetPortNames. This will typically be like COM1 or COM2

Categories