I have a project where I need to communicate with Arduino over the serial ports. The problem I face is that I cannot print continously the data I receive from the serial monitor on multiple lines on a richtextbox. When I press the button "Reveice" I do receive only one value and after this, pressing again the Receive button will overwrite the line.
I'm tring to fix this for few days, but it's my first time programming in c# so I'm asking for your help.
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 aplicatie_comanda_v1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getAvilablePorts();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
progressBar1.Value = 0;
button3.Enabled = true;
button1.Enabled = false;
receive.Enabled = false;
richTextBox1.Clear();
}
private void label1_Click(object sender, EventArgs e)
{
}
void getAvilablePorts()
{
string[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "" && serialPort1 != null && serialPort1.IsOpen)
{
richTextBox1.Text = "Select COM port and BAUD rate !";
serialPort1.Close();
}
else
{
string cmd = Convert.ToString(comboBox1.Text);
int baud = Convert.ToInt32(comboBox2.Text);
serialPort1.PortName = cmd;
serialPort1.BaudRate = baud;
serialPort1.DtrEnable = true;
serialPort1.RtsEnable = true;
serialPort1.Open();
progressBar1.Value = 100;
button1.Enabled = true;
button2.Enabled = true;
textBox1.Enabled = true;
button3.Enabled = false;
}
}
catch (UnauthorizedAccessException)
{
richTextBox1.Text = "Unauthorized !";
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
serialPort1.Write(text);
}
private void receive_Click(object sender, EventArgs e)
{
try
{
richTextBox1.Text = serialPort1.ReadLine() + "\n";
}
catch (TimeoutException)
{
richTextBox1.Text = "Timeout !";
}
}
private void button4_Click(object sender, EventArgs e)
{
serialPort1.Write("w");
}
private void button5_Click(object sender, EventArgs e)
{
serialPort1.Write("s");
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
}
private void button6_Click(object sender, EventArgs e)
{
serialPort1.Write("a");
}
private void button7_Click(object sender, EventArgs e)
{
serialPort1.Write("d");
}
private void button12_Click(object sender, EventArgs e)
{
serialPort1.Write("b");
}
private void button13_Click(object sender, EventArgs e)
{
string cmd = Convert.ToString(trackBar1.Value);
serialPort1.Write(cmd);
}
private void button8_Click(object sender, EventArgs e)
{
serialPort1.Write("q");
}
private void button11_Click(object sender, EventArgs e)
{
serialPort1.Write("e");
}
private void button9_Click(object sender, EventArgs e)
{
serialPort1.Write("z");
}
private void button10_Click(object sender, EventArgs e)
{
serialPort1.Write("c");
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
while (serialPort1.IsOpen)
{
try
{
string date = serialPort1.ReadLine();
richTextBox1.Text = date + "\n";
}
catch (TimeoutException)
{
richTextBox1.Text = "Timeout !";
}
}
}
}
}
Print screen of the final app: http://i.imgur.com/5f8EOly.png
Thank you !
I haven't written any Serial applications in C# yet, but already did a few projects involving Java <-> Arduino communication.
My first guess would be that you overwrite the existing line with the received line.
richTextBox1.Text = serialPort1.ReadLine() + "\n";
instead you would want:
richTextBox1.Text += serialPort1.ReadLine() + "\n";
Also you should take a look at this article on MSDN:
https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived(v=vs.110).aspx
This shows how you could use Events to continuously receive text from the Arduino.
Related
I am extremely new to C# and any help would be appreciated. I am trying to create a simple multiple option menu with User Controls and I have got it in a semi functional state. I am trying to get the user controls to show in a certain location because as of now they are only showing from the top left down and that is not where I would like them. Any help would be appreciated. My Form1 code is below:
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 Menu_V2
{
public partial class Form1 : Form
{
StartScreen u1;
Softaim u2;
Triggerbot u3;
Macro u4;
Misc u5;
public static bool flag = true;
public Form1()
{
u1 = new StartScreen();
u2 = new Softaim();
u3 = new Triggerbot();
u4 = new Macro();
u5 = new Misc();
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void toolStripContainer1_ContentPanel_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void label4_Click(object sender, EventArgs e)
{
u1.Hide();
u2.Hide();
u3.Hide();
u4.Hide();
u5.Show();
u5.Dock = DockStyle.Fill;
this.Controls.Add(u5);
}
private void insert(object sender, KeyEventArgs e)
{
}
private void bunifuThinButton21_Click(object sender, EventArgs e)
{
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F8)
{
}
}
private void button1_Click(object sender, EventArgs e)
{
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert)
{
this.Hide();
}
}
private void bunifuThinButton21_KeyUp(object sender, KeyEventArgs e)
{
}
private void bunifuThinButton22_Click(object sender, EventArgs e)
{
}
private void bunifuThinButton22_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F8)
{
this.Show();
}
}
private void misc1_Load(object sender, EventArgs e)
{
}
private void label6_Click(object sender, EventArgs e)
{
u1.Hide();
u2.Hide();
u3.Hide();
u4.Show();
u5.Hide();
u4.Dock = DockStyle.Fill;
this.Controls.Add(u4);
}
private void button1_Click_1(object sender, EventArgs e)
{
}
private void startScreen1_Load(object sender, EventArgs e)
{
}
private void label2_Click_1(object sender, EventArgs e)
{
u1.Hide();
u2.Show();
u3.Hide();
u4.Hide();
u5.Hide();
u2.Dock = DockStyle.Fill;
this.Controls.Add(u2);
}
private void label3_Click(object sender, EventArgs e)
{
u1.Hide();
u2.Hide();
u3.Show();
u4.Hide();
u5.Hide();
u3.Dock = DockStyle.Fill;
this.Controls.Add(u3);
}
}
}```
I don't know exactly where the code should be put and what code should look like. I need help, because I am very new to c#
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
this.timer1.Start();
}
private void Timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Increment(1);
}
private void Form1_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void ProgressBar1_Click(object sender, EventArgs e)
{
}
}
}
When I try the method from old videos, there is no such a thing as it and it shows that progressBar1 doesn't exist.
private void Timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Increment(1);
If (progressBar1.Value >= progressBar1.Maximum)
{
// do something
}
}
Just compare the progressBar1.Value
// progressBar1.Value = 0;
// progressBar1.Minimum = 0;
// progressBar1.Maximum = 100;
private void Timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Increment(1);
if(progressBar1.Value == progressBar1.Maximum){
Process.Start("c:\\file.bat");
}
}
can someone help me on my problem I'm making an ordering system for our thesis and I don't know what to do next if 3 button is clicked
Things I want to happen:
user need to pick an item first then he/she will pick a quantity for the item(I have 10 buttons for quantity: 1,2,3,4,5,6,7,8,9,0)
so I add a button0 so the user need to pick item and then click button1 then button0 to have a quantity of 10 that will display in my listview
1-9 button is working now but my problem is what if the user wants the item for a quantity of 10 or more
so here I have my code for an item button1
private void button1_Click(object sender, EventArgs e)
{
ms = 1;
}
and the quantity button
private void button1_Click(object sender, EventArgs e)
{
if(ms == 1)
{
ListViewItem item = new ListViewItem(btnms1.Text);
item.SubItems.Add("1");
item.SubItems.Add("118");
listView1.Items.Add(item);
ms = 0;
}
}
private void button2_Click(object sender, EventArgs e)
{
//working
}
private void button3_Click(object sender, EventArgs e)
{
//working
}
private void button4_Click(object sender, EventArgs e)
{
//working
}
private void button5_Click(object sender, EventArgs e)
{
//working
}
private void button6_Click(object sender, EventArgs e)
{
//working
}
private void button7_Click(object sender, EventArgs e)
{
//working
}
private void button8_Click(object sender, EventArgs e)
{
//working
}
private void button9_Click(object sender, EventArgs e)
{
//working
}
here is the 0 button
private void button0_Click(object sender, EventArgs e)
{
// magic please
}
I'm not really sure what you want to achieve but it might be something like this.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text += "1";
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text += "2";
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text += "3";
}
private void button4_Click(object sender, EventArgs e)
{
textBox1.Text += "4";
}
private void button5_Click(object sender, EventArgs e)
{
textBox1.Text += "5";
}
private void button6_Click(object sender, EventArgs e)
{
textBox1.Text += "6";
}
private void button7_Click(object sender, EventArgs e)
{
textBox1.Text += "7";
}
private void button8_Click(object sender, EventArgs e)
{
textBox1.Text += "8";
}
private void button9_Click(object sender, EventArgs e)
{
textBox1.Text += "9";
}
private void button10_Click(object sender, EventArgs e)
{
textBox1.Text += "0";
}
private void button11_Click(object sender, EventArgs e)
{
int quantity = 0;
bool quantityParse = int.TryParse(textBox1.Text, out quantity);
string productName = "Product Name"; // Sample Name
double productPrice = 300; // Sample Price
if (quantityParse)
{
ListViewItem lvi = new ListViewItem(productName); // Name
lvi.SubItems.Add(quantity.ToString()); // Quantity
lvi.SubItems.Add(productPrice.ToString()); // Price
lvi.SubItems.Add((productPrice * quantity).ToString()); // Subtotal
listView1.Items.Add(lvi);
}
}
}
Firstly, please start picking more meaningful names for variables as they help with code comprehension, especially when your code gets too complex for you or when you are sharing with others.
Secondly, how you're doing this at the moment is not the most intuitive way to go about things, always aim for the least amount of code as possible.
What I would be doing is calling the same event handler for each of the quantity buttons, but parsing the text in the buttons as a integer and adding that to a total string.
Ie:
private string QuantityText = string.Empty;
private void QtyButton_Click(object sender, EventArgs e)
{
if (sender is Button)
{
Button theButton = (Button)sender;
string qtyText = theButton.Content.ToString();
QuantityText += qtyText;
}
}
Then call something like this method when you want to process the quantity string:
Private Void ProcessQuantity()
{
int qtyAmount = -1;
int.TryParse(QuantityText, out qtyAmount)
if (qtyAmount > -1)
{
//Do Processing here
}
else
{
throw new InvalidArgumentException("Quantity is invalid");
}
}
i Need to open a second serialPort in my Visual C# program to read data from my arduino.
it already worked fine, but in the case you see below it does not work..
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 CommandsPD4I;
namespace CSharpExample
{
public partial class CSharpExample : Form
{
public ComMotorCommands motor1;
public CSharpExample()
{
InitializeComponent();
motor1 = new ComMotorCommands();
motor1.SetSteps(Convert.ToInt32(numericSchritte.Value));
}
SerialPort arduino;
delegate void InvokeLB(string Data);
InvokeLB lbRecievedDelegate;
int xPos = 0;
private void StartBtn_Click(object sender, EventArgs e)
{
// Set comm settings for motor 1
motor1.SelectedPort = ComPortBox1.Text;
motor1.Baudrate = Convert.ToInt32(BaudrateBox1.Text);
// Set motor address
motor1.MotorAddresse = Convert.ToInt32(Motor1ID.Value);
// Set relative positioning mode
motor1.SetPositionType(1);
// Start travel profile
if (motor1.ErrorFlag)
{
StatusLabel1.Text = "Status 1: " + motor1.ErrorMessageString;
}
else
{
StatusLabel1.Text = "Status 1: OK";
}
}
private void StopBtn_Click(object sender, EventArgs e)
{
// Stop travel profile
motor1.StopTravelProfile();
}
private void timer1_Tick(object sender, EventArgs e)
{
lblPosition.Text = Convert.ToString(motor1.GetPosition());
lblStatus.Text = motor1.ErrorMessageString;
// this.chart1.Series["Kraft"].Points.AddXY(xPos, Convert.ToDouble(lblKraft.Text));
// xPos++;**strong text**
}
private void btnHoch_Click(object sender, EventArgs e)
{
motor1.SetDirection(0);
motor1.SetPositionType(1);
motor1.StartTravelProfile();
}
private void btnRunter_Click(object sender, EventArgs e)
{
motor1.SetDirection(1);
motor1.SetPositionType(1);
motor1.StartTravelProfile();
}
private void numericSchritte_ValueChanged(object sender, EventArgs e)
{
motor1.SetSteps(Convert.ToInt32(numericSchritte.Value));
}
private void numericGeschwindigkeit_ValueChanged(object sender, EventArgs e)
{
motor1.SetMaxFrequency(Convert.ToInt32(numericGeschwindigkeit.Value));
}
private void btnDiagramm_Click(object sender, EventArgs e)
{
if (timer1.Enabled)
{
timer1.Stop();
}
else
{
timer1.Start();
}
}
private void btnResetDiagramm_Click(object sender, EventArgs e)
{
this.chart1.Series["Kraft"].Points.Clear();
xPos = 0;
}
private void arduino_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string RecievedLine = " ";
while (RecievedLine != "")
{
RecievedLine = arduino.ReadLine();
lblKraft.Invoke(lbRecievedDelegate, new object[] { RecievedLine });
}
}
void Invokelabel1(string Data)
{
label1.Text = Data;
this.chart1.Series["Kraft"].Points.AddXY(xPos, Convert.ToDouble(lblKraft.Text));
xPos++;
}
private void btnArduino_Click(object sender, EventArgs e)
{
//Hier erstellen wir unseren Serialport und legen die Einstellungen fest
arduino = new SerialPort("COM7", 9600);
if (!arduino.IsOpen)
{
arduino.Open();
if (arduino.IsOpen)
{
lblArduino.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(200)))), ((int)(((byte)(0)))));
lblArduino.Text = "Verbunden mit " + arduino.PortName;
}
}
lbRecievedDelegate = new InvokeLB(Invokelabel1);
arduino.DataReceived += new SerialDataReceivedEventHandler(arduino_DataReceived); //DataRecieved Event abonnieren
}
}
}
When i leave out this:
motor1.SelectedPort = ComPortBox1.Text;
motor1.Baudrate = Convert.ToInt32(BaudrateBox1.Text);
then it works..
I hope you can help :)
I have an app that has 3 text boxes, (users name, what company they are from, and who they are visiting) A button to print, and a keyboard on the screen (monitor is touch screen). I have everything working and functioning...
BUT, the one thing that does not work is when the user points to previous character in the text box that has already been typed, the buttons that "AppendText" (keyboard) do not start typing where the user pointed but it continues typing at the end of what has been typed.
Is this because of "AppendText" or some other issue that I have in my code?
I also am trying to get the first text box (Name_Box) to be sent to form one, which then will be split into two labels (1, first name| 2, last name) right now I have it being sent to one label But I want to split it so the first name is stacked above the second name in the next form (which is printed out).
Thank you so much.
Here is my code: First Form
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
namespace SMART
{
public partial class Form1 : Form
{
private TextBox tbSelected; // Last focused TextBox
private int posCaret; // Caret position
private int selLength; // Selection length
public Form1()
{
InitializeComponent();
// We will use leave event for textboxes
Name_Box.Leave += new System.EventHandler(textBox_Leave);
Company_Box.Leave += new System.EventHandler(textBox_Leave);
Visiting_Box.Leave += new System.EventHandler(textBox_Leave);
// Set initial selection to the first textbox
Name_Box.Select();
tbSelected = Name_Box;
posCaret = 0;
selLength = 0;
}
// Leave event handler
private void textBox_Leave(object sender, EventArgs e)
{
// Remember the last focused thextbox,
// the caret position in it and the selection length
tbSelected = (TextBox)sender;
posCaret = tbSelected.SelectionStart;
selLength = tbSelected.SelectionLength;
}
// Helper method to restore selection
private void RestoreLastSelection()
{
tbSelected.Select();
posCaret = tbSelected.SelectionStart;
selLength = tbSelected.SelectionLength;
}
private void Form1_Load(object sender, EventArgs e)
{
label5.Text = DateTime.Now.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
label5.Text = DateTime.Now.ToString();
Form2 frm = new Form2(Name_Box.Text);
frm.Show();
frm.Close();
StreamWriter sw;
sw = File.AppendText ("C:\\SignIn.txt");
sw.WriteLine ("Date and Time: " + label5.Text + " | Name: " + Name_Box.Text + " | Company: " + Company_Box.Text + " | Visiting: " + Visiting_Box.Text + " |");
sw.Close ();
Name_Box.Clear();
Company_Box.Clear();
Visiting_Box.Clear();
}
private void button42_Click(object sender, EventArgs e)
{
//SPACE BAR
tbSelected.AppendText(" ");
}
private void button24_Click(object sender, EventArgs e)
{
//DELETE
string t = tbSelected.Text;
if (t.Length > 0)
{
tbSelected.Text = t.Remove(t.Length - 1);
}
}
private void button12_Click(object sender, EventArgs e)
{
tbSelected.AppendText("-");
}
private void button13_Click(object sender, EventArgs e)
{
tbSelected.AppendText("Q");
}
private void button14_Click(object sender, EventArgs e)
{
tbSelected.AppendText("W");
}
private void button15_Click(object sender, EventArgs e)
{
tbSelected.AppendText("E");
}
private void button16_Click(object sender, EventArgs e)
{
tbSelected.AppendText("R");
}
private void button17_Click(object sender, EventArgs e)
{
tbSelected.AppendText("T");
}
private void button18_Click(object sender, EventArgs e)
{
tbSelected.AppendText("Y");
}
private void button19_Click(object sender, EventArgs e)
{
tbSelected.AppendText("U");
}
private void button20_Click(object sender, EventArgs e)
{
tbSelected.AppendText("I");
}
private void button21_Click(object sender, EventArgs e)
{
tbSelected.AppendText("O");
}
private void button22_Click(object sender, EventArgs e)
{
tbSelected.AppendText("P");
}
private void button25_Click(object sender, EventArgs e)
{
tbSelected.AppendText("A");
}
private void button26_Click(object sender, EventArgs e)
{
tbSelected.AppendText("S");
}
private void button27_Click(object sender, EventArgs e)
{
tbSelected.AppendText("D");
}
private void button28_Click(object sender, EventArgs e)
{
tbSelected.AppendText("F");
}
private void button29_Click(object sender, EventArgs e)
{
tbSelected.AppendText("G");
}
private void button30_Click(object sender, EventArgs e)
{
tbSelected.AppendText("H");
}
private void button31_Click(object sender, EventArgs e)
{
tbSelected.AppendText("J");
}
private void button32_Click(object sender, EventArgs e)
{
tbSelected.AppendText("K");
}
private void button33_Click(object sender, EventArgs e)
{
tbSelected.AppendText("L");
}
private void button35_Click(object sender, EventArgs e)
{
tbSelected.AppendText("Z");
}
private void button36_Click(object sender, EventArgs e)
{
tbSelected.AppendText("X");
}
private void button37_Click(object sender, EventArgs e)
{
tbSelected.AppendText("C");
}
private void button38_Click(object sender, EventArgs e)
{
tbSelected.AppendText("V");
}
private void button39_Click(object sender, EventArgs e)
{
tbSelected.AppendText("B");
}
private void button40_Click(object sender, EventArgs e)
{
tbSelected.AppendText("N");
}
private void button41_Click(object sender, EventArgs e)
{
tbSelected.AppendText("M");
}
private void button2_Click_1(object sender, EventArgs e)
{
tbSelected.AppendText("'");
}
private void button3_Click(object sender, EventArgs e)
{
tbSelected.Clear();
}
}
}
Heres is my code: Second Form
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.Drawing.Printing;
namespace SMART
{
public partial class Form2 : Form
{
public Form2(string strTextBox)
{
InitializeComponent();
label3.Text = strTextBox;
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToString();
PrintDocument pd = new PrintDocument();
Margins margins = new Margins(0, 0, 0, 0);
pd.DefaultPageSettings.Margins = margins;
pd.PrintPage += new PrintPageEventHandler(PrintImage);
pd.Print();
/*
//My sad attempt at splitting the Name
var fullname = strTextBox;
var names = fullname.Split (" ");
label3.Text = names[0];
label5.Text = names[1];
*/
}
void PrintImage(object o, PrintPageEventArgs e)
{
int x = SystemInformation.WorkingArea.X;
int y = SystemInformation.WorkingArea.Y;
int width = this.Width;
int height = this.Height;
Rectangle bounds = new Rectangle(x, y, width, height);
Bitmap img = new Bitmap(width, height);
this.DrawToBitmap(img, bounds);
Point p = new Point(0, 0);
e.Graphics.DrawImage(img, p);
}
}
}
You're right in that your problem is the use of AppendText, which always appends to the end (that's what append means).
You need to Insert the character at the current carat position.
You might do better to post a message that simulates a keypress from a physical keyboard.
If you want to insert text at the user's current position, you can use SelectedText. This will replace the current selection (if the user has selected characters):
tbSelected.SelectedText = "V";
Edit: The problem is in here:
private void button24_Click(object sender, EventArgs e)
{
//DELETE
string t = tbSelected.Text;
if (t.Length > 0)
{
tbSelected.Text = t.Remove(t.Length - 1);
}
}
You set the text, which returns the cursor to the beginning of the textbox. You should set tbSelected.SelectionStart after you clear the text.