System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' C# - c#

I am currently working on a project where I connect an arduino uno to a windows form and display the temperature in it using serial communication.
However I got this weird error every time I compiled my app
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.
I have declared my string array correctly. Can anyone help me to overcome this issue?
using System;
using System.Windows.Forms;
using System.Threading.Tasks;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
serialPort1.Open();
}
public String[] towTemp = new string[1];
public Task Tempdisplay()
{
//timer1.Start();
return Task.Factory.StartNew(() =>
{
try
{
String tempFromArduino = serialPort1.ReadLine().ToString();
towTemp = tempFromArduino.Split(',');
CheckForIllegalCrossThreadCalls = false;
if (float.TryParse(towTemp[0], out float result1))
{
result1 = (float)(Math.Round(Convert.ToDecimal(result1), 1));
label2.Text = result1.ToString();
aGauge1.Value = result1;
}
else
{
return;
}
if (float.TryParse(towTemp[1], out float result2))
{
result2 = (float)(Math.Round(Convert.ToDecimal(result2), 1));
label3.Text = result2.ToString();
aGauge2.Value = result2;
}
else
{
return;
}
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
});
}
private async void timer1_Tick(object sender, EventArgs e)
{
timer1.Interval = 1000;
await Tempdisplay();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
timer1.Stop();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
}
}
}

With that line towTemp = tempFromArduino.Split(','); you overwrite the array that means it can have the length 0 now.
Check its length before you access it.

Related

Communication between 2 Form in C#(Keep connecting from Fom1 for Form2) [duplicate]

This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I am a newbie in C# and I have questions as below:
I have a Form1 name is setting Port Name, Baud Rate, Parity... of modbus protocol and I can open serial Port.
Also, I have another Form is called Form2, When Port is opened i want to close Form1 and Port alway Open => I can do it. But this problem that was I want to get data such as FC03 HolodingRegister, FC01 WriteSingleCoil... for Form2 but didnot.
I used delegate to transfer data from Form 1 to Form 2 but I could not use button Form2 to send FC01 signal.
How to use FC01, FC03,04... for Form2 when Form 1 connected.
Code Form1:
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;
using Modbus.Device;
namespace ATS
{
public partial class frCommunication : Form
{
SerialPort serialPort = new SerialPort();
ModbusMaster Master;
public delegate void truyendulieu(string text);
public truyendulieu truyendata;
public delegate void truyendulieu1(string text1);
public truyendulieu1 truyendata1;
public delegate void truyendulieu2(string text2);
public truyendulieu2 truyendata2;
public frCommunication()
{
InitializeComponent();
}
private void frCommunication_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
cboxPort.Items.AddRange(ports);
cboxPort.SelectedIndex = 0;
}
private void btnConnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
try
{
serialPort.PortName = cboxPort.Text;
serialPort.BaudRate = Convert.ToInt32(cboxBaudRate.Text);
serialPort.DataBits = Convert.ToInt32(cboxDataBits.Text);
serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboxStopBits.Text);
serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboxParity.Text);
serialPort.Open();
Master = ModbusSerialMaster.CreateRtu(serialPort);
Master.Transport.Retries = 0; // don't have to to retries
Master.Transport.ReadTimeout = 300;//miliseconds
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (serialPort.IsOpen)
{
lblDisplay.Text = "Connected";
lblDisplay.ForeColor = System.Drawing.Color.Red;
cboxBaudRate.Enabled = false;
}
else
{
lblDisplay.Text = "Disconnected";
MessageBox.Show("Error!");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
try
{
serialPort.Close();
lblDisplay.Text = "Disconnected";
lblDisplay.ForeColor = System.Drawing.Color.Green;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
ushort[] holding_register = Master.ReadHoldingRegisters(1, 0, 10);
txtV_Grid.Text = Convert.ToString(holding_register[0]);
txtC_Grid.Text = Convert.ToString(holding_register[1]);
txtP_Grid.Text = Convert.ToString(holding_register[2]);
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (txtV_Grid.Text.Length > 0 || txtC_Grid.Text.Length > 0 || txtP_Grid.Text.Length > 0)
{
if (truyendata != null || truyendata1 != null)
{
truyendata(txtV_Grid.Text);
truyendata1(txtC_Grid.Text);
truyendata2(txtP_Grid.Text);
}
this.Hide();
}
}
private void txtV_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata != null)
{
truyendata(txtV_Grid.Text);
}
}
private void txtC_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata1 != null)
{
truyendata1(txtC_Grid.Text);
}
}
private void txtP_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata2 != null)
{
truyendata2(txtP_Grid.Text);
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void btnOn_ACB_Grid_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
DialogResult dl = MessageBox.Show("Would you like to turn On ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dl == DialogResult.Yes)
{
Master.WriteSingleCoil(1, 0, true);
}
else
{
Master.WriteSingleCoil(1, 0, false);
}
}
}
private void btnOff_ACB_Grid_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
DialogResult dl = MessageBox.Show("Would you like to turn Off ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dl == DialogResult.Yes)
{
Master.WriteSingleCoil(1, 0, false);
}
else
{
Master.WriteSingleCoil(1, 0, true);
}
}
}
}
}
Code Form2:
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 SymbolFactoryDotNet;
namespace ATS
{
public partial class frMain : Form
{
public frMain()
{
InitializeComponent();
}
private void communicationToolStripMenuItem_Click(object sender, EventArgs e)
{
frCommunication frm = new frCommunication();
frm.ShowDialog();
}
private void standardControl1_Load(object sender, EventArgs e)
{
}
private void LoadData(string data)
{
txtV.Text = "";
txtV.Text = data;
}
private void LoadData1(string data1)
{
txtC.Text = "";
txtC.Text = data1;
}
private void LoadData2(string data2)
{
txtP.Text = "";
txtP.Text = data2;
}
private void btnConnect_Click(object sender, EventArgs e)
{
frCommunication frm = new frCommunication();
frm.truyendata = new frCommunication.truyendulieu(LoadData);
frm.truyendata1 = new frCommunication.truyendulieu1(LoadData1);
frm.truyendata2 = new frCommunication.truyendulieu2(LoadData2);
frm.ShowDialog();
}
private void txtV_TextChanged(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
if(picOn.Visible == false)
{
picOn.Visible = true;
picOff_Grid.Visible = false;
// standardControl3.DiscreteValue2 = true;
}
else
{
picOn.Visible = false;
picOff_Grid.Visible = true;
}
}
private void frMain_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("HH:mm:ss dd-MM-yyyy");
}
private void btnOn_Grid_Click(object sender, EventArgs e)
{
}
}
}
When I understand you right, you will in Form1 open a connection, close the Form, open a new Form2 and use this connection there?
Well, when that's the case, you could make an special Connection Singleton to hold this connection then you can use it in your Form2
using System;
namespace Sandbox
{
public sealed class Connection
{
private static readonly Lazy<Connection> _instance = new Lazy<Connection>(() => new Connection());
public static Connection Instance => _instance.Value;
private Connection()
{ }
// Implement your Connection Code here.
}
}

