OpenEdv-开源电子网

 找回密码
 立即注册
正点原子全套STM32/Linux/FPGA开发资料,上千讲STM32视频教程免费下载...
查看: 6547|回复: 10

【发一个我改的串口小助手,半成品都算不上】

[复制链接]

12

主题

85

帖子

0

精华

初级会员

Rank: 2

积分
153
金钱
153
注册时间
2013-11-24
在线时间
0 小时
发表于 2014-4-23 10:24:42 | 显示全部楼层 |阅读模式

看了两周C#,还是什么都不会,只能改程序。参考了网上几份代码,修改了下,弄成这样。还有很多不好使,比如在接收数据时突然关闭串口会死,向电脑发回车时好像“\n”就行了。下载了原子哥串口实验,有的地方打不出来,把"\r\n"改成"\n"会好点。贴上来这个半成品都算不上的东西首先是为了给更多像我一样的上位机新手一个参考,再就是让大家帮助我一起学习!把这些问题解决喽~~~

代码如下:::  大家一定帮我解决这些啊!!!谢谢啦

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;
using System.IO.Ports;

namespace SerialCOM

    public partial class Form1 : Form
    {
        SerialPort serialPort = new SerialPort();
      
        public Form1()
        {
            InitializeComponent();
            this.toolStripStatusLabel1.Text = "端口号:端口未打开";
            this.toolStripStatusLabel2.Text = "波特率:端口未打开";
            this.toolStripStatusLabel3.Text = "数据位:端口未打开";
            this.toolStripStatusLabel4.Text = "停止位:端口未打开";
        }
        /// <summary>
        /// 串口检测
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCheckCOM_Click(object sender, EventArgs e)
        {
           
                comboBox1.Items.Clear();
                for (int i = 0; i < 20; i++)
                {
                    try
                    {
                    SerialPort serialPort = new SerialPort("COM" + (i + 1).ToString());
                    serialPort.Open();
                    serialPort.Close();
                    comboBox1.Items.Add("COM" + (i + 1).ToString());
                       }
                    catch (Exception)
                    {
                        comboBox1.Text = "COM" + (i + 1).ToString() + "不可用";
                        continue;
                    }
                }
                comboBox1.SelectedIndex = 0;    //串口号
                comboBox2.SelectedIndex = 3;    //波特率
                comboBox3.SelectedIndex = 0;    //数据位
                comboBox4.SelectedIndex = 0;    //停止位
            }
  
      
   
        /// <summary>
        /// 关闭串口按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCloseCom_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnOpenCom.Enabled == false)
                {
                    btnOpenCom.Enabled = true;
                    btnCheckCOM.Enabled = true;
                    comboBox1.Enabled = true;
                    comboBox2.Enabled = true;
                    comboBox3.Enabled = true;
                    comboBox4.Enabled = true;
                    serialPort.Close();
                    //MessageBox.Show("串口关闭成功!");
                    this.toolStripStatusLabel1.Text = "端口号:端口未打开";
                    this.toolStripStatusLabel2.Text = "波特率:端口未打开";
                    this.toolStripStatusLabel3.Text = "数据位:端口未打开";
                    this.toolStripStatusLabel4.Text = "停止位:端口未打开";
                }
                else
                {
                    MessageBox.Show("请先打开串口哦亲~~!");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("串口关闭失败"); return;
            }
        }
        /// <summary>
        /// 打开串口按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenCom_Click(object sender, EventArgs e)
        {
            try
            {

                String str1 = comboBox1.Text;
                String str2 = comboBox2.Text;
                String str3 = comboBox3.Text;
                String str4 = comboBox4.Text;
                Int32 int2 = Convert.ToInt32(str2);
                Int32 int3 = Convert.ToInt32(str3);


                if (str1 == null)
                {
                    MessageBox.Show("请先选择串口!", "Error");
                    return;
                }


                serialPort.PortName = str1;
                serialPort.BaudRate = int2;
                serialPort.DataBits = int3;
                switch (comboBox4.Text)
                {
                    case "1":
                        serialPort.StopBits = StopBits.One;
                        break;
                    case "1.5":
                        serialPort.StopBits = StopBits.OnePointFive;
                        break;
                    case "2":
                        serialPort.StopBits = StopBits.Two;
                        break;
                    default:
                        MessageBox.Show("参数不正确哦", "Error");
                        break;
                }
                serialPort1.ReadBufferSize = 1;//设置串口读缓冲区大小数值
                serialPort1.WriteBufferSize = 1;//设置串口写缓冲区大小数值
              

                if (serialPort.IsOpen == true)
                {
                    serialPort.Close();
                }

                serialPort.Open();
                //MessageBox.Show("串口打开成功!", str1);
                Control.CheckForIllegalCrossThreadCalls = false;    
                serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
                this.toolStripStatusLabel1.Text = "端口号:" + serialPort.PortName + " ";
                this.toolStripStatusLabel2.Text = "波特率:" + serialPort.BaudRate + " ";
                this.toolStripStatusLabel3.Text = "数据位:" + serialPort.DataBits + " ";
                this.toolStripStatusLabel4.Text = "停止位:" + serialPort.StopBits + " ";

                btnOpenCom.Enabled = false;
                btnCheckCOM.Enabled = false;
                comboBox1.Enabled = false;
                comboBox2.Enabled = false;
                comboBox3.Enabled = false;
                comboBox4.Enabled = false;

            }
            catch (Exception)
            {
                MessageBox.Show("没发现串口设备,请检测串口!");
                return;
            }
        }
        /// <summary>
        /// 清除接收区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCleanRec_Click(object sender, EventArgs e)
        {
           // tbRec.Text = "";
            tbRec.Clear();
          //  serialPort.DiscardInBuffer();
        }
        /// <summary>
        /// 退出软件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort.Close();
            }
            catch (Exception we)
            {
                MessageBox.Show("串口关闭异常"+we.Message);
            }
            Application.Exit();
        }

        private void btSendData_Click(object sender, EventArgs e)
        {


            if (serialPort.IsOpen==false) //如果没打开
            {
                MessageBox.Show("请先打开串口!", "Error");
                return;
            }
          
            string strSend = tbSend.Text;

            if (radio1.Checked == true) //“HEX发送” 按钮
            {
                //处理数字转换
                string sendBuf = strSend;
                string sendnoNull = sendBuf.Trim();
                string sendNOComma = sendnoNull.Replace(',', ' ');    //去掉英文逗号
                string sendNOComma1 = sendNOComma.Replace(',', ' '); //去掉中文逗号
                string strSendNoComma2 = sendNOComma1.Replace("0x", " ");   //去掉0x
                strSendNoComma2.Replace("0X"," ");   //去掉0X
                string[] strArray = strSendNoComma2.Split(' ');

                int byteBufferLength = strArray.Length;
                for (int i = 0; i < strArray.Length; i++)
                {
                    if (strArray == "")
                    {
                        byteBufferLength--;
                    }
                }
                // int temp = 0;
                byte[] byteBuffer = new byte[byteBufferLength];
                int ii = 0;
                for (int i = 0; i < strArray.Length; i++)        //对获取的字符做相加运算
                {

                    Byte[] bytesOfStr = Encoding.Default.GetBytes(strArray);

                    int decNum = 0;
                    if (strArray == "")
                    {    
                        continue;
                    }
                    else
                    {
                        decNum = Convert.ToInt32(strArray, 16); 
                    }

                    try    //防止输错,使其只能输入一个字节的字符
                    {
                        byteBuffer[ii] = Convert.ToByte(decNum);
                    }
                    catch (Exception qw)
                    {
                        MessageBox.Show("输入多了!"+qw.Message);
                        tbSend.Enabled = false;
                        return;
                    }

                    ii++;
                }
                serialPort.Write(byteBuffer, 0, byteBuffer.Length);
              
            }
            else  //以字符串形式发送时
            {
                serialPort.WriteLine(strSend+"\r\n");    //写入数据
              
            }
        }


        void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (serialPort.IsOpen)    
            {
                //输出当前时间
                //DateTime dt = DateTime.Now;
                //tbRec.Text += dt.GetDateTimeFormats('f')[0].ToString() + "\r\n";
               // tbRec.SelectAll();
                //tbRec.SelectionColor = Color.Blue;         //改变字体的颜色

                byte[] byteRead = new byte[serialPort.BytesToRead];    //BytesToRead:sp1接收的字符个数
                if (radio2.Checked == false)                          //'发送字符串'单选按钮
                {
                    serialPort.Encoding = System.Text.Encoding.Default;//
                    tbRec.Text += serialPort.ReadLine() + "\r\n"; 
         
                    this.tbRec.SelectionStart = this.tbRec.TextLength;
                    this.tbRec.ScrollToCaret();                     
                    serialPort.DiscardInBuffer();                     
                }
                else                                            //接收16进制按钮'
                {
                    try
                    {
                        serialPort.Encoding = System.Text.Encoding.ASCII;
                        Byte[] receivedData = new Byte[serialPort.BytesToRead];        //创建接收字节数组
                        serialPort.Read(receivedData, 0, receivedData.Length);         //读取数据    
                        serialPort.DiscardInBuffer();                                  //清空SerialPort控件的Buffer
                        string strRcv = null;          
                        for (int i = 0; i < receivedData.Length; i++) //窗体显示
                        {
                            strRcv += receivedData.ToString("X2")+" ";  //16进制显示
                        }
                        tbRec.Text += strRcv;
                        this.tbRec.SelectionStart = this.tbRec.TextLength;
                        this.tbRec.ScrollToCaret(); 
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "出错提示");
                        tbSend.Text = "";
                    }
                }
            }
            else
            {
                MessageBox.Show("请打开某个串口", "错误提示");
            }
        }


 


    }
}

