+91-9464001760
29-404, LPU, Jal-Del G.T. Road - Phagwara, PB, India
09:30 am – 05:30 pm

USB Communication with IoT Devices

Published On: Tuesday, June 18, 2019 219 views

Hello,

        IoT devices are taking over the world by being always connected and extremely functional to serve as a solution for variety of technical requirements. I’ve been experimenting with them for a couple of months and found them technically intriguing and worth great value. However, if you’re experimenting with an IoT device or wish to communicate with the same using a regular desktop-pc or laptop running any modern OS, there will be a need to communicate with the device after deployment to debug issues or collect sensors data.

This communication with the IoT Device usually happens through the famous and extremely versatile Universal Serial Bus (USB) communication protocol found in modern electronics hardware. In order to use an IoT device to communicate with a pc, one can simply connect the same via regular UART/USB interface cable and use following code (written in C#) to communicate with the device:

Code Snippet:

[DllImport("user32.dll")]    //Required for the Serial Communication

static void Main(string[] args)

{

 Initialize();

}


private static void Initialize()

{

SerialPort mySerialPort = new SerialPort("COM3"); //Port Selection

           mySerialPort.BaudRate = 115200; //Set as per setting on Device

           mySerialPort.Parity = Parity.None;

           mySerialPort.StopBits = StopBits.One;

           mySerialPort.DataBits = 8;

           mySerialPort.Handshake = Handshake.None;

           mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

           mySerialPort.Open();

           Console.WriteLine("Awaiting for the data...");

           Console.ReadKey();

           mySerialPort.Close();

}

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)

        {

            try

            {

              SerialPort sp = (SerialPort)sender;

              string indata = sp.ReadLine();

              Console.WriteLine(indata); //Print received information

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.Message.ToString());

            }

}




Post by: Sarabpreet Singh
Contact author: click here

Key Words

static variety Handshake mySerialPort Hello Serial code regular modern layout extremely indata device functional blue SerialPort experiment DataReceivedHandler Console green height same WriteLine serve connect sender string found data requirement autospace normal solution StopBit communicate communication Parity world always technical