C# can't use variable from IF statement

I'm making easy password generator, but i cant pick int from try and string from if. Here's the code. I hope you help me. I cant make this I as textbox and i cant do nothing with it.
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
return;
}
catch
{
}
CreatePassword(i);
}
and here is part of CreatePassword function
public string CreatePassword(int length)
{
if (checkBox2.Checked)
{
const string src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
return src;
}
else
{
const string src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
return src;
}
}
There are several problems with your code. First, you're trying to access the variable i outside of the scope in which it is declared; it's not visible outside of the try statement. Second, it seems like you're expecting the password to be generated from the integer you parsed, but you're explicitly returning before the password can be created. Thirdly, you're not doing anything with the created password, just throwing it away.
Try the following:
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
string password = CreatePassword(i);
// TODO: use the 'password' string for something.
return;
}
catch
{
}
}
You should also consider using int.TryParse instead, which won't throw an exception.
if (int.TryParse(textbox2.Text, out int i) {
string password = CreatePassword(i);
// Do something with 'password'
} else {
// Display an error.
}
From your example, it looks like all your need is Int32.TryParse:
int.TryParse(textBox2.Text, out int i);
CreatePassword(i);
However, to answer your original question: you need to initialize i variable outside of the try block in order to be able to use it after it. For instance:
int i = 0;
try
{
i = int.Parse("test");
}
catch
{
}
Console.WriteLine(i); // 0
You logic is a bit flawed. If Textbox2 does not contain a valid integer, you ignore the exception and just create a password. What kind of password you expect to create?
I think you mean to do something like this:
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
CreatePassword(i);
}
catch
{
// Show a messagebox or something
}
}
Guys all thanks for help. I did it. Here you have my source of my application as thanks for you all. My app completely work and i believe you understand my logic :D
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Password_generator
{
public partial class Form1 : Form
{
private bool _dragging = false;
private Point _start_point = new Point(0, 0);
public Form1()
{
InitializeComponent();
}
public string CreatePassword(int length)
{
string src;
var sb = new StringBuilder();
Random RNG = new Random();
src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (checkBox2.Checked)
{
src += "1234567890";
}
if (checkBox3.Checked)
{
src += "##$%^&*()";
}
for (var i = 0; i < length; i++)
{
var c = src[RNG.Next(0, src.Length)];
sb.Append(c);
}
textBox1.Text = sb.ToString();
if (checkBox1.Checked)
{
try
{
File.AppendAllText("hesla.txt", textBox1.Text + Environment.NewLine);
}
catch(Exception o)
{
MessageBox.Show("Něco se nepovedlo! " + Environment.NewLine + "(" + o.Message + ")");
}
}
return textBox1.Text;
}
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
CreatePassword(i);
}
catch
{
MessageBox.Show("Musíš zadat číslo!");
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
_dragging = false;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (_dragging)
{
Point p = PointToScreen(e.Location);
Location = new Point(p.X - this._start_point.X, p.Y - this._start_point.Y);
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
_dragging = true;
_start_point = new Point(e.X, e.Y);
}
private void panel3_Paint(object sender, PaintEventArgs e)
{
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
try
{
Clipboard.SetText(textBox1.Text);
}
catch
{
}
}
}
}

