Sergii Baidachnyi

Blog about technologies

Posts Tagged ‘IoT

IoT: Visual Studio and Arduino boards

leave a comment »

Two days ago I decided to start video training about micro boards and Microsoft technologies there. I already have Galileo, Netduino and Raspberry but in order to have the complete line I bought Arduino Uno R3 board. This board is not very powerful but it’s very popular and you can find lots of stuff for Arduino in the market. So I cannot ignore this board.

Once I bought it I decided to create several examples. Of course, I knew that Arduino boards require Arduino IDE but if you have experience with Visual Studio you can see that the difference between Arduino IDE and Visual Studio is the same as the difference between Visual Studio and Notepad. So, I spent some time to understand if there is a way to develop Arduino software using Visual Studio. And, finally, I found Visual Micro plug-in.

This plug-in exists in two versions: free and paid version. The paid version promises a better debugger and many additional features. But if you just started to work with Arduino you can use the free version, which extends Visual Studio and supports IntelliSense, basic debugging, settings, samples and so on. Of course it’s not ideal but I was excited to use many cool features for free. And if you are going to develop lots of Arduino applications you can spend 29 dollars and get all paid features on your development machine.

So, in order to install the plug-in you need to install Arduino IDE first. Visual Micro supports Arduino 1.6.1 at this time but it’s changing quickly, so check the latest version installation guide to find the right Arduino IDE version. Once you installed Arduino IDE you may install Visual Micro plug-in for Visual Studio but check version of your Visual Studio because Visual Micro doesn’t support Express versions though you may use Community edition which is free as well.

Once you launch Visual Studio for the first time after installation of plug-in you will get a window which asks to setup Arduino IDE directory and offers to buy the plug-in. Arduino IDE directory is needed to have the same storage place for your sketches.

I don’t know why but to start new project in Visual Studio you need to select not New->Project but New->Sketch Project. It took 30 seconds to find where I can create a project but it’s not a very big problem.

So, once you create a project you are ready to start coding. Visual Studio has several combo boxes which allows to select Arduino SDK version, type of your boards and the port which you are using to connect your board. Additionally, there is access to examples, property window and many other tools which you can find in Tools->Visual Micro menu item.

clip_image002

Debug mode is not as powerful as debug mode for Galileo or Netduino but it’s still useful. Pay attention that there is no strong integration with Debug menu item and sometimes it’s not easy to understand if your application is still in Debug mode. But you can adapt your experience in 3-5 minutes and it’s better than no debugger at all. Free version of plug-in allows to navigate through your breakpoints only. You can check output window to understand if your application is in pause mode and you can use F5 button in order to run your code up to next breakpoint.

Finally, I found that Visual Micro can be very useful and really help me to develop using my favorite tool. And if you are developing not just Arduino code but some services and external applications you can do it inside the single solution.

Advertisement

Written by Sergiy Baydachnyy

04/22/2015 at 8:45 PM

Posted in IoT

Tagged with

IoT: How to run a brushless motor using Netduino

leave a comment »

In one of my articles about Galileo I showed how to run a simple DC motor using L293D chip. But it’s not very interesting because if you are going to build your own robot or drone, you need to use more powerful motors. For example, I have a dream: I want to build my own drone using boards like Galileo or Netduino. So, I decided to start my research with the most expensive part of drones – motor system. I already printed several propellers using my 3D printer, so I wanted to reach two goals: test the printed propellers to understand, if I can use them; understand, how to use Netduino or Galileo boards to operate more powerful motor.

If you are going to build your own drone you need several multirotor brushless motors. It’s very important because motor should work in both directions to guarantee stability of the drone and you should have a way to regulate speed to move drone in 3D space. Additionally you need to buy ESC (electronic speed controller), which will help to operate the motor. It’s kind of like more advanced version of L293D chip. Finally you need a battery. Because your motor should be powerful and you need 4-6 motors there (I decided to use 6), you cannot use a simple 9V battery – you should use lithium polymer and a charger for your LiPo battery as well. All these things are not very cheap and you need to spend more than 150 dollars in order to buy everything but don’t worry, because it’s the most expensive part of the drone.

Finally I bought the following things:

· 1000 Kv brushless motor + 30A ESC – I bought 6 motors and 6 ESC;

· 5100 mAh IRIS+ battery – It’s a very powerful battery, which is used by IRIS drone;

· A charger – there many different charges in the market, so you can select the cheapest one;

Once I got my package I spent much time to run the motor. It was not easy because you should understand which signals to send ESC to start moving. In my case I got ESC without any instructions, model number etc. So, I tried to use the standard procedure to initialize it:

Attention: ESC has three wires, which you connect to your board (ground, signal and power). Don’t connect red wire (power) to your board. ESC doesn’t require additional power because it’s enough power from LiPo battery. Officially you can use it in order to send some power to your board (or fly controller) but I still didn’t test it.

· First of all, you should setup your ESC. In order to do it you need to send the highest power signal from ESC range and plugin you ESC to power (LiPo). Your ESC should initialize the highest number and finish it with one beep;

· Once you have heard ESC beep you should send the lowest signal. If you are using your ESC for the second time you need to send the lowest signal before you connect ESC to LiPo. If everything is OK, your ESC will send several beeps, which are signals about number of cells in your battery;

· If everything is OK, you can start to send different signals inside your range in order to operate your motor;

