0% found this document useful (0 votes)
13 views5 pages

Serial Port Control in C# WinForms

The document is a C# code for a Windows Forms application that interfaces with serial ports. It includes functionalities for connecting and disconnecting from COM ports, sending commands based on time, and handling data received from the serial port to update the UI. The application supports both manual and automatic modes for sending commands to connected devices.

Uploaded by

hịhd Hdhc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views5 pages

Serial Port Control in C# WinForms

The document is a C# code for a Windows Forms application that interfaces with serial ports. It includes functionalities for connecting and disconnecting from COM ports, sending commands based on time, and handling data received from the serial port to update the UI. The application supports both manual and automatic modes for sending commands to connected devices.

Uploaded by

hịhd Hdhc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

using [Link].

Forms;
using [Link];
using System;

namespace baiCOM
{
public partial class Form1 : Form
{
private bool isManualMode = false;
private bool isMode3Active = false;
private int lastHour = -1;

public Form1()
{
InitializeComponent();
[Link] += new EventHandler(this.button1_Click);
[Link] += new EventHandler(this.button2_Click);
[Link] += new EventHandler(this.button3_Click_1);
[Link] += new EventHandler(this.button6_Click_1);
[Link] += new EventHandler(this.button7_Click_1);
[Link] += serialPort1_DataReceived;
[Link] += timer1_Tick;
[Link] = 1000;
[Link] = true;
}

private void Form1_Load(object sender, EventArgs e)


{
string[] ports = [Link]();
foreach (string port in ports)
{
[Link](port);
}
}

private void timer1_Tick(object sender, EventArgs e)


{
[Link] = [Link]("HH:mm:ss");

if (isMode3Active && !isManualMode)


{
int currentHour = [Link];
if (currentHour != lastHour)
{
lastHour = currentHour;
SendMode3CommandByTime();
}
}
}

private void SendMode3CommandByTime()


{
if (![Link]) return;

int hour = [Link];


if (hour >= 5 && hour < 22)
{
[Link]("C");
}
else
{
[Link]("B");
}
}

private void serialPort1_DataReceived(object sender,


SerialDataReceivedEventArgs e)
{
string data = [Link]();
[Link](new Action(() =>
{
if ([Link]("R"))
{
[Link] = [Link];
}
if ([Link]("Y"))
{
[Link] = [Link];
}
if ([Link]("G"))
{
[Link] = [Link];
}
}));
}

private void button4_Click(object sender, EventArgs e)


{
if ([Link] == "")
{
[Link]("Vui lòng chọn cổng COM.",
"Cảnh báo", [Link],
[Link]);
}
else
{
try
{
if (![Link])
{
[Link] = [Link];
[Link]();
[Link] = "Connected";
[Link] = [Link];
[Link] = false;
}
else
{
[Link]("Cổng COM đã được kết nối.",
"Cảnh báo", [Link],
[Link]);
}
}
catch
{
[Link]("Không thể kết nối cổng COM, vui lòng kiểm
tra.",
"Cảnh báo", [Link],
[Link]);
}
}
}

private void button5_Click(object sender, EventArgs e)


{
try
{
if ([Link])
{
[Link]();
[Link] = "Disconnected";
[Link] = [Link];
[Link] = true;
}
else
{
[Link]("Cổng COM đã được ngắt kết nối.",
"Cảnh báo", [Link],
[Link]);
}
}
catch
{
[Link]("Không thể ngắt kết nối cổng COM, vui lòng kiểm
tra.",
"Cảnh báo", [Link],
[Link]);
}
}

private void button1_Click(object sender, EventArgs e)


{
isMode3Active = false;

if (isManualMode) return;

if ([Link])
{
try
{
[Link]("A");
}
catch (Exception ex)
{
[Link]("Lỗi gửi dữ liệu: " + [Link],
"Lỗi", [Link],
[Link]);
}
}
}

private void button2_Click(object sender, EventArgs e)


{
isMode3Active = false;

if (isManualMode) return;
if ([Link])
{
try
{
[Link]("B");
}
catch (Exception ex)
{
[Link]("Lỗi gửi dữ liệu: " + [Link],
"Lỗi", [Link],
[Link]);
}
}
}

private void button3_Click_1(object sender, EventArgs e)


{
if (isManualMode) return;

if ([Link])
{
try
{
isMode3Active = true;
lastHour = -1;
SendMode3CommandByTime();
}
catch (Exception ex)
{
[Link]("Lỗi gửi dữ liệu: " + [Link]);
}
}
}

private void button6_Click_1(object sender, EventArgs e)


{
isManualMode = true;
isMode3Active = false;

[Link] = false;
[Link] = false;
[Link] = false;

[Link] = "Chế độ Thủ công";

if ([Link])
{
try
{
[Link]("M");
}
catch (Exception ex)
{
[Link]("Lỗi gửi M: " + [Link],
"Lỗi", [Link],
[Link]);
}
}
}
private void button7_Click_1(object sender, EventArgs e)
{
isManualMode = false;
[Link] = true;
[Link] = true;
[Link] = true;

[Link] = "Chế độ Giao diện";

if ([Link])
{
try
{
[Link]("G");
}
catch (Exception ex)
{
[Link]("Lỗi gửi G: " + [Link],
"Lỗi", [Link],
[Link]);
}
}
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { }


private void textBox1_TextChanged(object sender, EventArgs e) { }
private void textBox2_TextChanged(object sender, EventArgs e) { }
private void pictureBox2_Click(object sender, EventArgs e) { }
private void button1_Click_1(object sender, EventArgs e) { }
private void button8_Click(object sender, EventArgs e) { }
private void textBox2_TextChanged_1(object sender, EventArgs e) { }
private void textBox3_TextChanged(object sender, EventArgs e) { }
private void textBox4_TextChanged(object sender, EventArgs e) { }
private void textBox6_TextChanged(object sender, EventArgs e) { }
}
}

Common questions

Powered by AI

The application utilizes event-driven programming by linking user interface controls to specific event handlers. Each button click triggers associated methods that change the state of the application or execute direct actions, like sending serial commands or updating UI elements. This concept allows asynchronous operation management, providing a responsive user interface that reacts to user input independently of other ongoing processes .

The application provides distinct functionalities for manual and automatic modes using state variables. When entering manual mode, all automatic controls are disabled, and a command 'M' is sent to the serial port. Conversely, enabling interface mode reactivates automatic controls and sends a command 'G'. These modes are toggled by altering button states and updating text boxes accordingly, indicating a layered user interface design .

The application updates the UI by changing text box backgrounds and enabling/disabling buttons to reflect connection status and operational modes. Usability improvements could include adding visual indicators like icons for mode status, an activity log for operations performed, or tooltips for button functions to enhance user understanding and interaction feedback .

Multi-threading is handled through the 'Invoke' method, which allows updating UI elements from the data received event. This ensures that these updates run on the UI thread, preventing cross-thread operation issues while maintaining responsiveness during data reception from the serial port .

When "button4" is clicked and the serial port is not already open, the program attempts to open a connection to the port specified in the combobox. If successful, the status text box is updated to "Connected" with a lime background, and the combobox is disabled to prevent further changes .

The software updates traffic light colors using a data-driven approach by checking the received data for specific characters. If the data contains 'R', 'Y', or 'G', the software sets the image of a picture box to corresponding red, yellow, or green light resources, thus changing the visual cue .

The error handling mechanism for opening the serial port relies on a try-catch block which displays an error message if the connection fails. Potential improvements include logging detailed error information to a file for troubleshooting, allowing the user to reattempt the connection, or providing more specific guidance on error resolution steps .

Using a global timer allows for scheduled tasks, such as periodically checking time-based triggers, without additional input from the user. However, this approach may lead to performance issues if not managed properly, particularly if multiple time-dependent actions are added. Optimizing timer tick intervals and ensuring that each call efficiently manages computational resources could enhance application responsiveness .

The application checks the current hour using a timer that ticks every second. If the mode 3 is active and not in manual mode, it verifies if the current hour has changed since the last execution. If so, it sends the command 'C' between 5 AM and 9 PM, and 'B' from 9 PM to 5 AM .

'comboBox1' serves as an interface for users to select available COM ports for serial communication. Its state is significant because it determines whether the user can change the port. Once a port connection is established, it is disabled to prevent accidental changes that could disrupt communication .

You might also like