通过RS232传输命令并从微控制器接收数据 [英] Transmit command and receive data from microcontroller via RS232

查看:83
本文介绍了通过RS232传输命令并从微控制器接收数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一个项目,我想控制一些基于PIC16F688和C#的家庭应用程序。



我设计了一个使用C#的用户界面图形并向PIC发送命令。

当我向微控制器发送一个命令然后打开/关闭灯等等。

这个功能没问题。



但是当我向微控制器发送一个命令时我想从温度传感器接收一个响应数据(那个连接到PIC)。

我收到RS232缓冲区中的所有数据(都发送数据和接收数据)。

如何才能接收响应数据(温度值)?



每个人都请帮帮我!

Hello everybody,

I have a project that I want to control some home applications based on PIC16F688 and C#.

I designed a user interface graphic use C# and send to PIC a command.
When I send to microcontroller a command then turn on/off light and something like that.
This function is OK.

But when I send to microcontroller a command and I want to received a response data from temperature sensor (that connect to PIC).
I received all data have in buffer of RS232 (both send data and receive data).
How can I do to only receive response data (temperature value)?

Everybody help me please!

推荐答案

你只需要使用类 System.IO.Ports.SerialPort ,请参阅 http ://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx [ ^ ]。



没问题同时接收和发送数据。它实际上取决于您的设备指示的某些应用程序级协议,因此您需要解决其文档。



您无法读取只是温度值 。
这是串行通信。 您需要阅读所有发送给您的内容并动态解释这些数据。您最好的选择是创建一个单独的线程,无条件地读取所有内容并在发生事件时将数据推送到其他线程。读取操作是阻塞的,所以你不想阻止你的主线程。



对于适当的线程间通信,请阅读我的简短提示/技巧文章用于线程通信和线程间调用的简单阻塞队列 [ ^ ]。br />


要通知UI线程,您需要使用方法调用 BeginInvoke of System.Windows.Threading.Dispatcher (对于Forms或WPF)或 System.Windows.Forms.Control (仅限表格)。



您将在我过去的答案中找到有关工作原理和代码示例的详细说明:

< a href =http://www.codeproject.com/Questions/159098/Control-Invoke-vs-Control-BeginInvoke.aspx> Control.Invoke()vs. Control.Be ginInvoke() [ ^ ],

Treeview扫描仪和MD5的问题 [ ^ ]。



另请参阅我过去的线程回答链接集:

如何获得keydown事件在vb.net中的另一个线程上运行 [ ^ ],

ç启用禁用+多线程后,ontrol事件未触发 [ ^ ]。







实际上,并非一切都如我所描述的那么简单。我最近意识到阅读线程被唤醒存在一个微妙的问题,并详细解释了问题和解决方案。请参阅: thread.suspend,thread.resume方法 [ ^ ]。br />


-SA
All you need is using the class System.IO.Ports.SerialPort, see http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx[^].

There is not problem to receive and send data at the same time. It actually depends on some application-level protocol dictating by your device, so you need to address to its documentation.

You cannot read "just temperature value".
This is serial communication. You need to read all what is sent to you and interpret this data on the fly. Your best option is creating a separate thread which unconditionally reads everything and push data to other thread when something happen. Read operation is blocking, so you don't want to block you main thread.

For appropriate inter-thread communication read my short Tips/Tricks article Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].

To notify UI thread, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also my collection of links to my past answers on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].



Actually, not everything is so simple as I described. I recently realized that there is a delicate problem with a reading thread waken up and explained the issue and the solution in detail. Please see: thread.suspend, thread.resume methods[^].

—SA


这是我的代码,请您帮我解读。

谢谢!

This is my code, you read help me please.
Thank you!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.IO;

namespace GTPT_688
{
    public partial class Form1 : Form
    {
        //byte ack = 0;
        //byte[] buff;
        string valueOfTemperature;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //configuring the serial port
            serialPort1.PortName = "COM5";
            serialPort1.BaudRate = 19200;
            serialPort1.DataBits = 8;
            serialPort1.Parity = Parity.None;
            serialPort1.StopBits = StopBits.One;
            serialPort1.DtrEnable = true;
            serialPort1.RtsEnable = true;
            //valueOfTemperature = 0;
            //buff = new byte[1];
            if (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Open();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
            }
        }
       private void Send_Click(object sender, EventArgs e)
       {
           if (ck1.Checked == true)
           {
               byte[] mBuffer = new byte[1];
               mBuffer[0] = 0x6F; //ASCII for o;.
               serialPort1.Write(mBuffer, 0, mBuffer.Length);
           }
           if (ck1.Checked==false)
           {
               byte[] mBuffer = new byte[1];
               mBuffer[0] = 0x66; //ASCII for f;.
               serialPort1.Write(mBuffer, 0, mBuffer.Length);
           }
                if (ck2.Checked==true)
                {
                    byte[] mBuffer = new byte[1];
                    mBuffer[0] = 0x74; //ASCII for t;.
                    serialPort1.Write(mBuffer, 0, mBuffer.Length);
                }
        }
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
               valueOfTemperature += serialPort1.ReadExisting();
               this.Invoke(new EventHandler(DisplayText));
        }
        private void DisplayText(object sender, EventArgs e)
        {
            //if (sender == serialPort1)
            //byte[] buff = new byte[serialPort1.BytesToRead];
            //serialPort1.Read(buff, 0, buff.Length);
            //string str = Encoding.ASCII.GetString(buff);
                lb1.Text = valueOfTemperature;
        }
        private void bn1_Click(object sender, EventArgs e)
        {

        }
    }
}


这篇关于通过RS232传输命令并从微控制器接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