System.IO.Ports.SerialPort.Close()

Here are the examples of the csharp api System.IO.Ports.SerialPort.Close() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

138 Examples 7

19 Source : SerialController.cs
with GNU General Public License v3.0
from akmadian

public void Dispose()
        {
            _Port.Close();
        }

19 Source : ArduinoReceive_ Section 6.cs
with GNU General Public License v3.0
from AlexandreDoucet

void OnDestroy()
	{
		arduinoPort.Close();
	}

19 Source : Serial.cs
with MIT License
from AlexGyver

public bool Open()
        {
            if (serial.IsOpen)
            {
                try { serial.Close(); }
                catch { }
            }

            serial.PortName = Port;

            try
            {
                serial.Open();
            }
            catch (IOException e)
            {
                return false;
            }

            return true;
        }

19 Source : Serial.cs
with MIT License
from AlexGyver

public void Close()
        {
            if (serial.IsOpen)
            {
                serial.Close();
            }
        }

19 Source : Serial.cs
with MIT License
from AlexGyver

public void Write(byte[] data)
        {
            if (serial.IsOpen)
            {
                try
                {
                    serial.Write(data, 0, data.Length);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ошибка отправки данных в COM-порт:\r\n\r\n" + ex.Message);

                    try { serial.Close(); }
                    catch { }

                    Open();
                }
            }
        }

19 Source : Heatmaster.cs
with MIT License
from AlexGyver

public override void Close() {
      serialPort.Close();
      serialPort.Dispose();
      serialPort = null;
      base.Close();
    }

19 Source : ModbusClient.cs
with MIT License
from AndreasAmMueller

private void DisconnectInternal()
		{
			try
			{
				logger?.LogTrace("ModbusClient.DisconnectInternal enter");

				if (!isStarted)
					return;

				try
				{
					stopCts?.Cancel();
					reconnectTcs?.TrySetResult(false);
					reconnectTcs = null;
				}
				catch
				{ }

				try
				{
					sendCts?.Cancel();
					lock (queueLock)
					{
						foreach (var task in sendQueue)
						{
							task.TaskCompletionSource.TrySetCanceled();
							task.Registration.Dispose();
						}
						sendQueue.Clear();
					}
				}
				catch
				{ }

				bool connected = false;
				lock (reconnectLock)
				{
					connected = IsConnected;
					IsConnected = false;
					wasConnected = false;
				}

				try
				{
					serialPort?.Close();
					serialPort?.Dispose();
					serialPort = null;
				}
				catch
				{ }

				if (connected)
					Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();

				isStarted = false;

				if (driverModified)
				{
					try
					{
						var rs485 = GetDriverState();
						rs485.Flags = serialDriverFlags;
						SetDriverState(rs485);
						driverModified = false;
					}
					catch (Exception ex)
					{
						logger?.LogError(ex, "ModbusClient.Disconnect failed to reset the serial driver state.");
						throw;
					}
				}
			}
			finally
			{
				logger?.LogTrace("ModbusClient.DisconnectInternal leave");
			}
		}

19 Source : ModbusRtuSerialPort.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

public void Close()
        {
            _serialPort.Close();
        }

19 Source : SerialReceiver.cs
with MIT License
from atakansarioglu

public void ClosePort()
        {
            // Close if it is open.
            if(IsOpen())
                serialPort.Close();
        }

19 Source : LoraArduinoSerial.cs
with MIT License
from Azure

public void Dispose()
        {
            this.serialPort.DataReceived -= OnSerialDeviceData;
            this.serialPort.Close();
            this.serialPort = null;
            GC.SuppressFinalize(this);
        }

19 Source : Program.cs
with MIT License
from AzureIoTGBB

