我在VS中使用过这段代码
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string RxString,ComPort;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.PortName = "COM5";
serialPort1.BaudRate = 9600;
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
serialPort1.Handshake = Handshake.None;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void Start_Click(object sender, EventArgs e)
{
serialPort1.PortName = ComPort;
serialPort1.BaudRate = 9600;
serialPort1.Open();
if(serialPort1.IsOpen)
{
Start.Enabled = false;
Stop.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void Stop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
Start.Enabled = true;
Stop.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!serialPort1.IsOpen) return;
char[] buff = new char[1];
buff[0] = e.KeyChar;
serialPort1.Write(buff, 0 , 1);
e.Handled = true;
}
private void DisplayText(object sender, EventArgs e)
{
textBox1.AppendText(RxString);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComPort = comboBox1.SelectedItem.ToString();
}
}
}
但它不起作用,我尝试使用 avr 传输字符并在 hercules 中成功测试了它的传输内容。但它没有出现在我的程序中。请帮忙。
我已经更新了代码,它的接收部分工作正常,但没有正确传输,我没有收到任何错误,它只是不能正常工作,因为它应该工作。