I have an Arduino connected to an interface I made. Everything is working fine, however the Arduino is sending a string to the interface. The program is reading the data, and storing it in a variable.
The problem I am having is that the variable stores the data, but doesn't update it when new data is coming in from the Arduino .
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 WindowsFormsApp3
{
public partial class Form1 : Form
{
public SerialPort myport;
int irisvalue;
string myString;
string s = "";
//String s2;
public Form1()
{
InitializeComponent();
//Load += new EventHandler(Form1_Load);
connectbtn.Text = "Connect";
disconnect.Text = "Disconnect";
this.connectbtn.Click += new EventHandler(connectbtn_Click);
this.disconnect.Click += new EventHandler(disconnect_Click);
this.iris1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.iris1_MouseDown);
this.iris1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.iris1_MouseUp);
this.iris2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.iris2_MouseDown);
this.iris2.MouseUp += new System.Windows.Forms.MouseEventHandler(this.iris2_MouseUp);
this.focus1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.focus1_MouseDown);
this.focus1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.focus1_MouseUp);
this.focus2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.focus2_MouseDown);
this.focus2.MouseUp += new System.Windows.Forms.MouseEventHandler(this.focus2_MouseUp);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void connect()
{
myport = new SerialPort();
myport.BaudRate = 9600;
myport.PortName = "COM3";
myport.Open();
}
void read()
{
s = myport.ReadLine();
//Form1_Load();
}
void discon()
{
myport.Close();
}
private void disconnect_Click(object sender, System.EventArgs e)
{
discon();
if (myport.IsOpen)
{
}
else
{
connectbtn.Text = "Connect";
disconnect.BackColor = default(Color);
connectbtn.BackColor = default(Color);
}
}
private void connectbtn_Click(object sender, System.EventArgs e)
{
connect();
if (myport.IsOpen)
{
connectbtn.Text = "Connected";
connectbtn.BackColor = Color.Green;
//Load += new EventHandler(Form1_Load);
Form1_Load();
disconnect.BackColor = Color.Red;
disconnect.Text = "Disconnect";
read();
//s = myport.ReadLine();
}
else
{
connectbtn.Text = "Error";
connectbtn.BackColor = Color.Red;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void iris1_MouseDown(object sender, MouseEventArgs e)
{
//Console.WriteLine("Hello");
irisvalue = 1;
myString = irisvalue.ToString();
Form1_Load();
}
private void iris1_MouseUp(object sender, MouseEventArgs e)
{
irisvalue = 0;
myString = irisvalue.ToString();
Form1_Load();
}
private void iris2_MouseDown(object sender, MouseEventArgs e)
{
irisvalue = 2;
myString = irisvalue.ToString();
Form1_Load();
}
private void iris2_MouseUp(object sender, MouseEventArgs e)
{
irisvalue = 0;
myString = irisvalue.ToString();
Form1_Load();
}
private void focus1_MouseDown(object sender, MouseEventArgs e)
{
irisvalue = 3;
myString = irisvalue.ToString();
Form1_Load();
}
private void focus1_MouseUp(object sender, MouseEventArgs e)
{
irisvalue = 0;
myString = irisvalue.ToString();
Form1_Load();
}
private void focus2_MouseDown(object sender, MouseEventArgs e)
{
irisvalue = 4;
myString = irisvalue.ToString();
Form1_Load();
}
private void focus2_MouseUp(object sender, MouseEventArgs e)
{
irisvalue = 0;
myString = irisvalue.ToString();
Form1_Load();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void Form1_Load()
{
textBox1.Text = s;
Console.WriteLine(s);
myport.WriteLine(myString);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
To receive updates you should subscribe on serial port events. Try this code:
myport.DataReceived += (sender, e) =>
{
if (e.EventType == SerialData.Chars)
s = myport.ReadLine();
};
Related
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");
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System;
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 WindowsFormsApplication21
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
button1.BackColor = Color.Red;
label1.Text = " OCCUPIED";
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
this.Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
string InputString = serialPort1.ReadExisting();
string[] data = InputString.Split(',');
textBox1.Text = data[0];
textBox2.Text = data[1];
int b;
int d;
bool result = Int32.TryParse(data[0], out b);
bool sonuc = Int32.TryParse(data[1], out d);
if (result)
{
if (b < 224)
{
button1.BackColor = Color.Red;
label1.Text = " OCCUPIED";
}
else
{
button1.BackColor = Color.Lime;
label1.Text = "AVAILABLE";
}
}
if (sonuc)
{
if (d< 224)
{
button1.BackColor = Color.Red;
label1.Text = " OCCUPIED";
}
else
{
button1.BackColor = Color.Lime;
label1.Text = "AVAILABLE";
}
}
int b = Int16.Parse(a);
textBox1.Text= a.ToString();*/
private void button3_Click(object sender, EventArgs e)
{
listBox1.Visible = true;
listBox1.Items.Add("Değerler alınıyor!");
if (!serialPort1.IsOpen)
{
serialPort1.PortName = "COM11";
serialPort1.Open();
}
}
private void button4_Click(object sender, EventArgs e)
{
serialPort1.Close();
listBox1.Items.Add("Durduruldu!");
}
}
}
I am getting an error:
"serialport1 does not exist in context"
What can l do? Whenever I want to compile I get the above mention error.
Do I have to add any library?
I am using visual Studio 2010
I've been trying to use a proxy on my webBrowser1.Navigate request using the following stackoverflow answer: https://stackoverflow.com/a/9036593/7443548
But this code would crash my for loop which I'm running in my own code.
How could I use a proxy for each request inside my code function?
Function which needs to use a proxy:
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Uri currentUri = new Uri(bunifuMaterialTextbox1.Text);
int views = bunifuSlider1.Value;
for (int i = 0; i < views; i++)
{
webBrowser1.Navigate(currentUri);
System.Threading.Thread.Sleep(3000);
backgroundWorker.ReportProgress(i + 1);
}
}
My full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows.Forms;
namespace YoutubeViewBot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
backgroundWorker.WorkerReportsProgress = true;
}
youtubeViewBot youtubeBot = new youtubeViewBot();
List<string> proxyList = new List<string>();
private void bunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
private void bunifuImageButton2_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void bunifuSlider1_ValueChanged(object sender, EventArgs e)
{
bunifuCustomLabel5.Text = bunifuSlider1.Value + " Views will be added.";
}
private void bunifuFlatButton3_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
proxyList = youtubeBot.getProxyList(openFileDialog1.FileName);
bunifuCustomLabel2.Text = proxyList.Count().ToString();
}
}
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
if (!backgroundWorker.IsBusy)
{
backgroundWorker.RunWorkerAsync();
}
else
{
MessageBox.Show("There is already a process running.", "YoutubeViewbot response");
}
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Uri currentUri = new Uri(bunifuMaterialTextbox1.Text);
int views = bunifuSlider1.Value;
for (int i = 0; i < views; i++)
{
webBrowser1.Navigate(currentUri);
System.Threading.Thread.Sleep(3000);
backgroundWorker.ReportProgress(i + 1);
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
bunifuCustomLabel7.Text = e.ProgressPercentage.ToString();
bunifuCustomLabel7.Update();
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bunifuCustomLabel9.Text = "Finished";
MessageBox.Show("Finished", "YoutubeViewBot response");
}
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
}
}
}
And here the code which I was trying to use:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows.Forms;
namespace YoutubeViewBot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
backgroundWorker.WorkerReportsProgress = true;
}
youtubeViewBot youtubeBot = new youtubeViewBot();
List<string> proxyList = new List<string>();
Uri currentUri;
private void bunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
private void bunifuImageButton2_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void bunifuSlider1_ValueChanged(object sender, EventArgs e)
{
bunifuCustomLabel5.Text = bunifuSlider1.Value + " Views will be added.";
}
private void bunifuFlatButton3_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
proxyList = youtubeBot.getProxyList(openFileDialog1.FileName);
bunifuCustomLabel2.Text = proxyList.Count().ToString();
}
}
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
if (!backgroundWorker.IsBusy)
{
backgroundWorker.RunWorkerAsync();
}
else
{
MessageBox.Show("There is already a process running.", "YoutubeViewbot response");
}
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Uri currentUri = new Uri(bunifuMaterialTextbox1.Text);
int views = bunifuSlider1.Value;
for (int i = 0; i < views; i++)
{
Random rnd = new Random();
int r = rnd.Next(proxyList.Count);
string proxy = proxyList[r];
currentUri = new Uri(bunifuMaterialTextbox1.Text);
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(currentUri);
WebProxy myProxy = new WebProxy(proxy);
myRequest.Proxy = myProxy;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
webBrowser1.DocumentStream = myResponse.GetResponseStream();
webBrowser1.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
backgroundWorker.ReportProgress(i + 1);
}
}
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (e.Url.AbsolutePath != "blank")
{
currentUri = new Uri(currentUri, e.Url.AbsolutePath);
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(currentUri);
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
webBrowser1.DocumentStream = myResponse.GetResponseStream();
e.Cancel = true;
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
bunifuCustomLabel7.Text = e.ProgressPercentage.ToString();
bunifuCustomLabel7.Update();
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bunifuCustomLabel9.Text = "Finished";
MessageBox.Show("Finished", "YoutubeViewBot response");
}
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
}
}
}
Steps it should do:
On click on the button: bunifuFlatButton2_Click it should start the backgroundWorker_DoWork functon
backgroundWorker_DoWork should run the loop x times and for each run it should attach a new proxy to the request
I would appreciate any kind of help.
Edit 1:
While debugging step by step, I realized the for loop crashes after running the second time on the following line:
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Video can be seen here:
https://www.youtube.com/watch?v=H3y2jFvuK3M
It finished after running the for loop twice instead of 454 times.
I am working on an interface in C#, which reads data from the serial port and displays it on a graph. I wrote the following code, but the graph doesn't display anything. What is wrong? I don't know exactly what should I modify.
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public long rt = 0;
string dataReceived = string.Empty;
private delegate void SetTextDeleg(string text);
// public string kp, kd, ki;
public int distanta;
public string potentiometru;
public Form1()
{
InitializeComponent();
this.chart1.ChartAreas[0].AxisX.Minimum = 0;
this.chart1.ChartAreas[0].AxisY.Minimum = 0;
this.chart1.ChartAreas[0].AxisY.Maximum = 55;
}
private void Connect_button_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
Connect_button.Enabled = false;
}
serialPort1.BaudRate = 9600;// Convert.ToUInt16(comboBox1.Text);
serialPort1.PortName = comboBox3.Text;
serialPort1.DataBits = 8;
serialPort1.StopBits = (System.IO.Ports.StopBits)2;
timer1.Start();
serialPort1.Open();
}
private void Sent_Button_Click(object sender, EventArgs e)
{
// kp = Convert.ToString(Kp_textbox.Text);
//kd = Convert.ToString(Kd_textbox.Text);
//ki = Convert.ToString(Ki_textbox.Text);
//serialPort1.Write(kp);
//serialPort1.Write(ki);
//serialPort1.Write(kd);
//string transmit = "$kp$" + kp + "$kd$" + kd + "$ki$" + ki;
// $kp$0.25
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string x = serialPort1.ReadLine();
this.BeginInvoke(new SetTextDeleg(DataReceived), new object[] { x });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void DataReceived(string data)
{
dataReceived = data.Trim();
if (rt < 2)
return;
if (dataReceived.Contains("."))
{
senzor_textbox.Text = dataReceived;
this.chart1.Series["Distance"].Points.AddXY(0, dataReceived);
}
else
{
potentiometru_textbox.Text = dataReceived;
this.chart1.Series["SetPoint"].Points.AddXY(0, dataReceived);
}
rt = 0;
}
private void button1_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
rt++;
}
private void button2_Click(object sender, EventArgs e)
{
if(serialPort1.IsOpen)
serialPort1.Close();
}
}
}
I have this a controller from UIRobot. Here is manual: enter link description here
I want to write software to controle it in C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace hhh
{
class Program
{
static void Main(string[] args)
{
string ot = "Port je otvoreny";
string za = "Port je zavrety";
string COM = "COM1";
string command = "ENABLE";
SerialPort sp = new SerialPort(COM, 9600);
sp.Open();
if (sp.IsOpen)
{
Console.WriteLine(ot);
sp.Write(command);
sp.ReadLine();
}
else
{
sp.Write(za);
}
Console.ReadKey();
}
}
}
In manual is command ENABLE to initialize controller but it does not work in my code. How Can I send command or where I do a mistake?
I have learned something new so here is update my code and new question.
I want to recieve position of motor. There is command "POS;" which has to give me the value but I get message box with question mark (?) instead number value. Why?
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 UIRFocuser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
enable.Enabled = true;
disable.Enabled = false;
zero.Enabled = false;
increase.Enabled = false;
inc10.Enabled = false;
decrease.Enabled = false;
dec10.Enabled = false;
fbk.Enabled = false;
}
private void enable_Click(object sender, EventArgs e)
{
sp.PortName = "COM1";
sp.BaudRate = 9600;
int max = -7000; //max position motor
int min = 0; //min positio of motor
sp.Open();
if (sp.IsOpen)
{
enable.Enabled = false;
disable.Enabled = true;
zero.Enabled = true;
increase.Enabled = true;
inc10.Enabled = true;
decrease.Enabled = true;
dec10.Enabled = true;
fbk.Enabled = true;
sp.Write("ENABLE;");
}
}
private void disable_Click(object sender, EventArgs e)
{
if (sp.IsOpen)
{
sp.Write("OFFLINE;");
sp.Close();
enable.Enabled = true;
disable.Enabled = false;
zero.Enabled = false;
increase.Enabled = false;
inc10.Enabled = false;
decrease.Enabled = false;
dec10.Enabled = false;
fbk.Enabled = false;
}
}
private void zero_Click(object sender, EventArgs e)
{
sp.Write("POS0; SPD400;");
}
private void increase_Click(object sender, EventArgs e)
{
sp.Write("STP1000; SPD400;");
}
private void inc10_Click(object sender, EventArgs e)
{
sp.Write("STP10; SPD400;");
}
private void decrease_Click(object sender, EventArgs e)
{
sp.Write("STP-1000; SPD400;");
}
private void dec10_Click(object sender, EventArgs e)
{
sp.Write("STP10; SPD400;");
}
private void close_Click(object sender, EventArgs e)
{
if (sp.IsOpen)
{
sp.Write("OFFLINE;");
sp.Close();
}
Application.Exit();
}
private void fbk_Click(object sender, EventArgs e)
{
sp.Write("POS;");
string msg = sp.ReadExisting();
MessageBox.Show(msg);
}
}
}
According to that document, the command is "ENABLE;" You have to include the semicolon. So change your code to:
string command = "ENABLE;";