static void Main(string[] args)
        {
            Thread readThread = new Thread(Read);

            InitDeviceClient().Wait();

            _serialPort = new SerialPort();

                    // Allow the user to set the appropriate properties.
            _serialPort.PortName = PortName;
            _serialPort.BaudRate = 9600;
            _serialPort.Parity = Parity.None;
            _serialPort.DataBits = 8;
            _serialPort.StopBits = StopBits.One;
            _serialPort.Handshake = Handshake.None;

            // Set the read/write timeouts
            _serialPort.ReadTimeout = 500;
            _serialPort.WriteTimeout = 500;

            _serialPort.Open();
            Console.WriteLine($"Serial port [{PortName}] opened");

            _continue = true;
            readThread.Start();

            Console.WriteLine("press <enter> to exit");

            Console.ReadLine();

            _continue = false;

            readThread.Join();
            _serialPort.Close();
            //_deviceClient.Close();

        }

19 Source : SerialMonitor.cs
with GNU General Public License v3.0
from benlye

public void SerialDisconnect()
        {
            SerialPort serialPort = this.SerialPort;

            if (serialPort != null)
            {
                serialPort.DtrEnable = false;
                serialPort.RtsEnable = false;
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }

                serialPort.Dispose();
            }

            this.SerialPort = null;
            this.buttonConnect.Enabled = true;
            this.buttonDisconnect.Enabled = false;

            this.Text = $"Flash Multi Serial Monitor - {this.SerialPortName} (Disconnected)";

            Debug.WriteLine($"Disconnected from {this.SerialPortName}.");
        }

19 Source : ComPort.cs
with GNU General Public License v3.0
from benlye

public static bool CheckPort(string port)
        {
            // Skip the check and return true if the selected port is 'DFU Device'
            if (port == "DFU Device")
            {
                return true;
            }

            bool result = false;

            // Try to open the serial port, catch an exception if we fail
            SerialPort serialPort = new SerialPort(port);
            try
            {
                serialPort.Open();
                if (serialPort.IsOpen)
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                Thread.Sleep(50);
                serialPort.Close();
            }

            return result;
        }

19 Source : MainForm.cs
with MIT License
from bestyize

private void Btn_open_com_Click(object sender, EventArgs e)
        {
            if (mSerialPort != null)
            {
                if (mSerialPort.IsOpen)
                {
                    try
                    {
                        mSerialPort.Close();
                        btn_open_com.Text = "打开串口";
                        btn_open_com.ForeColor = Color.Black;
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("串口关闭失败");
                    }
                }
                else
                {
                    try
                    {
                        mSerialPort.Open();
                        btn_open_com.Text = "关闭串口";
                        btn_open_com.ForeColor = Color.Red;
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("串口" + mSerialPort.PortName + "被占用,无法打开,请关闭占用串口的程序");
                        btn_open_com.Text = "打开串口";
                        btn_open_com.ForeColor = Color.Black;
                    }
                }

                
            }
            else
            {
                serialPortListInit();
            }

        }

19 Source : MainForm.cs
with MIT License
from bestyize

private void Cb_com_list_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            if (mSerialPort != null)
            {
                if (mSerialPort.IsOpen)
                {
                    mSerialPort.Close();
                }
                btn_open_com.Text = "打开串口";
                btn_open_com.ForeColor = Color.Black;
                mSerialPort = null;
                serialPortListInit();
                
            }
            


        }

19 Source : InfiniteDiscoveryMachineSimulator.cs
with MIT License
from Binomica-Labs

