Sergiy Baydachnyy

Blog about technologies

Archive for the ‘IoT’ Category

Windows 10: How to use IoT extension for Raspberry Pi 2 (part 1)

leave a comment »

If you have already installed Windows 10 on Raspberry it’s time to discuss how to use pins and I2C there. Of course, if you are going to deploy an application which doesn’t work with GPIO, you don’t have to do anything special – you need to create the same Universal application like for desktop or phone using C# or other languages and deploy it using ARM platform selection directly from Visual Studio. But GPIO is device-specific feature for which it makes no sense to include it to the common library. So, if you are going to use some IoT specific features you need to add IoT Extension to you project.

clip_image002

This extension declares just two contracts: Windows.Devices.DevicesLowLevelContract and Windows.System.SystemManagementContract. It’s easy to find this declarations if you go to the following folder C:\Program Files (x86)\Windows Kits\10\Extension SDKs\WindowsIoT\10.0.10069.0 and check SDKManifest.xaml. SystemManagement doesn’t contain anything special – just classes which help shutdown the device and change time zone. But DevicesLowLevelContract contains many important classes. Let’s looks at the Raspberry and see that we can achieve thanks to these classes.

clip_image004

In case of GPIO you can use the yellow pins to send signals to sensors or receive data from them. On Raspberry, all pins generate 3.3 volts of voltage. Pink pins supports SPI protocol and you can connect up to two devices/sensors there (probably three but I never made this experiment). Finally, blue pins allow to use I2C hub which supports more than hundred devices/sensors. Of course, GND pins are for ground and there is for power pins (two 5V pins and two 3.3V pins).

Let’s start with GPIO. You can find necessary classes (and enumeration types) in Windows.Devices.Gpio namespace and they allow developers to control GPIO pins on the board. The first class there is GpioController which allows to get access to controller and get reference to needed pins. If you are going to use GPIO you need to start with calling of GetDefault method which return reference to current GPIO controller (if exist):

var controller=GpioController.GetDefault();

If you are going to write really universal code you need to check if controller is null. If it is, your device doesn’t have GPIO (desktop, phone etc.) It’s very useful because starting with Windows 10 we have Universal platform and you can run the same binary anywhere.

Once you have access to controller you can try to get reference to pins. OpenPin method allows to get reference to pin lock it exclusively or leave it in shared mode. Of course, this method doesn’t help you to setup the pin and just return reference to GpioPin object. There is the same thing like for GpioController – you need to check if returned reference is not null, because other processes could lock the pin for own purposes.

var pin = controller.OpenPin(0); if (pin == null) { return; }

OpenPin method should get number of the pin and you should use the same numbers like on the image above. Finally, if you got access to the pin you can try to work with it. There are three important methods like SetDriveMode, Read and Write. With the first one you can setup the pin like input or output pin. Read and Write methods allow to send or receive signal there.

So, if you already worked with some micro boards, you will not find anything special but if you are new in IoT you can start with creation of a simple Blinky project, which Microsoft published here.

Of course, more interesting classes are located in Windows.Devices.I2C and Windows.Devices.SPI namespaces. Finally I got my MPU6050 sensor, so next time we will get data from there.

Written by Sergiy Baydachnyy

05/08/2015 at 6:59 AM

Posted in IoT

Tagged with ,

Raspberry Pi 2 and Windows 10: My first experience

leave a comment »

Finally, Microsoft published Windows 10 preview build for Raspberry Pi 2 (and not just for Raspberry). So, if you have Raspberry, you can visit https://dev.windows.com/en-US/iot and download the build and setup instructions.

Of course, it’s easy to prepare an SD card and put it to Raspberry but pay special attention that:

· You need to use microSD card class 10. I missed this requirement and was very upset when found that my Raspberry is not even trying to start. When I checked manual once again I checked my SD and found that it has class 4! So, I changed it and everything started working fine;

· First start requires much time to finish all things. So, you need to be patient;

· You need to connect your board to network using network cable. It’s a preview and many famous WiFi adapters don’t work on Raspberry right now. So, if your application connects to Internet you will need to use network cable all the time but if you want to create a simple LED project you need access to network at least for deploying your project;

