A
A
Andrey2020-10-13 19:06:03
Microcontrollers
Andrey, 2020-10-13 19:06:03

Are there any nuances in working with a COM port in c#?

I'm trying to work with two com ports in c# WPF. I wrote a simple application in which I read two com ports at the same time. Arduino UNO is connected to one COM3, Arduino Pro Micro is connected to another COM6.
Uno has no problem.
With Micro - silence. Swapped - the result is 0.
If you connect to the Micro using putty, you can see that the data is being transmitted.
But they are not visible in the application.

Where to dig?

My code:

public partial class MainWindow : Window
    {
        private SerialPort serialPortCmd;
        private SerialPort serialPortData;
              
       

        public string Weigth { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {             
            //ReadFromSerailPortC();
            ReadFromSerailPortD();
        }

        private void ReadFromSerailPortC()
        {            
            serialPortCmd = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
            serialPortCmd.DataReceived += new  SerialDataReceivedEventHandler(DataReceirvedCmd);
            serialPortCmd.Open();            
        }

        private void DataReceirvedCmd(object sender, SerialDataReceivedEventArgs e)
        {
            string _message = null;
            serialPortCmd = (SerialPort)sender;
            _message = serialPortCmd.ReadLine();
            System.Diagnostics.Debug.WriteLine(_message);
        }

        private void ReadFromSerailPortD()
        {
            serialPortData = new SerialPort("COM6", 9600, Parity.None, 8, StopBits.One);
            serialPortData.DataReceived += new SerialDataReceivedEventHandler(DataReceirvedDt);
            serialPortData.Open();
        }

        private void DataReceirvedDt(object sender, SerialDataReceivedEventArgs e)
        {
            string _message = null;
            serialPortData = (SerialPort)sender;
            _message = serialPortData.ReadLine();
            System.Diagnostics.Debug.WriteLine(_message);
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Pavlov, 2020-10-13
@Stalker31

Why did you comment out

ReadFromSerailPortC()
private void Window_Loaded(object sender, RoutedEventArgs e)
        {             
            //ReadFromSerailPortC();
            ReadFromSerailPortD();
        }
?
I also recommend doing this:
while(serialPortData.isOpen!=true){//открывать порт пока он не откроется
serialPortData.Open();
}

it is possible that the signal from the port does not have time to reach the board.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question