Attention. ESC has three wires which you should connect to the motor wires. You can use any sequence. Depends on sequence, the motor will operate in different directions.

The procedure looks very simple but there are still several questions. For example, it is not clear, which signal I should send to ESC and how to setup your PWM pin in order to send the right signals.

Attention. In order to send signals to ESC you should use PMW signals. In case of Galileo, all PMW are marked by “~”. In case of Netduino 2 Plus you can use pins 3,5,6,9,10,11.

Officially you can use Servo library for Galileo and find the similar library for Netduino. I tried to use this approach but my ESC just sent beep-beep-beep… signals without any results (these beeps say that signals from the board are not in the range). So, I decided to forget about standard libraries and use PMW directly. Finally I found the following parameters for PMW constructor in .NET Micro Framework:

· High signal – PWM(PWMChannels.PWM_PIN_D5, 20000, 1750, PWM.ScaleFactor.Microseconds, false);

· Low signal – PWM(PWMChannels.PWM_PIN_D5, 20000, 1250, PWM.ScaleFactor.Microseconds, false);

So, in order to initialize my PMW I just use these lines of code in debug mode. I send high signal, stop execution (using breakpoint) there and attach my LiPo battery. Once the motor sent the right signal I executed the second command.

In order to test my motor I connected a joystick to my board and implemented the following code:

public static void Main()
{
AnalogInput an1 = new AnalogInput(AnalogChannels.ANALOG_PIN_A0,1000,0,-1);
AnalogInput an2 = new AnalogInput(AnalogChannels.ANALOG_PIN_A1, 1000, 0, -1);
InputPort p = new InputPort(Pins.GPIO_PIN_D8,
true, Port.ResistorMode.PullUp);

PWM pwm = new PWM(Cpu.PWMChannel.PWM_0, 20000,
1750, PWM.ScaleFactor.Microseconds, false);

bool flag = false;
bool isStarted = false;

while(true)
{
if (flag)
{
if (isStarted==false)
{
pwm.Duration = 1250;
pwm.Period = 20000;

pwm.Start();
isStarted = true;
Thread.Sleep(5000);
}
double posx=an1.Read();
double posy=an2.Read();
if ((posx<500)||(posy<500))
{
uint duration = pwm.Duration;
if (posx<500)
{
duration-=10;
}
if (posy<500)
{
duration+=10;
}
if (duration > 1750) duration = 1750;
if (duration < 1250) duration = 1250;
pwm.Duration = duration;
pwm.Period = 20000;
pwm.Start();
Thread.Sleep(500);

}
if (p.Read() == false)
{
pwm.Stop();
isStarted = false;
flag = false;
Thread.Sleep(1000);
}
}
else
{
if (p.Read()==false)
{
flag = true;
Thread.Sleep(1000);
}
}
}
}

clip_image002

Thanks to that code I got a chance to turn on and turn off my motor using click, and speed up and down my motor using up and left directions of joystick (my joystick has been broken, so I could not use up and down).

Of course, in order to test the motor with a propeller, you should think about the right environment. First of all you should fix your motor. I made a mistake there, I used several bolts in order to fix my motor on top of the cardboard box. It didn’t stop my motor and it was trying to fly with a piece of the box. Thanks to Galaxy I am still alive but right now I am printing a new propeller. I still don’t understand why I decided that a cardboard box would stop the motor which should be able to get the drone up to the sky.

Written by Sergiy Baydachnyy

03/10/2015 at 2:34 AM

Posted in IoT

Tagged with

Internet if Things: How to create a simple Web server (part 2)

leave a comment »

Last time I promised to show how to create a simple Web server on Galileo board. Since we have Windows on Galileo there can be several ways to create a simple web server but, finally, I found just one “stable” way to do it – sockets (WinSock 2.2 library). Additionally, I found one more way which doesn’t require development at all but first things first.

Since I am a .NET developer, I started my research with some libraries, which could help me to avoid sockets and not require using the Win32 API a lot. According to the samples presented by Microsoft, there is a way to use C++ Rest SDK and node.js. But both of them don’t have official support of Galileo boards. Windows image for Galileo contains subset of desktop Win32 API, so, there is no guarantee that these SDKs work fine or will work fine in future releases.

For example, if you are going to use C++ Rest SDK, you should download version 2.2 but current version 2.4 will not work. Version 2.2 uses WinHTTP API in some classes, which is not supported in Galileo image as well. That’s why I didn’t have a chance to use http_listener there.

The same situation with node.js. I did all recommended things with user32.dll but the latest version of node.js simply didn’t work. If I have some time I will try to find the solution of the problem there but I needed to find a simple way to launch Web server without spending much time.

That’s why I decided to use Winsock API which is a common part of all modern Windows images. But before I show my Web server, I want to discuss one more thing – httpsrv.exe.

If you had a chance to use the Galileo Watcher, you saw several menu items in context menu there and one of these items was “Web Browser Here”:

clip_image001

This menu allows you to launch a browser, which opens a web page on th Galileo board with several links there. It uses an IP address of the board and port 80 there. So, it’s easy to understand that Galileo contains a web server by default. If you launch Telnet and run tlist command you will find that there is httpsrv.exe process.

clip_image003

This process is a simple web server, which is part of Windows mini image. It’s not easy to find something about this server but I found that it maps c:\Windows\System32\Web folder as a Web server directory. In fact there is a simple page and several applications which are initiated by the page:

