Why visual studio cant recieve data serial from arduino uno r4 wifi?

hello, i just tried arduino uno r4 wifi. i tried to read serial data from arduino uno r4 wifi connected to DHT22 sensor via visual studio, but serial data is not readable in visual studio. when i try to use arduino mega 2560 data is readable in visual studio. are there any special or different steps that need to be done so that arduino uno r4 wifi can be read in visual studio?
Arduino Code:

#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
}

void loop() {
  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  Serial.println(t);
}

Code Visual Studio:

using System;
using System.IO.Ports;
using System.Windows.Forms;

namespace Test_Data_Arduino
{
    public partial class Form1 : Form
    {
        SerialPort serialPort;
        public Form1()
        {
            InitializeComponent();
            timer1.Interval = 1000;
            timer1.Start();
            serialPort = new SerialPort("COM6", 9600);
            try
            {
                serialPort.Open();
            }
            catch
            {
                Console.WriteLine("Unable to open COM port - check it's not in use.");
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            bool haveTemperature = false;
            string temperature = string.Empty;

            while (!haveTemperature)
            {
                temperature = serialPort.ReadLine();
                if (!string.IsNullOrEmpty(temperature))
                {
                    haveTemperature = true;
                }
            }

            if (haveTemperature) {
                textBox1.Text += "Temperature is:" + temperature + " °C" +  Environment.NewLine;
            }
        }
    }
}

Welcome to the forum

Which pins on the R4 are you reading from ?

1 Like

thanks for replying
I use usb port to read the data to the computer. For dht22 I use pin 2

have you modified the Visual Studio code between it working with the Mega and it failing with the UNO R4?
the UNO R4 Serial COM port would probably not be the same as the Mega - have you checked the port COM setting?
does the UNO R4 communicate with the IDE Serial Monitor OK?
did you remember to close the serial monitor when using Visual Studio?

1 Like

I did modified the visual studio between Arduino uno r4 wifi. There's no problem in COM port setting and I work just fine in serial monitor. I always close the serial monitor when running the visual studio

are you sure the timer is ticking?
I always find it a good idea to display an * on the Console - it can be commented out when you know it is working
also display the temperature, e.g.

private void timer1_Tick(object sender, EventArgs e)
        {
            Console.WriteLine("*");
            bool haveTemperature = false;
            string temperature = string.Empty;

            while (!haveTemperature)
            {
                temperature = serialPort.ReadLine();
               Console.WriteLine("temperature " + temperature);
                if (!string.IsNullOrEmpty(temperature))
                {
                    haveTemperature = true;
                }
            }

why don't you use SerialPort DataReceived event to handle the received text?, e.g.

    public partial class Form1 : Form
    {
        // delegate to transfer received data to TextBox
        public delegate void AddDataDelegate(String myString);
        public AddDataDelegate myDelegate;

      public Form1()
        {
            InitializeComponent();
            this.myDelegate = new AddDataDelegate(AddDataMethod);
 ......
      }

    // data received from serial port - display on textbox
     private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //textBox1.AppendText(serialPort1.ReadExisting());  // not thread safe
            string s = serialPort1.ReadExisting();
            textBox1.Invoke(this.myDelegate, new Object[] { s });
        }

     // display seral data on textbox
     public void AddDataMethod(String myString)
     {
         textBox1.AppendText(myString);
     }

1 Like

i am sure it ticking, because when i use arduino mega it work just fine.

i did try use it with different code. but it didn't work as well

public partial class Form1 : Form
{
    private SerialPort serialPort;
    private string filePath;

    public Form1()
    {
        InitializeComponent();
        PopulateComPorts();
    }

    private void PopulateComPorts()
    {
        cboxComport.Items.AddRange(SerialPort.GetPortNames());
    }

    private void btnConnect_Click(object sender, EventArgs e)
    {
        if (serialPort == null || !serialPort.IsOpen)
        {
            serialPort = new SerialPort(cboxComport.SelectedItem.ToString(), 9600);
            serialPort.DataReceived += SerialPort_DataReceived;
            serialPort.Open();
            btnConnect.Text = "Disconnect";
            LogMessage("Connected to " + serialPort.PortName);
        }
        else
        {
            serialPort.Close();
            serialPort = null;
            btnConnect.Text = "Connect";
            LogMessage("Disconnected");
        }
    }

    private void btnOpenFile_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                filePath = openFileDialog.FileName;
                textBoxFile.Text = filePath;
            }
        }
    }

    private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string incomingData = serialPort.ReadLine().Trim();
        this.Invoke((MethodInvoker)delegate {
            LogMessage("Received: " + incomingData);
            ProcessData(incomingData);
        });
    }

    private void ProcessData(string data)
    {
        if (string.IsNullOrEmpty(filePath))
        {
            LogMessage("No file selected.");
            return;
        }

        // Parse the data
        string[] parts = data.Split(',');
        int id = int.Parse(parts[0].Split(':')[1]);
        string temp = parts[1].Split(':')[1];
        string hum = parts[2].Split(':')[1];

        // Read all lines from the file
        string[] lines = File.ReadAllLines(filePath);

        // Update the specific line based on ID
        lines[id - 1] = $"ID:{id},TEMP:{temp},HUM:{hum}";

        // Write the updated lines back to the file
        File.WriteAllLines(filePath, lines);

        LogMessage($"Updated ID {id} in {filePath}");
    }

    private void LogMessage(string message)
    {
        richTextBoxLog.AppendText(message + Environment.NewLine);
    }
}

One important distinction between those boards that may or may not have anything to do with your issue. When your VS program connects to the mega it will cause the mega to reset. This won't happen on the R4.

1 Like

have you tested using a terminal emulator such as teraterm or realterm etc?
I assume you are using C#?

1 Like

I tried using realterm and it reads data from arduino uno r4 wifi. but in the data that is read there is a CRLF at the end of the incoming data and I don't know where it came from.
this is a photo from realterm:

can you elaborate more about it?

You're using println() in your Arduino code; that will add the CR/LF.

1 Like

probably from the println()

Serial.println(t);

try this simple C# terminal emulator

using System;
using System.Windows.Forms;
using System.IO.Ports;

namespace CsharpTerminal
{
    public partial class Form1 : Form
    {
        // delegate to transfer received data to TextBox
        public delegate void AddDataDelegate(String myString);
        public AddDataDelegate myDelegate;
        
        public Form1()
        {
            InitializeComponent();
            this.myDelegate = new AddDataDelegate(AddDataMethod);
            serialPort1.Open();
            textBox1.AppendText(serialPort1.PortName + " open" + Environment.NewLine);
        }

        // key on textbox pressed, read key and transmit down serial line
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {        
        if( serialPort1.IsOpen)
            serialPort1.Write(e.KeyChar.ToString());
        else
            textBox1.AppendText("No COM port open" + Environment.NewLine);
        }

     // data received from serial port - display on textbox
     private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //textBox1.AppendText(serialPort1.ReadExisting());  // not thread safe
            string s = serialPort1.ReadExisting();
            textBox1.Invoke(this.myDelegate, new Object[] { s });
        }

     // display seral data on textbox
     public void AddDataMethod(String myString)
     {
         textBox1.AppendText(myString);
     }


     private void Form1_FormClosed(object sender, FormClosedEventArgs e)
     {
         serialPort1.Close();
     }

     }
}

it has a Form and a SerialPort

check the SerialPort properties Baudrate and PortName - you may need to set DtrEnable True depending on the serial port driver

a run communicating with an ESP32
image

1 Like

After I Enable Dtr, Visual studio read the data from arduino. Thanks