本文介绍了如何发送“1”到串口,然后接收pic在收到“1”后发送给我的值。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以写一个字节到串口然后读取它会发给我的值吗?

i希望能够写入串口1

,当我的微型控制器收到这个1时,它会发给我稍后想要使用的portD的值



但是我不能与串口正确通信



这不是我正在尝试构建的程序,但我只测试了如何从/向读取和写入的基础知识一个串口,到目前为止没有任何工作:/



我只是测试如何与串口通信,这是我正在尝试的代码



i有一个按钮,当我点击我想要发送1然后textbox1将显示收到的值



can i write a byte to the serial port and then read the values it 'll send me ?
i want to be able to write to the serial port "1"
and when my pic micro controller receives this "1" it will sends me the values of portD in which i want to use later

but i 'm not able to communicate correctly with the serial port

this is not the program i'm trying to build but i' just testing the basics on how to read and write from/to a serial port and nothing is working so far :/

i'm just testing how to communicate with the serial port and this is the code i'm trying

i have a button that when i click i want a "1" to be sent and then the textbox1 will display the value received

SerialPort serialPort1 = new SerialPort("COM2", 300, Parity.None, 8, StopBits.One);
        
        private void button1_Click(object sender, EventArgs e)
        {
            serialPort1.Open();
            serialPort1.Write("1");
            serialPort1.Close();

            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
                serialPort1.Open();

            }
            else
            {
                serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
                serialPort1.Open(); //opens the port
            }

        }
        int rs;

        private void serialPort1_DataReceived(object sender,SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort1=(SerialPort)sender;
            try
            {

                rs = serialPort1.ReadByte();
                this.Invoke(new EventHandler(type));
            }
            catch (System.TimeoutException)
            {
            }


        }
        private void type(object s,EventArgs e)
        {
            textBox1.Text = rs.ToString();
        }

推荐答案

string data = SerialPort1.ReadExisting();
Invoke(new MethodInvoker(() => { ShowData(data);}));




private void ShowData(string s)
   {
   textBox1.Text += s;
   }


这篇关于如何发送“1”到串口,然后接收pic在收到“1”后发送给我的值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 06:35