Create a file from the Arduino serial communication (using a HMI)

AyalaOrtiz

New member
Joined
Apr 8, 2023
Messages
2
Programming Experience
Beginner
I am trying to create a file with the data that my Arduino sends me from a graphical interface created in Windows Forms App (.NET Framework), currently I already receive the information and I use a graph to show the behavior of these variables type floats but I need to store that information.
Thank you very much.
C#:
 private void buttonSaveFile_Click(object sender, EventArgs e)
        {
            ///crear un archivo
            string path = "./TextData/TestFile.txt";
            if (!File.Exists(path))
            {
                using (StreamWriter sw = File.CreateText(path))
                {
                    while (serialPort1.IsOpen && serialPort1.BytesToRead > 0)
                    {
                        string serialData = serialPort1.ReadLine();
                        
                        try
                        {
                            for (int i = 0; i < 500; i++)
                            {
                              
                                sw.WriteLine(serialPort1.ReadLine());
                            }



                        }
                        catch (Exception error)
                        {
                            MessageBox.Show(error.Message);
                        }

                    }
                    
                }


            }
        }
C#:
 
Yes sir, to go adding line by line the data recorded in serial port in a .txt or .cvs. I have achieved this using a python code but I would like to achieve it from the same interface I am building.
 
So why not just follow the same approach you had in Python?

It's unclear why in the code yau have above why you read a line on 11, but throw it away, and then on lines 15-19, you are reading 500 lines and writing those out into a file.

Why do you need lines 9-29, when lines 9,10, 18, and 29 would likely suffice? What problem are you trying to solve?
 
Here is how I get the incoming data.
C#:
Snippetpublic void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string buffer = string.Empty;
    try
    {
        while ((sender as SerialPort).BytesToRead > 0)
        {
            buffer += (sender as SerialPort).ReadExisting();
        }
        (sender as SerialPort).DiscardInBuffer();
        string portName = (sender as SerialPort).PortName;
 
        //Call DataReporter
        DataReporter(buffer, portName);
    }
    catch (InvalidOperationException ex)
    {
        _logger.LogIt($"InvalidOperationException exception thrown at DataReceived {ex.Message}.", LogLevel.Information);
    }
}

The buffer is then passed to a method that sends it back to the MainWindowViewModel (this is running on a background thread so it has to report back to the method to handle the Background Worker Reporting). All I do there is parse the data and upload it to a database. You will have a string you can do anything you want with it. You can open a stream writer and save the string to a file.
 
It maybe worth creating a temporary variable to minimize duplication of code (sender as SerialPort):
C#:
var serialPort = (SerialPort) sender;
This also has the extra benefit of giving your a hard runtime error of invalid cast exception if sender is not a SerialPort, instead of a mystery null reference exception if sender as SerialPort returns null.
 
Hello, this is Gulshan Negi.
Well, I did some search on Google and in my opinion and you need to modify your code as below:
C#:
private void buttonSaveFile_Click(object sender, EventArgs e)
{
    // Create a file or append to an existing one
    string path = "./TextData/TestFile.txt";
    using (StreamWriter sw = File.AppendText(path))
    {
        // Read the data from the serial port
        while (serialPort1.IsOpen && serialPort1.BytesToRead > 0)
        {
            string serialData = serialPort1.ReadLine();
           
            try
            {
                // Write the data to the file
                sw.WriteLine(serialData);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }
    }

    MessageBox.Show("Data saved to file.");
}
Thanks
 
Last edited by a moderator:
@gulshan212 : Please post code in code tags. I'll edit your post above for you.
 
Out of curiosity, why catch exceptions writing to the file, and then continue on?

Also why not catch exceptions trying to read from the serial port?
 
@fabierro : The OP is using a file based storage system. He just happens to be writing it out as plain text.
 
Back
Top Bottom