If everything is ok you will see Raspberry image and important information like device name and IP address on the screen. So, your device is ready and it’s time to establish connection between your PC and Raspberry. In order to do it you can visit the following page to setup connection using PowerShell. I tried to make it several times and discovered some issues on my PC. Because I am not admin it was very hard to understand what happened there, so I want to share all stoppers I had:

· Set-Item issue – when I ran this command I got an exception with complicated message about private and public networks and some advice to change network from Public to Private. When I checked my network settings (Network and Sharing Center) I found that my network is Private but I have Virtual Ethernet Adapter which was created by Visual Studio installation. I simply disabled it and the exception was gone;

· Enter-PsSession – when I ran this command I got one more exception “The WinRM client cannot process the request. If the authentication scheme is different from Kerberos…” Once I got it I spent much time to understand how to setup WinRM but my knowledge in this area is not enough, so I selected the simplest way: I ran Gpedit.msc and navigated to Local Computer Policy->Computer Configuration->Administrative Templates->Windows Components->Windows Remote Management->WinRM Client. There I enabled Allow unencrypted traffic and Trusted Hosts and, additionally, I enabled all hosts there. And the problem was gone. I hope that you can find a way to configure it in a better way but I simply didn’t have much time to check all combinations because I wanted to start development!;

clip_image002

Once you connect to your Raspberry you can change password, device name, run some configuration cmdlets etc. Pay special attention that Raspberry supports two modes: headed and headless (with GUI and without GUI). You can read more about the modes here.

Right after you establish connection between your PC and Raspberry you can try to develop something. Thanks to Visual Studio it’s very easy to develop, deploy and debug solutions on Raspberry. Raspberry runs Remote Debuger by default so you should not make any additional configuration.

In order to start you need to select the language. You can select between Node.js, Python and standard languages for Universal applications like C#. Of course, I decided to use C# but you can easily install Python or Node.js tools from Connect site. So, in order to start you need to create a simple Universal application, change platform to ARM and select Remote Machine for deploying and debugging.

clip_image004

Finally I develop and deploy my first application for Raspberry:

clip_image006

Written by Sergiy Baydachnyy

05/04/2015 at 8:38 AM

IoT: I2C and Galileo board

leave a comment »

I spent last weekend finishing my first drone. It’s nothing special, I bought some standard components like brushless motors with ESCs, a radio receiver and transmitter and flight control board. The last one is compatible with Arduino and supports MultiWii open source project which helps manage drones based on gyroscope and accelerometer sensors. But it didn’t satisfy me because the drone in the existing configuration is just a toy and it doesn’t contain any brain. And, frankly speaking, Arduino board is not a good choice to make some sort of brain due to performance and memory limitations. So, if you want to develop a drone which will be able to fly “without you”, analyze existing environment and execute tasks like intercepting other drones, you need something more powerful. I believe that Raspberry Pi 2 is the best choice but I still don’t have Window 10 image there but I have wrote it before Build, so I decided to use Galileo 2. It’s very powerful and should satisfy my requirements except of tasks related to video (due to lack of GPU).

If you are going to add some brain to your drone you can follow one of the two ways. In the first one you will keep the existing flight control board and will place “your brain” like proxy between radio receiver and flight control board. In this case, the flight control board will continue to stabilize your drone but will get commands from Galileo and not from receiver, and Galileo can support several modes like autopilot and manual modes. The second way requires to remove your flight control board and implement the same logic in “the brain”. Of course, in this case you need to add some sensors like accelerometer and gyroscope to Galileo and analyze all incoming data from them. Obviously, the second way is more complex and you should not follow it in the most cases. But if you really want to develop a drone which will intercept enemy drones and use different flying techniques you need to implement your own code there. Because I want to have maximum fun I decided to follow the second way.

Of course, before implementing some algorithms I should think if it’s possible to connect all needed things to my Galileo. Since Galileo is Arduino compatible, there are 6 PWM pins which I can use to operate 6 brushless motors that are enough for my hexacopter. Additionally, I need 4 input pins in order to get data. Everything might be good but I need to connect some sensors as well. Frankly speaking, I need to connect many sensors like accelerometer and gyroscope to stabilize my drone, magnetometer, and GPS to navigate the drone to a goal, airspeed sensor for better navigation, distance sensor for better landing, GPRS to get some command and send logs when the drone is out of range etc. Looks like that standard IO pins will not satisfy all my requirements. So, it’s time to look at the board and find two more pins which are marked like SCL and SDA.

