基于c#环境的单片机和PC串口通信

c#程序:

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            SendData(sendtxt.Text);
        }


        private void SendData(string data)
        {
            byte[] senddata=new byte[1];
            //senddata[0] = Convert.ToByte(data,2);
            senddata= Encoding.Default.GetBytes(data);
            serialPort1.Write(senddata,0,1);
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            SetComConfig();
        }


        private void SetComConfig()
        {
            serialPort1.PortName = "COM2";
            serialPort1.BaudRate = 4800;
            serialPort1.Open();
        }


        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            ReceivedData();
        }


        private void ReceivedData()
        {
            byte[] sbufdata=new byte[1];
            serialPort1.Read(sbufdata,0,1);
            receive.Invoke((EventHandler)delegate{
                //receive.Text = Convert.ToString(sbufdata[0],2);
                receive.Text = Encoding.Default.GetString(sbufdata);
            });
            
        }
    }

}


单片机程序:

  1. #include <reg51.h>  
  2. #include <string.h>    
  3. #include <intrins.h>  
  4.   
  5. sbit LS138A = P2^2;     //定义138译码器的输入A脚由P2.2控制   
  6. sbit LS138B = P2^3;     //定义138译码器的输入脚B由P2.3控制  
  7. sbit LS138C = P2^4;     //定义138译码器的输入脚C由P2.4控制  
  8.   
  9. unsigned char ch;  
  10. bit read_flag= 0 ;  
  11. //此表为 LED 的字模, 共阴数码管 0-9  -   
  12. unsigned char code Disp_Tab[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x40};   
  13. void delay(unsigned int i);  
  14. void init_serialcom( void )  
  15.   
  16.    {  
  17.   
  18.        SCON = 0x50 ;  //SCON: serail mode 1, 8-bit UART, enable ucvr    
  19.   
  20.                          //UART为模式1,8位数据,允许接收  
  21.   
  22.           TMOD |= 0x20 ; //TMOD: timer 1, mode 2, 8-bit reload              
  23.   
  24.                          //定时器1为模式2,8位自动重装  
  25.   
  26.           PCON |= 0x80 ; //SMOD=1;  
  27.   
  28.           TH1 = 0xF3;                   // //baud*2  /*  波特率4800、数据位8、停止位1。效验位无 (12M)  
  29.   
  30.           IE |= 0x90 ;     //Enable Serial Interrupt  
  31.   
  32.           TR1 = 1 ;       // timer 1 run  
  33.   
  34.           TI=1;  
  35.   
  36.            
  37.   
  38.        }  
  39.   
  40.            
  41.   
  42. //向串口发送一个字符  
  43.   
  44. void send_char_com( unsigned char ch)  
  45.   
  46.          {  
  47.             SBUF=ch;  
  48.             while (TI== 0);  
  49.                TI= 0 ;  
  50.   
  51.           }  
  52.   
  53.    
  54.   
  55. //串口接收中断函数  
  56.   
  57. void serial () interrupt 4 using 3  
  58.   
  59. {  
  60.     if (RI)  
  61.           {   
  62.   
  63.                  RI = 0 ;  
  64.   
  65.                  ch=SBUF;   
  66.                    
  67.                  read_flag= 1 ; //就置位取数标志  
  68.   
  69.               }  
  70.   
  71. }  
  72.   
  73.    
  74.   
  75.  main()  
  76.   
  77.     {  
  78.     int LedNumVal = 0;  
  79.     unsigned char LedOut[3];  
  80.     int i = 0;  
  81.   
  82.            init_serialcom(); //初始化串口  
  83.   
  84.                   while ( 1 )  
  85.                   {  
  86.   
  87.                     if (read_flag) //如果取数标志已置位,就将读到的数从串口发出  
  88.   
  89.                     {  
  90.   
  91.                      read_flag= 0 ; //取数标志清0  
  92.                      send_char_com(ch);  
  93.                      LedNumVal = ch;  
  94.                      }  
  95.   
  96.      LedOut[0]=Disp_Tab[LedNumVal / 100];  
  97.      LedOut[1]=Disp_Tab[(LedNumVal / 10) % 10];  
  98.      LedOut[2]=Disp_Tab[LedNumVal % 10]|0x80;  
  99.        
  100.   
  101.      for( i=0; i<3; i++)  //实现8位动态扫描循环  
  102.      {     
  103.       P0 = LedOut[i];  //将字模送到P0口显示  
  104.                                                
  105.       switch(i)   //使用switch 语句控制位选   
  106.          {        
  107.             case 0:LS138A=0; LS138B=0; LS138C=0;  break;           
  108.             case 1:LS138A=1; LS138B=0; LS138C=0;  break;  
  109.             case 2:LS138A=0; LS138B=1; LS138C=0;  break;                  
  110.          }  
  111.     delay(100);    
  112.       }  
  113.                    }  
  114. }  
  115.   
  116. void delay(unsigned int i)  
  117. {  
  118.     char j;  
  119.     for(i; i > 0; i--)  
  120.         for(j = 200; j > 0; j--);  
  121. }

or

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里提供一个基于STM32F103单片机和Windows PC的USB串口通信的示例程序: 单片机端: ```c #include "stm32f10x.h" #include "usb_device.h" #include "usbd_cdc_if.h" int main(void) { // 初始化USB设备 SystemClock_Config(); MX_USB_DEVICE_Init(); while (1) { // 读取USB串口接收缓冲区中的数据 if (CDC_Receive_FS((uint8_t*)rx_buffer, CDC_DATA_FS_MAX_PACKET_SIZE) == USBD_OK) { // 处理接收到的数据 process_received_data(rx_buffer); } // 发送数据 if (should_send_data()) { CDC_Transmit_FS((uint8_t*)tx_buffer, strlen(tx_buffer)); } } } void process_received_data(char* rx_data) { // 处理接收到的数据 // ... // 发送响应数据 sprintf(tx_buffer, "Received data: %s\r\n", rx_data); } int should_send_data() { // 判断是否需要发送数据 // ... return 1; } ``` PC端: ```c# using System; using System.IO.Ports; namespace SerialCommunication { class Program { static SerialPort serialPort; static void Main(string[] args) { // 初始化串口 serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One); serialPort.DataReceived += SerialPort_DataReceived; serialPort.Open(); while (true) { // 发送数据 if (should_send_data()) { serialPort.WriteLine("Hello, world!"); } } } private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { // 读取数据 string receivedData = serialPort.ReadLine(); Console.WriteLine("Received data: " + receivedData); } private static bool should_send_data() { // 判断是否需要发送数据 // ... return true; } } } ``` 需要注意的是,单片机PC之间的波特率、数据位、校验位、停止位等参数需要保持一致。此外,单片机需要预先安装好USB-CDC驱动程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值