public void generateHardwareRandomDNA()
        {
            try
            {
                UpdateStatusBar("Generating Random DNA...");
                rngRawNums = new int[desiredRandomDNALength];
                rngNucleotides = new char[desiredRandomDNALength];



                for (int i = 0; i < desiredRandomDNALength; i++)
                {
                    UpdateStatusBar("Generating Random DNA..." + ((i / desiredRandomDNALength) * 100).ToString());
                    rngRawNums[i] = rngPort.ReadByte();

                    if (rngRawNums[i] >= 0 && rngRawNums[i] <= 63)
                    {
                        rngNucleotides[i] = 'A';
                    }
                    else if (rngRawNums[i] >= 64 && rngRawNums[i] <= 127)
                    {
                        rngNucleotides[i] = 'T';
                    }
                    else if (rngRawNums[i] >= 128 && rngRawNums[i] <= 191)
                    {
                        rngNucleotides[i] = 'G';
                    }
                    else if (rngRawNums[i] >= 192 && rngRawNums[i] <= 255)
                    {
                        rngNucleotides[i] = 'C';
                    }
                }

                rngDNA = string.Join("", rngNucleotides);
                rngRaw = string.Join(" ", rngRawNums);
                rngPort.Close();
                UpdateStatusBar("Generation Complete!");

                txtDNA.Invoke((MethodInvoker)delegate
                {
                    txtDNA.Text = rngDNA;
                });

                txtRawData.Invoke((MethodInvoker)delegate
                {
                    txtRawData.Text = rngRaw;
                });

                btnShred.Invoke((MethodInvoker)delegate
                {
                    btnShred.Enabled = true;
                });

                btnSave.Invoke((MethodInvoker)delegate
                {
                    btnSave.Enabled = true;
                });

                btnGlue.Invoke((MethodInvoker)delegate
                {
                    btnGlue.Enabled = true;
                });

                txtDNA.Invoke((MethodInvoker)delegate
                {
                    txtDNA.Text = rngDNA;
                });

                txtDNALength.Invoke((MethodInvoker)delegate
                {
                    txtDNALength.Text = rngDNA;
                });
                generatorThreadComplete = true;
            }

            catch (Exception e)
            {
                UpdateStatusBar("Generation Error. Check RNG connection...");
                rngPort.Close();
                MessageBox.Show(e.Message);
            }

        }

19 Source : InfiniteDiscoveryMachineSimulator.cs
with MIT License
from Binomica-Labs

private void IDMsimulator_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (rngPort.IsOpen == true)
            {
                rngPort.DiscardInBuffer();
                rngPort.DiscardOutBuffer();
                rngPort.Dispose();
                rngPort.Close();
            }
        }

19 Source : Arduino.cs
with MIT License
from bonsai-rx

private void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    serialPort.Close();
                    disposed = true;
                }
            }
        }

19 Source : SerialPortManager.cs
with MIT License
from bonsai-rx

internal static SerialPortDisposable ReserveConnection(string portName, SerialPortConfiguration serialPortConfiguration)
        {
            if (string.IsNullOrEmpty(portName))
            {
                if (!string.IsNullOrEmpty(serialPortConfiguration.PortName)) portName = serialPortConfiguration.PortName;
                else throw new ArgumentException("An alias or serial port name must be specified.", "portName");
            }

            Tuple<SerialPort, RefCountDisposable> connection;
            lock (openConnectionsLock)
            {
                if (!openConnections.TryGetValue(portName, out connection))
                {
                    var serialPortName = serialPortConfiguration.PortName;
                    if (string.IsNullOrEmpty(serialPortName)) serialPortName = portName;

                    var configuration = LoadConfiguration();
                    if (configuration.Contains(serialPortName))
                    {
                        serialPortConfiguration = configuration[serialPortName];
                    }

                    var serialPort = new SerialPort(
                        serialPortName,
                        serialPortConfiguration.BaudRate,
                        serialPortConfiguration.Parity,
                        serialPortConfiguration.DataBits,
                        serialPortConfiguration.StopBits);
                    serialPort.ReceivedBytesThreshold = serialPortConfiguration.ReceivedBytesThreshold;
                    serialPort.ReadBufferSize = serialPortConfiguration.ReadBufferSize;
                    serialPort.WriteBufferSize = serialPortConfiguration.WriteBufferSize;
                    serialPort.ParityReplace = serialPortConfiguration.ParityReplace;
                    serialPort.Handshake = serialPortConfiguration.Handshake;
                    serialPort.DiscardNull = serialPortConfiguration.DiscardNull;
                    serialPort.DtrEnable = serialPortConfiguration.DtrEnable;
                    serialPort.RtsEnable = serialPortConfiguration.RtsEnable;

                    var encoding = serialPortConfiguration.Encoding;
                    if (!string.IsNullOrEmpty(encoding))
                    {
                        serialPort.Encoding = Encoding.GetEncoding(encoding);
                    }

                    serialPort.Open();
                    serialPort.ReadExisting();
                    var dispose = Disposable.Create(() =>
                    {
                        serialPort.Close();
                        openConnections.Remove(portName);
                    });

                    var refCount = new RefCountDisposable(dispose);
                    connection = Tuple.Create(serialPort, refCount);
                    openConnections.Add(portName, connection);
                    return new SerialPortDisposable(serialPort, refCount);
                }
            }

            return new SerialPortDisposable(connection.Item1, connection.Item2.GetDisposable());
        }

