int bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes); serialPort1.Open(); serialPort1.Close(); serialPort1.Write(byte[] buffer, offset, count); Donde offset es un byte inicial y count es el máximo de bytes que quieres enviar del arreglo buffer //////////////////////////////
//Variable global
List<byte> recibido = new List<byte>();
//////////////////////////////
//Abrir puerto COM14
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Open();
recibido.Clear();
}
//////////////////////////////
//Datos en el buffer
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
int bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes);
foreach(byte elem in buffer)
{
recibido.Add(elem);
}
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
//Guarda todo en archivo
if (File.Exists("Prueba.jpg"))
File.Delete("Prueba.jpg");
FileStream archivoP = new FileStream("Prueba.jpg",
FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter escribirP = new BinaryWriter(archivoP);
foreach(byte elem in recibido)
{
escribirP.Write(elem);
}
escribirP.Close();
archivoP.Close();
Process.Start("Prueba.jpg");
}
using System.IO; //Requerido para manejar archivos
btnBotoncito.Text="Apriétame";
string fila;
string[] datos;
datos = fila.Split(",".ToCharArray()); //Separa por comas
String cadena;
float flota;
flota = float.Parse(cadena);
Hola Sauron
Cuando llega un dato al buffer del puerto serial se detona un evento que VC# administra automáticamente. Cuando ocurre el evento se ejecuta una función en donde uno puede revisar si recibió el dato y leer el buffer. Una vez habiendo leído el buffer, éste es vaciado y está listo para recibir más datos.
Los 2 eventos útiles que se pueden monitorear son DataReceived y ErrorReceived.
Desconozco el código para vincular el evento con la función, pero por eso me gusta C#, porque no tengo que andarlo buscando... solo doy click y listo :D
String cadena = "Datos: " + dato;
txtCadena.Text = cadena;
//Variable global
Boolean semaforo = false;
//Código en thread1
while(semaforo==true)
Thread.Sleep(10); //Espera 10ms a que thread2 pierda control de textbox
semaforo=true;
textbox.Text = "Thread1 bajo control de textbox";
semaforo = false;
//Código en thread2 que imagino es la atención al event serialport_DataReceived
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
int bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes);
while(semaforo==true)
Thread.Sleep(10); //Espera 10ms a que thread1 pierda control de textbox
semaforo=true;
textbox.Text = "Thread1 bajo control de textbox";
semaforo = false;
}
jeje
A ver si cuando quede nos ayudas con el asunto de los threads porque quiero aprender a usarlos.
jeje
A ver si cuando quede nos ayudas con el asunto de los threads porque quiero aprender a usarlos.
Pues aqui te presento una forma de hacerlo ;-)
jejeje. pues si, es una de las de cosas de C#, por mucho que crees que sabes siempre te queda por aprender, yo cada dia me percato mas de ello (por lo menos ese es mi caso :mrgreen: :mrgreen:).
;-)
Muy bueno el post. me re-interesa.
Disculpen mi total ingnoracia en C#. PEro es posible hacer un programa que se ejecute solo sin tener intalado el VS 2008 Express?
Tengo que hacer una muy pequeña aplicacion de recepcion de datos por puerto serie. Y quiero que el usuario final lo ejecute simplemente haciendo click con el mouse.
Disculpen mi total ingnoracia en C#. PEro es posible hacer un programa que se ejecute solo sin tener intalado el VS 2008 Express?
Hola, usé VS 2008 Express Edition. Talvez estés usando una versión anterior o no sé. Danos más datos sobre el error dado.
2) Quiero exponerles el siguiente caso: Supongan dos PC, de la PC1 se envía un dato al PC2, se necesita verificar que el dato que llegó al PC2, es el mismo (sin algún tipo de error) que se envió del PC1, ahora, de que forma creen ustedes compañeros, que se puede hacer esto?
He pensado en convertir todos los caracteres ASCII en decimal y realizar una suma de esos valores, entonces este valor se transmite en la trama junto con el dato y el PC receptor hace la misma conversión ASCII a decimal y compara su valor con el enviado y si es igual, la transmisión fue correcta.....no se si se puede hacer ésto, pero qué otra manera puede haber?
No estoy completamente seguro de lo que voy a decir, pero creo que el protocolo RS232 ya tiene incluido el chequeo de errores mediante un checksum.-
2) Quiero exponerles el siguiente caso: Supongan dos PC, de la PC1 se envía un dato al PC2, se necesita verificar que el dato que llegó al PC2, es el mismo (sin algún tipo de error) que se envió del PC1, ahora, de que forma creen ustedes compañeros, que se puede hacer esto?
He pensado en convertir todos los caracteres ASCII en decimal y realizar una suma de esos valores, entonces este valor se transmite en la trama junto con el dato y el PC receptor hace la misma conversión ASCII a decimal y compara su valor con el enviado y si es igual, la transmisión fue correcta.....no se si se puede hacer ésto, pero qué otra manera puede haber?
Gracias por sus respuestas.
No estoy completamente seguro de lo que voy a decir, pero creo que el protocolo RS232 ya tiene incluido el chequeo de errores mediante un checksum.-
Es la manera más fácil. Está bien.
¿Qué excepción?
No se controló System.FormatException
Message="La cadena de entrada no tiene el formato correcto."
Source="mscorlib"
StackTrace:
en System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
en System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
en System.Convert.ToInt32(String value)
en SoftwarePC_Beta.SoftwarePC_Beta.BtnEnviar_Click(Object sender, EventArgs e) en D:\Mis documentos\Visual Studio 2008\Projects\SoftwarePC_Beta\SoftwarePC_Beta\SoftwarePC_7450_(Beta).cs:línea 73
en System.Windows.Forms.Control.OnClick(EventArgs e)
en System.Windows.Forms.Button.OnClick(EventArgs e)
en System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
en System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
en System.Windows.Forms.Control.WndProc(Message& m)
en System.Windows.Forms.ButtonBase.WndProc(Message& m)
en System.Windows.Forms.Button.WndProc(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
en System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
en System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
en System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
en System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
en System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
en System.Windows.Forms.Application.Run(Form mainForm)
en SoftwarePC_Beta.Program.Main() en D:\Mis documentos\Visual Studio 2008\Projects\SoftwarePC_Beta\SoftwarePC_Beta\Program.cs:línea 18
en System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
en System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
en Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
en System.Threading.ThreadHelper.ThreadStart_Context(Object state)
en System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
en System.Threading.ThreadHelper.ThreadStart()
InnerException:
Lo estás haciendo mal, estás convirtiendo una cadena de texto en enteros y eso no se puede.
Ok, gracias por la aclaración, me estaba guiando por ésta ayuda de MSDN, allí dicen que se puede aplicar así pero bueno...
http://msdn.microsoft.com/es-es/library/1aey0kb6.aspx (http://msdn.microsoft.com/es-es/library/1aey0kb6.aspx)
Probé de ésta manera y funcionó:Código: C#
//Cambia el StringBinario en un entero UInt32 Checksum = BitConverter.ToUInt32(BinarioEnviar, 0); //BinarioEnviar es un byte array
Ahora, quiero analizar como es la conversión que hace, éstos son los datos que arroja:
Ingreso en el TextBox Convierte al entero
12345 875770417
1234 875770417
1234568 875770417
87654321 892745528
asdf 1717859169
asdfghj 1717859169
jhgfdsa 1718052970
¿Al ser cada cadena diferente no debería convertir a números diferentes también?
Lo estás haciendo mal, estás convirtiendo una cadena de texto en enteros y eso no se puede.Si se puede, mientras se respete cierto formato.
¿Qué es lo que deseas hacer?
Ya entendí :). Se trata de obtener el equivalente decimal de cada caracter, no lo conseguirás de la forma que estás intentando. La clase String permite obtener cada letra que contenga como un Char utilizando los operadores [], de ahí con un "cast" a int obtienes el equivalente decimal del caracter.
Con esto lo consigues:
:mrgreen: Excelente compañero Geo, funciona perfecto, se puede hacer un CheckSum con esa función, muchas gracias!De nada. Ya contarás cómo avanza el proyecto :).
De nada. Ya contarás cómo avanza el proyecto :).
BluetoothDeviceInfo[] bdi;
string BTMAC;
string BTName;
OpenNETCF.Net.BluetoothAddress btaddress;
OpenNETCF.Net.Sockets.BluetoothClient client;
OpenNETCF.Net.BluetoothEndPoint endpoint;
NetworkStream stream;
OpenNETCF.Net.Sockets.BluetoothListener lis;
//Looking for devices in the area
private void discover()
{
//discover devices
addtolog("Discovering Devices...");
BluetoothClient bc = new BluetoothClient();
bdi = bc.DiscoverDevices(5);
comboBox1.DataSource = bdi;
comboBox1.DisplayMember = "DeviceName";
addtolog("Done, " + bdi.Length + " Device(s) found");
}
private void addtolog(string msg)
{
txtmessage.Text = txtmessage.Text + msg + "\r\n";
Application.DoEvents(); // update display
}
//DISCOVER
private void button1_Click(object sender, EventArgs e)
{
AXWS.URL = abc1;
AXWS.Ctlcontrols.play();
txtmessage.Visible = true;
comboBox1.Visible = true;
discover();
}
//TEXT BOX
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
//COMBO BOX
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
BTMAC = bdi[comboBox1.SelectedIndex].DeviceID.ToString();
BTName = bdi[comboBox1.SelectedIndex].DeviceName.ToString();
Application.DoEvents(); // update display
}
//CONNECT BUTTON
private void button2_Click(object sender, EventArgs e)
{
AXWS.URL = ab;
AXWS.Ctlcontrols.play();
BTMAC = bdi[comboBox1.SelectedIndex].DeviceID.ToString();
BTName = bdi[comboBox1.SelectedIndex].DeviceName.ToString();
if (OBEXOpenStream(BTMAC))
{
if (OBEXConnect())
{
addtolog("Connected To: "+BTMAC);
//stream = client.GetStream();
//receiver();
}
else
{
txtmessage.Text = txtmessage.Text + "Unable to connect\r\n";
}
OBEXCloseStream();
}
else
{
addtolog("Failed to connect to OBEX Server");
AXWS.Ctlcontrols.play();
AXWS.URL = abc2;
}
}
private void addtolog2(string msg)
{
textBox1.Text = textBox1.Text + msg + " ";
Application.DoEvents(); // update display
}
//SEND BUTTON
private string mens;
public int cont=0;
public string funcion;
private string fil="";
private void button3_Click(object sender, EventArgs e)
{
if (textBox2.Text != "")
{
cont = cont + 1;
int art = 0; int brt = 0; int xrt = 0;//a, x y b
funcion = "(" + Convert.ToString(art) + Convert.ToString(xrt) + "+" + Convert.ToString(brt) + ")%104";
string a = textBox2.Text;
string envio="";
for (int m = 0; m< textBox2.TextLength; m++)
{
string b = a.Substring(m,(textBox2.Text.Length+1)-(textBox2.Text.Length));
char sHex1 = Convert.ToChar(b);
for (int x = 0; x < 104; x++)
{
string sHex = Cript[x];
byte newByte = byte.Parse(sHex, System.Globalization.NumberStyles.AllowHexSpecifier);
int i = Convert.ToInt32(newByte.ToString());
Char schar = Convert.ToChar(i);
if (schar == sHex1)
{
envio= envio+ " "+ Cript[x];
x = 105;
}
}
}
textBox1.Text += envio +"\n";
mens = envio;
string min=Convert.ToString(DateTime.Now.Minute);
FileStream ab = File.Create(Application.StartupPath + "\\Mensajes\\" + cont.ToString() + ".txt");
fil = Convert.ToString(cont) + ".txt";
string todo = funcion + " " + min + " " + envio;
byte[] by = Encoding.Default.GetBytes(todo);
foreach(byte b in by)
{
ab.WriteByte(b);
}
ab.Flush();
ab.Close();
string strConexion, strOrden;
OleDbDataAdapter dtaMor = new OleDbDataAdapter();
DataTable dTable = new DataTable();
DataSet dtsC = new DataSet();
string conex = Application.StartupPath + "\\mensajes.mdb";
strConexion = "Provider = Microsoft.jet.OLEDB.4.0; Data Source =" + conex;
strOrden = "INSERT INTO Mensajes (Id,Encriptado, Descencriptado) Values ('"+ cont+"','" + mens + "', '" + textBox2.Text + "')";
dtaMor = new OleDbDataAdapter(strOrden, strConexion);
dtaMor.Fill(dtsC);
dataGridView1.DataSource = dtsC.Tables["'+Mensajes+'"];
if (dtsC.HasChanges())
{
dtaMor.Update(dtsC);
}
}
else
MessageBox.Show("NO HA INGRESADO UN MENSAJE TODAVÍA");
if (txtmessage.Visible == true)
{
//Send a file
addtolog("Sending File...");
if (OBEXOpenStream(BTMAC))
{
if (OBEXConnect())
{
//send client request, start put
string tName = "HelloWorld.txt";
string tType = "";
// string tFileContent = "Hi this is a test!!";
string tFileContent = OpenFile();
int result = OBEXRequest("PUT", tName, tType, tFileContent);//mensaje, minuto, funcion
switch (result)
{
case 160: // 0xa0
addtolog("OK");
break;
case 197: // 0xc5
addtolog("Method not allowed");
break;
case 192: // 0xc0
addtolog("Bad Request");
break;
default:
addtolog("Other Error");
break;
}
}
OBEXCloseStream();
}
else
{
addtolog("Failed to connect to OBEX Server");
}
}
}
/*************************************************************************************/
private bool OBEXOpenStream(string BTMAC)
{
// serial port UUID
Guid spguid = OpenNETCF.Net.Bluetooth.BluetoothService.ObexObjectPush;
btaddress = OpenNETCF.Net.BluetoothAddress.Parse(BTMAC);
client = new OpenNETCF.Net.Sockets.BluetoothClient();
// define endpoint
endpoint = new OpenNETCF.Net.BluetoothEndPoint(btaddress, spguid);
lis = new OpenNETCF.Net.Sockets.BluetoothListener(endpoint);
try
{
//open socket
client.Connect(endpoint);
}
catch (System.Exception e)
{
//unable to connect (server not listening on spguid)
return false;
}
//connect socket
stream = client.GetStream();
return true;
}
private void OBEXCloseStream()
{
stream.Close();
client.Close();
}
private bool OBEXConnect()
{
//send client request
byte[] ConnectPacket = new byte[7];
ConnectPacket[0] = 0x80; // Connect
ConnectPacket[1] = 0x00; // Packetlength Hi Byte
ConnectPacket[2] = 0x07; // Packetlength Lo Byte
ConnectPacket[3] = 0x10; // Obex v1
ConnectPacket[4] = 0x00; // no flags
ConnectPacket[5] = 0x20; // 8k max packet size Hi Byte
ConnectPacket[6] = 0x00; // 8k max packet size Lo Byte
stream.Write(ConnectPacket, 0, ConnectPacket.Length);
//listen for server response
byte[] ReceiveBufferA = new byte[3];
stream.Read(ReceiveBufferA, 0, 3);
if (ReceiveBufferA[0] == 160) // 0xa0
{
//success, decode rest of packet
int plength = (0xff * ReceiveBufferA[1]) + ReceiveBufferA[2]; //length of packet is...
//listen for rest of packet
byte[] ReceiveBufferB = new byte[plength - 3];
stream.Read(ReceiveBufferB, 0, plength - 3);
//serialPort1.Read(ReceiveBufferB, 0, plength - 3);
int obver = ReceiveBufferB[0]; //server obex version (16 = v1.0)
int cflags = ReceiveBufferB[1]; //connect flags
int maxpack = (0xff * ReceiveBufferB[2]) + ReceiveBufferB[3]; //max packet size
return true;
}
else
{
return false;
}
}
private int OBEXRequest(string tReqType, string tName, string tType, string tFileContent)
{
//send client request
int i;
int offset;
int packetsize;
byte reqtype = 0x82;
int tTypeLen = 0x03;
int typeheadsize;
int typesizeHi = 0x00;
int typesizeLo = 0x03;
if (tReqType == "GET")
{
reqtype = 0x83; // 131 GET-Final
}
if (tReqType == "PUT")
{
reqtype = 0x82; // 130 PUT-Final
}
packetsize = 3;
//Name Header
int tNameLength = tName.Length;
int nameheadsize = (3 + (tNameLength * 2) + 2);
int namesizeHi = (nameheadsize & 0xff00) / 0xff;
int namesizeLo = nameheadsize & 0x00ff;
packetsize = packetsize + nameheadsize;
if (tType != "")
{
//Type Header
tTypeLen = tType.Length;
typeheadsize = 3 + tTypeLen + 1;
typesizeHi = (typeheadsize & 0xff00) / 0xff;
typesizeLo = typeheadsize & 0x00ff;
packetsize = packetsize + typeheadsize;
}
//Body
int fileLen = tFileContent.Length;
int fileheadsize = 3 + fileLen;
int filesizeHi = (fileheadsize & 0xff00) / 0xff; ;
int filesizeLo = fileheadsize & 0x00ff; ;
packetsize = packetsize + fileheadsize;
int packetsizeHi = (packetsize & 0xff00) / 0xff;
int packetsizeLo = packetsize & 0x00ff;
byte[] tSendByte = new byte[packetsize];
//PUT-final Header
tSendByte[0] = reqtype; // Request type e.g. PUT-final 130
tSendByte[1] = Convert.ToByte(packetsizeHi); // Packetlength Hi
tSendByte[2] = Convert.ToByte(packetsizeLo); // Packetlength Lo
offset = 2;
//Name Header
tSendByte[offset + 1] = 0x01; // HI for Name header
tSendByte[offset + 2] = Convert.ToByte(namesizeHi); // Length of Name header (2 bytes per char)
tSendByte[offset + 3] = Convert.ToByte(namesizeLo); // Length of Name header (2 bytes per char)
// Name+\n\n in unicode
byte[] tNameU = System.Text.Encoding.BigEndianUnicode.GetBytes(tName);
tNameU.CopyTo(tSendByte, offset + 4);
offset = offset + 3 + (tNameLength * 2);
tSendByte[offset + 1] = 0x00; // null term
tSendByte[offset + 2] = 0x00; // null term
offset = offset + 2;
if (tType != "")
{
//Type Header
tSendByte[offset + 1] = 0x42; // HI for Type Header 66
tSendByte[offset + 2] = Convert.ToByte(typesizeHi); // Length of Type Header
tSendByte[offset + 3] = Convert.ToByte(typesizeLo); // Length of Type Header
for (i = 0; i <= (tTypeLen - 1); i++)
{
tSendByte[offset + 4 + i] = Convert.ToByte(Convert.ToChar(tType.Substring(i, 1)));
}
tSendByte[offset + 3 + tTypeLen + 1] = 0x00; // null terminator
offset = offset + 3 + tTypeLen + 1;
}
//Body
tSendByte[offset + 1] = 0x49; //HI End of Body 73
tSendByte[offset + 2] = Convert.ToByte(filesizeHi); //
tSendByte[offset + 3] = Convert.ToByte(filesizeLo); //1k payload + 3 for HI header
for (i = 0; i <= (fileLen - 1); i++)
{
tSendByte[offset + 4 + i] = Convert.ToByte(Convert.ToChar(tFileContent.Substring(i, 1)));
}
//tSendByte[offset+4+fileLen] = 0x00; // null terminator
offset = offset + 3 + fileLen;
stream.Write(tSendByte, 0, tSendByte.Length);
//listen for server response
//TODO: can hang here forever waiting response...
bool x = stream.DataAvailable; // changed bluetoothclient - public NetworkStream GetStream()
byte[] tArray4 = new byte[3];
stream.Read(tArray4, 0, 3);
x = stream.DataAvailable;
if (tArray4[0] == 160) // 0xa0
{
int plength = (tArray4[1] * 256) + tArray4[2] - 3;
byte[] tArray5 = new byte[plength];
if (plength > 0)
{
stream.Read(tArray5, 0, plength);
//TODO: data in returned packet to deal with
}
return 160;
}
if (tArray4[0] == 197) // 0xc5 Method not allowed
{
return 197;
}
if (tArray4[0] == 192) // 0xc0 Bad Request
{
return 192;
}
return 0;
}
/************************************************************************************/
public String OpenFile()
{
StreamReader sr = new StreamReader(Application.StartupPath+"\\Mensajes\\"+fil);
String line = sr.ReadLine();
return line;
}
Hola por favor me pueden ayudar estoy haciendo un programa en el que deseo enviar una letra de encendido y otra de apagado por el serial port del pc que vaya al pic 18f2550 y se prenda y apague un led, esto mediante visual C# desde el pc y con Micro C programar para el pic.
He estado buscando informacion pero no tengo claro aun por favor ayudenme como abrir y cerrar el portico serial del pc y como enviar la informacion.
Gracias de antemano. Estaré esperando su ayuda.
hola a todos, no se si la pregunta esta en el hilo correcto, lo q pasa es que en este momento no tengo entrenadora y no tengo nada de hard para ensayar y retomar a c#, entonces lo que quiero saber es si el siow o algun otro programa me serviría para emular o hacer puertos COM virtuales (escribir y recibir) en el portatil mientras corro mi programa en c#?
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string dato;
int bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes);
dato = Convert.ToString(buffer[0]);
label1.Text(dato);
}label1.Text = dato;
public partial class Form1 : Form
{
string dato;
int bytes;
public byte[] buffer;
namespace YourNamespacepero asi no me funciona :huh:
{
class YourClass
{
}
label1.text=convert.tostring(dato);deberia ver el 1?? :huh:String s = System.Text.ASCIIEncoding.ASCII.GetString(buffer);
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string dato;
int bytes;
byte[] buffer;
string numero;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Write(textBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
this.Close();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes);
dato = Convert.ToString(buffer[0]);
}
private void button4_Click(object sender, EventArgs e)
{
serialPort1.Close();
button4.Enabled = false;
button3.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
serialPort1.Open();
button3.Enabled = false;
button4.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
numero = System.Text.ASCIIEncoding.ASCII.GetString(dato);
label1.Text = numero;
}
}
}
Byte[] buffer = new byte[] {49};
String s = System.Text.ASCIIEncoding.ASCII.GetString(buffer);