原创 搜集到有关SerialPort控件的代码片段

2008-10-30 19:26 4422 2 2 分类: 软件与OS
 
// This is a new namespace in .NET 2.0
// that contains the SerialPort class
using System.IO.Ports;

private static void SendSampleData()
{
// Instantiate the communications
// port with some basic settings
SerialPort port = new SerialPort(
"COM1", 9600, Parity.None, 8, StopBits.One);

// Open the port for communications
port.Open();

// Write a string
port.Write("Hello World");

// Write a set of bytes
port.Write(new byte[] {0x0A, 0xE2, 0xFF}, 0, 3);

// Close the port
port.Close();
}


#region Namespace Inclusions
using System;
using System.IO.Ports;
using System.Windows.Forms;
#endregion

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());
}
}
}

 
using System.IO;

private static void SendTextFile(
SerialPort port, string FileName)
{ port.Write(File.OpenText(FileName).ReadToEnd()); }

private static void SendBinaryFile(
SerialPort port, string FileName)
{
using (FileStream fs = File.OpenRead(FileName))
port.Write((
new BinaryReader(fs)).ReadBytes(
(int)fs.Length), 0, (int)fs.Length);
}

DB9 Male (Pin Side)                   DB9 Female (Pin Side)
DB9 Female (Solder Side)              DB9 Male (Solder Side)
    -------------                          -------------
    \ 1 2 3 4 5 /                          \ 5 4 3 2 1 /
     \ 6 7 8 9 /                            \ 9 8 7 6 /
      ---------                              ---------

DB9 Female to DB9 Female Null-Modem Wiring
2 |  3 |  7 |  8 | 6&1|  5 |  4
---- ---- ---- ---- ---- ---- ----
3 |  2 |  8 |  7 |  4 |  5 | 6&1

9-pin   25-pin  Assignment                 From PC
------  ------  -------------------------  ------------
Sheild  1       Case Ground                Gnd
1       8       DCD (Data Carrier Detect)  Input
2       3       RX  (Receive Data)         Input
3       2       TX  (Transmit Data)        Output
4       20      DTR (Data Terminal Ready)  Output
5       7       GND (Signal Ground)        Gnd
6       6       DSR (Data Set Ready)       Input
7       4       RTS (Request To Send)      Output
8       5       CTS (Clear To Send)        Input
9       22      RI  (Ring Indicator)       Input



using System;


using System.IO.Ports;


using System.Collections.Generic;


 


namespace SerialComBuffering


{


  class Program


  {


    SerialPort com = new SerialPort(SerialPort.GetPortNames()[0],


      9600, Parity.None, 8, StopBits.One);


    List<byte> bBuffer = new List<byte>();


    string sBuffer = String.Empty;


 


    static void Main(string[] args)


    { new Program(); }


 


    Program()


    {


      com.DataReceived +=


        new SerialDataReceivedEventHandler(com_DataReceived);


      com.Open();


 


      Console.WriteLine("Waiting for incoming data...");


      Console.ReadKey();


    }


 


    void com_DataReceived(object sender,


      SerialDataReceivedEventArgs e)


    {


      // Use either the binary OR the string technique (but not both)


 


      // Buffer and process binary data


      while (com.BytesToRead > 0)


        bBuffer.Add((byte)com.ReadByte());


      ProcessBuffer(bBuffer);


 


      // Buffer string data


      sBuffer += com.ReadExisting();


      ProcessBuffer(sBuffer);


    }


 


    private void ProcessBuffer(string sBuffer)


    {


      // Look in the string for useful information


      // then remove the useful data from the buffer


    }


 


    private void ProcessBuffer(List<byte> bBuffer)


    {


      // Look in the byte array for useful information


      // then remove the useful data from the buffer


    }


  }


}



private List<byte> PortBuffer = new List<byte>();

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;

byte[] data = new byte[port.BytesToRead];

port.Read(data, 0, data.Length);

PortBuffer.AddRange(data);

ProcessIncomingData(PortBuffer);
}

private void ProcessIncomingData(List<byte> PortBuffer)
{
// Search through the bytes to find the data you want
// then remove the data from the list. It is good to
// clean up unused bytes (usually everything before
// what you're looking for)
}


void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int intBytes = serialPort.BytesToRead;
byte[] bytes = new byte[intBytes];
serialPort.Read(bytes, 0, intBytes);

tbReceive.Text += intBytes.ToString() + ";";
}


