Visual Studio ( Windows Form ) 程式碼 :
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 RS232_TF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.Close();
CheckForIllegalCrossThreadCalls = false; //允許 Text 跨執行緒作業無效
//取得所有可用的連接埠
foreach(string com in System.IO.Ports.SerialPort.GetPortNames())
{
comboBox2.Items.Add(com);
}
}
//設定通訊埠的Baud Rate
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
serialPort1.BaudRate = Convert.ToInt32(comboBox1.Text);
}
//設定通訊埠的Chanel
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
serialPort1.PortName = Convert.ToString(comboBox2.Text);
}
//收到資料
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (serialPort1.IsOpen)
{
if (serialPort1.BytesToRead != 0)
{
string message = serialPort1.ReadTo(Convert.ToString('\n')); //將資料讀取至'\n'
textBox1.Text += Convert.ToString(message) + '\r' + '\n';
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
comboBox1.Enabled = true;
comboBox2.Enabled = true;
button1.Text = "啟動";
}
else
{
serialPort1.Open();
comboBox1.Enabled = false;
comboBox2.Enabled = false;
button1.Text = "中斷";
textBox1.Text += "Connect" + '\r' + '\n';
}
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Write("" + textBox2.Text + '\n'); //輸出字
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
8051燒錄程式碼 ( Keil ) :
void main( void ){
int i;
System_Init();
printf("Hello World!\r\n");
while(1){
if( b1s ){
b1s = 0;
LED ^= 1;
}
if( bRI ){
bRI = 0;
}
if( B_Print ){
B_Print = 0;
printf( "%s\r\n" , BufRx );
}
}
}
void RS233() interrupt 4 {
char ch;
if( RI ){
RI = 0;
ch = SBUF;
bRI = 1;
word = ch;
if( ( ch != LF ) && ( ch != CR ) ) { // if not (carriage return) or (line feed)
BufRx[BufIndex++] = ch; //put received data to BufRx[]
BufIndex &= 0x3F; // Boundary of BufIndex is 0-63
}
if ( (ch == CR )|| (ch == LF) ) {
BufRx[BufIndex++] = 0;
for( C_Bufindex = BufIndex; C_Bufindex < 32; C_Bufindex++ ) BufRx[C_Bufindex] = 0;
B_Print = 1;
BufIndex = 0;
}
}else{
TI = 0;
bTI = 1;
}
}
char putchar( char ch ){
static int i;
bTI = 0;
while ( (!bTI) && ( i < 2000 ) ) i++;
i = 0;
SBUF = ch;
return ch;
}