19 Source : SerialStream.cs
with GNU General Public License v3.0
from BrianLima

private void BackgroundWorker_DoWork(object tokenObject)
        {
            var cancellationToken = (CancellationToken)tokenObject;
            SerialPort serialPort = null;

            if (String.IsNullOrEmpty(COM_PORT)) return;

            //retry after exceptions
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    const int baudRate = 1000000; // 115200;
                    serialPort = new SerialPort(COM_PORT, baudRate);
                    serialPort.Open();

                    //send frame data
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        _stopwatch.Start();

                        byte[] outputStream = GetOutputStream();
                        serialPort.Write(outputStream, 0, outputStream.Length);

                        //ws2812b LEDs need 30 µs = 0.030 ms for each led to set its color so there is a lower minimum to the allowed refresh rate
                        //receiving over serial takes it time as well and the arduino does both tasks in sequence
                        //+1 ms extra safe zone
                        var fastLedTime = (outputStream.Length - _messagePreamble.Length) / 3.0 * 0.030d;
                        var serialTransferTime = outputStream.Length * 10.0 * 1000.0 / baudRate;
                        var minTimespan = (int)(fastLedTime + serialTransferTime) + 1;

                        var delayInMs = Math.Max(minTimespan, 0 - (int)_stopwatch.ElapsedMilliseconds);
                        if (delayInMs > 0)
                        {
                            Task.Delay(delayInMs, cancellationToken).Wait(cancellationToken);
                        }

                        _stopwatch.Reset();
                    }
                }
                catch (OperationCanceledException)
                {
                    _log.Debug("OperationCanceledException catched. returning.");
                    running = false;
                    return;
                }
                catch (Exception ex)
                {
                    _log.Debug(ex, "Exception catched.");
                    //to be safe, we reset the serial port
                    if (serialPort != null && serialPort.IsOpen)
                    {
                        serialPort.Close();
                    }
                    serialPort?.Dispose();
                    serialPort = null;
                    running = false;
                }
                finally
                {
                    if (serialPort != null && serialPort.IsOpen)
                    {
                        serialPort.Close();
                        serialPort.Dispose();
                    }
                }
            }
        }

19 Source : SerisePortClientChannel.cs
with Apache License 2.0
from cdy816

protected override bool InnerClose()
        {
            try
            {
                mIsConnected = false;
                if (mClient != null)
                {
                    mClient.Close();
                    mClient = null;
                }
            }
            catch
            {

            }
            return base.InnerClose();
        }

19 Source : Uart.cs
with Apache License 2.0
from chenxuuu

public void Close()
        {
            Tools.Logger.AddUartLogDebug($"[UartClose]refreshSerialDevice");
            refreshSerialDevice();
            Tools.Logger.AddUartLogDebug($"[UartClose]Close");
            serial.Close();
            Tools.Logger.AddUartLogDebug($"[UartClose]done");
        }

19 Source : SerialReader.cs
with GNU General Public License v3.0
from Cleric-K

public virtual void ClosePort() {
            serialPort.Close();
            serialPort = null;
        }

19 Source : SerialReader.cs
with GNU General Public License v3.0
from Cleric-K

bool OpenLinuxPortCustomBaudRate(string port, Configuration.SerialParameters sp) {
            try {
                // first try to open with safe baudrate
                serialPort = new SerialPort(port, 9600, sp.Parity, sp.DataBits, sp.StopBits);
                serialPort.Open();
                // it worked, no try to set the custom baud rate
                if (!SetLinuxCustomBaudRate(port, sp.BaudRate))
                {
                    serialPort.Close();
                    return false;
                }
                return true;
            }
            catch(Exception) {
                return false;
            }
        }

19 Source : SerialConnecter.cs
with Apache License 2.0
from Coldairarrow

