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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] portNames = System.IO.Ports.SerialPort.GetPortNames();
for (int i = 0; i <= portNames.Length - 1; i++)
{
comboBox1.Items.Add(portNames[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
//---close the serial port if it is open---
if (serialPort1.IsOpen)
{
serialPort1.Close();
}
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = 9600;
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
//---open the serial port---
serialPort1.Open();
}
private void button2_Click(object sender, EventArgs e)
{
//---close the serial port---
serialPort1.Close();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//---invoke the delegate to retrieve the received data---
textBox1.BeginInvoke(new myDelegate(updateTextBox)) ;
}
public delegate void myDelegate();
public void updateTextBox()
{
//---append the received data into the TextBox control---
textBox1.AppendText(serialPort1.ReadExisting());
textBox1.ScrollToCaret();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
แล้วถ้าเปลี่ยนจาก Serial Port มาเป็น USB Port หล่ะครับ ผมต้องกำหนดการเรียกใช้ Port ผ่าน C# อย่างไรครับ เพราะผมกำลังใช้ อุปกรณ์ USB Convert to TTL มาใช้ครับ