My goal is to make a project that can be able to control a simple system using the NodeMcu esp 8266, by a another simple Windows Form Application in C#.
But I had some mistakes on my code and I don't know why. So I would like to someone help me doing this.
Errors:
When I sent the position to the servo, he works only one time and every time in the same position.
When I sent the comand to the Bulbs turn on off, only one of them works.
Just the buzzer works as I want
Here is the Arduino Code:
// Programação do controle de dispositivos via Serial com ESP8266
#include <Servo.h>
// #include <Process.h>
Servo servo;
const int buzzer = D2;
const int lamp1 = D4;
const int lamp2 = D0;
const int pinServo = D3;
String serialData;
// String comando;
bool estadoBuzzer = LOW;
bool estadoLam1 = LOW;
bool estadoLam2 = LOW;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
//SerialUSB.begin(115200);
pinMode(buzzer, OUTPUT);
pinMode(lamp1, OUTPUT);
pinMode(lamp2, OUTPUT);
servo.attach(pinServo);
Serial.setTimeout(10);
//Bridge.begin();
//while (!SerialUSB);
}
void loop() {
// put your main code here, to run repeatedly:
serialEvent(Serial.readString());
}
void serialEvent(String data){
/*Process p;
comando = "echo " + data + " > teste_arduino_serial_comandos.txt";
p.runShellCommand(comando);
*/
if(data.charAt(0) == 'B'){
if(estadoBuzzer == HIGH){
digitalWrite(buzzer, LOW);
estadoBuzzer = LOW;
} else {
digitalWrite(buzzer, HIGH);
estadoBuzzer = HIGH;
}
} else if(data.charAt(0) == 'L'){
data.remove(0);
if(data.toInt() == 1){
lampada1();
} else {
lampada2();
}
} else if(data.charAt(0) == 'A'){
data.remove(0);
int angulo = data.toInt();
Serial.println(angulo);
if(angulo >= 0 && angulo <= 180){
servo.write(angulo);
}
}
}
void lampada1(){
if(estadoLam1 == HIGH){
digitalWrite(lamp1, LOW);
estadoLam1 = LOW;
} else {
digitalWrite(lamp1, HIGH);
estadoLam1 = HIGH;
}
}
void lampada2(){
if(estadoLam2 == HIGH){
digitalWrite(lamp2, LOW);
estadoLam2 = LOW;
}
else {
digitalWrite(lamp2, HIGH);
estadoLam2 = HIGH;
}
}
And here is the C# 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.Diagnostics;
namespace ControleDeDispositivosViaSerialNodeMcuEsp8266
{
public partial class Form1 : Form
{
public Stopwatch watch { get; set; }
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
watch = Stopwatch.StartNew();
port.Open();
}
public void writeToPort(String indicador, String valor="0")
{
if (watch.ElapsedMilliseconds > 15)
{
watch = Stopwatch.StartNew();
port.Write(String.Format(indicador+valor));
System.Windows.Forms.MessageBox.Show(indicador + valor);
}
// System.Windows.Forms.MessageBox.Show(port.ReadExisting());
}
private void anguloBtn_Click(object sender, EventArgs e)
{
writeToPort("A", angulos.Text);
angulos.Refresh();
}
private void onoff1_Click(object sender, EventArgs e)
{
writeToPort("L", "1");
}
private void onoff2_Click(object sender, EventArgs e)
{
writeToPort("L", "2");
}
private void buzzerBtn_Click(object sender, EventArgs e)
{
writeToPort("B");
}
}
}
Your data.toInt() is not working, this is why it gets always only one lamp and to same postion on the servo.
The data.Remove(0) is removing all after first char so will be empty.
Use data = data. Substring(1)
What i normally do as feedback to check is write: Serial.println(data) etcto check if i really work with what i think i have.
Related
I am making a password generator and on websites when you enter certain conditions are met the strength of the password changes how can I change the color and text of the label when the password strength is >= 8, <8<10, >12?
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 Password_Generator
{
public partial class PassGen : Form
{
int currentPasswordLength = 0;
Random Character = new Random();
private void PasswordGenerator(int PasswordLength)
{
String validChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$&?";
String randomPassword = "";
//25
for(int i = 0; i < PasswordLength; i++)
{
int randomNum = Character.Next(0, validChars.Length);
randomPassword += validChars[randomNum];
}
Password.Text = randomPassword;
}
public PassGen()
{
InitializeComponent();
PasswordLengthSlider.Minimum = 5;
PasswordLengthSlider.Maximum = 22;
PasswordGenerator(5);
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Copy_Click(object sender, EventArgs e)
{
Clipboard.SetText(Password.Text);
}
//52
private void PasswordLength_Click(object sender, EventArgs e)
{
}
private void PasswordLengthSlider_Scroll(object sender, EventArgs e)
{
PasswordLength.Text = "Password Length:" + " " + PasswordLengthSlider.Value.ToString();
currentPasswordLength = PasswordLengthSlider.Value;
PasswordGenerator(currentPasswordLength);
}
private void pswdStrengthTest()
{
if (currentPasswordLength <= 8)
{
pswdStrength.Text = "weak";
pswdStrength.ForeColor = Color.Red;
} else if (currentPasswordLength<= 9)
{
pswdStrength.Text = "ok";
pswdStrength.ForeColor = Color.Blue;
}
}
//78
private void pswdStrength_Click(object sender, EventArgs e)
{
}
}
}
If anyone could help me with this it would be greatly appreciated. This is based off a tutorial I found on YouTube. I'm not sure what the video is called but if it helps I could search for it and update my posting.
Try this:
Password.TextChanged += (s1, e1) =>
{
if (Password.Text.Length > 10)
pswdStrength.ForeColor = Color.Green
else if (Password.Text.Length > 8)
pswdStrength.ForeColor = Color.Blue
else
pswdStrength.ForeColor = Color.Red
};
Your code looks like a windows form application.
If you have for example one objetc txt_password, check to code some of these events:
TextChanged: this occurs when your textbox has been changed
Others events could be:
KeyPress or KeyDown
I am beginning with C#. When I run the following code and click the generate button the output does not appear in the textbox. Why is this? I am calling the function palendrome and its not updating the textbox. What am I doing wrong? Am I missing something? What do I need to fix. I don't see the error. Please help. :(
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 PalendromeChecker
{
public partial class Form1 : Form
{
int num;
int count;
static int result;
int setPalendromeValue;
int copyCount;
public Form1()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
count = Int32.Parse(textBox2.Text);
copyCount = count;
if (!int.TryParse(textBox2.Text, out count))
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (count < 0 || count > 100)
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
public static int palendrome(int num)
{
int temp = num; ;
int r;
int rv = 0;
while (num > 0)
{
r = num % 10;
rv = rv * 10 + r;
num /= 10;
}
if (rv == temp)
{
result = temp;
return temp;
}
else
{
return 0;
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
while (copyCount != 0)
{
string resultInString = result.ToString();
textBox3.Text = resultInString;
textBox3.Visible = true;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
num = Int32.Parse(textBox1.Text);
//MessageBox.Show(this.textBox1.Text);
if (!int.TryParse(textBox1.Text, out num))
{
//MessageBox.Show("This is a number only field");
//return;
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (num < 0 || num > 1000000000)
{
// MessageBox.Show("Invalid Input needs to be between 0 and 1,000,000,000");
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
label4.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
int palendromeValue;
while (count != 0)
{
palendromeValue = palendrome(num);
count--;
}
}
}
}
It is not generating any input on the textbox because your function palendrome is not generating in anyway output on any of textbox1 to textbox3.
Try this:
textBox1.Text = "output"; //Whatever output you want.
If you want to show result in textBox3 the code to update it's text property should be inside button click handler, not in text changed handler.
Also while (count != 0) or while (copyCount != 0) are like infinite loops (almost). They are going to make your form unresponsive. You need to avoid those.
I have created this Arduino sketch that communicates with my pc through the Console library and using the serial monitor over my network. Essentially, when I enter the digit 1, my Arduino stepper motor moves 30 steps etc. However, it is inconvenient to have to type in the serial monitor. I was hoping anyone would know how I can create an executable windows form or something that can connect over my network, to the Arduino Yun console.
#include <Stepper.h>
#include <Console.h>
char incomingByte;
Stepper stepper(64,8,9,10,11);
int stepCount = 1;
void setup() {
Bridge.begin();
Console.begin();
while (!Console);
stepper.setSpeed(60);
}
void loop() {
if (Console.available() > 0)
{
incomingByte = Console.read();
if (incomingByte == '1')
{
stepCount += 30;
if (stepCount > 0 && stepCount < 4096)
{
stepper.step(30);
Console.println(stepCount);
}
else{stepCount = stepCount - 30;}
}
if (incomingByte == '2')
{
stepCount = stepCount - 30;
if (stepCount > 0 && stepCount < 4096)
{
stepper.step(-30);
Console.println(stepCount);
}
else{stepCount += 30;}
}
if (incomingByte == '3')
{
stepCount += 200;
if (stepCount > 0 && stepCount < 4096)
{
stepper.step(200);
Console.println(stepCount);
}
else{stepCount = stepCount - 200;}
}
if (incomingByte == '4')
{
stepCount = stepCount - 200;
if (stepCount > 0 && stepCount < 4096)
{
stepper.step(-200);
Console.println(stepCount);
}
else{stepCount += 200;}
}
}
}
Here is the windows form app I was hoping would 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;
namespace Remote_Focuser
{
public partial class Form1 : Form
{
private SerialPort myPort;
public Form1()
{
Console.Read();
InitializeComponent();
Init();
}
private void Fwd_30_Button_Click(object sender, EventArgs e)
{
myPort.WriteLine("1");
}
private void Backward_30_Button_Click(object sender, EventArgs e)
{
myPort.WriteLine("2");
}
private void Forward_200_Button_Click(object sender, EventArgs e)
{
myPort.WriteLine("3");
}
private void Backward_200_Button_Click(object sender, EventArgs e)
{
myPort.WriteLine("4");
}
private void Init()
{
myPort = new SerialPort();
myPort.BaudRate = 9600;
myPort.PortName = "10.1.1.211";
myPort.Open();
}
}
}
Thanks heaps in advance, and yes I have probably made a big mistake, I am not too proficient yet... :)
what i am attempting to do is, get user input from a text box, convert it to an int and then use that. i got everything to work except the the try and catch. incase the person puts a letter instead of a number. with the code below it always catches something. i have no idea what is catches something. i've taken out the bool test and if i put in a letter it will just throw the exception then go to the beeping. other then waiting for a valid input.
please excuse my messy code, i am still a beginner c# programmer :D thanks in advanced!
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 WindowsFormsApplication4
{
public partial class Form1 : Form
{
bool tone = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bool test = true;
speedInput.Clear();
beep.Clear();
int beepspeed = 90;
int speed = 100;
string speedtext = this.speedInput.Text;
string beeptext = this.beep.Text;
try
{
test = true;
beepspeed = Convert.ToInt32(beeptext);
speed = Convert.ToInt32(speedtext);
}
catch (Exception)
{
MessageBox.Show("numbers above 37 only!!");
test = false;
}
if (test)
{
for (int i = 0; i < beepspeed; i++)
{
if (this.tone)
{
Random ran = new Random();
int rand = ran.Next(400, 3000);
Console.Beep(rand, speed);
}
else
{
Console.Beep(1000, speed);
}
}
}
}
private void radioButtonYes_CheckedChanged(object sender, EventArgs e)
{
this.tone = true;
}
private void radioButtonNo_CheckedChanged(object sender, EventArgs e)
{
this.tone = false;
}
}
}
You are cleaning the content of the inputs at the beginning of the button1_click
speedInput.Clear();
beep.Clear();
Then when you try to convert empty string to int32 it fails
beepspeed = Convert.ToInt32(beeptext);
speed = Convert.ToInt32(speedtext);
I have a program that gets the incoming number, date and time. I want to check however if the person who is ringing me has put the phone down, how can I do this?
Below is the code which I currently have:
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 CallerID
{
public partial class CallerID : Form
{
int timesTicked = 0;
Point defaultLocation = new Point();
Point newLocation = new Point();
public CallerID()
{
InitializeComponent();
port.Open();
SetModem(); // SetModem(); originally went after WatchModem();
WatchModem();
//SetModem();
telephoneTimer.Interval = 16;
telephoneTimer.Tick += new EventHandler(telephoneTimer_Tick);
defaultLocation = pictureBox1.Location;
newLocation = pictureBox1.Location;
}
void telephoneTimer_Tick(object sender, EventArgs e)
{
if (timesTicked <= 2)
newLocation.X++;
if (timesTicked >= 4)
newLocation.X--;
if (timesTicked == 6)
{
timesTicked = 0;
pictureBox1.Location = defaultLocation;
newLocation = defaultLocation;
}
pictureBox1.Location = newLocation;
timesTicked++;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
WatchModem();
}
private SerialPort port = new SerialPort("COM3");
string CallName;
string CallNumber;
string ReadData;
private void SetModem()
{
port.WriteLine("AT+VCID=1\n");
//port.WriteLine("AT+VCID=1");
port.RtsEnable = true;
}
private void WatchModem()
{
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
public delegate void SetCallerIdText();
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
ReadData = port.ReadExisting();
//Add code to split up/decode the incoming data
//if (lblCallerIDTitle.InvokeRequired)
if (ReadData.Contains("NMBR"))
{
lblData.Invoke(new SetCallerIdText(() => lblData.Text = ReadData));
}
//else
// lblCallerIDTitle.Text = ReadData;
}
private void lblData_TextChanged(object sender, EventArgs e)
{
telephoneTimer.Start();
button1.Visible = true;
}
}
}
Please ignore the Timer Code as that is just for animation.
Have you tried the PinChanged event? Normally Carrier Detect will go low when the remote end disconnects.