我正在創建程式來用 Arduino 測量真空值并以用 C# 創建的形式顯示它。我想將時間存盤為常數。這是節目的開始時間。我為它分配了“連接”按鈕。當我點擊時,時間值正在存盤。然后我使用“計時器滴答”方法立即查看測量值。此外, DateTime.Now 顯示即時系統時間。它像時鐘一樣在變化。 點擊這里查看圖片
這是連接按鈕的代碼;
public void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
try
{
if (comboBox1.Text == "")
{
MessageBox.Show("Please select the port name!");
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.ReadBufferSize = 8;
serialPort1.Open();
timeval.Clear();
button1.Enabled = false;
button2.Enabled = true;
timer1.Start();
DateTime myDateTime = DateTime.Now; //It stores the instant time information when button is clicked.
label14.Text = myDateTime.ToString(); // shows in the label
//serialPort1.ReadTimeout = 300;
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorized Access!");
}
}
這是計時器滴答的代碼;
public void timer1_Tick(object sender, EventArgs e)
{
label12.Text = DateTime.Now.ToString();
//TimeSpan time_difference = DateTime.Now - myDateTime; // trying to calculate time difference.
//double saniye = time_difference.Seconds;
//double dakika = time_difference.Minutes;
//label10.Text = (Math.Round(saniye)).ToString();
//label16.Text = (Math.Round(dakika)).ToString();
new_data = 756 * (float.Parse(data) - 1023) / 1023;
sensorval.Add(Math.Round(new_data, 1));
all_data.Add(Math.Round(new_data, 1));
textBox1.Text = Convert.ToString(Math.Round(new_data, 2));
all_data.Sort();
var peak_vacuum = all_data[0];
textBox4.Text = peak_vacuum.ToString();
if (sensorval.Count % 100 == 0)
{
sensorval.Sort();
var find_max = sensorval[0];
var find_min = sensorval[sensorval.Count - 1];
textBox3.Text = find_min.ToString();
textBox2.Text = find_max.ToString();
sensorval.RemoveRange(0, 99);
}
}
我無法計算時間差,因為 myDateTime 變數在 button2 中計算并在 button2 方法中定義。但是 DateTime.Now 是在計時器滴答方法中定義的。因此,我收到“當前內容中不存在名稱‘myDateTime’”的錯誤訊息。在計時器滴答方法中。順便說一句,我嘗試在計時器滴答聲中使用計數器來查看程式運行后的秒數。它不是那么準確。它比實際時間慢。所以,我選擇了上面的方法。先感謝您。
uj5u.com熱心網友回復:
我認為它就像你想要的。
public partial class Form1 : Form
{
// accessable from all methods, events on Form1
private DateTime myDateTime;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myDateTime = DateTime.Now;
// other codes
}
private void timer1_Tick(object sender, EventArgs e)
{
// other codes
}
private void button2_Click(object sender, EventArgs e)
{
// other codes
var diffrenceSpan = DateTime.Now - myDateTime;
var hours = diffrenceSpan.Hours;
var minutes = diffrenceSpan.Minutes;
var seconds = diffrenceSpan.Seconds;
}
}
gits 專案鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468880.html
上一篇:相互使用多個Linq查詢
