0
votes

I have this Arduino code just for testing purpose:

int num=0;
void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.println(num);
    num+=1;
    delay(800);
}

Now it prints an integer and increments its value by one. When I open up Serial Monitor it prints as expected every 800ms.

My Arduino is connected on PORT-6

Now if I try to access the port, it says it is in use, I'm trying to access that from a .NET application. How can I do so?

c# code, collected from the internet, modified a little:

using System;
using System.IO.Ports;
using System.Threading;
namespace ConsoleApp1
{
    class Program
    {
        static SerialPort _serialPort;
        public static void Main()
        {
            _serialPort = new SerialPort();
            _serialPort.PortName = "COM6";//Set your board COM
            _serialPort.BaudRate = 9600;
            _serialPort.Open();
            while (true)
            {
                string a = _serialPort.ReadExisting();
                Console.WriteLine(a);
            }
        }
    }
}

How can I sniff data from that serial port ? [Educational Purpose]

1
you should use serialPort event - DataReceivedPeter Ksenak
You never close it. Of course it will stay "in use". Even if you close it, the OS will need some time to effectively shut it down and make it available for reopening. Use a try/finally and put the close in the finally block, so it will be closed if there is an exception or not.Fildor
Ah, wait. Do you want to use your application and Serial Monitor at the same time?Fildor
@Fildor yes, that's what i'm trying to do..Maifee Ul Asad

1 Answers

1
votes

You can't open a serial port twice.

If what you want is to get to see what is going through the bus (sniffing), you can use virtual ports and port forwarding, see here for a complete example.

Nothing will stop you from replacing any of the tools discussed in the link with your own code (.NET or other), in case they don't suit your needs or if you have enough determination to reinvent the wheel.