Serial Programming using Mono and C sharp (C#) on Linux

Pinterest icon

Serial Programming tutorial using mono framework and C# on Linux Operating System

Mono is a free and opensource equivalent to the Microsoft's .Net Framework platform developed by Xamarin which can be used to run programs using the .Net framework on Linux and other Unix like systems.Mono Framework can be used to write cross platform programs that would run on both Windows and Linux like OS's with minimal or no change to the source code.

In this tutorial we will learn how to install a mono runtime and compiler on a Linux System (I am using Ubuntu here),Compile a simple hello world program and communicate with the external world ie a microcontroller board through serial port using a USB to Serial Converter (USB2SERIAL).

The Mono Project consists of an ECMA complaint Common Language Runtime called Mono Runtime for running the executables and a C# compiler for compiling your .CS files into executables called Mono Csharp Compiler or mcs.

Sourcecodes

link to xanthium enterprises repo on Github containing code for serial communication using CSharp and Dot net Framework 

All the CSharp (C#) source files used in this tutorial can be downloaded from our GitHub Page.

If you are new to Github Check this article to download code .

Hardware Used 

Buy USB to RS485 converter online from here   Buy USB to RS485 converter online from here (made in India )

USB2SERIAL - Any easy to use multi protocol converter that can convert from USB to RS485/RS232/Serial.The Board comes with selectable voltage levels for interfacing with 5V and 3.3V logic families.

 

Contents

Installing Mono 
Compiling C# files
Serial Port Programming
Opening a Serial Port
Writing to Serial Port
Reading from Serial Port
RTS DTR pin control

Installing Mono on your Linux system

On most Linux systems mono is not installed by default, you can check whether mono is installed by typing mono on your terminal.If you are getting a response as shown below, mono is not installed on your system.

checking whether mono is installed on linux

Mono runtime and compiler is available on Ubuntu's software repositories so you can directly install them from Ubuntu Software center.Just click on the Mono/CLI icon and install the two runtimes

installing mono runtime from ubuntu software center

installing mono runtime and mcs compiler from ubuntu software center

You can also install the complete Mono framework using command line.

For Serial Programming it is recommended to install the complete Mono runtime and libraries.Open up your terminal window and type

$ sudo apt-get install mono-complete

provide the password for your account to install mono as shown in the figure below.This will install the complete Mono runtime and avoid any dependency issues.

installing mono runtime on linux using command line

After Mono is installed on your system,you can check them using the whereis command or by just typing mono or mcs on the terminal.

checking whether mono runtime and mcs is installed on Linux using whereis command

Compiling C Sharp (C#) files on Mono

Now lets compile a simple "Hello World" program using mcs and run it on the mono runtime.Open up a text editor and type the following code in it.

using System;

namespace MyMonoProgram
{
  class MyProgram
  {
    public static void Main()
    {
        Console.WriteLine("\nHello Mono from Ubuntu\n");
    }
  }
}

Now save the file as "HelloMono.cs" on your home directory (or an other directory) and compile it by typing

$ mcs HelloMono.cs

if there are no errors the HelloMono.cs file will be compiled into a HelloMono.exe file,  which you can view by using the ls command (as shown in the below figure).

compiling code using mcs

You can then run the resulting exe file using the mono runtime by typing

$ mono HelloMono.exe

on the terminal.

running the exe file using mono runtime

In the above example we have used command line tools to compile and run the C# file ,If you like a proper IDE mono project also develops MonoDevelop which comes with features like automatic code completion, source control, a graphical user interface (GUI) and Web designer.It also supports several languages like Boo, C, C++, C#,F#,Java,Python,and Visual Basic.NET.

monodevelop IDE running on Linux Mint

MonoDevelop on Windows 7

monodevelop on windows 7

Serial Port Programming using Mono

Now lets go to the main course,programming your serial port using Mono.If you have any experience building embedded systems you may have encountered situations where you want to communicate with an external microcontroller board to log data to your PC or send AT Commands to a GSM modem.

The easiest way to achieve that is to send your data through a Serial Port,Even though hardware serial ports are being replaced with USB ports, you can find cheap USB to Serial converters based on FTDI FT232 like USB2SERIAL for doing the conversion.

In Linux serial ports are named as ttyS1,ttyS2 for hardware ports and  ttyUSB0 (FTDI based) or ttyACM0 (TUSB3410 based) for USB to Serial Converters,the port numbers may vary on your system.You can check this tutorial for finding out your serial port number.

Opening a Serial Port in Mono

Now lets write a small C# program to open up a connection with your Serial Port (Hardware Port or USB to Serial Converter).Open up a text editor,type out the code shown below and save it as "MonoSerial.cs" on your harddisk.   

using System;
using System.IO.Ports;

namespace MonoSerial
{
  class Program
  {
    public static void Main()
    {
      SerialPort Serial_tty = new SerialPort(); 

      Serial_tty.PortName = "/dev/ttyUSB0"; //Assign the port name,
      //here ttyUSB0 is the name of the USB to Serial Converter used. 

      try
      {
       Serial_tty.Open();//Open the Port
       Console.WriteLine("Serial Port {0} Opened",Serial_tty.PortName);
      }    
      catch
      {
        Console.WriteLine("ERROR in Opening Serial Port");
      }  
    }
  }
}

Please note that ttyUSB0 is the name of the USB to Serial converter chip detected by my system,Find out the name of you serial port and substitute that instead of ttyUSB0 in the above code before compiling . After saving the file ,compile it using mcs.On successful compilation it would create an executable named as " MonoSerial.exe " .

In Linux access to the serial port is only available to the root user ,so you will have to run the exe file with root privileges using "sudo" command as shown below.

$ sudo mono MonoSerial.exe 

Now give the password to your system so that the code can run ,if all goes well it will print

Serial Port /dev/ttyUSB0 Opened " on the terminal as shown in the below figure.

opening a serial port in Linux using Mono and C#

 

Writing a Character to Serial Port using Mono

After we have opened a connection to the Serialport,let's write some characters to the serial port.Open up a text editor and type the following code to it ,save the file as "MonoSerialWrite.cs".

using System;
using System.IO.Ports;

namespace MonoSerialWrite
{
 class Program
 {
   public static void Main()
   {
     string ttyname;
     SerialPort Serial_tty = new SerialPort();
            
     Console.Write("\n\nEnter Your SerialPort[tty] name (eg ttyUSB0)->");
     ttyname = Console.ReadLine();
     ttyname = @"/dev/" + ttyname;
            
     Serial_tty.PortName = ttyname;            // assign the port name 
     Serial_tty.BaudRate = 9600;               // Baudrate = 9600bps
     Serial_tty.Parity   = Parity.None;        // Parity bits = none  
     Serial_tty.DataBits = 8;                  // No of Data bits = 8
     Serial_tty.StopBits = StopBits.One;       // No of Stop bits = 1
            
     try
     {
        Serial_tty.Open();                 // Open the port     
        Serial_tty.Write("A");             // Write an ascii "A"
        Serial_tty.Close();                // Close port
        Console.WriteLine("\nA written to port {0}", Serial_tty.PortName);
     }
     catch
     {
       Console.WriteLine("Error in Opening {0}",Serial_tty.PortName);
     }
   }
  }
}

Connect a microcontroller board to your serial port using null modem connection in order to receive the transmitted character.

In Null modem connection TX pin of PC serialport is connected to the RX pin of Microcontroller and vice versa as shown in the below figure.

null modem connection between linux pc and msp430 microcontroller

In case you don't have a hardware serial port use a USB to Serial Converter like USB2SERIAL.USB2SERIAL can also be used as an USB to RS485 converter or as an FT232 development Board.The Board can be purchased online from ebay.

Compile the code using mcs compiler and run it using mono runtime .Please remember to run your executable as root using sudo command.Screenshot shown below.

Writing a ascii character to serial port  using mono and C# on Linux Operating System

When the data is transmited the TX/RX LED on the USB2SERIAL board will blink indicating that a byte has been transmitted.Now on the microcontroller side you can write  code to take some action like lighting up an LED or turning on a motor.

Receiving a Byte through Serial Port using Mono

Here we will receive the data send from a microcontroller board(Transmitter) to the Linux PC through the serial port.The Microcontroller board (Here I am using MSP430 Launchpad from TI) will send a string "Hello from MSP430" serialy to the PC.You can use any microcontroller like 8051,PIC,ARM,STM32 etc instead of MSP430 on the transmitter side.

The code for receiving the data send from the microcontroller is shown below.Here we are using Console.ReadLine() function to read the data send from the MSP430.Please note that the timeout's for the serial port are not set so the program will wait indefinitely till the data is received.

using System;
using System.IO.Ports;

namespace MonoSerialRead
{
 class Program
 {
   public static void Main()
   {
    string ttyname = "";
    string ReceivedData = "";
            
    SerialPort Serial_tty = new SerialPort();
            
    Console.Write("\nEnter Your SerialPort[tty] name (eg ttyUSB0)->");
    ttyname = Console.ReadLine();
    ttyname = @"/dev/" + ttyname;
            
    Serial_tty.PortName = ttyname;
    Serial_tty.BaudRate = 9600;               // Baudrate = 9600bps
    Serial_tty.Parity   = Parity.None;        // Parity bits = none  
    Serial_tty.DataBits = 8;                  // No of Data bits = 8
    Serial_tty.StopBits = StopBits.One;       // No of Stop bits = 1
            

    try
    {
      Serial_tty.Open();
      Console.WriteLine("\nWaiting for Data......"); 
      ReceivedData = Serial_tty.ReadLine();     // Read the data send                                                          //from microcontroller
      Serial_tty.Close();                       // Close port
      Console.WriteLine("\n{0} received\n", ReceivedData);
    }
    catch
    {
     Console.WriteLine("Error in Opening {0}\n",Serial_tty.PortName);
    }
   }
  }
}

Compile the program and run it.Enter the name of your serial port and the program will wait for data to be transmitted by the microcontroller as shown in the below figure.

Reset your microcontroller to send the string "Hello from MSP430".

The program will then print out the received string on the console window. 

One thing to note that, is Console.ReadLine() will return only after encountering the end of line character "\n".Please make sure that the microcontroller sends the "\n" character otherwise the Console.ReadLine() will never return and program will hang.

Controlling RTS and DTR pins 

Controlling the RTS and DTR pins can be accomplished by using RtsEnable and DtrEnable properties of the SerialPort object.

using System;
using System.IO.Ports;

namespace MonoSerialRTSDTRControl
{
    class Program
    {
        public static void Main()
        {
             string ttyname = "/dev/ttyUSB0"; // port name 
             SerialPort Serial_tty = new SerialPort();
             
Serial_tty.PortName = ttyname;
             Serial_tty.Open();             // Open the port
             Serial_tty.RtsEnable = true;   // RTS pin = 1 ,~RTS = 0
             Console.Read();                // Press any key
             Serial_tty.RtsEnable = false;  // RTS pin = 0 ,~RTS = 1
             Console.Read();              
             Serial_tty.DtrEnable = true;   // DTR pin = 1, ~DTR = 0
             Console.Read();
             Serial_tty.DtrEnable = false;  // DTR pin = 0, ~DTR = 1
             Console.Read();

             Serial_tty.Close();            // Close port
        }
    }
}

One use of RTS and DTR pins is used to control the RS485 chips during a USB to RS485 conversion.When you have to control some thing over several 100's of meters ,RS232 or USB will not be suitable.In such cases we have to use RS485 protocol, one problem with RS485 is that most PC's / Laptops will not have an RS485 port.You can solve that problem by using USB to RS485 converters like USB2SERIAL .In USB2SERIAL RTS pin is used to put the RS485 chip in receive mode and DTR pin is used to put theRS485 chip in transmit mode.

Please note that in FT232 based USB to Serial converters (like USB2SERIALthe RTS and DTR pins are inverted internally so setting the pins high will make then low and vice versa.

Connect a couple of LED's  to Visualize the logic levels of RTS and DTR pins of  USB2SERIAL.

CSharp ode for controlling the RTS and DTR pins of FT232 serial port,C# Robotics

You can check out our other serial programming tutorials here.