Chenghsien Lin
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # C# Serial Port Communication ###### tags: `C#` `Serial Port` # [Communicating With Serial Port In C#](https://www.c-sharpcorner.com/UploadFile/eclipsed4utoo/communicating-with-serial-port-in-C-Sharp/) In the past, to communicate with a Serial Port using .NET 1.1, you had to either use the Windows API or a third-party control. With .NET 2.0 and above, Microsoft has added this support with the inclusion of the ``SerialPort`` class as part of the ``System.IO.Ports namespace``. Implementation of the ``SerialPort`` class is very straight-forward. To create an instance of the ``SerialPort`` class, you simply pass the ``SerialPort`` __options__ to the constructor of the class. ``` // all of the options for a serial device // ---- can be sent through the constructor of the SerialPort class // ---- PortName = "COM1", Baud Rate = 19200, Parity = None, // ---- Data Bits = 8, Stop Bits = One, Handshake = None SerialPort _serialPort = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One); _serialPort.Handshake = Handshake.None; ``` To receive data, we will need to create an ``EventHandler`` for the ``SerialDataReceivedEventHandler``: ``` // "sp_DataReceived" is a custom method that I have created _serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); ``` You can also set other options, such as the ReadTimeout and WriteTimeout. ``` // milliseconds _serialPort.ReadTimeout = 500; _serialPort.WriteTimeout = 500; ``` Once you are ready to use the Serial Port, you will need to open it: ``` // Opens serial port _serialPort.Open(); ``` Now, we are ready to receive the data. However, to write this data to the ``TextBox`` on a form, we need to create a delegate. .NET __does not allow cross-thread action, so we need to use a delegate__. The delegate is used to __write to the UI thread from a non-UI thread__. ``` // delegate is used to write to a UI control from a non-UI thread private delegate void SetTextDeleg(string text); ``` We will now create the ``sp_DataReceived`` method that will be executed when data is received through the serial port, ``` void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) { Thread.Sleep(500); string data = _serialPort.ReadLine(); // Invokes the delegate on the UI thread, and sends the data that was received to the invoked method. // ---- The "si_DataReceived" method will be executed on the UI thread which allows populating of the textbox. this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data }); } ``` Now we create our "si_DataReceived" method, ``` private void si_DataReceived(string data) { textBox1.Text = data.Trim(); } ``` We can now receive data from a serial port device and display it on a form. Some devices will send data without being prompted. However, some devices need to be send certain commands, and it will reply with the data that the command calls for. For these devices, you will write data to the serial port, and use the previous code to get the data that will be sent back. In my example, I will be communicating with a scale. For this particular scale, sending the command "SI\r\n" will force it to return the weight of whatever is on the scale. This command is specific for this scale. You will need to read the documentation of your serial device to find commands that it will receive. To write to the serial port, I have created a "Start" button on the form. I have added code to its Click_Event: ``` private void btnStart_Click(object sender, EventArgs e) { // Makes sure serial port is open before trying to write try { if(!(_serialPort.IsOpen)) _serialPort.Open(); _serialPort.Write("SI\r\n"); } catch (Exception ex) { MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!"); } } ``` And that is all you need to do. I have attached the Visual Studio 2005 solution. ``` using System; using System.IO.Ports; using System.Threading; public class PortChat { static bool _continue; static SerialPort _serialPort; public static void Main() { string name; string message; StringComparer stringComparer = StringComparer.OrdinalIgnoreCase; Thread readThread = new Thread(Read); // Create a new SerialPort object with default settings. _serialPort = new SerialPort(); // Allow the user to set the appropriate properties. _serialPort.PortName = SetPortName(_serialPort.PortName); _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate); _serialPort.Parity = SetPortParity(_serialPort.Parity); _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits); _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits); _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake); // Set the read/write timeouts _serialPort.ReadTimeout = 500; _serialPort.WriteTimeout = 500; _serialPort.Open(); _continue = true; readThread.Start(); Console.Write("Name: "); name = Console.ReadLine(); Console.WriteLine("Type QUIT to exit"); while (_continue) { message = Console.ReadLine(); if (stringComparer.Equals("quit", message)) { _continue = false; } else { _serialPort.WriteLine( String.Format("<{0}>: {1}", name, message) ); } } readThread.Join(); _serialPort.Close(); } public static void Read() { while (_continue) { try { string message = _serialPort.ReadLine(); Console.WriteLine(message); } catch (TimeoutException) { } } } public static string SetPortName(string defaultPortName) { string portName; Console.WriteLine("Available Ports:"); foreach (string s in SerialPort.GetPortNames()) { Console.WriteLine(" {0}", s); } Console.Write("COM port({0}): ", defaultPortName); portName = Console.ReadLine(); if (portName == "") { portName = defaultPortName; } return portName; } public static int SetPortBaudRate(int defaultPortBaudRate) { string baudRate; Console.Write("Baud Rate({0}): ", defaultPortBaudRate); baudRate = Console.ReadLine(); if (baudRate == "") { baudRate = defaultPortBaudRate.ToString(); } return int.Parse(baudRate); } public static Parity SetPortParity(Parity defaultPortParity) { string parity; Console.WriteLine("Available Parity options:"); foreach (string s in Enum.GetNames(typeof(Parity))) { Console.WriteLine(" {0}", s); } Console.Write("Parity({0}):", defaultPortParity.ToString()); parity = Console.ReadLine(); if (parity == "") { parity = defaultPortParity.ToString(); } return (Parity)Enum.Parse(typeof(Parity), parity); } public static int SetPortDataBits(int defaultPortDataBits) { string dataBits; Console.Write("Data Bits({0}): ", defaultPortDataBits); dataBits = Console.ReadLine(); if (dataBits == "") { dataBits = defaultPortDataBits.ToString(); } return int.Parse(dataBits); } public static StopBits SetPortStopBits(StopBits defaultPortStopBits) { string stopBits; Console.WriteLine("Available Stop Bits options:"); foreach (string s in Enum.GetNames(typeof(StopBits))) { Console.WriteLine(" {0}", s); } Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString()); stopBits = Console.ReadLine(); if (stopBits == "") { stopBits = defaultPortStopBits.ToString(); } return (StopBits)Enum.Parse(typeof(StopBits), stopBits); } public static Handshake SetPortHandshake(Handshake defaultPortHandshake) { string handshake; Console.WriteLine("Available Handshake options:"); foreach (string s in Enum.GetNames(typeof(Handshake))) { Console.WriteLine(" {0}", s); } Console.Write("Handshake({0}):", defaultPortHandshake.ToString()); handshake = Console.ReadLine(); if (handshake == "") { handshake = defaultPortHandshake.ToString(); } return (Handshake)Enum.Parse(typeof(Handshake), handshake); } } ``` --- #[C# await event and timeout in serial port communication](https://stackoverflow.com/questions/53335736/c-sharp-await-event-and-timeout-in-serial-port-communication/) Hi I have a simple communication on serial port well all is according to book and documentation so open port method looks like this: ``` public SerialPort OpenPort(string portName) { SerialPort serialPort = new SerialPort(portName, BaudRate); try { serialPort.Open(); serialPort.DtrEnable = true; serialPort.RtsEnable = true; serialPort.DataReceived += DataReceivedEvent; } catch (Exception cause) { Console.WriteLine($"ERRROR: {e.Message}"); } return serialPort; } ``` Here we have an event on data read: ``` private async void DataReceivedEvent(object sender, SerialDataReceivedEventArgs e) { var data = new byte[Port.BytesToRead]; await serialPort.BaseStream.ReadAsync(data, 0, data.Length); Response = data; isFinished = true; } ``` Well all is fine and dandy, but now i want to send a message on demand and store response in a property, also i want to add cancellation token on that task timeout. So i came up with this method: ``` public async Task SendMessenge(byte[] messange) { var cancellationTokenSource = new CancellationTokenSource(); CancellationToken token = cancellationTokenSource.Token; cancellationTokenSource.CancelAfter(5000); token.ThrowIfCancellationRequested(); isFinished = false; try { Task worker = Task.Run(() => { while (!isFinished) { } }, token); await Port.BaseStream.WriteAsync(messange, 0, messange.Length, token); await worker; } catch (OperationCanceledException e) { throw new OperationCanceledException(e.Message, e, token); } } ``` Problem is with this while loop, if it is task it goes into endless loop, and it does not capture timeout token, if i put it outside a task and remove worker it works but im loosing cancellation token. I guess i could do some manual countdown like: ``` double WaitTimeout = Timeout + DateAndTime.Now.TimeOfDay.TotalMilliseconds; while (!(DateAndTime.Now.TimeOfDay.TotalMilliseconds >= WaitTimeout)|| !isFalse) ``` --- # [C# Async Serial Port Read](https://stackoverflow.com/questions/24041378/c-sharp-async-serial-port-read) --- # [Cancel C# 4.5 TcpClient ReadAsync by timeout](https://stackoverflow.com/questions/15273784/cancel-c-sharp-4-5-tcpclient-readasync-by-timeout/41193744#41193744) ``` public static async Task<int> ReadAsync(this NetworkStream stream, byte[] buffer, int offset, int count, int TimeOut) { var ReciveCount = 0; var receiveTask = Task.Run(async () => { ReciveCount = await stream.ReadAsync(buffer, offset, count); }); var isReceived = await Task.WhenAny(receiveTask, Task.Delay(TimeOut)) == receiveTask; if (!isReceived) return -1; return ReciveCount; } ``` * [SerialPort.BaseStream.ReadAsync missing the first byte](https://stackoverflow.com/questions/35870794/serialport-basestream-readasync-missing-the-first-byte) * [Asynchronous message receiver](https://riptutorial.com/dot-net/example/19111/asynchronous-message-receiver) * [Correct Implementation of Async SerialPort Read](https://stackoverflow.com/questions/33226414/correct-implementation-of-async-serialport-read) * [C# Async Serial Port Read](https://stackoverflow.com/questions/24041378/c-sharp-async-serial-port-read) --- * [adamkewley/SerialPortExtensions.cs](https://gist.github.com/adamkewley/c607e872dbd260d15c63) * [Wait for response from the Serial Port and then send next data](https://stackoverflow.com/questions/55026042/wait-for-response-from-the-serial-port-and-then-send-next-data) * [C# await event and timeout in serial port communication](https://stackoverflow.com/questions/53335736/c-sharp-await-event-and-timeout-in-serial-port-communication/53633030#53633030) [Top 5 SerialPort Tips [Kim Hamilton]] https://docs.microsoft.com/zh-tw/archive/blogs/bclteam/top-5-serialport-tips-kim-hamilton [Serial Comms in C# for Beginners] https://www.codeproject.com/Articles/678025/Serial-Comms-in-Csharp-for-Beginners [Serial Terminal Basics ] https://learn.sparkfun.com/tutorials/terminal-basics/all https://freeserialanalyzer.com/

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully