Click here to Skip to main content
16,004,505 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
The above code is not going in Data Receive to get data, am I missing anything.

C#
<pre>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            // Initialize SerialPort
            serialPort1 = new SerialPort();
            serialPort1.PortName = "COM5"; // Example port name, adjust as needed
            serialPort1.BaudRate = 460800; // Example baud rate, adjust as needed

            // Event handler for receiving data
            
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(ReceiveData);

            serialPort1.Open();
        }

        private void ReceiveData(object sender, SerialDataReceivedEventArgs e)
        {
            // Read data from the serial port
            string data = serialPort1.ReadExisting();

            // Process the data received from the serial port
            // Example: Update UI controls with received data
            this.Invoke(new Action(() =>
            {
                txtReceive.Text += data;
            }));
        }
    }
}


What I have tried:

I want to read data from Serial port
Posted
Comments
PIEBALDconsult 21-Jul-24 10:59am    
I can't help you, but I recommend that you not put that code directly within your forms methods. Begin to think of writing applications modularly.

The communication parameters you set the serialPort object up with MUST match what the device you're listening to is using. If those parameters don't match, you will receive nothing or garbage. There parameters include the baud rate, data bits, stop bits, parity, and handshake.

You have to be sure of what parameters your device is using and make sure your code is setup to match.
 
Share this answer
 
Most Serial Devices are not sending something from their own - they want to be triggered. Mostly you have a Communication-Handshake with those devices. But without knowing something about your device it's impossible to help here ... perhaps you improve your question with some additional information ...
 
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