SCL (clock) and SDA (data) are implementation of I2C bus (Inter-Integrated Circuit) which allows to make communications between various integrated circuits using just two wires (SCL and SDA). And what is more important you can use the I2C to connect lots of different circuits in any order because each device has its own address and if you want to send or receive data from particular device you need to use this address, so other devices will ignore your message. That’s why you can find thousands of sensors in the market which support I2C because in Arduino world it’s the best way to manage hundred sensors using one board only.

So, if you are going to build something complex you need to check if selected sensor supports I2C before buying it. I checked all my sensors and found that I have SparkFun weather shield only which supports I2C. So, right now I am going to work with the shield.

The weather shield might contains several sensors like GPS and wind but all editions contain humidity and pressure sensors and you can work with any of them directly. In this case, the shield is just a board which combines all sensors together and allows to use I2C. So, the best way to start working there is to check datasheet for particular sensor there. Because temperature is something clear for me, I decided to use humidity sensor there for my experiments. You can find the datasheet for this sensor using the following link.

There are the following things in the datasheet which we are going to use in our application:

· The humidity sensor requires up to 50 ms to make measurement of temperature (page 4). It’s maximum value for 14 bits resolution and we definitely can count on it;

· The device address is 0x80 including data bit (page 9). I2C devices has 7 bits addresses but eight (zero bit) bit shows direction of command (read or write). It’s not so important for us because Arduino library uses different approach;

· 0xE3 and 0xF3 are codes for commands to the sensor which will request to measure temperature (page 10). The first one is hold I2C channel while measurement in progress but the second one allows to make other operations at the same time. We are going to use the second one;

· Request to the humidity sensor returns 3 bytes (page 10): 14 bits of data, 2 bits for status and 8 bits for checksum. The status allows to see if you get temperature or humidity and checksum allows to check the data;

· You can measure temperature like -46.85 + 175.72*data/65536 (page 14);

So, right now we are ready to write some code. I am not going to check errors from sensors or something like it in order to make the code as simple as possible. The good news there that you should not work with SDA, SCL pins directly. Arduino supports Wire library and it was successfully to Galileo platform as well. Using the library I developed the following code:

#include "stdafx.h" #include "arduino.h" #include "Wire.h" int _tmain(int argc, _TCHAR* argv[]) { return RunArduinoSketch(); } void setup() { Wire.begin(); } const byte humAddress = 0x40; const uint8_t measureTemp = 0xF3; void loop() { Wire.beginTransmission(humAddress); Wire.write(measureTemp); Wire.endTransmission(); delay(50); Wire.requestFrom(humAddress, 3); byte msb, lsb, checksum; msb = Wire.read(); lsb = Wire.read(); checksum = Wire.read(); unsigned int raw = ((unsigned int)msb << 8) | (unsigned int)lsb; raw = raw&0xFFFC; float rh = -46.85 + 175.72 * raw / (float)65536; Log("%f\n", rh); delay(1000); }

 

In order to start working with Wire library you need to include Wire.h and prepare I2C using Wire.begin. Of course, setup function is the best place to do it. Right after you are ready to talk to I2C device you need to call Wire.beginTransmission. And there is a trick because this function requires an address. You should not use 0 bit for direction instead of it you need to fill first 7 bits with the address. So, if we have 0x80 address including direction bit we need to shift 7 last bits right and get 0x40 – this address we should use in all commands. In order to write something to I2C we can use Wire.write and I am sending 0xF3 command in order to ask the sensor to measure temperature. Finally I need to call endTransmittion in order to stop communication and wait for 50 ms to give the sensor some time to make measurement.

In 50 ms we can send the second command and ask data from sensor. Thanks to requestFrom we should not think about begin, end and direction bits – we need to pass the address and number of bytes only. If data is available we can use read to get it byte by byte.

Of course, it’s better to check if data is available and correct but in general this code will work as well and it’s not so bad. The hardest part here is to understand the datasheet. It’s not easy sometimes and you need to read many pages.

I hope that next week I will get my MPU6050 and will show how to use it and combine accelerometer and gyros data using I2C bus.

Written by Sergiy Baydachnyy

04/30/2015 at 7:47 PM

Posted in IoT

Tagged with

IoT: Raspberry Pi 2, C# and blinking LED

