2009-08-07 9 views
24

Je commence juste à apprendre comment envoyer et recevoir des données de mon matériel via l'interface graphique C#.Comment lire et écrire à partir du port série

Quelqu'un peut-il s'il vous plaît écrire un détail comment lire données du port série?

+0

double possible de [Gestion des ports série en C#] (http://stackoverflow.com/questions/7275084/managing-serial-ports-in-c-sharp) –

+0

Le d'un autre côté: le message lié est un doublon de celui-ci. Veuillez utiliser cette question comme doublon canonique. – Lundin

Répondre

57

SerialPort (RS-232 Serial COM Port) in C# .NET
Cet article explique comment utiliser la classe SerialPort .NET pour lire et écrire des données, déterminer les ports série sont disponibles sur votre machine, et comment envoyer des fichiers. Il couvre même les affectations de broches sur le port lui-même.

Exemple de code:

using System; 
using System.IO.Ports; 
using System.Windows.Forms; 

namespace SerialPortExample 
{ 
    class SerialPortProgram 
    { 
    // Create the serial port with basic settings 
    private SerialPort port = new SerialPort("COM1", 
     9600, Parity.None, 8, StopBits.One); 

    [STAThread] 
    static void Main(string[] args) 
    { 
     // Instatiate this class 
     new SerialPortProgram(); 
    } 

    private SerialPortProgram() 
    { 
     Console.WriteLine("Incoming Data:"); 

     // Attach a method to be called when there 
     // is data waiting in the port's buffer 
     port.DataReceived += new 
     SerialDataReceivedEventHandler(port_DataReceived); 

     // Begin communications 
     port.Open(); 

     // Enter an application loop to keep this thread alive 
     Application.Run(); 
    } 

    private void port_DataReceived(object sender, 
     SerialDataReceivedEventArgs e) 
    { 
     // Show all the incoming data in the port's buffer 
     Console.WriteLine(port.ReadExisting()); 
    } 
    } 
} 
Questions connexes