private void cliButton_Click(object sender, EventArgs e)
{
sp = new SerialPort();
sp.PortName = "COM14";
sp.BaudR开发者_高级运维ate = 19200;
sp.Parity = Parity.None;
sp.DataBits = 8;
sp.StopBits = StopBits.One;
sp.Handshake = Handshake.RequestToSend;
sp.DtrEnable = true;
sp.RtsEnable = true;
sp.Open();
if (!sp.IsOpen)
{
MessageBox.Show("Serial port is not opened");
return;
}
sp.WriteLine("AT" + Environment.NewLine);
sp.WriteLine("AT+CLIP=1" + Environment.NewLine);
byte [] data= new byte [sp.BytesToRead];
sp.Read(data, 0, data.Length);
}
Here is my code. it is use to communicate with the mobile phone through serial port. Here im sending AT command (AT+CLIP=1 this command use to take CLI of the incomming call) to serialport. Then i read the data of the serial port. My problem is How can i print this readed data in the label.
BytesToRead is going to be 0 when you run this code without a debugger. It takes time for the serial port device to send a response. This ought to solve your problem:
label1.Text = sp.ReadLine();
ReadLine() keeps reading until it detects a SerialPort.NewLine in the response.
If you just want to display the result that is returned you can do:
label.Text = sp.ReadExisting();
If you want to display port output in hex format separated by space use this:
_label.Text = string.Join(" ", data.Select(b => string.Format("{0:X2}", b)));
精彩评论