问题描述
我正在开发一个Project,当您在MFRC522阅读器上传递picc时,它会验证WPF应用程序中的UID。每次我尝试它看起来似乎没有认出picc。
该程序理论上应该像这样工作:
Arduino MFRC522防护罩寻找picc,它找到一个获取uid并在串口中打印它。
然后,c#programm读取串口中的内容并将其保存在变量中。一个void,然后它验证该变量是否与UID匹配'if'循环,如果匹配特定的UID,如果它没有发送'no',则发送到端口'ok'。
我的程序,知道uid是什么,并将其复制到必须验证它的地方,总是发送没有。
我尝试过:
这是我的arduino代码:
Hi, I´m working on a Project, that verifies a UID in a WPF application when you pass a picc on the MFRC522 reader. Every time I´ve tried it looks like it didn´t recognised the picc.
The programm should theoretically work like this:
The Arduino MFRC522 shield looks for a picc, when it finds one it gets the uid and print it in the serial port.
The c# programm, then, reads what´s in the serial port and saves it in a variable. A void, then it verifies if that variable matches the UID with a 'if' loop and if matches a specific UID, sends to the port 'ok' if it doesn´t it sends 'no'.
And my programm, knowing what the uid is, and copying it to where it has to verify it, sends always no.
What I have tried:
Here is my arduino code:
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
MFRC522 nfc(SS_PIN, RST_PIN); // Create nfc instance.
MFRC522::MIFARE_Key key;
String dato;
void setup()
{
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
nfc.PCD_Init(); // Init nfc car
}
void loop()
{
if(Serial.available()){
delay(100);
while(Serial.available() > 0){
// statement
dato = Serial.readString();
}
}
if(dato == "ok"){
admited();
dato = "";
}
if(dato == "no"){
noAdmited();
dato = "";
}
if ( ! nfc.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! nfc.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
Serial.println();
for (byte i = 0; i < nfc.uid.size; i++) {
Serial.print(nfc.uid.uidByte[i] < 0x10 ? "0" : "");
Serial.print(nfc.uid.uidByte[i], HEX);
}
delay(500);
}
void admited()
{
Serial.println();
Serial.println("The picc is been admited");
}
void noAdmited()
{
Serial.println();
Serial.println("The hasn´t been admiteed ");
}
这是我的c#代码:
and here is my c# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Threading;
namespace nfc_to_wpf
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SerialPort port1 = new SerialPort();
private delegate void SetTextDeleg(string text);
string data_saved;
string data2;
public MainWindow()
{
InitializeComponent();
loadConnections();
}
private void loadConnections()
{
port1.BaudRate = 9600;
port1.PortName = "COM7";
try
{
port1.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
recieveData();
}
private void recieveData()
{
if (port1.IsOpen == true)
{
port1.DataReceived += port1_DataReceived;
}
}
void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(100);
try
{
string data = port1.ReadLine();
Dispatcher.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// Invokes the delegate on the UI thread, and sends the data that was received to the invoked method.
// ---- The "si_DataReceived" method will be executed on the UI thread which allows populating of the textbox.
}
private void si_DataReceived(string data) //Modifica la entrada del serial a legible
{
data_saved = data;
tb1.Text = data_saved;
tryToSend();
}
private void tryToSend()
{
if (port1.IsOpen == true)
{
if (data_saved == "239A0701")
{
port1.Write("ok");
tb1.Text = "Sended ok";
tb1.Text = data_saved;
data2 = data_saved;
tb2.Text = data2;
}
else
{
tb1.Text = "Sended no";
data2 = data_saved;
tb2.Text = data2;
}
}
}
}
}
所以你可以看到,当arduino读取一个picc时,它获取UID并将其打印在SerialPort中。当c#programm接收数据时,从端口(也就是uid)验证它并且它是否与UID匹配:239A0701它向端口发送'ok',如果不是,则向端口发送'no'。但它总是(在我的程序中),我现在不知道,发送否,并且从不匹配uid(知道我正在使用的picc有那个uid(239A0701));
请帮助我;谢谢!!
So as you can see, when the arduino reads a picc, it gets the UID and prints it in the SerialPort. When the c# programm receives data, from the port (which is the uid) verifies it and if it matches the UID: 239A0701 it send 'ok' to the port and if it doesn´t it sends 'no' to the port. But it always (in my programm), and I don´t now why, sends no, and never matches the uid (knowing that the picc I´m using has that uid (239A0701));
Please, help me; Thank You!!
推荐答案
Serial.println()
(告诉程序执行回车和换行)你必须把
(which tells the program to do a carriage return and a new line) you have to put
Serial.print("\n");
只创建新行,问题解决了。
所以arduino代码应该会结束喜欢这个
which only creates the new line, problema solved.
So the arduino code should end up like this
#include <spi.h>
#include <mfrc522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
MFRC522 nfc(SS_PIN, RST_PIN); // Create nfc instance.
MFRC522::MIFARE_Key key;
String uid;
byte try1[5];
String dato;
int number;
byte readCard[1];
void setup()
{
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
nfc.PCD_Init(); // Init nfc car
}
void loop()
{
if(Serial.available()){
delay(100);
while(Serial.available() > 0){
// statement
dato = Serial.readString();
}
}
if(dato == "ok"){
admited();
dato = "";
}
if(dato == "no"){
noAdmited();
dato = "";
}
if ( ! nfc.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! nfc.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
int contador = 0;
for (byte i = 0; i < nfc.uid.size; i++) {
contador++;
Serial.print(nfc.uid.uidByte[i] < 0x10 ? "0" : "");
Serial.print(nfc.uid.uidByte[i], HEX);
if(contador == 4){
Serial.print("\n");
}
}
delay(500);
}
void admited()
{
Serial.println("La tarjeta ha sido admitida");
}
void noAdmited()
{
Serial.println("La tarjeta no ha sido admitida");
}
c#夏普代码还可以,但你可以删除一些不必要的东西... c#代码最终会像:
And the c# Sharp code is ok but you can remove some uneccesary things... The c# code would end up like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using try1.Properties;
using System.Threading;
namespace try1
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SerialPort port1 = new SerialPort();
SerialPort port2 = new SerialPort();
string port1_com = Settings.Default.com_port_1;
int port1_baud_rate = Settings.Default.baud_port_1;
private delegate void SetTextDeleg(string text);
string data_saved;
string button_1_data = Settings.Default.button1_data;
string button_2_data = Settings.Default.button2_data;
string button_3_data = Settings.Default.button3_data;
string button_4_data = Settings.Default.button4_data;
string uid = Settings.Default.uid;
string choosen_button;
string completed_uid;
public MainWindow()
{
InitializeComponent();
loadSetup();
loadPort1();
proveUID();
loadButtonsOnComboxAndloadButtons();
serialPortReceiving();
serialPortSending();
}
private void proveUID() //Void para verficar el UID de las tarjetas
{
if (port1.IsOpen == true) //Si el puerto está abierto
{
pb_sending.IsIndeterminate = false; //Interfaz
pb_sending.Value = 10;
if (uid == "239A0701") //Si el uid se corresponde a el de la tarjeta
{
port1.Write("ok"); //Enviar por el serial 'ok'
lb_serial_sending.Content = "";
lb_serial_sending.Content = "Sended 'ok' to serial";
}
else //Si no
{
}
}
}
private void loadButtonsOnComboxAndloadButtons() //Añade los botones al comboBox y añade el setup de estos, pertenece a la interfaz gráfica
{
cb_choose_button.Text = choosen_button;
cb_choose_button.Items.Add("Button1");
cb_choose_button.Items.Add("Button2");
cb_choose_button.Items.Add("Button3");
cb_choose_button.Items.Add("Button4");
if (button_1_data == "")
{
button1.Content = "Button1";
}
else
{
button1.Content = button_1_data;
}
if (button_2_data == "")
{
button2.Content = "Button2";
}
else
{
button2.Content = button_2_data;
}
if (button_3_data == "")
{
button3.Content = "Button3";
}
else
{
button3.Content = button_3_data;
}
if (button_4_data == "")
{
button4.Content = "Button4";
}
else
{
button4.Content = button_4_data;
}
}
private void serialPortSending() //Configura el pb_sending, pertenece a la interfaz gráfica
{
if (port1.IsOpen == true) //Mientras el puerto está abierto
{
pb_sending.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Violet);
pb_sending.IsIndeterminate = true;
}
if (port1.IsOpen == false) //Mientras el puerto está cerrado
{
pb_sending.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Red);
pb_sending.IsIndeterminate = true;
}
}
private void serialPortReceiving() //Busca si el serial port1 escribe algo
{
pb_receiving.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Turquoise);
pb_receiving.IsIndeterminate = true;
if (port1.IsOpen == true) //Mientras el puerto esté abierto
{
port1.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); //Cuando recibe información del serial genera un evento con una string
}
if (port1.IsOpen == false) //Mientras el puerto este cerrado
{
pb_receiving.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Red);
pb_receiving.IsIndeterminate = true;
}
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) //Si recibe data del serial
{
Thread.Sleep(100);
try //Prueba
{
string data = port1.ReadLine(); //Lee una línea del serial y la pasa a string (variable local)
Dispatcher.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data }); //Pasar variable local a variable general (no arduino eventhandler string)
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); //Muestra errores
}
}
private void si_DataReceived(string data) //Modifica la entrada del serial a legible
{
uid = "";
data_saved = "";
data_saved = data; //Pasa la información en data a una variable global (dispacher generated)
tb_data.Text = data_saved;
uid = data; //Pasa la información en data a una variable global (utilizada solo en el reconociemiento de tarjetas)
lb_serial_port.Content = "";
lb_serial_port.Content = data_saved;
pb_receiving.IsIndeterminate = true;
proveUID(); //Llama al void proveUID()
}
private void loadSetup() //Carga la interfaz gráfica predeterminada
{
if (port1.IsOpen == false)
{
pb_connection_1.IsIndeterminate = true;
}
cb_port_1.Text = port1_com;
cb_baud_rate_1.Text = port1_baud_rate.ToString();
lb_status_1.Content = "";
lb_status_1.Content = "Last save port '" + port1_com + "' and baud rate '" + port1_baud_rate + "'";
bt_close_port1.IsEnabled = false;
lb_serial_sending.Content = "";
lb_serial_port.Content = "";
}
private void loadPort1() //Load com ports and baudrates of port 1
{
cb_port_1.Items.Clear();
cb_baud_rate_1.Items.Clear();
foreach (string ports_1 in SerialPort.GetPortNames())
{
cb_port_1.Items.Add(ports_1);
}
cb_baud_rate_1.Items.Add("300");
cb_baud_rate_1.Items.Add("1200");
cb_baud_rate_1.Items.Add("2400");
cb_baud_rate_1.Items.Add("4800");
cb_baud_rate_1.Items.Add("9600");
cb_baud_rate_1.Items.Add("19200");
cb_baud_rate_1.Items.Add("38400");
cb_baud_rate_1.Items.Add("57600");
cb_baud_rate_1.Items.Add("115200");
cb_baud_rate_1.Items.Add("230400");
cb_baud_rate_1.Items.Add("250000");
}
private void cb_port_1_DropDownClosed(object sender, EventArgs e) //Reacciona cuando se cierra el combo box que elige los puertos de port1
{
if (cb_port_1.SelectedItem != null) //Si has seleccionado algo
{
port1_com = cb_port_1.SelectedItem.ToString(); //Guarda lo que has seleccionado a un string
Settings.Default.com_port_1 = port1_com; //Guardar en la memoria a largo plazo de la aplicación
Settings.Default.Save(); //Guarda cualquier dato de tipo Settings.Default.
lb_status_1.Content = "";
lb_status_1.Content = "You selected " + port1_com;
cb_port_1.Text = port1_com;
}
else //Si no
{
MessageBox.Show("You hav to choose something");
}
}
private void cb_baud_rate_1_DropDownClosed(object sender, EventArgs e) //Reacciona cuando se cierra el cb que elige el baud rate del port1
{
if (cb_baud_rate_1.SelectedItem != null) //Si has seleccionado algo
{
port1_baud_rate = int.Parse(cb_baud_rate_1.Text); //Seleccion -> Int32 -> variable
Settings.Default.baud_port_1 = port1_baud_rate; //Guarda en la memoria a largo plazo
Settings.Default.Save(); //Guarda todo lo que sea Settings.Default.
lb_status_1.Content = "";
lb_status_1.Content = "You selected " + port1_baud_rate;
cb_baud_rate_1.Text = port1_baud_rate.ToString();
}
else //Si no
{
MessageBox.Show("You have to select something");
}
}
private void bt_connect_1_Click(object sender, RoutedEventArgs e) //Reacciona cuando se pulsa el bt de conectar
{
conneciont_on_port1();
}
private void conneciont_on_port1() //se intenta connectar a port1
{
pb_connection_1.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Green);
pb_connection_1.IsIndeterminate = true;
if (port1_com != "")
{
if (port1_baud_rate.ToString() != "")
{
try //Conexión al port1
{
lb_status_1.Content = "";
lb_status_1.Content = "Trying to connect " + port1_com + " at " + port1_baud_rate + " baud rate";
port1.BaudRate = port1_baud_rate; //El BaudRate es = a la variable port1_baud_rate
port1.PortName = port1_com;//El puerto es = a la variable port1_com
port1.Open(); //Abre el puerto port1 (definido al principio)
serialPortSending(); //Llama al void serialPortSending
serialPortReceiving();
pb_connection_1.IsIndeterminate = false;
pb_connection_1.Value = 10;
lb_status_1.Content = "";
lb_status_1.Content = "Connected succesfully";
bt_connect_1.IsEnabled = false;
bt_close_port1.IsEnabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
pb_connection_1.IsIndeterminate = false;
pb_connection_1.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Red);
pb_connection_1.Value = 10;
lb_status_1.Content = "";
lb_status_1.Content = ex.Message;
bt_connect_1.IsEnabled = true;
bt_close_port1.IsEnabled = false;
}
}
}
else //Si no
{
if (port1_com == "") //Excepciones
{
MessageBox.Show("You didn´t select a 'COM' port, please select one");
}
else if (port1_baud_rate.ToString() == "")
{
MessageBox.Show("You have to select a 'BAUD' rate");
}
}
}
private void bt_close_port1_Click(object sender, RoutedEventArgs e) //Intenta cerrar port1
{
close_port_1(); //Llama al void que cierra el puerto
}
private void close_port_1() //Void de cerrado del port
{
if (port1.IsOpen == true)
{
try
{
port1.Close(); //Cierra el puerto
lb_status_1.Content = "";
lb_status_1.Content = "The port has been closed succesfully";
pb_connection_1.IsIndeterminate = false;
pb_connection_1.Foreground = new SolidColorBrush(System.Windows.Media.Colors.DodgerBlue);
pb_connection_1.Value = 10;
bt_connect_1.IsEnabled = true;
bt_close_port1.IsEnabled = false;
serialPortReceiving();
serialPortSending();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
pb_connection_1.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Red);
pb_connection_1.Value = 10;
lb_status_1.Content = "";
lb_status_1.Content = ex.Message;
bt_connect_1.IsEnabled = false;
bt_close_port1.IsEnabled = true;
}
}
}
private void bt_refresh_port_1_Click(object sender, RoutedEventArgs e) //Vuelve a buscar puertos com
{
loadPort1(); //Llama al void que busca los puertos
pb_connection_1.IsIndeterminate = false;
pb_connection_1.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Coral);
pb_connection_1.Value = 10;
}
private void bt_send_Click(object sender, RoutedEventArgs e) //Envía el texto a el port1
{
if (port1.IsOpen == true)
{
if (tb_cmd.Text != "") //Para que no haya errores
{
try
{
pb_sending.IsIndeterminate = false;
pb_sending.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Violet);
pb_sending.Value = 10;
port1.Write(tb_cmd.Text); //Envía lo que haya en el tb
lb_serial_sending.Content = "";
lb_serial_sending.Content = "Sended " + tb_cmd.Text + " to serial port";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
lb_port1.Content = "";
lb_port1.Content = ex.Message;
pb_sending.IsIndeterminate = false;
pb_sending.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Red);
pb_sending.Value = 10;
}
}
}
else
{
lb_port1.Content = "";
lb_port1.Content = "You are not connected to any port";
}
}
private void tb_cmd_GotMouseCapture(object sender, MouseEventArgs e) //pb_sending action, interfaz gráfica
{
pb_sending.IsIndeterminate = true;
}
private void cb_choose_button_DropDownClosed(object sender, EventArgs e) //Guarda la seleccion del combo box para elegir el Button a una variable
{
if (cb_choose_button.SelectedItem != null) //Guarda la seleccion en una variable
{
choosen_button = cb_choose_button.Text;
lb_serial_port.Content = "";
lb_serial_port.Content = choosen_button + " was selected in the comboBox";
}
else
{
MessageBox.Show("You have to select something");
}
}
private void bt_set_cmd_as_Click(object sender, RoutedEventArgs e) //Establece el código al Button
{
choosen_buttonVoid();
}
private void choosen_buttonVoid() //Guarda la selección en una variable que será llamada cuando pulses ese botón
{
if (choosen_button != "")
{
if (choosen_button == "Button1")
{
if (tb_cmd.Text != "")
{
button_1_data = tb_cmd.Text; //Guarda en una variable lo que haya en el tb
lb_serial_port.Content = "Guardando " + button_1_data;
button1.Content = button_1_data; //La variable anterior la ponemos como nombre de el botón seleccionado
Settings.Default.button1_data = button_1_data;//Guardar en la memoria de larga distancia
Settings.Default.Save(); //Guardar todo lo que esté dentro de Settings.Default.
}
}
if (choosen_button == "Button2")
{
if (tb_cmd.Text != "")
{
button_2_data = tb_cmd.Text;
lb_serial_port.Content = "Guardando " + button_2_data;
button2.Content = button_2_data;
Settings.Default.button2_data = button_2_data;
Settings.Default.Save();
}
}
if (choosen_button == "Button3")
{
if (tb_cmd.Text != "")
{
button_3_data = tb_cmd.Text;
lb_serial_port.Content = "Guardando " + button_3_data;
button3.Content = button_3_data;
Settings.Default.button3_data = button_3_data;
Settings.Default.Save();
}
}
if (choosen_button == "Button4")
{
if (tb_cmd.Text != "")
{
button_4_data = tb_cmd.Text;
lb_serial_port.Content = "Guardando " + button_4_data;
button4.Content = button_4_data;
Settings.Default.button4_data = button_4_data;
Settings.Default.Save();
}
}
}
else
{
MessageBox.Show("Please, write the code on the textBox");
}
}
private void button1_Click(object sender, RoutedEventArgs e) //Si hay algo guardado en button1 enviar al serial
{
if (port1.IsOpen == true) //Si el puerto está abierto
{
if (button_1_data != "")
{
port1.Write(button_1_data); //Envia por el serial la variable button_1_data
lb_serial_sending.Content = "";
lb_serial_sending.Content = "Sended " + button_1_data + " to serial";
}
}
else
{
lb_serial_sending.Content = "";
lb_serial_sending.Content = "You have to connect to a port";
}
}
private void button2_Click(object sender, RoutedEventArgs e) //Si hay algo guardado en button2 enviar al serial
{
if (port1.IsOpen == true)
{
if (button_2_data != "")
{
port1.Write(button_2_data);
lb_serial_sending.Content = "";
lb_serial_sending.Content = "Sended " + button_2_data + " to serial";
}
}
else
{
lb_serial_sending.Content = "";
lb_serial_sending.Content = "You have to connect to a port";
}
}
private void button3_Click(object sender, RoutedEventArgs e)
{
if (port1.IsOpen == true)
{
if (button_3_data != "")
{
port1.Write(button_3_data);
lb_serial_sending.Content = "";
lb_serial_sending.Content = "Sended " + button_3_data + " to serial";
}
}
else
{
lb_serial_sending.Content = "";
lb_serial_sending.Content = "You have to connect to a port";
}
}
private void button4_Click(object sender, RoutedEventArgs e)
{
if (port1.IsOpen == true)
{
if (button_4_data != "")
{
port1.Write(button_4_data);
lb_serial_sending.Content = "";
lb_serial_sending.Content = "Sended " + button_4_data + " to serial";
}
}
else
{
lb_serial_sending.Content = "";
lb_serial_sending.Content = "You have to connect to a port";
}
}
}
}
by kardexx1 (the guy who asked the question) :).
by kardexx1 (the guy who asked the question) :).
这篇关于如何在wpf应用程序中验证mfrc522 arduino uid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!