SerialCOM.exe

18 KB, 下载次数: 108

学一天不会,我学两天;再不会,再两天·········
正点原子逻辑分析仪DL16劲爆上市
回复

使用道具 举报

12

主题

85

帖子

0

精华

初级会员

Rank: 2

积分
153
金钱
153
注册时间
2013-11-24
在线时间
0 小时
 楼主| 发表于 2014-4-23 10:32:19 | 显示全部楼层

串口例程改成这样好像好点,但还是有问题

  if(USART_RX_STA&0x8000)
  {       
   len=USART_RX_STA&0x3fff;//得到此次接收到的数据长度
   printf("您发送的是:\n");
   for(t=0;t<len;t++)
   {
    USART_SendData(USART1, USART_RX_BUF[t]);//向串口1发送数据
    while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//等待发送结束
   }
   printf("\n");//插入换行
   USART_RX_STA=0;
  }else
  {
   times++;
   if(times%500==0)
   {
    printf("正点原子STM32\n");
   }
   if(times%200==0)printf("请输入数据\n"); 
   if(times%30==0)LED0=!LED0;//闪烁LED,提示系统正在运行.
   delay_ms(10);  

学一天不会,我学两天;再不会,再两天·········
回复 支持 反对

使用道具 举报

10

主题

108

帖子

0

精华

初级会员

Rank: 2

积分
176
金钱
176
注册时间
2013-12-23
在线时间
2 小时
发表于 2014-4-23 11:37:36 | 显示全部楼层
回复【2楼】正点妹子:
---------------------------------
我学C++没学懂。
果断用了易语言。写简单的上位机很简单。
只要肯努力,知识是自己的,别人拿不走
回复 支持 反对

使用道具 举报

12

主题

85

帖子

0

精华

初级会员

Rank: 2

积分
153
金钱
153
注册时间
2013-11-24
在线时间
0 小时
 楼主| 发表于 2014-4-23 11:41:31 | 显示全部楼层
回复【3楼】monicacoma:
---------------------------------
易语言是什么呢?  教教我啊
学一天不会,我学两天;再不会,再两天·········
回复 支持 反对

使用道具 举报

10

主题

108

帖子

0

精华

初级会员

Rank: 2

积分
176
金钱
176
注册时间
2013-12-23
在线时间
2 小时
发表于 2014-4-23 11:44:47 | 显示全部楼层
回复【4楼】正点妹子:
---------------------------------
汉语编程。有人会攻击,但是无所谓,做硬件的只是想顺便做个上位机测试用而已。用不是纯软。
我做电机驱动,这玩意做个控制台软件很简单。
只要肯努力,知识是自己的,别人拿不走
回复 支持 反对

使用道具 举报

9

主题

126

帖子

0

精华

中级会员

Rank: 3Rank: 3

积分
226
金钱
226
注册时间
2014-4-3
在线时间
18 小时
发表于 2014-4-23 13:59:47 | 显示全部楼层
不懂你要别人帮忙看什么?传递数据时突然关闭串口直接导致应用程序卡死是正常的,处理方法应该让它自行结束,有点忘了,添加个进程,让串口工作在进程环境下,就不会导致主函数卡死了。
回复 支持 反对

使用道具 举报

10

主题

108

帖子

0

精华

初级会员

Rank: 2

积分
176
金钱
176
注册时间
2013-12-23
在线时间
2 小时
发表于 2014-4-23 14:37:40 | 显示全部楼层
回复【6楼】dixdsqaid:
---------------------------------
线程吧。。。
只要肯努力,知识是自己的,别人拿不走
回复 支持 反对

使用道具 举报

38

主题

2061

帖子

6

精华

论坛大神

Rank: 7Rank: 7Rank: 7

积分
3273
金钱
3273
注册时间
2012-1-16
在线时间
37 小时
发表于 2014-4-23 17:42:18 | 显示全部楼层
在接受事件中不要直接对界面更新,会报异常。建议使用委托。
站在巨人的肩膀上不断的前进。。。
回复 支持 反对

使用道具 举报

12

主题

85

帖子

0

精华

初级会员

Rank: 2

积分
153
金钱
153
注册时间
2013-11-24
在线时间
0 小时
 楼主| 发表于 2014-4-23 18:58:35 | 显示全部楼层
回复【8楼】xiaoyan:
---------------------------------
嗯嗯  刚看到那里,还不会用呢
学一天不会,我学两天;再不会,再两天·········
回复 支持 反对

使用道具 举报

12

主题

85

帖子

0

精华

初级会员

Rank: 2

积分
153
金钱
153
注册时间
2013-11-24
在线时间
0 小时
 楼主| 发表于 2014-4-23 18:59:22 | 显示全部楼层
回复【6楼】dixdsqaid:
---------------------------------
哦哦,我继续学习下
学一天不会,我学两天;再不会,再两天·········
回复 支持 反对

使用道具 举报

530

主题

11万

帖子

34

精华

管理员

Rank: 12Rank: 12Rank: 12

积分
165475
金钱
165475
注册时间
2010-12-1
在线时间
2115 小时
发表于 2014-4-23 22:42:01 | 显示全部楼层
谢谢分享
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则



关闭

原子哥极力推荐上一条 /2 下一条

正点原子公众号

QQ|手机版|OpenEdv-开源电子网 ( 粤ICP备12000418号-1 )

GMT+8, 2025-5-10 04:46

Powered by OpenEdv-开源电子网

© 2001-2030 OpenEdv-开源电子网

快速回复 返回顶部 返回列表