Problem with write serial output via Button Clicked - c#

I'm currently trying to write Wisco protocol (similar to MODBUS ASCII) out to my digital output devices but faced a problem. If I clicked the ON or Off buttons (see the Image WinForm UI) that already have code to send protocol to my digital output it wouldn't do it.
But in another program where I use a textbox and write the protocol myself then I have to press Enter (If I don't press Enter key it will not work) before clicking send button and it works. What seems to be the problem here?
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 WindowsFormsApp4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = "COM5";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.Open();
progressBar1.Value = 100;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnClose_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
progressBar1.Value = 0;
}
}
private void btnOn_Click(object sender, EventArgs e)
{
serialPort1.Write("#00WDO1,1");
}
private void btnOff_Click(object sender, EventArgs e)
{
serialPort1.Write("#00WDO1,0");
}
}
}

It turns out I just have to add \r\n to solve this problem.
private void btnSend_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Write("#00WDO1,1");
serialPort1.Write("\r\n");
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Write("#00WDO1,0");
serialPort1.Write("\r\n");
}
}

Related

Why is System.Speech.Recognition not detecting or inserting into textbox?

On visual studio code; I'm trying to get a text box to be used as a speech to text. However, when I enable it no error get thrown, nor does any speech appear. So, not entirely sure were I went wrong here. Very new to C# and visual studio. Any help is appreciated!! :) My mic is set to the default device and is able to detect me speaking. Other function such as copy to clipboard and clear 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.Speech;
using System.Speech.Recognition;
using System.Threading;
namespace MercyProto
{
public partial class Form1 : Form
{
public Grammar grammar;
public Thread RecThread;
public Boolean RecognizerState = true;
public SpeechRecognitionEngine recognizer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GrammarBuilder build = new GrammarBuilder();
build.AppendDictation();
grammar = new Grammar(build);
recognizer = new SpeechRecognitionEngine();
recognizer.LoadGrammar(grammar);
recognizer.SetInputToDefaultAudioDevice();
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>
(recognizer_SpeechRecognized);
RecognizerState = true;
RecThread = new Thread(new ThreadStart(RecThreadFunction));
RecThread.Start();
}
public void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
//Recognizer recognizes the speech
if (!RecognizerState)
return;
this.Invoke((MethodInvoker)delegate
{
textBox1.Text += (" " + e.Result.Text.ToLower());
//This will add a space between each word you say
});
}
public void RecThreadFunction()
{
while (true)
{
try
{
recognizer.Recognize();
}
catch
{
//Handles errors
//Won't hear you, nothing will happen
}
}
private void button21_Click(object sender, EventArgs e)
{
RecognizerState = true;
}
private void button22_Click(object sender, EventArgs e)
{
RecognizerState = false;
}
private void button23_Click(object sender, EventArgs e)
{
Clipboard.SetText(textBox1.Text);
}
private void button24_Click(object sender, EventArgs e)
{
textBox1.Text = String.Empty;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}

How to make two forms receive information from the serial port that receives information from Arduino?

I am developing a graphical interface that reads variables from different sensors that arrive through the serial port, so far I have managed to read all the variables with a single form but now I want to have two forms.
The first form asks the user to choose the COM and confirms whether the connection was successful or not. Once the connection is successful, the second form is opened where the variables from the sensors will be shown in "labels", the readings sent from Arduino are read by the serial port and stored in an array:
data[0], data[1], data[2] etc...
This is the first form where Serialport1 is found and the data arrives through the serialPort1_DataReceived event:
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 System.Media;
namespace AUTOCLAVES_GUI
{
public partial class GUI_AUTOCLAVES_GENERADOR_DE_VAPOR : Form
{
/*VARIABLES GLOBALES*/
string puerto_seleccionado;
public GUI_AUTOCLAVES_GENERADOR_DE_VAPOR()
{
InitializeComponent();
string[] puertos = SerialPort.GetPortNames();
foreach (string mostrar in puertos)
{
comboBox1.Items.Add(mostrar);
}
}
private void Salir_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Minimizar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
}
private void Maximizar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
Maximizar.Visible = false;
Restaurar.Visible = true;
}
private void Restaurar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Normal;
Restaurar.Visible = false;
Maximizar.Visible = true;
}
private void MenuSideBar_Click(object sender, EventArgs e)
{
if (Sidebar.Width == 270)
{
Sidebar.Visible = false;
Sidebar.Width = 68;
SidebarWrapper.Width = 90;
LineaSidebar.Width = 68;
AnimacionSidebar.Show(Sidebar);
}
else
{
Sidebar.Visible = false;
Sidebar.Width = 270;
SidebarWrapper.Width = 300;
LineaSidebar.Width = 268;
AnimacionSidebarBack.Show(Sidebar);
}
}
private void bunifuFlatButton8_Click(object sender, EventArgs e)
{
try
{
serialPort1.Close();
serialPort1.Dispose();
serialPort1.Open();
CheckForIllegalCrossThreadCalls = false;
label2.Text = "CONEXIÓN EXITOSA";
label2.ForeColor = Color.Green;
label2.Font = new Font(label2.Font, FontStyle.Bold);
openChildForm(new MUESTREO_EN_TIEMPO_REAL());
}
catch
{
label2.Text = "CONEXIÓN FALLIDA";
label2.ForeColor = Color.Red;
label2.Font = new Font(label2.Font, FontStyle.Bold);
MessageBox.Show("REVISE CONEXIÓN DE ARDUINO", "ADVERTENCIA", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
puerto_seleccionado = comboBox1.Text;
serialPort1.PortName = puerto_seleccionado;
}
private void bunifuFlatButton7_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
label2.Text = "SIN CONEXIÓN";
label2.ForeColor = Color.White;
string[] puertos = SerialPort.GetPortNames();
foreach (string mostrar in puertos)
{
comboBox1.Items.Add(mostrar);
}
}
private Form activeForm = null;
private void openChildForm(Form childForm)
{
if (activeForm != null)
activeForm.Close();
activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
panel1.Controls.Add(childForm);
panel1.Tag = childForm;
childForm.BringToFront();
childForm.Show();
}
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
openChildForm(new MUESTREO_EN_TIEMPO_REAL());
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string[] data = serialPort1.ReadLine().Split(',');
if (data.Length > 10)
{
}
else
{
MessageBox.Show("Intente nuevamente", "ADVERTENCIA", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
}
}
Here is my 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.Threading.Tasks;
using System.Windows.Forms;
namespace AUTOCLAVES_GUI
{
public partial class MUESTREO_EN_TIEMPO_REAL : Form
{
public MUESTREO_EN_TIEMPO_REAL()
{
InitializeComponent();
}
private void MUESTREO_EN_TIEMPO_REAL_Load(object sender, EventArgs e)
{
}
private void Salir_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I hope someone can help me overcome this problem.

Why I am coming across "Format Exception" while execution in C# TCP/IP Application?

The code is as follows:
The ServerForm 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 SimpleTCP;
namespace TCPIP
{
public partial class ServerForm : Form
{
public ServerForm()
{
InitializeComponent();
}
SimpleTcpServer server;
private void Form1_Load(object sender, EventArgs e)
{
server = new SimpleTcpServer();
server.Delimiter = 0x13; //enter
server.StringEncoder = Encoding.UTF8;
server.DataReceived += Server_DataReceived;
}
private void Server_DataReceived(object sender, SimpleTCP.Message e)
{
StatusText.Invoke((MethodInvoker)delegate ()
{
StatusText.Text = e.MessageString;
e.ReplyLine(string.Format("You said: {0}",e.MessageString));
});
// throw new NotImplementedException();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void StartButton_Click(object sender, EventArgs e)
{
StatusText.Text += "Server Starting !";
System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(HostText.Text)); //error here
server.Start(ip,Convert.ToInt32(PortText.Text));
}
private void StopButton_Click(object sender, EventArgs e)
{
if(server.IsStarted)
{
server.Stop();
}
}
}
}
The Code of the ClientForm is as follows:
using SimpleTCP;
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 Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SimpleTcpClient client;
private void ConnectButton_Click(object sender, EventArgs e)
{
ConnectButton.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
client = new SimpleTcpClient();
client.StringEncoder = Encoding.UTF8;
client.DataReceived += Client_DataReceived;
}
private void Client_DataReceived(object sender, SimpleTCP.Message e)
{
StatusText.Invoke((MethodInvoker)delegate ()
{
StatusText.Text = e.MessageString;
//...
});
//throw new NotImplementedException();
}
private void SendButton_Click(object sender, EventArgs e)
{
client.WriteLineAndGetReply(TextMessage.Text, TimeSpan.FromSeconds(4));
}
}
}
The issue in the above code is that it is 'build'ing correctly and even when I am debug it with the new instance, the code is running fine, but will I debug, as soon as I press the "start" button in the Server form it shows the error in line :
System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(HostText.Text));
The error is: System.FormatException: 'Input string was not in a correct format.'
Please refer the Screenshot for details and suggest a potential fix to the issue.Image of Screenshot of Error inLine
Clearly HostText.Text is returning a value that can't be parsed into a long.
This exception is coming from long.Parse, which is really a language shortcut for Int64.Parse, whose documentation states that it will throw this exception if the input string is not formatted correctly.

