本文介绍了Visual Studio 2010 C#Serial,无法读取端口。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好。
我在收到并显示在文本框中时遇到问题。
我可以毫无问题地发送数据(到微控制器),但我不能显示微型发送的内容。
我尝试了每个可用的教程,但仍然无法收到。
Hello.
I have an issue with receiving and displaying in a text box.
I can send data with no problem (to the microcontroller) but I can`t display what the micro is sending.
I tried every tutorial available but still can`t receive.
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;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getAvailablePorts();
}
void getAvailablePorts()
{
string[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
if(comboBox1.Text==""){
readBox.Text = "Select Port COM";
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = 115200;
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
serialPort1.Handshake = Handshake.None;
serialPort1.Open();
initButton.Enabled = false;
sendButton.Enabled = true;
readButton.Enabled = true;
disconnectButton.Enabled = true;
//
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
}
catch (UnauthorizedAccessException)
{
readBox.Text = "Error";
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.Text = serialPort1.PortName;
}
private void sendButton_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(input1.Text);
input1.Text = "";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private string DispString;
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
DispString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
}
//
private void DisplayText(object sender, EventArgs e)
{
readBox.AppendText(DispString);
}
private void readButton_Click_1(object sender, EventArgs e)
{
try
{
//readBox.Text = serialPort1.ReadExisting();
}
catch (TimeoutException)
{
readBox.Text = "timeout";
}
}
private void disconnectBotton_Click(object sender, EventArgs e)
{
initButton.Enabled = true;
sendButton.Enabled = false;
readButton.Enabled = false;
}
private void readBox_TextChanged(object sender, EventArgs e)
{
}
}
}
推荐答案
Ed Tenholder
这篇关于Visual Studio 2010 C#Serial,无法读取端口。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!