public void Stop()
        {
            try
            {
                _sp.Close();
                HandleStopped?.Invoke();
            }
            catch (Exception ex)
            {
                HandleException?.Invoke(ex);
            }
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from CoretechR

private void comboBox2_SelectionChangeCommitted(object sender, EventArgs e)
        {
            _serialPort.Close();
            _serialPort.PortName = comboBox2.SelectedItem.ToString();
            try
            {
                _serialPort.Open();
            }
            catch { }                     
        }

19 Source : BluetoothCommunication.cs
with MIT License
from Cosmik42

public void Disconnect()
		{
			if(_serialPort != null)
			{
				_serialPort.DataReceived -= SerialPortDataReceived;
				_serialPort.Close();
				_serialPort = null;
			}
		}

19 Source : SlaveHost.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS

public void Start()
        {
            mPort = new SerialPort(mLaunchSettings.PortName);
            mPort.Open();

            Send("");
            // Set to digital input
            Send("CH1.SETMODE(2)");

            if (IsOn())
            {
                TogglePowerSwitch();
                WaitPowerState(false);
                // Small pause for discharge
                Thread.Sleep(1000);
            }

            TogglePowerSwitch();
            // Give PC some time to turn on, else we will detect it as off right away.
            WaitPowerState(true);
            
            mPowerStateThread = new Thread(delegate ()
            {
                while (true)
                {
                    Thread.Sleep(1000);
                    if (!IsOn())
                    {
                        mPort.Close();
                        ShutDown?.Invoke(this, EventArgs.Empty);
                        break;
                    }
                }
            });

            mPowerStateThread.Start();
        }

19 Source : SlaveHost.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS

public void Kill()
        {
            if (mPowerStateThread != null)
            {
                mPowerStateThread.Abort();
                mPowerStateThread.Join();
            }

            if (IsOn())
            {
                TogglePowerSwitch();
                WaitPowerState(false);
            }
            mPort.Close();
        }

19 Source : AdalightDiscovery.cs
with GNU General Public License v3.0
from d8ahazard

private static Dictionary<string, KeyValuePair<int, int>> FindDevices(int speed = 115200) {
			Dictionary<string, KeyValuePair<int, int>> dictionary = new();
			foreach (var portName in SerialPort.GetPortNames()) {
				if (!portName.Contains("COM") && !portName.Contains("ttyACM")) {
					continue;
				}

				Log.Debug("Testing port: " + portName);
				try {
					SerialPort serialPort = new() {
						PortName = portName,
						BaudRate = speed,
						Parity = Parity.None,
						DataBits = 8,
						StopBits = StopBits.One,
						ReadTimeout = 2500
					};
					Log.Debug("Opening...");
					serialPort.Open();
					Log.Debug("Opened.");
					if (serialPort.IsOpen) {
						Log.Debug("Reading");
						var line = serialPort.ReadLine();
						Log.Debug("Response line: " + line);
						if (line[..3].ToLower() == "ada") {
							Log.Debug("Line match.");
							dictionary[portName] = new KeyValuePair<int, int>(0, 0);
						}

						serialPort.Close();
					} else {
						Log.Debug($"Unable to open port {portName}.");
					}
				} catch (Exception ex) {
					Log.Warning($"Exception testing port {portName}: " + ex.Message);
				}
			}

			return dictionary;
		}

19 Source : SerialPortCommunication.cs
with GNU General Public License v3.0
from DeepView

public bool Close()
      {
         COMDevice.Close();
         return !IsOpened;
      }

19 Source : Arduino.Monitor.cs
with MIT License
from dotnet

public static void Main(string[] args)
        {
            string portName = "COM4";
            if (args.Length > 0)
            {
                portName = args[0];
            }

            using (var port = new SerialPort(portName, 115200))
            {
                Console.WriteLine($"Connecting to Arduino on {portName}");
                try
                {
                    port.Open();
                }
                catch (UnauthorizedAccessException x)
                {
                    Console.WriteLine($"Could not open COM port: {x.Message} Possible reason: Arduino IDE connected or serial console open");
                    return;
                }

                ArduinoBoard board = new ArduinoBoard(port.BaseStream);
                try
                {
                    Console.WriteLine($"Firmware version: {board.FirmwareVersion}, Builder: {board.FirmwareName}");
                    DisplayModes(board);
                }
                catch (TimeoutException x)
                {
                    Console.WriteLine($"No answer from board: {x.Message} ");
                }
                finally
                {
                    port.Close();
                    board?.Dispose();
                }
            }
        }

19 Source : RgbIntegration.cs
with MIT License
from egordorichev

public override void Destroy() {
			base.Destroy();
			port.Close();
		}

19 Source : FormMain.cs
with BSD 3-Clause "New" or "Revised" License
from eried

private static void SendReset(string port)
        {
            var arduboy = new SerialPort
            {
                BaudRate = 1200,
                PortName = port,
                DtrEnable = true
            };
            arduboy.Open();

            while (!arduboy.IsOpen)
                Thread.Sleep(Resources.WaitIdleFastMs);

            arduboy.DtrEnable = false;
            arduboy.Close();
            arduboy.Dispose();
        }

19 Source : Program.cs
with GNU General Public License v3.0
from flyAkari

static void Main(string[] args)
        {
            for (; ; )
            { 
                try
                {
                    string tempString = string.Empty;
                    tempString += "<AIDA64>";

                    MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("AIDA64_SensorValues");
                    MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
                    tempString = tempString + "";
                    for (int i = 0; i < accessor.Capacity; i++)
                    {
                        tempString = tempString + (char)accessor.ReadByte(i);
                    }
                    tempString = tempString.Replace("\0", "");
                    tempString = tempString + "";
                    accessor.Dispose();
                    mmf.Dispose();

                    tempString += "</AIDA64>";
                    XDoreplacedent aidaXML = XDoreplacedent.Parse(tempString);
                    var sysElements = aidaXML.Element("AIDA64").Elements("sys");
                    var tempElements = aidaXML.Element("AIDA64").Elements("temp");
                    var fanElements = aidaXML.Element("AIDA64").Elements("fan");
                    var dutyElements = aidaXML.Element("AIDA64").Elements("duty");
                    var voltElements = aidaXML.Element("AIDA64").Elements("volt");
                    var pwrElements = aidaXML.Element("AIDA64").Elements("pwr");
                    SerialPort serialPort1 = new SerialPort("COM7", 1500000, Parity.None, 8, StopBits.One); //先到设备管理器里找CH340G对应的端口
                    serialPort1.Open();
                    List<AIDA64Item> items = new List<AIDA64Item>();
                    foreach (var i in sysElements)
                    {
                        Console.WriteLine(i.Element("id").Value + "\t" + i.Element("label").Value + "\t" + i.Element("value").Value);
                        AIDA64Item item = new AIDA64Item();
                        switch (i.Element("id").Value)
                        {
                            case "SCPUUTI":  //CPU使用率
                                item.id = i.Element("id").Value;
                                item.value = i.Element("value").Value;
                                break;
                            case "SCPUCLK":  //CPU时钟频率
                                item.id = i.Element("id").Value;
                                item.value = i.Element("value").Value;
                                break;
                        }
                        if (item.id != null)
                        {
                            items.Add(item);
                        }
                    }
                    foreach (var i in tempElements)
                    {
                        Console.WriteLine(i.Element("id").Value + "\t" + i.Element("label").Value + "\t" + i.Element("value").Value);
                        AIDA64Item item = new AIDA64Item();
                        switch (i.Element("id").Value)
                        {
                            case "TCPU":   //CPU温度
                                item.id = i.Element("id").Value;
                                item.value = i.Element("value").Value;
                                break;
                        }
                        if (item.id != null)
                        {
                            items.Add(item);
                        }
                    }
                    foreach (var i in voltElements)
                    {
                        Console.WriteLine(i.Element("id").Value + "\t" + i.Element("label").Value + "\t" + i.Element("value").Value);
                        AIDA64Item item = new AIDA64Item();
                        switch (i.Element("id").Value)
                        {
                            case "VCPU":  //CPU核心电压
                                item.id = i.Element("id").Value;
                                item.value = i.Element("value").Value;
                                break;
                        }
                        if (item.id != null)
                        {
                            items.Add(item);
                        }
                    }
                    foreach (var i in items)
                    {
                        serialPort1.Write("?" + i.id + "=" + i.value + "!");
                    }
                    Thread.Sleep(1000);
                    serialPort1.Close();
                }
                catch
                {
                    continue;
                }
            }
        }

19 Source : Program.cs
with Apache License 2.0
from flyfire-cn

private static void TestWinUart(string portName)
        {
            SerialPort sp;

            try
            {
                sp = new SerialPort()
                {
                    PortName = portName,
                    BaudRate = baudRate
                };
                sp.Open();
                string msg;
                msg = "Hello Uart";
                sp.WriteLine(msg);
                Console.WriteLine(msg);
                msg = "Byebye Uart";
                sp.WriteLine(msg);
                sp.Close();
                sp.Dispose();
                sp = null;
                Console.WriteLine(msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Open Uart Exception:{ex}");
            }
        }

19 Source : ModbusRTUDriver.cs
with GNU Lesser General Public License v3.0
from GavinYellow

public void Dispose()
        {
            foreach (IGroup grp in _grps)
            {
                grp.Dispose();
            }
            _grps.Clear();
            _serialPort.Close();
        }

19 Source : GodSerialPort.cs
with MIT License
from godsharp

public bool Close()
        {
            try
            {
                if (serialPort.IsOpen) serialPort.Close();

                return true;
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine("Close SerialPort Exception:" + PortName + "\r\nMessage:" + ex.Message + "\r\nStackTrace:" + ex.StackTrace); 
#endif
                throw new Exception(ex.Message, ex);
            }
        }

19 Source : FormMain.cs
with MIT License
from hagronnestad

private void btnConnect_Click(object sender, EventArgs e) {
            try {
                sp1.BaudRate = int.Parse(cmbPort1Speed.Text);
                sp1.PortName = cmbPort1.Text;

                sp2.BaudRate = int.Parse(cmbPort2Speed.Text);
                sp2.PortName = cmbPort2.Text;

                sp1.Open();
                sp2.Open();

                t1.Start();
                bw1.RunWorkerAsync();
                bw2.RunWorkerAsync();

                btnConnect.Enabled = false;
                btnDisconnect.Enabled = true;

            } catch (Exception ex) {
                if (sp1.IsOpen) sp1.Close();
                if (sp2.IsOpen) sp2.Close();

                btnConnect.Enabled = true;
                btnDisconnect.Enabled = false;

                MessageBox.Show(ex.Message, "Error");
            }
        }

19 Source : Form1.cs
with MIT License
from HackingThings

private void btnStop_Click(object sender, EventArgs e)
        {
            btnStartSniff.Enabled = true;
            btnStopSniff.Enabled = false;
            ws.WiresharkPipe.Close();
            th.Abort();
            if (port.IsOpen) port.Close();
            port.Dispose();
        }

19 Source : Form1.cs
with MIT License
from HackingThings

private void btnStopReplay_Click(object sender, EventArgs e)
        {
            btnStartReplay.Enabled = true;
            btnStopReplay.Enabled = false;
            th.Abort();
            if (port.IsOpen) port.Close();
            port.Dispose();
        }

19 Source : FormMain.cs
with MIT License
from hagronnestad

private void btnDisconnect_Click(object sender, EventArgs e) {
            btnDisconnect.Enabled = false;

            bw1.CancelAsync();
            bw2.CancelAsync();

            while (bw1.IsBusy || bw2.IsBusy) {
                Application.DoEvents();
            }

            sp1.Close();
            sp2.Close();

            t1.Stop();

            lblPort1to2.Text = "0 bytes/s";
            lblPort2to1.Text = "0 bytes/s";

            bps1 = 0;
            bps2 = 0;

            btnConnect.Enabled = true;
        }

19 Source : ModbusTcpServer.cs
with GNU Lesser General Public License v3.0
from HslCommunication-Community

public void CloseSerialPort( )
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close( );
            }
        }