I Want To Make A Automated Key Presser For A Game

hi i want to make a program that presses ctrl + v every 130 secs but it didnt worked for games (it worked for google, notepad etc.) i tried this code down below before
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 TradeChatBot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void start_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void stop_Click(object sender, EventArgs e)
{
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
SendKeys.Send("^{v}");
SendKeys.Send("{ENTER}");
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
You can look into Clipboard class. https://msdn.microsoft.com/en-Us/library/system.windows.forms.clipboard(v=vs.110).aspx
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text= "SendKeys.Send(^{v}); ";
Clipboard.SetText(textBox1.Text);
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Focus();
SendKeys.Send("^{v}");
SendKeys.Send("{ENTER}");
}

skype4comlib Create List of Friends

I'm trying to grab a list of all of my Skype friends who are online and put it into my listbox named lst1.
I'm also trying to make my tool answer to some commands like if some one sends !news to me it messages them a text that I've set in the code.
This is what I've tried so far, I'm just playing around with the code to learn how to use skype4comlib.
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 MetroFramework;
using MetroFramework.Forms;
using MetroFramework.Components;
using SKYPE4COMLib;
using System.Threading;
namespace betaskypetool
{
public partial class Form1 : MetroForm
{
#region Definitions
Skype Merk = new Skype();
private int count = 1;
#endregion
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void metroButton1_Click(object sender, EventArgs e)
{
try
{
this.Merk.Attach(5, true);
MessageBox.Show("You are now connected enjoy!", "Tutorial Skype Tool!");
}
catch (Exception)
{
MessageBox.Show("Failed To Connect?\n Be Sure Skype Is Open!", "Tutorial Skype Tool!");
}
}
private void metroButton2_Click(object sender, EventArgs e)
{
this.Merk.CurrentUserStatus = TUserStatus.cusOnline;
}
private void metroButton3_Click(object sender, EventArgs e)
{
this.Merk.CurrentUserStatus = TUserStatus.cusDoNotDisturb;
}
private void metroButton4_Click(object sender, EventArgs e)
{
this.Merk.CurrentUserStatus = TUserStatus.cusAway;
}
private void metroButton5_Click(object sender, EventArgs e)
{
this.Merk.CurrentUserStatus = TUserStatus.cusInvisible;
}
private void metroButton6_Click(object sender, EventArgs e)
{
this.Merk.CurrentUserStatus = TUserStatus.cusOffline;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if(checkBox1.Checked == true)
{
timer1.Start();
}
else
{
timer1.Stop();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Merk.CurrentUserStatus = TUserStatus.cusOnline;
Thread.Sleep(20);
this.Merk.CurrentUserStatus = TUserStatus.cusAway;
Thread.Sleep(20);
this.Merk.CurrentUserStatus = TUserStatus.cusDoNotDisturb;
Thread.Sleep(20);
this.Merk.CurrentUserStatus = TUserStatus.cusInvisible;
Thread.Sleep(20);
}
private void metroButton7_Click(object sender, EventArgs e)
{
foreach(User spamall in Merk.Friends)
{
Merk.SendMessage(spamall.Handle, "Haiiiii" + spamall.FullName + ",\n" + richTextBox1.Text + "\n\n(cash) Sent From Merk's Tutorial Tool! (cash)");
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
I hope you understand my question and can help me out with what I need to do to add those 2 features to my project
You can get a collection of your online friends like this:
var onlineFriends = Merk.Friends.Cast<User>().Where(u => u.OnlineStatus == TOnlineStatus.olsOnline);
After this it's easy to put them in a ListBox.
WPF example:
foreach (var friend in onlineFriends)
{
MyListBox.Items.Add(friend.FullName);
}
That said, I'm not sure if it's worth to spend a lot of time learning it, because according to this blog post, Microsoft doesn't really support skype4comlib anymore.
https://support.skype.com/en/faq/FA12384/how-does-my-3rd-party-application-work-with-skype-and-how-will-changes-to-skype-impact-my-3rd-party-application
As communicated in this blog post, due to technology improvements we are making to the Skype experience, some features of the API will stop working with Skype for desktop. For example, delivery of chat messages using the API will cease to work.
For example, I'm not able to send a message using the library anymore.
PS.: I'm using Skype 7.17.0.106

Categories

Resources