I'm trying to display the data received on textbox. But I realized that when data were being received on Br@y terminal it look fine (eg. 14:02:33.43 > T 11 22.32) but running on the software the time stamp is missing.
Am I missing out anything which lead to this?
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.Data.OleDb;
using System.IO;
namespace SerialCom
{
public partial class Form1 : Form
{
string RxString; //Variable
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
btnStart.Enabled = false;
btnStop.Enabled = true;
txtData.ReadOnly = false;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
btnStart.Enabled = true;
btnStop.Enabled = false;
txtData.ReadOnly = true;
}
}
private void txtData_KeyPress(object sender, KeyPressEventArgs e)
{
if (!serialPort1.IsOpen) return; // If the port is closed, don't try to send a character.
char[] buff = new char[8]; // If the port is Open, declare a char[] array with one element.
buff[0] = e.KeyChar; // Load element 0 with the key character.
serialPort1.Write(buff, 0, 1); // Send the one character buffer.
e.Handled = true;// Set the KeyPress event as handled so the character won't
// display locally. If you want it to display, omit the next line.
}
private void DisplayText(object sender, EventArgs e)
{
txtData.AppendText(RxString);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
StreamWriter MyStreamWriter = new StreamWriter(@"c:\testing.txt",true); //True tell SW to append to file instead of overwriting
MyStreamWriter.Write(RxString);
MyStreamWriter.Flush();
MyStreamWriter.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen)
serialPort1.Close();
}
}
}
Basically, I was wrong by saying that the time stamp is originally included in the data i received.. I need to add in the time stamp on my own.. This was to act as a record of when did i actually received the following data.
As a result, what's missing is this
string time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff")
Hope this helps people who are struggling with the problem too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.