19 Source : LSisServer.cs
with GNU Lesser General Public License v3.0
from HslCommunication-Community

public void CloseSerialPort()
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }
        }

19 Source : LSisServer.cs
with GNU Lesser General Public License v3.0
from HslCommunication-Community

private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
           
              var sp = (SerialPort)sender;

            int rCount = 0;
            byte[] buffer = new byte[1024];
            byte[] receive = null;

            while (true)
            {
                System.Threading.Thread.Sleep(20);           
                int count = sp.Read(buffer, rCount, sp.BytesToRead);
                rCount += count;
                if (count == 0) break;

                receive = new byte[rCount];
                Array.Copy(buffer, 0, receive, 0, count);
            }

            if (receive == null) return;
            byte[] modbusCore = SoftBasic.BytesArrayRemoveLast(receive, 2);
            byte[] SendData = null;
            if (modbusCore[3] == 0x72)
            {
                // Read
                SendData = ReadSerialByCommand(modbusCore);
                RaiseDataReceived(SendData);
                serialPort.Write(SendData, 0, SendData.Length);

            }
            else if (modbusCore[3] == 0x77)
            {
                // Write
                SendData = WriteSerialByMessage(modbusCore);
                RaiseDataReceived(SendData);
                serialPort.Write(SendData, 0, SendData.Length);
                
            }
            else
            {
                serialPort.Close();
            }
           
            if (IsStarted) RaiseDataSend(receive);
            
        }

