c#serialport读不到ReadLine值(串口通信)
[复制链接]
using System;
using System.Linq;
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;
namespace MyWinCETest
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void InitCom(string portName)
{
serialPort1.PortName = portName;
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.Parity = Parity.None;
serialPort1.ReceivedBytesThreshold = 4;
serialPort1.Open();
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
StringBuilder strBuilder = new StringBuilder();
while (serialPort1.BytesToRead > 0)
{
char ch = (char)serialPort1.ReadByte();
strBuilder.Append(ch);
}
strBuilder = new StringBuilder();
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
InitCom("COM1");
SendStrData(txtSend.Text);
ReceiveStrData();
}
public void SendStrData(string strCom)
{
serialPort1.Write(strCom);
}
public void ReceiveStrData()
{
Thread.Sleep(1000);
string testStr = serialPort1.ReadLine();
byte[] data = Convert.FromBase64String(serialPort1.ReadLine());
txtReceive.Text = Encoding.Unicode.GetString(data, 0, data.Length);
}
}
}
小弟是新手,今天刚刚装了WinCE6.0,现在测试下,我读到的testStr 值为空,而程序运行到这里就断开了。QQ:596516940