leave a comment »

This week I decided to visit Lee’s Electronic in order to buy some sensors and capacitors for my future posts and, just in case, I asked if they have Raspberry PI 2 boards. The answer was: “Yes, we just received the package with plenty of them. Do you need just one?”

Of course, I was happy to get Raspberry Pi 2 because I still didn’t make any experiments with this board. I have a Raspberry Pi B+ but it’s “too lazy” for IoT projects. Of course, it has better CPU than Arduino and Netduino but developer experience is crazy there. So, I decided to avoid Raspberry up to more complex projects, which require cameras, GPU etc. But Raspberry Pi 2 should have better performance. I even heard that it should be in 6 times fasterJ So, I decided to buy a board.

So, Raspberry Pi 2 has the same form factor like B+ model.

clip_image002

And you can use the same operation system like before (several versions of Linux and RISK OS) but if you have a B+ board and you are going to use the same microSD, you need to rewrite operation system there. I have checked several articles and looks like that everybody recommends to use Debian/Raspbian, so I decided to use Raspbian as well.

Additionally I am using Edimax WiFi adapter to connect my Raspberry to WiFi. It’s a very common adapter and you should not make any additional actions in order to configure it. Just open Wi-Fi configuration window to select the right WiFi network and once your board is connected, you need to note assigned IP address. Finally, before disconnecting your board from the keyboard and the monitor, you need to activate xrdp:

sudo apt-get install xrdp

I discovered that many people use Putty and Xming in order to connect Raspberry in desktop mode. I installed these tools and I was playing with them some time but, finally, I decided to use Remote Desktop Connection, which is part of Windows 8, doesn’t require any actions to install it and allows to make any configuration changes very quickly.

Of course, I am a C# guy, so in the next step I installed mono-runtime and Mono Develop there.

$ sudo apt-get update

$ sudo apt-get install mono-runtime

$ sudo apt-get install monodevelop

Once Mono develop is installed I was ready to start my experiments. First of all, the latest board is really faster. I didn’t feel “6 times performance” but it requires no more than 10 seconds to launch Mono develop and 3-5 seconds to create a new project. At the same time Intellisense system works pretty good, compiler and debugger are fast as well. It still is no as fast as my Lenovo W530J but it’s possible to develop and debug IoT projects directly on board.

Additionally I think that there are some opportunities to increase speed of development once Windows 10 is available there. Probably it’s just my feeling but I think that Raspbian has the same problem as some versions of Android and simply doesn’t use all CPU cores in effective manner. So, you cannot see real performance improvement, which is guaranteed by additional cores.

The first problem, which I got during my experiments, was unusual behavior of Mono Develop. Once I created a new Console application and wrote my first “Hello World” there I got several compilation errors. I believe that it’s related to configuration of the template. I spent about 10 minutes to understand what has happened there but, finally, I decided to use a trick: I just created an Empty Project and added a class there. Inside the class I added Main method and launched my first “Hello World” without any problems.

The second problem is the right library to use GPIO from C#. It required much more time (I even wanted to start a new open source project) but finally I found a good library. Compared to other libraries this one doesn’t have problems with resources and pin locks, doesn’t require any additional actions to start using it, has good architecture and provides many examples.

In order to start using the library you need to download and recompile it. I made it in Mono develop and didn’t have any problems there. After that you need to add the assembly to your project. It’s easy to do using Edit references… dialog from the context menu there. Once you add the reference to the assembly you are ready to start development. Pay special attention that the library contains two similar sets of classes: GPIOMem and GPIOFile. The first one requires an additional library and because already precompiled version doesn’t work on my board I decided to use GPIOFile.

clip_image004

In order to initialize a pin you need to use the following code:

GPIOFile l=new GPIOFile(GPIOPins.V2_Pin_P1_07, GPIODirection.Out);

In order to understand, which pin you need to initialize, you can check the specification on raspberrypi.org. You can see that pin 7 is GPIO 4 and you can use it to output. You can use pins 2 or 4 in order to get 5V voltage.

clip_image005

Once you pin is ready you can use it to send signals there:

l.Write(true);

So, finally I made my blinking LED on Raspberry.

clip_image007

Written by Sergiy Baydachnyy

04/22/2015 at 8:57 PM

Posted in IoT

Tagged with

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.

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