int intBytes;
void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
intBytes = serialPort.BytesToRead;
byte[] bytes = new byte[intBytes];
serialPort.Read(bytes, 0, intBytes);

this.Invoke(new EventHandler(SetText));


}
void SetText()
{
tbReceive.Text += intBytes.ToString() + ";";
}


if (com.IsOpen) com.Close();
com.Open();

// send char 34,14,192,51,0,0
com.Write(new string(new char[] { (char)34, (char)14, (char)192, (char)51, (char)0, (char)0 }, 0, 6));

// for testing purposes I connected TX and RX pins of the port...

// receive routine:
private void com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{

// This method will be called when there is data waiting in the port's buffer

// Obtain the number of bytes waiting in the port's buffer
bytes = com.BytesToRead;

// Create a byte array buffer to hold the incoming data
buffer = new char[bytes];

// Read the data from the port and store it in our buffer
com.Read(buffer, 0, bytes);

}


private List<byte> PortBuffer = new List<byte>();

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;

byte[] data = new byte[port.BytesToRead];

port.Read(data, 0, data.Length);

PortBuffer.AddRange(data);

ProcessIncomingData(PortBuffer);
}

private void ProcessIncomingData(List<byte> PortBuffer)
{
// Search through the bytes to find the data you want
// then remove the data from the list. It is good to
// clean up unused bytes (usually everything before
// what you're looking for)
}


private void port_DataReceived(Object sender, System.IO.Ports.SerialDataReceivedEventArgs e)


       {


           Thread.Sleep(250);


           int total = sp.BytesToRead  


           buffer_rx = new char[total];


           sp.Read(buffer_rx, 0, total);


           for (int i = 0; i < buffer_rx.Length; i++)


           {


               sB.Append(buffer_rxIdea.ToString());


           }


           MessageBox.Show(sB.ToString());


           sB.Remove(0, sB.Length); //sB is a StringBuilder


       }


private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)


       {


          int total = serialPort1.BytesToRead;// here always read 8 just bytes and bufer_rx is a20 bytes


           serialPort1.Read(bufer_rx, 0, total);


private void port_DataReceived(Object sender, System.IO.Ports.SerialDataReceivedEventArgs e)


       {


           Thread.Sleep(250);


           int total = sp.BytesToRead  


           buffer_rx = new char[total];


           sp.Read(buffer_rx, 0, total);


           for (int i = 0; i < buffer_rx.Length; i++)


           {


               sB.Append(buffer_rxIdea.ToString());


           }


           MessageBox.Show(sB.ToString());


           sB.Remove(0, sB.Length); //sB is a StringBuilder


       }


private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // Event for receiving data,Read the buffer to text box.
    this.Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object sender, EventArgs e)
{
    statusBar1.Text = "Getting Data";
    statusBar1.Refresh();
    txtData.Text = txtData.Text + port.ReadExisting();
}



