Một bài tập môn Kỹ thuật giao tiếp máy tính của mình. Giao tiếp RS232 sử dụng vi điều khiển PIC16f877A, viết giao diện bằng C Sharp, nhập chuỗi vào giao diện và truyền hiển thị lên LCD.
#include <16F877A.h> #device PIC16F877*=16 ADC=10 // Su dung con tro 16bit (cho MCU 14bit) // Su dung ADC 10bit #fuses hs, nowdt, noprotect, nolvp, put, brownout #use delay(clock=20000000) #use rs232(baud=9600,parity=N,xmit=PIN_C6, rcv=PIN_C7,bits=8) #define use_portb_lcd true #include char ch; int i; #int_rda void serial_isr() { ch=getc(); // lay ky tu truyen xuong putc(ch); // gui ky tu len may tinh i=1; // co bao interrupt } void main() { lcd_init(); enable_interrupts(global); enable_interrupts(int_rda); while(TRUE) { if(i==1) // if interrupt occured { i=0; printf(lcd_putc,"%c",ch);// Hien ky tu nhan duoc } } }
Code C#
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; using System.IO.Ports; namespace RS232_tester { public partial class fclsRS232Tester: Form { delegate void SetTextCallback(string text); public fclsRS232Tester() { InitializeComponent(); string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { cmbComSelect.Items.Add(port); } } private void cmbComSelect_SelectionChangeCommitted(object sender, EventArgs e) { if (port.IsOpen) port.Close(); port.PortName = cmbComSelect.SelectedItem.ToString(); stsStatus.Text = port.PortName + ":9600,8N1"; try { port.Open(); } catch { MessageBox.Show("Serial port" + port.PortName + "cannot be opened!", "RS232 tester", MessageBoxButtons.OK, MessageBoxIcon.Warning); cmbComSelect.SelectedText = ""; stsStatus.Text = "Select serial port!"; } } private void btnOut_Click(object sender, EventArgs e) { if (port.IsOpen) port.WriteLine(txtOut.Text); else MessageBox.Show("Serial port is closed!", "RS232 tester", MessageBoxButtons.OK, MessageBoxIcon.Error); txtOut.Clear(); } private void btnClear_Click(object sender, EventArgs e) { txtIn.Clear(); } private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e) { String InputData = port.ReadExisting(); if (InputData != String.Empty) { //txtIn.Text=InputData; SetText(InputData); } } private void SetText(String text) { if (this.txtIn.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else this.txtIn.Text += text; } } }