clip_image005

So, I simply changed a page and added a link to my own application, which contains just one line of code:

#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "<body>Hello from Web <a href=http://microsoft.com>Microsoft</a></body>";
return 0;
}

Thanks to httpsrv I got a chance to run my own application and use output stream as a source for outgoing web page. This approach is very simple. In fact you can create two applications: the first one implements logic of your project and use some local files for data storage, the second one should read stored data and generate output stream for web page. Thanks to that you should not think about your own implementation of a web server at all. It was so easy that I lost all desire to use sockets but I had promised it last time. So, if you finally decided to implement your own server I will show the socket approach as well. Pay special attention that httpsrv uses port 80, so, if you want to use your own server using the port, you need to shutdown httpsvr or start httpsrv using other port.

In order to use Winsock API I decided to use existing code with some modifications. MSDN Samples allowed only one request and tried to make something with this request. In case of Web server, you need to allow many requests, so I used a simple while operator there. Additionally, I changed all printf to Log function.

#include "arduino.h"
#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

#pragma comment (lib, "Ws2_32.lib")

#define DEFAULT_BUFLEN 1024
#define DEFAULT_PORT "8080"

int __cdecl main(void)
{
WSADATA wsaData;
int iResult;

SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;

struct addrinfo *result = NULL;
struct addrinfo hints;

int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;

iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
Log("WSAStartup failed with error: %d\n", iResult);
return 1;
}

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
Log("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}

ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
Log("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}

iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
Log("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}

freeaddrinfo(result);

while (true)
{
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
Log("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
}

ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
Log("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
}

iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
{
Log("Bytes received: %d\n", iResult);

char ret[] = "Hello World";
iSendResult = send(ClientSocket, ret, sizeof(ret), 0);
if (iSendResult == SOCKET_ERROR)
{
Log("send failed with error: %d\n", WSAGetLastError());
}
Log("Bytes sent: %d\n", iSendResult);
}
else if (iResult == 0)
Log("Connection closing...\n");
else
{
Log("recv failed with error: %d\n", WSAGetLastError());
}

iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
Log("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
}

closesocket(ClientSocket);
}

return 0;
}

This code is not ideal because it accepts all requests, doesn’t generate the right response (like HTTP/1.0 200 OK…..) and it doesn’t support multithreading. But it works, it doesn’t depend on any third-party library, doesn’t require dancing with a tambourine and you can use it as a starting point for your server.

Written by Sergiy Baydachnyy

02/18/2015 at 6:01 AM

Posted in IoT

Tagged with

IoT: How to integrate two boards

leave a comment »

In the previous posts I described some features of Galileo 2 board but there are still some scenarios, which may not be implemented on Galileo 2 boards only. For example, Galileo doesn’t have GPU, so you cannot use Galileo to output video. But there are several micro boards in the market like Raspberry Pi board, which supports GPU, HDMI output and allows to use camera as well. So, on the one hand we have a good solution with the Intel inside processor but on the other hand we still have some scenarios when we need to use several boards there. So, in this post I decided to show how to integrate two boards.

I used the Netduino and Galileo boards but this approach will work for Raspberry PI and Arduino as well. The idea is in using TX/RX pins, which are implemented in the most boards and allow to make serial communications. In fact, TX/RX pins is the same like COM1.

In order to test TX/RX pins I decided to build something like this

image

The idea of the project is too simple: we will use Galileo board in order to get input from two buttons and thanks to them we are going to control two leds, which are connected to Netduino. Because we use Netduino compatible boards, we can find TX/RX pins connected to pins 0 and 1. One of this pins is used for sending data and the second one – for receiving. So we should connect pin 0 (Galileo) to pin 1 (Netduino) and pin 1 (Galileo) to pin 0 (Netduino).

The code of our applications is pretty simple. In case of Arduino you can use the following example:

public class Program
{
public static void Main()
{
// write your code here
OutputPort ledRed = new OutputPort(Pins.GPIO_PIN_D8,false);
OutputPort ledYellow = new OutputPort(Pins.GPIO_PIN_D9,false);
SerialPort serial = new SerialPort(SerialPorts.COM1,9600,
Parity.None, 8, StopBits.One);
serial.Open();

while(true)
{
if (serial.CanRead)
{
int b=serial.ReadByte();
char c = (char)b;
switch(c)
{
case 'r':
ledRed.Write(true);
break;
case 'y':
ledYellow.Write(true);
break;
case 'f':
ledRed.Write(false);
break;
case 'h':
ledYellow.Write(false);
break;
}
}
}
}
}

This code just get the commands from serial port and switch on or switch of the leds.

In case of Galileo, you can use the following code:

#include "stdafx.h"
#include "arduino.h"

int _tmain(int argc, _TCHAR* argv[])
{
return RunArduinoSketch();
}

int but1 = 8;
int but2 = 9;
bool flag1 = false;
bool flag2 = false;

void setup()
{
Serial.begin(CBR_9600, Serial.SERIAL_8N1);
pinMode(but1, INPUT);
pinMode(but2, INPUT);
}

void loop()
{
if ((digitalRead(but1) == HIGH) && (!flag1))
{
Serial.write('r');
flag1 = true;
Sleep(1000);
}
if ((digitalRead(but2) == HIGH) && (!flag2))
{
Serial.write('y');
flag2 = true;
Sleep(1000);
}
if ((digitalRead(but1) == HIGH) && (flag1))
{
Serial.write('f');
flag1 = false;
Sleep(1000);
}
if ((digitalRead(but2) == HIGH) && (flag2))
{
Serial.write('h');
flag2 = false;
Sleep(1000);
}
}

I used sleep there in order to avoid several inputs from one button click there.

Finally I run my project:

image

In our case we used Galileo for sending data. But if you want to write some code which will able to receive some data you should add the following preprocessor directive to C/C++ configuration properties: SERIAL_EVENT; Additionally you should implement serialEvent method, which is called if some data is available.

You can use TX/RX pins in order to communicate with PC as well. In order to do it you can but UART->USB adapter which costs around 6 dollars (use just two pins there).

image

Written by Sergiy Baydachnyy

02/17/2015 at 10:11 PM

Posted in IoT

Tagged with

Internet of Things: What about C# there?

leave a comment »

In my post about Galileo we used C++ language in order to build some code. But what about C# and is there a way to use management language in micro devices based on different types of microcontrollers? So, this post I decided to devote to C# language.

First of all you need to understand that there is no way to use C# for Arduino boards. Of course, Arduino is very popular today but there are many different solutions in the market as well. Some of these solutions are Netduino, Raspberry PI and Galileo. Today, you can find much more different boards but these microcontrollers have better support, community and popularity. So, let’s discuss all these boards and try to understand if there is a place for C# and .NET Framework.

I am going to start with Netduino boards. You can find many different models using the following link. I would recommend Netduino Plus 2, which is the most advanced board there but it’s not important right now because all these boards run .NET Micro Framework and allow to use C# there.

clip_image002

.NET Micro Framework is an open source platform, which is developed for low memory devices with limited amount of resources. In fact, .NET Micro Framework could be run on devices with 64 kilobytes memory that is very important for cheap and really small devices. .NET Micro Framework has a very interesting story. Probably, it was announced too early, about 9 years ago and since that time, .NET Micro Framework supported many different microcontrollers. Today, the most popular microcontrollers are Netduino 2 and Netduino Plus 2, which are Arduino compatible. It’s very important right now because it’s easy to find many different stuff for Arduino. At the same time there are special controllers for people, who don’t have enough knowledge in electronics – Netduino Go and Gadgeteer. These two boards allow to use plug and play modules to create your own prototype fast.

In my case I decided to buy Netduino Plus 2 board and make some small projects there. And of course, if you have a board you will need to install some stuff to your computer like: .NET Micro Framework SDK, Tools for Visual Studio and board specific SDK. In case of Netduino Plus 2 I would recommend the following steps there:

· Update Netduino firmware – when I bought the board I found that it has version of .NET MF less than 4.3. But if you have older version of firmware on your board you will not be able to use the latest version of SDKs. How to update firmware you can find in Arduino forum.

· Install .NET Micro Framework SDKs and tools for Visual Studio – you can find the package using the following link;

· Install Netduino SDK – you can download it there;

In any case, before download something, check the latest versions of SDKs and firmware.

Once you install all needed software, you can use USB -> micro USB cable in order to connect it to PC. You can use this cable in order to provide power to Netduino board. Using Visual Studio you can create an application based on special templates for Netduino boards and you can start to use C# and many classes from .NET Micro Framework and Arduino there. Visual Studio supports not just deployment of applications to Netduino but debugging and Intellisense system as well. So, you developer experience should look like common Windows platform experience. It’s really cool.

clip_image004

The second board, which allows to use C# there is Raspberry PI board. This board is not compatible with Arduino but it’s very popular because there is not just CPU but GPU as well. The board contains HDMI output and you can connect it to TV sets, projectors etc. And you still may use many sensors from Arduino world because Raspberry supports the same voltage. Frankly speaking, Raspberry doesn’t support Visual Studio or any special tools for Windows developers but Raspberry is designed for full version of Linux operation system. You can find many different Linux edition for Raspberry but in any case you need to work with Linux. But as you know, there is an open source version of .NET Framework – Mono. So, you still can use C# and .NET framework features there.

In my research I decided to use Raspbian image based on Debian Wheezy. Somebody told me that it’s very popular and it was the first in the list of images. Of course, for Windows developers it’s not easy to understand, how to use this image but I just connected my board to TV Set, using HDMI cable and plugin keyboard and mouse there. Thanks to Edimax WiFi adapter and WiFi Config tool in the image, I easily setup Internet connection there and got IP address. Once you get Internet connection, you need to run one more command, using LXTerminal:

sudo apt-get install xrdp

This command will activate remote desktop on your board. It’s time to disconnect your board from TV, keyboard and mouse because you may use Remote desktop right now.

In the next step, you need to run to more commands to install Mono runtime:

$ sudo apt-get update

$ sudo apt-get install mono-runtime

Thanks to Mono runtime you are ready to launch you C# application but you still don’t have tools. So, finally, in order to install Mono Develop, you can use the following command:

sudo apt-get install monodevelop

Now, you ready to run Mono Develop and launch your applications.

clip_image006

Frankly speaking, I am not sure if you will get much happiness while developing something on Raspberry directly. It’s not a very productive environment and it’s better to use your PC to create code and just use Raspberry to compile and launch it. While it’s interesting to create Windows Form applications on Raspberry usually you are interested in PINs there. In order to use pins from C# and make real micro solutions you will need to download RaspberryPI.NET library, which you can find using the link.

And a few words about Galileo. Officially Microsoft doesn’t support .NET Framework on Galileo boards. According to official FAQ there is a chance to see Windows Runtime or something like this soon:

Q: Will you support C#/WinRT/.NET/Node/JS… ?
A: For this first preview release, we’re focusing on C++ and Arduino compatibility. In future iterations, our intent is to support the Universal App model announced at Build.

But I found that many people already tried to make some research around Mono and Galileo board as well. For example, you can check this post in order to find some instructions about it.

Written by Sergiy Baydachnyy

02/17/2015 at 9:56 PM

Posted in IoT

Tagged with

Internet of Things: How to create a simple Web server (part 1)

leave a comment »

Today you can find many different boards in the market which have Ethernet socket or support Ethernet/Wi-Fi/3G shields. So, connection to Internet is a trivial task. I already mentioned several Azure services which you can use in order to send messages, store your data and analyze it. But I found that there are still some scenarios when customers don’t want to connect their devices to Internet. At the same time they still need access to data using phones, laptops etc. using local network without any special infrastructure. In this case there is a task, which requires to have a simple web server. Of course, you can try to create any type of server (not just Web) but in most cases it’s easy to use Web browser to get access to your data. It’s not very hard to implement several methods inside your IoT solution, which will prepare HTML output based on existing data. But what about Web server?

In order to do my research I decided to use Netduino and Galileo boards. In this post I will show code for Netduino in .NET and in the next post I am going to discuss more complex code for Galileo.

Because Netduino uses .NET Micro Framework, it’s easy to use already prepared classes, which will help to implement our code. The most important class there is HttpListener and you can find it in System.Http assembly which is not included to your references by default. This class allows to start listening HTTP request. In fact you can implement the following code inside your Main method:

var httpListener = new HttpListener("http", 80);

httpListener.Start();

while(true)
{
var context = httpListener.GetContext();
var buffer = Encoding.UTF8.GetBytes("<html><body>" + DateTime.Now + "</body></html>");
context.Response.ContentLength64 = buffer.Length;
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Close();
}

We just created an object of HttpListener type using http protocol and port 80 and initiated listening thanks to Start method there. In order to get request from users we should call GetContext method, which will be waiting for request. Once we have a request we can get information about Uri, parameters etc. and create a response. In our case we send back a simple Html document.

If you test this code, probably, it will work but there are two problems:

· This code will work fine just for one user and if you have several requests, probably, your board will go down;

· Usually you need to do something and not just listening to a request. If you leave this implementation, you won’t have a place to put device’s logic there;

So, we need to update our code using threads. In order to avoid the first problem you can generate your HTML and send response in separate thread and there will be a separate thread for each request. At the same time you can start listening in separate thread as well. This approach will allow you to start listening and return to application’s logic. So, my code looks like this:

new Thread(() =>
{
var httpListener = new HttpListener("http", 80);
httpListener.Start();
while (true)
{
var context = httpListener.GetContext();
new Thread(() =>
{
var buffer = Encoding.UTF8.GetBytes("<html><body>" +
DateTime.Now + "</body></html>");
context.Response.ContentLength64 = buffer.Length;
context.Response.OutputStream.Write(buffer, 0,
buffer.Length);
context.Close();
}).Start();
}
}).Start();

while(true)
{
//your logic
}

If you have some time your can rewrite this code using delegates approach.

Finally, I want to share the code which shows how to get ip address of your board. It will help you to reach your board using Web browser:

NetworkInterface ni;
while (true)
{
ni = NetworkInterface.GetAllNetworkInterfaces()[0];

if (ni.IPAddress != "0.0.0.0") break;
Debug.Print("Waiting for an IP Address...");
Thread.Sleep(1000);
}
Debug.Print(ni.IPAddress.ToString());

Next time we will use sockets in order to show how to build Web server on Galileo.

Written by Sergiy Baydachnyy

02/13/2015 at 8:34 AM

Posted in IoT

Tagged with

Azure services and Internet of Things

leave a comment »

I just finished several posts about Galileo board for beginners. In those posts I showed how to create simple projects, which help us to collect data from sensors. But there still is a question: what we should do with collected data there. That’s why in this post I want to show several cloud services, which will help you to collect and analyze data from many devices at the same time in order to be ready to present consolidated data for users.

Of course I am going to talk about Azure because Azure provides not just base services like VM hosting, WebSites, SQL Azure etc. but several specific services, which are ready for solutions based on “micro” devices – devices which might contain many different boards and sensors around the World.

Queue

I will start with most simple Storage service component like Queue, which was presented in the beginning of Azure era and which is important for some scenarios in Internet of Things area.

Queue supports REST API and works fine in IoT projects which have just one event publisher or just one event consumer and if you don’t need to implement any special algorithm for access data in queue.

For example, you design a device, which plays music in restaurants or bars. Everybody may order favorite music using smartphone, tablet, terminal at the bar etc. But the device can play just one composition at the same time. So, you will have a queue there with orders inside and each element will contain some expiration time as well. In these case you have just one consumer device and it doesn’t require any special algorithm for selecting messages.

You can design one more device, which will provide the next number in line to government officials. This device increases internal counter, provides a new number, prints tickers with the number and puts a given number to the queue. Each official has a table – one more device, which connects to the queue and takes the next number from the queue. In this case we have just one publisher but many consumers (several agents with own tables).

So, there are many scenarios where queue is good enough. You can find REST API documentation for queue using this link.

Pay special attention that there are very strong requirements for queue. You should use low case symbols only. I forget about it from time to time and then it takes some time to find a mistake.

Event Hub

If you have many publishers and consumers at the same time, a simple queue will not work fine.

Imagine cashiers at the food store. Usually each cashier has his own line and there is a chance to increase number of cashiers in real time etc. There is no ways to use just single queue. At the same time it’s too hard and expensive to use many queues, because you need to implement lots of code, which will create queues dynamically and manage elements there. In other words you will need super queue.

Probably it was a good idea to create something like super queue with much own code inside but today we have Event Hubs.

Event Hubs is a special service which supports messaging scenarios with many event publishers and many consumers at the same time.

clip_image002

Thanks to partitions, consumer groups and offsets it’s possible to implement any scenarios there. Of course, you can use Event Hubs in scenarios, which work with Queue as well. In this case you will use a universal approach.

Of course, Event Hubs like Queue and other services, support REST API as well.

Mobile Services

In some scenarios you might want to notify users about some events using standard Push notification services. In this case, it’s easy to use Azure Mobile Services. I already wrote a series about Azure Mobile Services. So, if you are interested in some aspects of it, you can read my series.

Tables and Blobs

Of course, previous services allow to use events in order to communicate between publishers and consumers. But in many scenarios you are required to store a lot of data from sensors. For example, you can create a device, which will collect data about pollution in the area. Your device is not going to send any events. Instead, you are going to use this data to analyze the situation for many years. So, you need a storage but Queue and Event Hubs cannot works like a storage.

Since usually devices send much non-relationship data, you will use non-SQL storages. In case of Azure you can use Tables and Blobs.

Tables allow to store data in table format and you can store hundred thousands terabytes there. But Tables have two disadvantages there. First of all in order to store data from sensors, your device need permanent access to Internet. Of course, you can preserve data to a local file but in this case it’s better to send to Azure file itself. The second disadvantage is related to format of data. You can store text data there but in case of images, videos etc. you need to return to files. So, usually, in IoT scenarios you will use Blobs instead of Tables.

Blobs allow to store any files inside and support REST API as well. So, usually you will preserve sensor data to a file and send it to Blobs based on your own scenario.

Stream Analytics

So, we already have some services which help with events and storage but we still need a way to analyze stored data. A new Azure service, called Stream Analytics, will help you to implement this task as well.

Stream Analytics can use Event Hubs and Blobs like a source for analysis. So, it is able to get and prepare all the needed data from your analysis. After that Stream Analytics provides query language, which helps you to implement your own algorithm in order to prepare data for analysis. Finally, stream analytics can upload all your results to new blobs, Event Hubs, SQL Azure database, which could be used as a source for many analysis tools.

Stream Analytics is still in preview mode but you can try it for free right now using trial accounts or your regular Azure account.

Therefore, as you can see, Azure supports full stack of needed services for IoT world and could be used with any IoT devices.

Written by Sergiy Baydachnyy

01/20/2015 at 11:10 PM

Posted in IoT, Microsoft Azure

Tagged with ,

Internet of Things: My first experience with Galileo 2 (part 6)

leave a comment »

Today it’s my last post about Galileo board for beginners. So I decided to test some features, which I avoided for some time due to soldering requirements. I have never used soldering iron before but I have a weather shield and a LCD panel, which don’t have already prepared pins.

For example, in order to operate, the weather shield requires four different “male to female” pin headers

clip_image001

In case of my LCD 1602 panel, it’s better to use something like this:

clip_image003

So, it’s time to visit a shop in order to buy some stuff for soldering. Finally, I spent around 30 Canadian dollars to buy the following:

clip_image005

There is the cheapest soldering iron, solder and some stuff for clearing iron itself.

Finally, I started to assemble the following device:

clip_image007

This device uses Weather board in order to measure temperature, pressure and humidity. In order to show collected data, I used LCD panel.

Of course, soldering requires some patience and frankly speaking, I didn’t have faith in the result and I was too surprised then it started to work.

So in order to create the device I used Weather shield. As I told before, I don’t like shields very much but in some cases shields help you to create something without special knowledge and very fast. You need just put your shield on your board and you should not think about circuits, voltage and anything else. At the same time, shields contains pins, which extends board’s pins and you may use them in usual way.

In case of LCD panel it’s not so easy. You need to know how to connect the panel to the board. So, you need review a datasheet for your panel. My panel has the following pins:

· VSS – pin that connects to ground

· VDD – pin that connects to 5V power supply

· V0 – pin that allow to change contrast of LCD

· RS – a special pin that controls where in memory you are writing data to;

· R/W – allows to select read/write modes;

· E – an enable pin;

· D0-D7 – pins for reading and writing data

· A and K – control the LED backlight

Review the datasheet more careful I found that I need connect my LCD to the board in the following way:

clip_image009

In order to connect V0 pin you may use potentiometer or resistor to control contrast but I decided to avoid one more component in my schema.

So, once you connected all pins properly you may start work with code. It’s not easy because you should understand right sequence of commands and prepare some functions there. But in many cases you can find already prepared libraries for your sensors and shields. In case of LCD and the weather shield you can find all needed files in Internet. There is a library for LCD and there is a library for humidity sensors and pressure sensor. You need to add all .cpp and .h files in your project and you are ready to create some code.

Thanks to our libraries, we just need to create objects of our sensors and panels and start listening data (begin method). After that we will use loop method in order to get the latest data and show it on LCD. You can use the following code:

#include "stdafx.h"
#include "HTU21D.h"
#include "MPL3115A2.h"
#include "arduino.h"

int _tmain(int argc, _TCHAR* argv[])
{
return RunArduinoSketch();
}

MPL3115A2 myPressure;
HTU21D myHumidity;

LiquidCrystal *lcd;

void setup()
{
//configure LCD to use selected pins
lcd =new LiquidCrystal(4, 5, 6, 7, 8, 9);

//16 symbols and 2 rows
lcd->begin(16, 2);

myHumidity.begin();
myPressure.begin();

// Configure the sensor
myPressure.setModeBarometer();
myPressure.setOversampleRate(7);
myPressure.enableEventFlags();
}

void loop()
{
float pressure = myPressure.readPressure();
Log(L"Pressure(Pa): %lf\n", pressure);

lcd->setCursor(0, 0);
lcd->print("Pressure");

lcd->setCursor(0, 1);
lcd->print(pressure, 4);
delay(1000);

float altitude = myPressure.readAltitudeFt();
Log(L"altitude(Ft): %lf\n", altitude);

lcd->setCursor(0, 0);
lcd->print("Altitude");

lcd->setCursor(0, 1);
lcd->print(altitude, 4);
delay(1000);

float temperature = myPressure.readTemp();
Log(L"Temperature(C): %lf\n", temperature);

lcd->setCursor(0, 0);
lcd->print("Temperature");

lcd->setCursor(0, 1);
lcd->print(temperature, 4);
delay(1000);

float humidity = myHumidity.readHumidity();
Log(L"Humidity(f): %lf\n\n", humidity);

lcd->setCursor(0, 0);
lcd->print("Humidity");

lcd->setCursor(0, 1);
lcd->print(humidity, 4);
delay(1000);
}

That’s all for today. As I told before, it’s my last post for beginners but I am going to continue to write posts about IoT. Next time I will describe how to integrate Galileo and Raspberry Pi boards together.

Written by Sergiy Baydachnyy

01/02/2015 at 9:40 PM

Posted in IoT

Tagged with

Internet of Things: My first experience with Galileo 2 (part 5)

leave a comment »

When you are planning to build your own device you should think about power. In some cases it’s OK to connect your device to the nearest socket but for some projects it will not work. Just imagine a robot, which requires access to socket. So, we need to use independent sources of power like batteries.

In order to understand, which power supply is supported by Galileo, I visited Intel site and found the Galileo 2 datasheet there. According to it, Galileo 2 supports power supplies from 7 V to 15 V. So, in order to be power independent, simple 9V battery should be OK. So, I visited Fry’s Electronics and found the following components there:

clip_image002

Finally, I spent about 2 minutes in order to assemble all components together and check that everything works fine. Right now I have an independent power supply and I may build something like a robot or a flying drone.

In order to build a robot you need to work with motors. There are three general types of motors: DC motors, Stepper-motors and Servos.

DC motors work based on electromagnetism and are used to rotate an axle continuously. You cannot control angle of rotation, so, usually this type of motors is using to turn wheels.

Stepper-motors allow to rotate axle step by step in fixed number of degrees. You should use this type of motors if you need good accuracy there. A simple example of Stepper-motors is second hand in many battery-powered clocks.

Servos are very popular in robotics because they are used in order to create joints. They cannot turn continuously but they can move to fixed number of degrees in both directions with great accuracy. Therefore in order to realize legs, hands, fingers etc. you will use servos.

Today I decided to make some experiments with a DC motor. Usually, DC motors have their own power supply, because they require more voltage than Galileo might give. At the same time we need a way to manage the source of external voltage in order to start and stop our motor. Of course, we may use relay and some components in order to do it or special motor shields but the best way is using a small control chip. This is L293D chip, which allows to control up to two DC motors.

I don’t like special motor shields, because they require a lot of space, they are expensive and limited to 2-4 motors. So, if you need more motors, you need to buy one more shield etc.

In case of L293D, the chip is pretty small, cheap and you can put as many chips as needed on your breadboard.

In order to understand how the chip works, you need to find a datasheet in Internet. In general, the chip looks like this:

clip_image004

There are the following pins:

· EN, A pins – we should use them in order to control our DC motor. We may use them in order to start a motor turning right or left and stop it;

· Y pins – we should use them in order to connect our motor. Thanks to L293D, you may use motors with voltage up to 36V;

· VCC2 pin – it should be used for power supply. This power chip be used in order to start motor turning. So, in general, we will use external power supply there (up to 36V);

· VCC1 pin – the chip requires power as well in order to operate, so we will use it in order to provide power from external supply or from the board (5V is OK);

The chip allows to use up to two motors. Because I have just one motor, I will not use 3A, 3Y, 4A, 4Y, 3,4 EN in my example.

Therefore, in order to use one motor you should implement the following schema:

clip_image006

I decided to use there 5V power from my board in order to set up VCC1 because recommended voltage for VCC1 is between 4.5V and 7V. But you may use external power there as well, using some resistors there. In order to set up VCC2 I decided to use 9V battery, because my DC motor operates find under this condition. Finally, we should understand, how to operate the motor. In order to do it, you can use the following table:

clip_image008

So, if you want to start the motor, you may use the following code:

pinMode(en, OUTPUT);       
pinMode(a1, OUTPUT);
pinMode(a2, OUTPUT);

digitalWrite(en, HIGH);
digitalWrite(a2, HIGH);
digitalWrite(a1, LOW);

There en, a1 and a2 are numbers of digital pins, which you use in your Galileo in order to communicate with chip.

Finally, I got a working solution:

clip_image010

Written by Sergiy Baydachnyy

12/15/2014 at 7:54 PM

Posted in IoT

Tagged with

Internet of Things: My first experience with Galileo 2 (part 4)

leave a comment »

Today I am going to continue my series about Galileo 2 board for beginners and I will discuss analog inputs. But before it, I want to discuss resistors as well.

We already used several resistors in our projects in previous posts but it’s still too hard to understand a value of particular resistor. There are two ways to do it. First of all we may use a multimeter device. You can buy it in any electronics shop. If you want to find a resistor in 330 ohm you need to set the dial of multimeter to 20 KOhm and touch red and black probes of multimeter to different legs of the resistor. You will see something around 0.330 for 330 ohm resistor.

image

At the same time it’s not easy to find a right resistor among many types of them. Here is my box with different types of resistors and there are about 4 resistors in 330 Ohm only. Probably I will spend up to one hour in order to check all of them.

image

So, in order to find a right resistor you need to use the second way – you need to understand color marks there. It’s not too hard. Usually, you will find resistors with 4 or 5 bands there. Based on these bands you can calculate resistance of a particular resistor. Here is a small table, which will help:

Color

1st Band

2nd Band

3rd Band

Multiplier

Tolerance

Black

0

0

0

1 Ohm

 

Brown

1

1

1

10 Ohm

1%

Red

2

2

2

100 Ohm

2%

Orange

3

3

3

1 KOhm

 

Yellow

4

4

4

10 KOhm

 

Green

5

5

5

100 KOhm

0.5%

Blue

6

6

6

1 MOhm

0.25%

Violet

7

7

7

10 MOhm

0.10%

Grey

8

8

8

 

0.05%

White

9

9

9

   

Gold

     

0.1

5%

Silver

     

0.01

10%

So, if you have resistor with 4 bands, you will not use 3rd band column. Just find the right number for the first band and the right number for the second band and combine them to the one number like <first number><second number>. And multiply this number by multiplier in order to get the final resistance. That’s why we need <Orange, Orange, Brown> forth band resistor in order to get 330 Ohm resistor.

Let’s start to create a project based on sensors, which can send inputs to our board. I wanted to use a flame sensor in the first project but today I woke up at 4 A. M. due to fire alarm in my building. Probably somebody forgot to turn off a stove or something like it but buzzer’s sound was terrible and I decided that it was a sign to stop my experiments with flame. So, we will use a photoresistor sensor.

If you have a modern car, you should have something like “Auto” mode for your lights. This mode allows to switch your light based on amount of external light. We will try to emulate the same behavior in our project. In order to do it we will create a circuit like this:

image

Depending on your kit, you will find many types of photoresistors there. In my case I have an analog sensor, which looks like as a separate board:

image

It has three legs, which should connect your sensor to power, ground and analog input pin on the board. You should check the datasheet for your sensor in order to understand how to connect it.

Since we are using an analog sensor, it should be connected to an analog pin. Photoresistor works like a variable resistor, which resists our voltage based on the amount of light. If you have a lot of light, the resistor will put down your voltage. Galileo converts the analog input to digital and it helps to understand the quantity of light. Here is a simple code, which you may use to test the project:

int led = 8;  
int photo = A0;

void setup()
{
pinMode(led, OUTPUT);
pinMode(photo, INPUT);
}

void loop()
{
int res=analogRead(photo);
if (res <= 700)
{
digitalWrite(led, LOW);
}
else
{
digitalWrite(led, HIGH);
}
delay(1000);
}

Galileo convertor will convert the analog input to a number between 0 and 1023. In this code I decided that if our number is smaller than 700 (resistor resists enough voltage), we will switch off our led because we have enough amount of light. If our resistor doesn’t resist enough voltage (it’s dark) we will switch on out led. Based on this example you are able to make many experiments with light and analog input.

Since we are using Visual Studio, it’s easy to launch our projects in a debug mode. When you will stop debugging, Visual Studio kills your process automatically. Visual Studio allows us to set breakpoints and review variables values etc. You may also use the Log method in order to print something to the output screen in the Debug mode. If you are launching your application without Debug mode, you need to kill your process using the Telnet as I mentioned in previous articles.

So, Visual Studio makes our life better but there still is a question: how to launch our projects just after startup of our operation system. It’s very important if you already created the final version of your project. Because we are using Windows, it’s easy to do in two steps. First of all you need to navigate to the following folder: \\mygalileo\c$\Windows\System32\Boot. You will need to enter your credentials there. On the next step, change autorun.cmd file and put one more command there, like start YourFolder\YourApp.exe. That’s all and your application will launch on the system startup.

Today I will finish my post. Next time I am planning to show more advanced projects.

Written by Sergiy Baydachnyy

12/01/2014 at 7:42 PM

Posted in IoT

Tagged with