本文介绍了通过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!推荐答案 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传输命令并从微控制器接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-26 14:38