Perform web searches through C # Windows forms

I'm trying to realize web searches to get the title of websites on a Google search.
I got a code that works well on other sites, but using Google I got duplicated results.
I have tried and tried, but I can't see where is the mistake.
Code simplified:
public partial class Form1 : Form
{
WebBrowser navegador = new WebBrowser();
private void Form1_Load(object sender, EventArgs e)
{
navegador.ScriptErrorsSuppressed = true;
navegador.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.datos);
}
private void datos(object sender, EventArgs e)
{
try
{
foreach (HtmlElement etiqueta in navegador.Document.All)
{
if (etiqueta.GetAttribute("classname").Contains("LC20lb DKV0Md"))
{
listBox1.Items.Add(etiqueta.InnerText);
}
}
}
catch (Exception exception) { }
}
private void function(object sender, EventArgs e)
{
/// string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate("https://google.com/search?q=water");
/// this.Text = query;
}
}
Result:
I don't know how google works but you can prevent duplicates like this
if(!listBox1.Items.Contains(etiqueta.InnerText))
listBox1.Items.Add(etiqueta.InnerText);
After a couple of days researching and improving the code I decided to change the list for a table.
In addition, now the searches are not duplicated and are positioned in the table as expected
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;
namespace SourceDownloader
{
public partial class Form1 : Form
{
strs valor = new strs();
public Form1()
{
InitializeComponent();
}
WebBrowser navegador = new WebBrowser();
private void Form1_Load(object sender, EventArgs e)
{
navegador.ScriptErrorsSuppressed = true;
navegador.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.datos);
}
private void datos(object sender, EventArgs e)
{
try
{
foreach (HtmlElement etq in navegador.Document.All)
{
if (etq.GetAttribute("classname").Contains("r")) /// LC20lb DKV0Md
{
foreach (HtmlElement a_et in etq.GetElementsByTagName("a"))
{
valor.link = a_et.GetAttribute("href");
}
foreach (HtmlElement t_et in etq.GetElementsByTagName("h3"))
{
valor.tit = t_et.InnerText;
}
bool exist = dataGridView1.Rows.Cast<DataGridViewRow>().Any(row => Convert.ToString(row.Cells["link"].Value) == valor.link);
var s1 = valor.link;
bool b = s1.Contains("google.com");
bool a = s1.Contains("googleusercontent");
if (!exist /* && !b && !a*/)
{
dataGridView1.Rows.Insert(0, valor.tit, valor.link);
}
}
if (etq.GetAttribute("classname").Contains("G0iuSb"))
{
valor.next = etq.GetAttribute("href");
}
}
more_ops.Enabled = true;
}
catch (Exception)
{
}
}
private void function(object sender, EventArgs e)
{
string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate(query);
this.Text = query;
}
private void more_ops_Click(object sender, EventArgs e)
{
string query = valor.next;
navegador.Navigate(query);
this.Text = query;
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
var msg = dataGridView1.CurrentCell.Value;
System.Diagnostics.Process.Start(msg.ToString());
}
catch (Exception)
{
MessageBox.Show("Error");
}
}
private void Enter(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
string texto = query_box.Text;
texto = texto.Replace("\n", "");
query_box.Text = texto;
string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate(query);
this.Text = query;
}
}
}
/// global values
class strs
{
private string _link = "N/A";
private string _tit = "N/A";
private string _next = "N/A";
public string tit
{
get
{
return _tit;
}
set
{
_tit = value;
}
}
public string link
{
get
{
return _link;
}
set
{
_link = value;
}
}
public string next
{
get
{
return _next;
}
set
{
_next = value;
}
}
}
}