19 Source : FP1_C72.cs
with GNU Lesser General Public License v3.0
from HslCommunication-Community

public bool PortOpen(int port,int baudrate,int databit,int stopbit,int oddEven,ref string errMsg )
        {
            serialPort1.PortName = "COM"+port;
            serialPort1.BaudRate = baudrate;
            string rets="",errs="";
            switch (oddEven)
            {
                case 0:
                    serialPort1.Parity = Parity.None;
                    break;
                case 1:
                    serialPort1.Parity = Parity.Odd;
                    break;
                case 2:
                    serialPort1.Parity = Parity.Even;
                    break;
                case 3:
                    serialPort1.Parity = Parity.Mark;
                    break;
                case 4:
                    serialPort1.Parity = Parity.Space;
                    break;
            }
           
            switch (stopbit)
            {
                case 0:
                    serialPort1.StopBits = StopBits.None ;
                    break;
                case 1:
                    serialPort1.StopBits = StopBits.One;
                    break;
                case 2:
                    serialPort1.StopBits = StopBits.OnePointFive;
                    break;
                case 3:
                    serialPort1.StopBits = StopBits.Two;
                    break;
            }
            serialPort1.DataBits = databit ;
            try{
                serialPort1.Open();
                if (!SendPlcCmd("%EE#RT", ref rets, ref errs))
                {
                    errMsg = "PLC未连接上,请检查连接线路或通讯参数设置是否正常!";
                    serialPort1.Close();
                    return false;
                }
            }catch(Exception ex)
            {
                errMsg = ex.Message;
                return false;
            }
            portOpened = true;
            return true;
        }

19 Source : FP1_C72.cs
with GNU Lesser General Public License v3.0
from HslCommunication-Community

public bool PortClose()
        {
            if (portOpened)
                serialPort1.Close();
            portOpened = false;
            return true;
        }

19 Source : SerialBase.cs
with GNU Lesser General Public License v3.0
from HslCommunication-Community

public void Close( )
        {
            if(SP_ReadData.IsOpen)
            {
                ExtraOnClose( );
                SP_ReadData.Close( );
            }
        }

19 Source : FormSerialDebug.cs
with GNU Lesser General Public License v3.0
from HslCommunication-Community

private void button2_Click( object sender, EventArgs e )
        {
            // 关闭串口
            try
            {
                SP_ReadData.Close( );
                button2.Enabled = false;
                button1.Enabled = true;

                panel2.Enabled = false;
            }
            catch(Exception ex)
            {
                HslCommunication.BasicFramework.SoftBasic.ShowExceptionMessage( ex );
            }
        }

19 Source : ISerialPortWrapper.cs
with MIT License
from inthehand

void ISerialPortWrapper.Close()
        {
            _child.Close();
        }

See More Examples