Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to write a command to a serial port. I have constructed the code below to connect to the serial port with the settings I am looking to have but I am running into the issue of how to set up the code to send the command I am looking to send. The C# code I have set up is:


Any ideas would be extremely helpful, I am still brand new to C#


C#
namespace System.IO.Ports
{
    class SerialPort
    {
        // Create the serial port with basic settings
        private SerialPort port = new SerialPort("COM5",
          9600, Parity.None, 8, StopBits.One);

        public SerialPort(string v1, int v2, Parity none, int v3, StopBits V4)
        {
            V1 = "com5";
            V2 = 115200;
            None = (Parity)0;
            V3 = 8;
            V4 = (StopBits)1;
        }

        public string V1 { get; }
        public int V2 { get; }
        public Parity None { get; }
        public int V3 { get; }
        public StopBits One { get; }

         public void Write(string text)
        {text = "IMGSNP1L1B0T";}
        
       
        
    }

}


What I have tried:

The powershell version of this command is:

PowerShell
$port.Write([char]22+[char]77+[char]13+[char]73+[char]77+[char]71+[char]83+[char]78+[char]80+[char]49+[char]76+[char]49+[char]66+[char]48+[char]84+[char]46)



I have also tried
C#
SerialPort.Write();

but get errors due the SerialPort.Write

Im a little lost on how I am able to send the command directly to the port
Posted
Updated 9-Aug-22 7:04am
Comments
0x01AA 9-Aug-22 13:02pm    
You forgot to open the serial port port.Open()
WadeWilson3 9-Aug-22 13:45pm    
Thank you so much! of course I forgot that.
WadeWilson3 9-Aug-22 16:32pm    
Do you know where in my code I should add the open? I have tried a few different areas but always get errors with it
0x01AA 10-Aug-22 2:03am    
Before you try to write to the port. To be sure it is open you can do this e.g. in the constructor of your class.
Have a look to solution 1, there you will find a link to a cp article which shows the basics in an easy way.

1 solution

You forgot to open the serial port. You do this with:
port.Open()

See here for a basic and easy to understand article on CP for serial port handling in c#:
Serial Comms in C# for Beginners[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900