7 November 2018

Read and write a text file with Netduino IoT

One interesting topic about Netduino is that it has a built-in micro SD card module.
It means that you can read and write files without any external modules.

Just an idea, you can create these following projects easily:
  • Read/Write log files 
  • Collect information from sensors, e.g. temperature, humidity, and PH values 
  • Log values with date and time
  • Persist some information and send data in a batch to a server periodically to save battery by not connecting to the server too often
Let’s start creating a Netduino project to read and write a text file.

Create a new console project named “NetduinoReadWriteFile”.

Reference these DLLs in the project


Microsoft.SPOT.IO
SecretLabs.NETMF.IO
System.IO


Add NetMf.CommonExtensions source code to the project.
We have the Nuget package “NetMf.CommonExtensions”
but it does not work with .NET Micro 4.3.0. It requires a lower version of .NET Micro.
Therefore, we need to compile it with .NET Micro 4.3.0.

I have forked  NetMf.CommonExtensions and will do a Nuget package later.
You may find the source code of NetMf.CommonExtensions  in the repository of this DEMO.

Result of all references in the project:
A little talk about SD card.
When an SD card is inserted into the Netduino board, it is mounted as the SD volume.
So for example, a file called log.txt in the root directory of the micro SD card will be accessed with the following path:

var path = Path.Combine("SD","log.txt");

The other thing to keep in mind is that after writing to a file, the FlushAll() method on the volume object must be called in order to force writing to a text file.
Otherwise, the file might not be fully written.

Go back to the project, add this source code:

Connect the Netduino board to your computer with a USB cable.

Go to the property window and select the .NET Micro Framework tab and select the following options:
Transport: USB
Device: Netduino3_Netduino

Press F5 to start the program with debugging.
This will compile your source code, then upload the program to the board in debug mode which will show you messages in the output window.
Interesting points:
  • Use the FileMode.Append enumeration when working with FileStream to create a file if it doesn’t exist and continue writing values to the existing file.
  • Two messages get written to a text file because of the FileMode.Append enumeration
  • DateTime.UtcNow always returns the same value, we can fix it with a real time clock module which I will show you in an upcoming blog post.

Download source codehttps://github.com/codesanook/NetduinoReadWriteFile

credit
.NET Micro framework site
http://developer.wildernesslabs.co/Netduino/Input_Output/File_Storage/