1/* 
2 * Project:    SerialPort Terminal
3 * Company:    Coad .NET, http://coad.net
4 * Author:     Noah Coad, http://coad.net/noah
5 * Created:    March 2005
6 * 
7 * Notes:      This was created to demonstrate how to use the SerialPort control for
8 *             communicating with your PC's Serial RS-232 COM Port
9 * 
10 *             It is for educational purposes only and not sanctified for industrial use. 
11 * 
12 *             Search for "comport" to see how I'm using the SerialPort control.
13 */
14
15#region Namespace Inclusions  
16using System;  
17using System.Data;  
18using System.Text;  
19using System.Drawing;  
20using System.IO.Ports;  
21using System.Windows.Forms;  
22using System.ComponentModel;  
23using System.Collections.Generic;  
24 
25using SerialPortTerminal.Properties;
26#endregion  
27 
28namespace SerialPortTerminal  
29{
30  #region Public Enumerations  
31  public enum DataMode { Text, Hex }  
32  public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
33  #endregion  
34 
35  public partial class frmTerminal : Form  
36  {
37    #region Local Variables  
38 
39    // The main control for communicating through the RS-232 port  
40    private SerialPort comport = new SerialPort();  
41 
42    // Various colors for logging info  
43    private Color[] LogMsgTypeColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red };  
44 
45    // Temp holder for whether a key was pressed  
46    private bool KeyHandled = false;
47    
48    #endregion  
49 
50    #region Constructor  
51    public frmTerminal()  
52    {  
53      // Build the form  
54      InitializeComponent();  
55 
56      // Restore the users settings  
57      InitializeControlValues();  
58 
59      // Enable/disable controls based on the current state  
60      EnableControls();  
61 
62      // When data is recieved through the port, call this method  
63      comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);  
64    }
65    #endregion  
66 
67    #region Local Methods  
68      
69    /// <summary> Save the user's settings. </summary>  
70    private void SaveSettings()  
71    {  
72      Settings.Default.BaudRate = int.Parse(cmbBaudRate.Text);  
73      Settings.Default.DataBits = int.Parse(cmbDataBits.Text);  
74      Settings.Default.DataMode = CurrentDataMode;  
75      Settings.Default.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);  
76      Settings.Default.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);  
77      Settings.Default.PortName = cmbPortName.Text;  
78 
79      Settings.Default.Save();  
80    }  
81 
82    /// <summary> Populate the form's controls with default settings. </summary>  
83    private void InitializeControlValues()  
84    {  
85      cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));  
86      cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));  
87 
88      cmbParity.Text = Settings.Default.Parity.ToString();  
89      cmbStopBits.Text = Settings.Default.StopBits.ToString();  
90      cmbDataBits.Text = Settings.Default.DataBits.ToString();  
91      cmbParity.Text = Settings.Default.Parity.ToString();  
92      cmbBaudRate.Text = Settings.Default.BaudRate.ToString();  
93      CurrentDataMode = Settings.Default.DataMode;  
94 
95      cmbPortName.Items.Clear();  
96      foreach (string s in SerialPort.GetPortNames())  
97        cmbPortName.Items.Add(s);  
98 
99      if (cmbPortName.Items.Contains(Settings.Default.PortName)) cmbPortName.Text = Settings.Default.PortName;  
100      else if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = 0;  
101      else 
102      {  
103        MessageBox.Show(this"There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.""No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error);  
104        this.Close();  
105      }  
106    }  
107 
108    /// <summary> Enable/disable controls based on the app's current state. </summary>  
109    private void EnableControls()  
110    {  
111      // Enable/disable controls based on whether the port is open or not  
112      gbPortSettings.Enabled = !comport.IsOpen;  
113      txtSendData.Enabled = btnSend.Enabled = comport.IsOpen;  
114 
115      if (comport.IsOpen) btnOpenPort.Text = "&Close Port";  
116      else btnOpenPort.Text = "&Open Port";  
117    }  
118 
119    /// <summary> Send the user's data currently entered in the 'send' box.</summary>  
120    private void SendData()  
121    {  
122      if (CurrentDataMode == DataMode.Text)  
123      {  
124        // Send the user's text straight out the port  
125        comport.Write(txtSendData.Text);  
126 
127        // Show in the terminal window the user's text  
128        Log(LogMsgType.Outgoing, txtSendData.Text + "\n");  
129      }  
130      else 
131      {  
132        try 
133        {  
134          // Convert the user's string of hex digits (ex: B4 CA E2) to a byte array  
135          byte[] data = HexStringToByteArray(txtSendData.Text);  
136 
137          // Send the binary data out the port  
138          comport.Write(data, 0, data.Length);  
139 
140          // Show the hex digits on in the terminal window  
141          Log(LogMsgType.Outgoing, ByteArrayToHexString(data) + "\n");  
142        }  
143        catch (FormatException)  
144        {  
145          // Inform the user if the hex string was not properly formatted  
146          Log(LogMsgType.Error, "Not properly formatted hex string: " + txtSendData.Text + "\n");  
147        }  
148      }  
149      txtSendData.SelectAll();  
150    }  
151 
152    /// <summary> Log data to the terminal window. </summary>  
153    /// <param name="msgtype"> The type of message to be written. </param>  
154    /// <param name="msg"> The string containing the message to be shown. </param>  
155    private void Log(LogMsgType msgtype, string msg)  
156    {  
157      rtfTerminal.Invoke(new EventHandler(delegate 
158      {  
159        rtfTerminal.SelectedText = string.Empty;  
160        rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold);  
161        rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];  
162        rtfTerminal.AppendText(msg);  
163        rtfTerminal.ScrollToCaret();  
164      }));  
165    }  
166 
167    /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>  
168    /// <param name="s"> The string containing the hex digits (with or without spaces). </param>  
169    /// <returns> Returns an array of bytes. </returns>  
170    private byte[] HexStringToByteArray(string s)  
171    {  
172      s = s.Replace(" """);  
173      byte[] buffer = new byte[s.Length / 2];  
174      for (int i = 0; i < s.Length; i += 2)  
175        buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);  
176      return buffer;  
177    }  
178 
179    /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>  
180    /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>  
181    /// <returns> Returns a well formatted string of hex digits with spacing. </returns>  
182    private string ByteArrayToHexString(byte[] data)  
183    {  
184      StringBuilder sb = new StringBuilder(data.Length * 3);  
185      foreach (byte b in data)  
186        sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));  
187      return sb.ToString().ToUpper();  
188    }
189    #endregion  
190 
191    #region Local Properties  
192    private DataMode CurrentDataMode  
193    {  
194      get 
195      {  
196        if (rbHex.Checked) return DataMode.Hex;  
197        else return DataMode.Text;  
198      }  
199      set 
200      {  
201        if (value == DataMode.Text) rbText.Checked = true;  
202        else rbHex.Checked = true;  
203      }  
204    }
205    #endregion  
206 
207    #region Event Handlers  
208    private void lnkAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)  
209    {  
210      // Show the user the about dialog  
211      (new frmAbout()).ShowDialog(this);  
212    }  
213      
214    private void frmTerminal_Shown(object sender, EventArgs e)  
215    {  
216      Log(LogMsgType.Normal, String.Format("Application Started at {0}\n", DateTime.Now));  
217    }  
218    private void frmTerminal_FormClosing(object sender, FormClosingEventArgs e)  
219    {  
220      // The form is closing, save the user's preferences  
221      SaveSettings();  
222    }  
223 
224    private void rbText_CheckedChanged(object sender, EventArgs e)  
225    { if (rbText.Checked) CurrentDataMode = DataMode.Text; }  
226    private void rbHex_CheckedChanged(object sender, EventArgs e)  
227    { if (rbHex.Checked) CurrentDataMode = DataMode.Hex; }  
228 
229    private void cmbBaudRate_Validating(object sender, CancelEventArgs e)  
230    { int x; e.Cancel = !int.TryParse(cmbBaudRate.Text, out x); }  
231    private void cmbDataBits_Validating(object sender, CancelEventArgs e)  
232    { int x; e.Cancel = !int.TryParse(cmbDataBits.Text, out x); }  
233 
234    private void btnOpenPort_Click(object sender, EventArgs e)  
235    {  
236      // If the port is open, close it.  
237      if (comport.IsOpen) comport.Close();  
238      else 
239      {  
240        // Set the port's settings  
241        comport.BaudRate = int.Parse(cmbBaudRate.Text);  
242        comport.DataBits = int.Parse(cmbDataBits.Text);  
243        comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);  
244        comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);  
245        comport.PortName = cmbPortName.Text;  
246 
247        // Open the port  
248        comport.Open();  
249      }  
250 
251      // Change the state of the form's controls  
252      EnableControls();  
253 
254      // If the port is open, send focus to the send data box  
255      if (comport.IsOpen) txtSendData.Focus();  
256    }  
257    private void btnSend_Click(object sender, EventArgs e)  
258    { SendData(); }  
259 
260    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)  
261    {  
262      // This method will be called when there is data waiting in the port's buffer  
263 
264      // Determain which mode (string or binary) the user is in  
265      if (CurrentDataMode == DataMode.Text)  
266      {  
267        // Read all the data waiting in the buffer  
268        string data = comport.ReadExisting();  
269 
270        // Display the text to the user in the terminal  
271        Log(LogMsgType.Incoming, data);  
272      }  
273      else 
274      {  
275        // Obtain the number of bytes waiting in the port's buffer  
276        int bytes = comport.BytesToRead;  
277 
278        // Create a byte array buffer to hold the incoming data  
279        byte[] buffer = new byte[bytes];  
280 
281        // Read the data from the port and store it in our buffer  
282        comport.Read(buffer, 0, bytes);  
283 
284        // Show the user the incoming data in hex format  
285        Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));  
286      }  
287    }  
288 
289    private void txtSendData_KeyDown(object sender, KeyEventArgs e)  
290    {   
291      // If the user presses [ENTER], send the data now  
292      if (KeyHandled = e.KeyCode == Keys.Enter) { e.Handled = true; SendData(); }   
293    }  
294    private void txtSendData_KeyPress(object sender, KeyPressEventArgs e)  
295    { e.Handled = KeyHandled; }
296    #endregion  
297  }  
298
PARTNER CONTENT

文章评论0条评论)

登录后参与讨论
EE直播间
更多
我要评论
0
2
关闭 站长推荐上一条 /3 下一条