Hi guys I need your help with my project. I have a 2 textboxes (type string) in a C# program and i need to send this numbers to Arduino using a Serial.Port. So far i got to send one of the values to arduino but it doesn't work very well if I enter "1200" arduino reads and show: 1,2,0,0 i need "1200". How i send 2 values from C# to Arduino? How the arduino will read these values (x and y)?
C#
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; // necessário para ter acesso as portas
namespace interfaceArduinoVS2013
{
public partial class Form1 : Form
{
string RxString;
public Form1()
{
InitializeComponent();
timerCOM.Enabled = true;
}
private void atualizaListaCOMs()
{
int i;
bool quantDiferente; //If there are more ports
i = 0;
quantDiferente = false;
//if there are new ports
if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
{
foreach (string s in SerialPort.GetPortNames())
{
if (comboBox1.Items[i++].Equals(s) == false)
{
quantDiferente = true;
}
}
}
else
{
quantDiferente = true;
}
//it was't detected difference
if (quantDiferente == false)
{
return;
}
//clean comboBox
comboBox1.Items.Clear();
//add all the COMs in the list
foreach (string s in SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
//select the first position
comboBox1.SelectedIndex = 0;
}
private void timerCOM_Tick(object sender, EventArgs e)
{
atualizaListaCOMs();
}
private void btConectar_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == false)
{
try
{
serialPort1.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString();
serialPort1.Open();
}
catch
{
return;
}
if (serialPort1.IsOpen)
{
btConectar.Text = "Desconectar";
comboBox1.Enabled = false;
}
}
else
{
try
{
serialPort1.Close();
comboBox1.Enabled = true;
btConectar.Text = "Conectar";
}
catch
{
return;
}
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if(serialPort1.IsOpen == true) // if the port is open
serialPort1.Close(); //close
}
private void btEnviar_Click(object sender, EventArgs e)
{
if(serialPort1.IsOpen == true) //porta está aberta
serialPort1.Write(textBoxX.Text); //send the text from textboxX
serialPort1.Write(textBoxY.Text);
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting(); //read data from serial
this.Invoke(new EventHandler(trataDadoRecebido));
}
private void trataDadoRecebido(object sender, EventArgs e)
{
textBoxReceber.AppendText(RxString);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Arduino Script
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(Serial.available())
{
char c = Serial.read();
Serial.println(c);
}
}
Reading data through serial port and separating them using strings.
In C#
Add a unique character to starting of 1st box data.
Add a unique character to starting of 2nd box data.
Add a unique character to ending of 2nd box data.
Append two strings and send as single string.
I had a VB example:
Dim WithEvents ADRport As SerialPort = New System.IO.Ports.SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
msg = "$" & box1.Text & "#" & box2.Text & "*" & vbCrLf
ADRport.Write(msg)
In Arduino:
//--- Wait for the message starting -----
while(Serial.read()!='$');
while (!flag)
{
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
mstr += inChar;
//Serial.write(inChar);
// if the incoming character is a end of line, set a flag
if (inChar == '*')
{
flag = true;
}
}
Seperate strings using
int 1start = int(mstr.indexOf('$'));
int 2start = int(mstr.indexOf('#',numstart+1));
int 2end = int(mstr.indexOf('*'));
text1 = mstr.substring(1start+1,2start);
text2 = mstr.substring(2start+1,2end);
text1.trim();
text1.trim();
Then display it onn lcd/serialport:
lcd.setCursor(0,0);
lcd.print(msg);
Please note that '$' will not get added to the string.
This is what i did, and it worked:
C#
serialPort1.WriteLine(eixver.Text.ToString()+";"+ eixHor.Text.ToString());
Arduino:
int val;
int h, v;
String cont;
void setup() {
Serial.begin(9600);
}
void loop() {
while(Serial.available())
{
char caracter = Serial.read();
cont.concat(caracter);
delay(5);
}
if(cont!="")
{
// Serial.println(cont);
v=cont.substring(0, cont.indexOf(';')).toInt();
h=cont.substring(cont.indexOf(';')+1, cont.length()).toInt();
Serial.print("v=");
Serial.print(v);
Serial.print(" - h=");
Serial.print(h);
cont="";
}
}
I think, this is good for you. C# part:
Connect();
if (serialPort1.IsOpen)
{
double MyInt = ToDouble(lblMixerCase.Text);
byte[] b = GetBytes(MyInt);
serialPort1.Write(b, 0, 1);
double MyInt2 = ToDouble(txtRPM.Text);
byte[] z = GetBytes(MyInt2);
serialPort1.Write(z, 0, 1);
if (MyInt2>1600)
{
MessageBox.Show("Please enter RPM value between 0 and 1600");
}
double MyInt3 = ToDouble(lblCaseRpmSecond.Text);
byte[] p = GetBytes(MyInt3);
serialPort1.Write(p, 0, 1);
double MyInt4 = ToDouble(lblRpmCaseThree.Text);
byte[] s = GetBytes(MyInt3);
serialPort1.Write(s, 0, 1);
serialPort1.Close();
Arduino part:
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (Serial.available() > 0) {
// read the incoming byte:
n = Serial.read();
if (i < 3)
{
number[i] = n;
switch (number[0])
{
case 1:
if (i == 2)
{
switch(number[1])
{
case 1:
openClose();
break;
case 2:
openCloseTwice();
break;
case 3:
openCloseThree();
break;
default:
openCloseIwanted(number[1], number[2]);
break;
}
}
break;
case 2:
if (i == 2)
{
switch(number[1])
{
case 1:
openClose();
break;
case 2:
openCloseTwice();
break;
case 3:
openCloseThree();
break;
default:
openCloseIwanted(number[1], number[2]);
break;
}
}
break;
case 3:
if (i == 2)
{
openCloseIwanted(number[1], number[2]);
}
break;
default:
if (i == 2)
{
openCloseIwanted(number[1], number[2]);
}
break;
}
i++;
if (i == 3)
{
asm volatile (" jmp 0"); //For reset Arduino
}
}
else
{
i = 0;
}
}
Related
How do I also make it so that if all 3 slots have a jackpot image, the user wins 5x their bet
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace Slot_Machine
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random rnd = new Random();
int a, b, c, move, wins,losses, bid;
int balance = 100;
If the user clicks the quit button, the program ends
private void QuitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
If the user presses the reset button, the game restarts
private void ResetBtn_Click(object sender, EventArgs e)
{
Application.Restart();
}
This function subtracts the bid from the balance before the slots start running
void Before_Game_Result()
{
bid = Convert.ToInt32(BidAmountTxt.Text);
balance = balance - bid;
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
}
This function decides whether or not the user won their bid
void Game_Result()
{
if (System.Convert.ToInt32(a) == b && System.Convert.ToInt32(b) == c)
{
wins++;
WinLbl.Text = "Wins: " + wins;
bid = Convert.ToInt32(BidAmountTxt.Text);
balance = balance + (bid * 2);
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
BidBtn.Enabled = true;
BidAmountTxt.Enabled = true;
BidAmountTxt.BackColor = Color.White;
}
else
{
if ((System.Convert.ToInt32(a) == b && System.Convert.ToInt32(b) != c) || (System.Convert.ToInt32(a) == c && System.Convert.ToInt32(b) != c) ||
(System.Convert.ToInt32(b) == c && System.Convert.ToInt32(a) != c))
{
wins++;
WinLbl.Text = "Wins: " + wins;
bid = Convert.ToInt32(BidAmountTxt.Text);
balance = balance + bid;
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
BidBtn.Enabled = true;
BidAmountTxt.Enabled = true;
BidAmountTxt.BackColor = Color.White;
}
else
{
losses++;
LossesLbl.Text = "Losses: " + losses;
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
BidBtn.Enabled = true;
BidAmountTxt.Enabled = true;
BidAmountTxt.BackColor = Color.White;
}
}
if (balance <= 0)
{
MessageBox.Show("You don't have any money!! SCRAM");
this.Close();
}
}
This function validates that the user enters a valid bid before pressing the bid button
private void BidBtn_Click(object sender, EventArgs e)
{
if(BidAmountTxt.Text =="")
{
MessageBox.Show("input a bid first!!");
}
else
{
int x = Convert.ToInt32(BidAmountTxt.Text);
bool success = false;
if(x <= balance)
{
success = true;
}
if(success)
{
Before_Game_Result();
timer1.Enabled = true;
BidAmountTxt.Enabled = false;
BidBtn.Enabled = false;
BidAmountTxt.BackColor = Color.Black;
}
else
{
MessageBox.Show("INVALID - please enter a bid lower or equal to your balance");
BidAmountTxt.Clear();
}
}
}
**This function runs the slots **
private void timer1_Tick(object sender, EventArgs e)
{
move++;
if (move < 30)
{
a = rnd.Next(5);
b = rnd.Next(5);
c = rnd.Next(5);
switch(a)
{
case 1:
Slot1.Image = Properties.Resources.basketball3;
break;
case 2:
Slot1.Image = Properties.Resources.soccer_ball2;
break;
case 3:
Slot1.Image = Properties.Resources.volleyball;
break;
case 4:
Slot1.Image = Properties.Resources.hockey_puck;
break;
}
switch (b)
{
case 1:
Slot2.Image = Properties.Resources.basketball3;
break;
case 2:
Slot2.Image = Properties.Resources.soccer_ball2;
break;
case 3:
Slot2.Image = Properties.Resources.volleyball;
break;
case 4:
Slot2.Image = Properties.Resources.hockey_puck;
break;
}
switch (c)
{
case 1:
Slot3.Image = Properties.Resources.basketball3;
break;
case 2:
Slot3.Image = Properties.Resources.soccer_ball2;
break;
case 3:
Slot3.Image = Properties.Resources.volleyball;
break;
case 4:
Slot3.Image = Properties.Resources.hockey_puck;
break;
}
}
else
{
timer1.Enabled = false;
move = 0;
Game_Result();
}
}
}
}
There's lot of ways to do what you want. My take on this is that a little abstraction would go a long way. Starting with an ImageList where you can select pictures by index.
Assign it to the ImageList property of the controls (e.g. Label) you are using to display a slot "wheel".
public MainForm()
{
InitializeComponent();
labelJackpot.Visible= false;
Slot1.ImageList = imageList;
Slot2.ImageList = imageList;
Slot3.ImageList = imageList;
}
Then you could abstract those index values to an enum.
enum SlotImage
{
Jackpot,
Basketball,
SoccerBall,
VolleyBall,
HockeyPuck,
}
Which simplifies your "wheel spinner" in your timer tick handler:
Label[] Slots => new [] { Slot1, Slot2, Slot3 };
SlotImage[] SlotImages { get; } = Enum.GetValues(typeof(SlotImage)).Cast<SlotImage>().ToArray();
private void timer1_Tick(object sender, EventArgs e)
{
move++;
if (move < 30)
{
foreach (var slot in Slots)
{
slot.ImageIndex= rnd.Next(SlotImages.Length);
}
}
else
{
timer1.Enabled = false;
move = 0;
// Probably goes in GameResult but here's how.
var isJackpot = Slots.All(_ => ((SlotImage)_.ImageIndex).Equals(SlotImage.Jackpot));
labelJackpot.Visible = isJackpot;
Game_Result();
}
}
Doing it in this manner would make the wheels comparable by int. So, one solution to your question is to use this System.Linq expression to see whether you've hit the jackpot.
isJackpot = Slots.All(_ => ((SlotImage)_.ImageIndex).Equals(SlotImage.Jackpot));
Here is a picture of when I run the program. I want the user to be able to only type on the current line. They shouldn't be able to edit the lines above.
Here is the link to the github if you want to downlaod it to use it for yourself. https://github.com/TeddyRoche/Calculator
Here is the code that is controlling the whole program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Calculator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
float number_Initial = 0;
float prev_Answer = 0;
List<float> number_List = new List<float>();
List<string> equations = new List<string>();
bool valid = true;
int key_Press = 0;
int maxLines = 0;
string lastLine = "";
public MainWindow()
{
InitializeComponent();
}
private void NumPressedButton(int i)
{
if (valid == false)
{
MessageBox.Show("Please enter only numbers.");
displayText.Text = displayText.Text.Remove(displayText.Text.Length - 1);
}
else
{
if (key_Press < 12)
{
this.displayText.Text += i;
number_Initial = number_Initial * 10 + i;
key_Press++;
}
}
valid = true;
}
private void NumPressedKeyboard(int i)
{
if (valid == false)
{
MessageBox.Show("Please enter only numbers.");
displayText.Text = displayText.Text.Remove(displayText.Text.Length - 1);
}
else
{
if (key_Press < 12)
{
number_Initial = number_Initial * 10 + i;
key_Press++;
}
}
valid = true;
}
private void OutputSymbol(string x)
{
switch (x)
{
case "+":
equations.Add("add");
break;
case "-":
equations.Add("sub");
break;
case "*":
equations.Add("mul");
break;
case "/":
equations.Add("div");
break;
}
}
private void SymbolPressedButton(String x)
{
if (lastLine == "")
{
this.displayText.AppendText("Ans");
number_List.Add(prev_Answer);
this.displayText.AppendText(x);
OutputSymbol(x);
key_Press = key_Press + 4;
}
else
{
if (number_Initial == 0)
{
this.displayText.AppendText(x);
OutputSymbol(x);
key_Press++;
}
else
{
number_List.Add(number_Initial);
this.displayText.AppendText(x);
OutputSymbol(x);
number_Initial = 0;
key_Press++;
}
}
}
private void SymbolPressedKeyboard(String x)
{
if (lastLine == "")
{
this.displayText.AppendText("Ans");
number_List.Add(prev_Answer);
OutputSymbol(x);
key_Press = key_Press + 4;
}
else
{
if (number_Initial == 0)
{
OutputSymbol(x);
key_Press++;
}
else
{
number_List.Add(number_Initial);
OutputSymbol(x);
number_Initial = 0;
key_Press++;
}
}
}
//Display____________________________________________________________________________________________________________________________________________________
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
maxLines = displayText.LineCount;
if(maxLines > 0)
{
lastLine = displayText.GetLineText(maxLines - 1);
}
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
//check to see if what the user presses is a number or one of the appropriate symbols allowed
//if not sets valid to false
valid = true;
if(e.Key < Key.D0 || e.Key > Key.D9)
{
if(e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
{
valid = false;
if (e.Key == Key.Add || e.Key == Key.Subtract || e.Key == Key.Multiply || e.Key == Key.Divide || e.Key == Key.Enter)
{
valid = true;
}
}
}
if(valid == true)
{
//Performing functions when a certain key is pressed
switch (e.Key)
{
case Key.NumPad0:
case Key.D0:
NumPressedKeyboard(0);
break;
case Key.NumPad1:
case Key.D1:
NumPressedKeyboard(1);
break;
case Key.NumPad2:
case Key.D2:
NumPressedKeyboard(2);
break;
case Key.NumPad3:
case Key.D3:
NumPressedKeyboard(3);
break;
case Key.NumPad4:
case Key.D4:
NumPressedKeyboard(4);
break;
case Key.NumPad5:
case Key.D5:
NumPressedKeyboard(5);
break;
case Key.NumPad6:
case Key.D6:
NumPressedKeyboard(6);
break;
case Key.NumPad7:
case Key.D7:
NumPressedKeyboard(7);
break;
case Key.NumPad8:
case Key.D8:
NumPressedKeyboard(8);
break;
case Key.NumPad9:
case Key.D9:
NumPressedKeyboard(9);
break;
case Key.Add:
SymbolPressedKeyboard("+");
break;
case Key.Subtract:
SymbolPressedKeyboard("-");
break;
case Key.Divide:
SymbolPressedKeyboard("/");
break;
case Key.Multiply:
SymbolPressedKeyboard("*");
break;
case Key.Enter:
Equals_Equation();
break;
}
}
else if(valid == false)
{
MessageBox.Show("Please enter only numbers.");
//displayText.Text = displayText.Text.Remove(displayText.Text.Length - 1);
}
}
//Display____________________________________________________________________________________________________________________________________________________
//Numbers ___________________________________________________________________________________________________________________________________________________
private void _0_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(0);
}
private void _1_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(1);
}
private void _2_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(2);
}
private void _3_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(3);
}
private void _4_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(4);
}
private void _5_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(5);
}
private void _6_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(6);
}
private void _7_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(7);
}
private void _8_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(8);
}
private void _9_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(9);
}
//Numbers____________________________________________________________________________________________________________________________________________________
//Equations__________________________________________________________________________________________________________________________________________________
private void Divide_Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("/");
}
private void Multiply_Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("*");
}
private void Subtract_Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("-");
}
private void Add__Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("+");
}
protected void Equals_Equation()
{
if(equations.Count != 0)
{
if(this.displayText.Text.StartsWith("1") || this.displayText.Text.StartsWith("2") || this.displayText.Text.StartsWith("3") || this.displayText.Text.StartsWith("4") || this.displayText.Text.StartsWith("5") || this.displayText.Text.StartsWith("6") || this.displayText.Text.StartsWith("7") || this.displayText.Text.StartsWith("8") || this.displayText.Text.StartsWith("9") || this.displayText.Text.StartsWith("0"))
{
number_List.Add(number_Initial);
this.displayText.AppendText("\n");
//loop that goes through the equations list and does the appropriate calculations
//Does Multiplication and Division first
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "mul")
{
number_List[s] = number_List[s] * number_List[s + 1];
}
else if (equations[s] == "div")
{
number_List[s] = number_List[s] / number_List[s + 1];
}
}
//Then does Addition and Subtraction next
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "add")
{
number_List[0] = number_List[0] + number_List[s + 1];
}
else if (equations[s] == "sub")
{
number_List[0] = number_List[0] - number_List[s + 1];
}
}
//changes the display to show the answer and creates a new line for the user to continue
this.displayText.Text += number_List[0];
number_Initial = number_List[0];
number_List.Clear();
prev_Answer = number_Initial;
//number_List.Add(number_Initial);
number_Initial = 0;
equations.Clear();
this.displayText.AppendText("\n");
this.displayText.PageDown();
displayText.Select(displayText.Text.Length, 0);
}
else if (this.displayText.Text.StartsWith("A"))
{
number_List.Insert(0, prev_Answer);
number_List.Add(number_Initial);
this.displayText.AppendText("\n");
//loop that goes through the equations list and does the appropriate calculations
//Does Multiplication and Division first
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "mul")
{
number_List[s] = number_List[s] * number_List[s + 1];
}
else if (equations[s] == "div")
{
number_List[s] = number_List[s] / number_List[s + 1];
}
}
//Then does Addition and Subtraction next
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "add")
{
number_List[0] = number_List[0] + number_List[s + 1];
}
else if (equations[s] == "sub")
{
number_List[0] = number_List[0] - number_List[s + 1];
}
}
//changes the display to show the answer and creates a new line for the user to continue
this.displayText.Text += number_List[0];
number_Initial = number_List[0];
number_List.Clear();
prev_Answer = number_Initial;
//number_List.Add(number_Initial);
number_Initial = 0;
equations.Clear();
this.displayText.AppendText("\n");
this.displayText.PageDown();
displayText.Select(displayText.Text.Length, 0);
}
}
else
{
}
key_Press = 0;
}
private void Equals_Click(object sender, RoutedEventArgs e)
{
Equals_Equation();
}
//Clears all stored data so the user can start from scratch
private void Clear_Click(object sender, RoutedEventArgs e)
{
number_List.Clear();
number_Initial = 0;
equations.Clear();
this.displayText.Clear();
key_Press = 0;
}
//Equations__________________________________________________________________________________________________________________________________________________
}
}
I havent found much that has helped with only allowing the user to edit the current line. I see a lot with not allowing the user to edit the whole textBox.
I want the user to only be able to edit the current line. Right know I can use the arrow keys or click with my mouse on the previous lines and can edit them and I dont want them to be allowed to do this.
Here is a quick example. Hopefully this gives you enough info.
XAML
<TextBox
AcceptsReturn="True"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto"
PreviewTextInput="TextBox_PreviewTextInput"/>
Code Behind
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (sender is not TextBox box) //semi-redundant safety check
return;
//make sure there is text, also make sure there is a newline in the box
if (string.IsNullOrEmpty(box.Text) || (!box.Text.Contains('\n') && !box.Text.Contains('\r')))
return;
//through some testing I found the \r would be there without a \n so I include both for completeness
var lastReturn = Math.Max(box.Text.LastIndexOf('\r'), box.Text.LastIndexOf('\n'));
if (box.CaretIndex <= lastReturn)
e.Handled = true;
}
This solution can be expanded on, but it mainly prevents the Text from changing whenever Text is entered on any line but the last. I like it as you can also move the Text Caret around to get standard functionality still (highlighting, selection, etc.)
I am trying to access RFID Reader through Arduino application which gives me the right output on control monitor.
But when I tried to access it through visual studio C#, it works only once and then gives me access is denied! And also stopped working on Arduino IDE.
//Function to initialize serial port
SerialPort RFIDPort
public SerialPort initializeRFIDPort()
{
try
{
RFIDPort = new SerialPort("COM4",9600,Parity.None,8, StopBits.One);
if (RFIDPort.IsOpen)
RFIDPort.Close();
if(!RFIDPort.IsOpen)
RFIDPort.Open();
}
catch (UnauthorizedAccessException ex) {MessageBox.Show( ex.Message); }
catch (Exception)
{
RFIDPort = null;
}
return RFIDPort;
}
I put the function here:
public products()
{
InitializeComponent();
initializeRFIDPort();
}
There is two scan button the first one for scanning and then add data to the database and the second button is to scan and search for data
private void ScanButton_Click(object sender, EventArgs e)
{
try
{
scanButtonIsClicked = true;
if (RFIDPort.IsOpen)
{
RFIDPort.DataReceived += serialPort1_DataReceived;
textBox1.Text = "";
}
else
MessageBox.Show("RFID Reader is not connected!");
}
catch (System.Exception)
{
MessageBox.Show("Please Try Again");
}
}
private void Searchbutton_Click(object sender, EventArgs e)
{
scansearchbtn = true;
scanButtonIsClicked = false;
try
{
if (RFIDPort.IsOpen)
{
RFIDPort.DataReceived += serialPort1_DataReceived;
textBox2.Text = "";
}
else
{
MessageBox.Show("RFID Reader is not connected!");
}
}
catch (IOException)
{
MessageBox.Show("Please reconnect your device ");
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
string line = RFIDPort.ReadLine();
if (scanButtonIsClicked == true)
this.BeginInvoke(new LineReceivedEvent(LineReceived), line);
else
this.BeginInvoke(new LineReceivedEvent(Line2Received), line);
}
catch (TimeoutException) { }
catch (Exception){ MessageBox.Show("Can't Read from RFID Device.Please try again"); }
}
private delegate void LineReceivedEvent(string line);
private void LineReceived(string line)
{
textBox2.Text = line;
}
private void Line2Received(string line)
{
textBox1.Text = line;
}
And then I closed serial port in Forum-Closing.
Please if anyone can lead me to the right way. I have try many times and it works randomly!
On Aruino side this is my code:
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class
MFRC522::MIFARE_Key key;
// Init array that will store new NUID
byte nuidPICC[10];
void setup()
{
Serial.begin(9600);
SPI.begin(); // Init SPI bus
rfid.PCD_Init(); // Init MFRC522
for (byte i = 0; i < 6; i++)
{
key.keyByte[i] = 0xFF;
}
printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
Serial.println();
}
void loop()
{
if ( ! rfid.PICC_IsNewCardPresent())
return;
if ( ! rfid.PICC_ReadCardSerial())
return;
// Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
// Serial.println(rfid.PICC_GetTypeName(piccType));
// Check is the PICC of Classic MIFARE type
if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType !=
MFRC522::PICC_TYPE_MIFARE_1K && piccType != MFRC522::PICC_TYPE_MIFARE_4K)
{
Serial.println(F("Your tag is not of type MIFARE Classic."));
return;
}
// Store NUID into nuidPICC array
for (byte i = 0; i < 4; i++)
{
nuidPICC[i] = rfid.uid.uidByte[i];
}
printHex(rfid.uid.uidByte, rfid.uid.size);
Serial.println();
// Halt PICC
rfid.PICC_HaltA();
// Stop encryption on PCD
rfid.PCD_StopCrypto1();
}
void printHex(byte *buffer, byte bufferSize)
{
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This code should monitor the user's keystrokes and stops him if s\he types a the wrong character .Yet when it comes to the if statement where it should compare to charecter everything just goes wrong
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.Diagnostics;
using System.Threading;
using System.Collections;
using System.IO;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
void Rest()
{
counter = -1;
txt1.Enabled = true;
txt2.Enabled = true;
txt3.Enabled = true;
txt4.Enabled = false;
txt5.Enabled = true;
btn2.Enabled = false;
btn1.Enabled = true;
pass = "";
txt4.Clear();
Dic.Clear();
turns = 0;
}
string path;
int counter = -1;
string pass;
Dictionary<char, letterInfo> Dic;
int turns = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (counter < pass.Length) { MessageBox.Show("WrongInput(Shorter) !!! "); Rest(); }
else
{
turns++;
if (turns == Convert.ToInt32(txt1.Text))
{
MessageBox.Show("Test is Done ");
/*Writting files */
Rest();
}
}
}
counter++;
if (counter >= pass.Length) { MessageBox.Show("WrongInput !!!exceded length "); Rest(); }
if ((char)e.KeyValue != pass[counter]) { MessageBox.Show("WrongInput !!!Wrong charecter " + ((char)e.KeyValue).ToString() + " " + pass[counter].ToString()); Rest(); }
if (Dic.ContainsKey((char)e.KeyValue))
{
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
else
{
Dic.Add((char)e.KeyValue, new letterInfo());
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
Dic[(char)e.KeyValue].end.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
private void button1_Click(object sender, EventArgs e)
{
string start = "";
string end = "";
string letter = "";
string all;
foreach (KeyValuePair<char, letterInfo> pair in Dic)
{
start = start + " " + pair.Value.start[0];
end = end + " " + pair.Value.end[0];
letter = letter + " " + pair.Key;
}
all = letter + "\n" + start + "\n" + end;
MessageBox.Show(all);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
txt1.Enabled = false;
txt2.Enabled = false;
txt3.Enabled = false;
txt4.Enabled = true;
txt5.Enabled = false;
btn2.Enabled = true;
btn1.Enabled = false;
pass = txt2.Text;
path = txt3.Text;
counter = Convert.ToInt32(txt1.Text);
Dic = new Dictionary<char, letterInfo>();
/* if (!File.Exists(path))
{
MessageBox.Show("Error..File not found");
Rest();
}Code to handle the xls files */
}
catch (Exception s)
{ MessageBox.Show(s.Message); }
}
}
}
This is the function where the problem occurs
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (counter < pass.Length)
{
MessageBox.Show("WrongInput(Shorter) !!! "); Rest();
}
else
{
turns++;
if (turns == Convert.ToInt32(txt1.Text))
{
MessageBox.Show("Test is Done ");
/*Writting files */
Rest();
}
}
}
counter++;
if (counter >= pass.Length)
{
MessageBox.Show("WrongInput !!!exceded length "); Rest();
}
if ((char)e.KeyValue != pass[counter])
{
MessageBox.Show("WrongInput !!!Wrong charecter "+((char)e.KeyValue).ToString()+" "+pass[counter].ToString()); Rest();
}
if (Dic.ContainsKey((char)e.KeyValue))
{
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
else
{
Dic.Add((char)e.KeyValue, new letterInfo());
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
}
And those are the problematic if statements
counter++;
if (counter >= pass.Length)
{
MessageBox.Show("WrongInput !!!exceded length "); Rest();
}
if ((char)e.KeyValue != pass[counter])
{
MessageBox.Show("WrongInput !!!Wrong charecter "+((char)e.KeyValue).ToString()+" "+pass[counter].ToString()); Rest();
}
You enter into if (counter >= pass.Length) because:
counter = -1; //starts at -1
pass = ""; //starts at empty string (length of zero)
Neither of these variables change in your code until:
counter++; //counter is now 0
counter is now equal to pass.Length. So the if statement is true and "WrongInput !!!exceded length " is printed.
You dont set the value of pass until button 2 is clicked. So on each keypress event that is fired, the pass value is empty.
In if ((char)e.KeyValue != pass[counter]) you are trying to compare the key entered, with the character number in pass. pass is empty and counter increments until you hit button 2. So e.Keyvalue will not equal pass[counter] every time.
I made this windows forms application in .net 3.5 (VS c# express) .
Now I want to convert it so it can run with just .net 2.0 installed. SO in my project properties: I selected "target framework " as 2.0 , fixed the errors that I got.
After this the app runs fine with .net 3.0 installed , but won't run on a fresh install of xp with with .net 2.0 installed. "Application has crashed. send error report"
What do I do ? I want this thing to run under 2.0.
here is the code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int numberOfMatches = 0;
string[,] data;
bool update = true ;
string fileToParse = Path.GetTempPath() + "cricketfile.xml";
int matchToShow = 0;
bool showschedule = true ;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd,
int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public Form1()
{
InitializeComponent();
if (Environment.OSVersion.Version.Major <= 5)
{
// MessageBox.Show("xp");
}
else
{
label1.Top = 1;
pictureBox1.Top = 1;
}
// label1.Left = 1;
int X = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2;
this.Location = new System.Drawing.Point(X, -5);
if (rkApp.GetValue("cricketscore") == null)
{
startWithWindowsToolStripMenuItem.Checked = false ;
}
else
{
startWithWindowsToolStripMenuItem.Checked = true ;
}
this.Region = new Region(new Rectangle(10, 10, 197, 17));
ToolTip tooltip = new ToolTip();
// MessageBox.Show(" F" + tooltip.AutomaticDelay);
tooltip.AutomaticDelay = 0;
tooltip.InitialDelay = 0;
tooltip.SetToolTip(pictureBox1, " right click for settings, left click to move");
tooltip.SetToolTip(label1, " right click for settings, left click to move");
fetchData();
addContextEntries();
chooseIndia();
updateScore();
// MessageBox.Show(data.GetLength(0).ToString());
//foreach (string s in data)
//{
// Console.WriteLine(s);
//}
timer1.Interval = 20 * 1000;
timer1.Enabled = true;
}
public void addContextEntries()
{
// MessageBox.Show("num- " + numberOfMatches);
List<ToolStripMenuItem> Mylist1 = new List<ToolStripMenuItem>();
for (int i = 0; i < numberOfMatches; i++)
{
Mylist1.Add( new ToolStripMenuItem() );
this.contextMenuStrip1.Items.Add(Mylist1[i]);
Mylist1[i].Text = "See Match " + (i + 1) + "'s score";
switch(i)
{
case 0:
Mylist1[i].Click += new System.EventHandler(this.match1);
break;
case 1:
Mylist1[i].Click += new System.EventHandler(this.match2);
break;
case 2:
Mylist1[i].Click += new System.EventHandler(this.match3);
break;
case 3:
Mylist1[i].Click += new System.EventHandler(this.match4);
break;
case 4:
Mylist1[i].Click += new System.EventHandler(this.match5);
break;
}
}
}
public void match1(object sender, EventArgs e)
{
// MessageBox.Show("match 1");
matchToShow = 0;
label1.Text = data[0, 0] + " " + data[0, 1];
}
public void match2(object sender, EventArgs e)
{
// MessageBox.Show("match 2");
matchToShow = 1;
label1.Text = data[1, 0] + " " + data[1, 1];
}
public void match3(object sender, EventArgs e)
{
matchToShow = 2;
label1.Text = data[2, 0] + " " + data[2, 1];
}
public void match4(object sender, EventArgs e)
{
matchToShow = 3;
label1.Text = data[3, 0] + " " + data[3, 1];
}
public void match5(object sender, EventArgs e)
{
matchToShow = 4;
label1.Text = data[4, 0] + " " + data[4, 1];
}
public void chooseIndia()
{
try
{
for (int i = 0; i < data.GetLength(0); i++)
{
// MessageBox.Show("i - " + i);
if (data[i, 3].ToLower().Contains("india"))
{
matchToShow = i;
// MessageBox.Show("i - " + i);
break;
}
}
}
catch (NullReferenceException ne)
{
}
}
public void updateScore()
{
fetchData();
if (update == true)
{
try
{
label1.Text = data[matchToShow, 0] + " " + data[matchToShow, 1];
}
catch (Exception e)
{
}
}
}
public void fetchData()
{
int matchnumber = -1;
numberOfMatches = 0;
WebClient Client = new WebClient();
try
{
Client.DownloadFile("http://synd.cricbuzz.com/score-gadget/gadget-scores-feed.xml", fileToParse);
}
catch (WebException we)
{
// if (we.ToString().ToLower().Contains("connect to"))
// MessageBox.Show("sdf");
label1.Text = "No Internet";
update = false ;
this.Update();
// System.Threading.Thread.Sleep(1000);
}
try
{
XmlTextReader xmlreader0 = new XmlTextReader(fileToParse);
while (xmlreader0.Read())
{
if (xmlreader0.Name.ToString() == "match" && xmlreader0.NodeType == XmlNodeType.Element)
{
++numberOfMatches;
}
}
data = new string[numberOfMatches, 4];
// numberOfMatches = 0;
// MessageBox.Show("matchnumbers - " + numberOfMatches);
// MessageBox.Show("asd");
XmlTextReader xmlreader = new XmlTextReader(fileToParse);
while (xmlreader.Read())
{
// MessageBox.Show("READING");
if (xmlreader.Name.ToString() == "header" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
data[matchnumber, 0] = xmlreader.Value;
// MessageBox.Show(xmlreader.Value);
}
if (xmlreader.Name == "description" && xmlreader.NodeType == XmlNodeType.Element)
{
// MessageBox.Show(xmlreader.Value);
xmlreader.Read();
// MessageBox.Show("matched - " + xmlreader.Value);
data[matchnumber, 1] = xmlreader.Value;
}
if (xmlreader.Name == "url-text" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
// MessageBox.Show(xmlreader.Value);
data[matchnumber, 2] = xmlreader.Value;
}
if (xmlreader.Name == "url-link" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
data[matchnumber, 3] = xmlreader.Value;
}
if (xmlreader.Name.ToString() == "match" && xmlreader.NodeType == XmlNodeType.Element)
{
matchnumber++;
showFullScorecardToolStripMenuItem.Text = "Show full scorecard";
showschedule = true;
update = true;
}
if (xmlreader.Name.ToString() == "nextlive" && xmlreader.NodeType == XmlNodeType.Element)
{
label1.Text = "No current match";
showFullScorecardToolStripMenuItem.Text = "Show Schedule";
showschedule = false;
update = false;
break;
}
}
xmlreader.Close();
xmlreader0.Close();
}
catch (FileNotFoundException fe)
{
// MessageBox.Show("no internet");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
updateScore();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void switchColrosToolStripMenuItem_Click(object sender, EventArgs e)
{
if ( label1.ForeColor == System.Drawing.Color.Black)
label1.ForeColor = System.Drawing.Color.White ;
else
label1.ForeColor = System.Drawing.Color.Black;
}
private void startWithWindowsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void startWithWindowsToolStripMenuItem_CheckStateChanged(object sender, EventArgs e)
{
if (startWithWindowsToolStripMenuItem.Checked == true)
{
rkApp.SetValue("cricketscore", Application.ExecutablePath.ToString());
}
else
{
rkApp.DeleteValue("cricketscore", false);
}
}
private void showFullScorecardToolStripMenuItem_Click(object sender, EventArgs e)
{
if ( showschedule == true )
System.Diagnostics.Process.Start(data[matchToShow, 3]);
else
System.Diagnostics.Process.Start("http://www.cricbuzz.com/component/cricket_schedule/");
}
private void label1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
//public void findNumberOfMatches()
//{
// if (xmlreader.Name.ToString() == "match" && xmlreader.NodeType == XmlNodeType.Element)
// {
// matchnumber++;
// }
//}
}
}
Thanks
The way it closes doesn't look like need to upgrade the framework but lets see those:
Try to test it under .NET 2.0 with latest .NET 2.0 service pack installed
Try to check the references in your project whether they're all clean to .NET 2.0 or not, sometimes this is not done correctly. Press F4 of every assembly that has 2.0 and 3.x versions to see properties and confirm (and remove/add if needed). If you see anything like LINQ or so, this needs to be removed.
Try to bring Visual C# 2005 Express or similar and see if the code compiles under it. Or create new .NET 2.0 project and copy your code to it.