I am using C# to design a calcuator and i get Complie Error CS0029

So for my homework I am asked to design a fully functioning calcuator that accepts both key presses and button clicks but for the numbers 0-9 button clicks events I get Compile Error Message: CS0029: Cannot implicitly convert type 'int' to 'string'
here is 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;
namespace Calculator
{
public partial class Form1 : Form
{
private String calculatedNumber; // Stores numbers in string form
private Boolean dot = false; // Falg: to control when a dot can be placed in a number
public Form1()
{
InitializeComponent();
}
private void BtnZero_Click(object sender, EventArgs e) //adds 0 to string
{
//calculatedNumber = Convert.ToString(0);
if (calculatedNumber = 0)
{
LblDisplay.Text=calculatedNumber;
}
else
{
}
}
private void BtnOne_Click(object sender, EventArgs e) //adds 1 to string
{
if (calculatedNumber = 1)
{
calculatedNumber = 1.ToString();
LblDisplay.Text = calculatedNumber;
}
else
{
}
}
private void BtnTwo_Click(object sender, EventArgs e) //adds 2 to string
{
if (calculatedNumber = 2)
{
LblDisplay.Text = calculatedNumber;
}
else
{
}
}
private void BtnThree_Click(object sender, EventArgs e) //adds 3 to string
{
if (calculatedNumber = 3)
{
LblDisplay.Text = calculatedNumber;
}
else
{
}
}
private void BtnFour_Click(object sender, EventArgs e) //adds 4 to string
{
if (calculatedNumber = 4)
{
LblDisplay.Text = calculatedNumber;
}
else
{
}
}
private void button5_Click(object sender, EventArgs e) //adds 5 to string
{
if (calculatedNumber = 5)
{
LblDisplay.Text = calculatedNumber;
}
else
{
}
}
private void BtnSix_Click(object sender, EventArgs e) //adds 6 to string
{
if (calculatedNumber = 6)
{
LblDisplay.Text = calculatedNumber;
}
else
{
}
}
private void BtnSeven_Click(object sender, EventArgs e) //adds 7 to string
{
if (calculatedNumber = 7)
{
LblDisplay.Text = calculatedNumber;
}
else
{
}
}
private void BtnEight_Click(object sender, EventArgs e) //adds 8 to string
{
if (calculatedNumber = 8)
{
LblDisplay.Text = calculatedNumber;
}
else
{
}
}
private void BtnNine_Click(object sender, EventArgs e) //adds 9 to string
{
calculatedNumber = 9.ToString();
if (calculatedNumber = 9)
{
LblDisplay.Text = calculatedNumber;
}
else
{
}
}
private void BtnDot_Click(object sender, EventArgs e) //adds . to string
{
if (!dot)
{
calculatedNumber += ".";
dot = true;
}
LblDisplay.Text = calculatedNumber;
}
what am I doing wrong?
PS: I am new to C#
You are getting the error message "Cannot implicitly convert type 'int' to 'string'" from all of your if statements. You should be passing in an expression which returns a bool. However you are trying to assign an int to calculatedNumber which is a string. But you are meaning to check equality which is == not =.
Change all of your if statements to:
if (calculatedNumber == "0") //or whatever number
However in your code calculatedNumber never seems to be set anywhere so will never be true.
Since you have action listeners for each button the whole if part is redundant. You can just have:
private void BtnOne_Click(object sender, EventArgs e) //adds 1 to string
{
LblDisplay.Text = "1";
}
However that still doesn't seem like the functionality you want as it replaces the number every time you click a new number, you probably want to append it like this:
private void BtnOne_Click(object sender, EventArgs e) //adds 1 to string
{
LblDisplay.Text = LblDisplay.Text + "1";
}

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