Sergii Baidachnyi

Blog about technologies

Archive for January 2015

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 ,

Azure Mobile Services: Did we forget something?

leave a comment »

This is my last post about Azure Mobile Services. Last time we finished implementation of Windows client and I used all needed features for my application. You can read all posts about the topic at the following links:

Azure Mobile Services: Notification Hub vs “native development”

Azure Mobile Services: Creating a simple Notification Hub

Azure Mobile Services: Sending notification from server-side

Azure Mobile Services: Creating a Universal Application

Azure Mobile Services: Creating of Universal Application (part 2)

Azure Mobile Services: Visual Studio

I described a very simple application but what about other features of Azure Mobile Services. Frankly speaking, I used just half of all features there. Therefore, I decided to describe all other features in order to have a completed view of the topic.

Tags

This feature is related to Push Notification Hub but Azure Mobile Services encapsulate it as well. The idea is very simple – use a special tags in order to target right groups of users. For example, if you create a news site you can create a tag for each group of news and user might select just the groups that are interesting to him. I don’t like politics so much but somebody else might not like sports news etc.

Of course in order to implement this approach you need have a way to select tags during user registration process and you should have a method to broadcast messages only for selected tags. There is a good news – Mobile Service API supports tags. For example, in order to make registration using some tags you can use the following code:

await mobileService.GetPush().RegisterNativeAsync(channel.Uri,

new List<string>() {"sport", "movies", "Canada" });

In this example, three tags will be associated with user registration.

In order to send message to all users with tags movies, you can use the following code (C#):

await Services.Push.SendAsync(message, "movies");

Pay special attention that methods, which we use to send messages to users, usually allow to pass tag expression. Tag expression could be used for passing expressions based on tags, using logical operators like &&, || and !: "(tagA && !tagB)"

Templates

Templates are one more way to create personalized messages for users. For example, in order to send message from C# to Windows users, you may use the following code:

WindowsPushMessage message = new WindowsPushMessage();

message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +

@"<toast><visual><binding template=""ToastText02"">" +

@"<text id=""1"">football.ua</text>" +

@"<text id=""2"">" + item.Text + @"</text>" +

@"</binding></visual></toast>";

And if you form a message in this way, all your users will see the same message. However, in some cases you might want to pass parameters to your message based on user preferences. For example, if your application supports several languages you might want to send localized messages; if your application provides some data like mileage or temperature, your might want to use measurement system, which is understandable for users, etc.

Templates allow us to use parameters in XML or JSon messages (based on platform), which we usually form on server side. In case of templates, your server side should not form message from scratch. Instead, client application should register a message template including parameters and the name of the template. Server side will send just parameter to selected templates.

For example, if you create Windows application, your client can use the following code in order to register a template:

string xmlTemplate = @"<?xml version=""1.0"" encoding=""utf-8""?>" +

@"<toast><visual><binding template=""ToastText02"">" +

@"<text id=""1"">football.ua</text>" +

@"<text id=""2"">$(ru_message)</text>" +

@"</binding></visual></toast>";

await mobileService.GetPush().RegisterTemplateAsync(

channel.Uri, xmlTemplate, "langTemplate");

In this case, client application is registering a template with langTemplate name and with parameter ru_message. The second device might use en_message parameter instead of ru_message etc. It’s needed in order to get message in native language for device’s user. So, all devices will have the same template but with different parameters there.

In the next step, server side should form a message, which will contain the template name and all parameters. It allows Notification Hub to create unique messages for all devices based on registered templates and parameters. In order to prepare server side message you can use already prepared classes. For example, if you use C#, you can use the following code:

TemplatePushMessage mess = new TemplatePushMessage();

mess.Add("ru_message", "Сообщение");

mess.Add("en_message", "Message");

await Services.Push.SendAsync(mess);

Notification Hub will look at every registered template and send a message if template contains one of these parameters.

Jobs

Some applications, like Facebook for Windows Phone, send many notifications during predefined time period. For example, usually at 11 pm. I get messages about upcoming birthdays of my friends. Of course, it’s a good idea to have something on Azure side, which might send notifications on schedule basis and Azure Mobile Services support this feature.

Using Azure Mobile Services, you can schedule any code there. You may set up a single timeframe or create a complex schedule there and you can use Azure Management panel, if you are going to create JavaScript code or Visual Studio – if you are going to create C# code.

In case of JavaScript it’s easy to create something using Sheduler tab. Pay attention that there is a way to create a job, which will run on demand:

JavaScript code may have access to all objects, which we used before, including push object.

In case of C# you need to work with Visual Studio like we did at the previous post and you should create a class, which derives from SheduledJob class. ExecuteAsync method there will allow you to create any code inside.

Custom API

One more interesting thing in Azure Mobile Services is the ability to create a custom API. You can create a set of JavaScript server-side functions using Management panel:

In case of Visual Studio, you need to create a class, which derives from ApiController.

Because you code will be called using standard HTTP protocol, you may use one of the following methods there like GET, POST, PUT, PATCH, DELETE.

Rest API

In the first article about Azure Mobile Services I told that the service will work for any type of platforms and languages because there is REST API support. Of course, I like Windows 8 and Windows Phone applications, so I used ready to use libraries, which encapsulate all work with REST and JSON but you still able to use REST API. Frankly speaking, Microsoft provides libraries for many platforms and languages (like Java, JavaScript, Objective C etc.) but in some cases it’s better to use REST directly. You can find REST API documentation here.

Written by Sergiy Baydachnyy

01/08/2015 at 9:20 PM

Posted in Microsoft Azure

Tagged with

Azure Mobile Services: Visual Studio

with one comment

In my series I used JavaScript backend in order to handle insert operation. Thanks to that I was able to send broadcast notifications to all subscribers. In this example we had small amount of code and using of JavaScript looks reasonable despite of my love in .NET. But in many projects your code might be more complex and you might want to use Visual Studio and C# in order to develop it. Therefore in this post I want to show how to use Visual Studio in order to build our backend.

First of all in order to use C# on the backend, you must select .NET as a backend technology in new Mobile Service dialog.

image

You may use Visual Studio as well to create Mobile Service but I like management panel. I simply got used to use management panel for several years:)

Right now we are ready to use Visual Studio. In the first step we will create project based on Azure Mobile Service template. You need to provide name of your project/solution there.

image

In the second step you need to select some options. You should switch off Host in the cloud checkbox. If you forget to do it, Visual Studio will propose to create a new Mobile Service.

image

Once you click OK, Visual Studio will create a project for you, which contains several ready to use classes like TodoItem, TodoItemController etc. You can use this code in order to deploy TodoItem table to Azure Mobile Service.

I am not going to remove auto-created code but I would prefer my own names for table and columns. So, I will change TodoItem to NotificationData. You can use refactoring tools to change class name. Additionally, I will remove Complete property and change Text to text property. Last changes you may make using JsonProperty attribute as well.

public class NotificationData : EntityData
{
[JsonProperty("text")]
public string Text { get; set; }
}

Because EntityFramework and Web API already have all needed infrastructure for our service, we will concentrate our attention around the following questions:

· How to send broadcast notifications from our code;

· How to set permissions for operations with tables;

· How to create own code, which will handle registrations of new devices;

The simplest question there is sending notifications. You need to open TodoItemController.cs file and modify PostTodoItem method in the following way:

public async Task<IHttpActionResult> PostTodoItem(NotificationData item)
{
NotificationData current = await InsertAsync(item);

WindowsPushMessage message = new WindowsPushMessage();

message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
@"<toast><visual><binding template=""ToastText02"">" +
@"<text id=""1"">football.ua</text>" +
@"<text id=""2"">" + item.Text + @"</text>" +
@"</binding></visual></toast>";
try
{
var result = await Services.Push.SendAsync(message);
Services.Log.Info(result.State.ToString());
}
catch (System.Exception ex)
{
Services.Log.Error(ex.Message, null, "Push.SendAsync Error");
}

return CreatedAtRoute("Tables", new { id = current.Id }, current);
}

You can see that there we used two classes there. WindowsPushMessages allows to create a toast message and ApiServices (Service instance) allows to send the message and put information to the log. Like in case of JavaScript we used ToastText02 template, which contains title and message there. So, we have the same code but in C#.

Let’s talk about permissions. In case of JavaScript we used Azure Management panel to set permissions but in case of C# we need to use attributes there. You need to use AutorizeLevel attribute in order to set the right permissions to methods on Controller class.

[AuthorizeLevel(AuthorizationLevel.Application)]
public async Task<IHttpActionResult> PostTodoItem(NotificationData item)
[AuthorizeLevel(AuthorizationLevel.Anonymous)]
public IQueryable<NotificationData> GetAllTodoItems()

Of course, this approach will work just for table operations but in case of JavaScript you had a chance to set authorization level using Azure Management panel. In case of C# you may set it in WebApiConfig.cs file. Just put the following line of code to Register method:

options.PushAuthorization = AuthorizationLevel.Anonymous;

In our example we didn’t change Registration pipeline but if you want to do it, you can implement INotificationHandler interface.

public class PushRegistrationHandler : INotificationHandler
{
public System.Threading.Tasks.Task Register(
ApiServices services, HttpRequestContext context, NotificationRegistration registration)
{
throw new NotImplementedException();
}

public System.Threading.Tasks.Task Unregister(
ApiServices services, HttpRequestContext context, string deviceId)
{
throw new NotImplementedException();
}
}

Implementation of the interface will be picked up automatically and you may run your own code there.

Finally, in order to test our solution, we need to deploy it. In order to do it just select Publish menu item from context menu and set up all needed parameters:

image

In order to simplify this process you can download Publishing profile from the dashboard already created service

image

Written by Sergiy Baydachnyy

01/06/2015 at 10:44 PM

Posted in Microsoft Azure

Tagged with

Azure Mobile Services: Creating of Universal Application (part 2)

with 2 comments

Interface of our application (continued)

It’s time to implement business logic of our application. Since data classes are not related to specific interface, I am going to use the shared project to create all needed classes. Let’s create Code folder there and DataClasses.cs code file inside. We will create two classes there.

One of these classes should describe our data table in Azure Mobile Service. We need to use table and column names there in order to avoid using attributes or any other mapping approaches. So, our class may look like this:

public class NotificationData
{
public string id { get; set; }
public string text { get; set; }
public DateTime __createdAt { get; set; }
}

The second class is a utility class. I am going to use it as a class for loading out data from Azure Mobile. So, we can use the following code there:

public class DataClass
{
public static async Task<ICollection<NotificationData>> LoadData()
{
MobileServiceClient client =
           new MobileServiceClient("https://test-ms-sbaidachni.azure-mobile.net/");
var table=client.GetTable<NotificationData>();
var query = (from item in table
orderby item.__createdAt descending
select item).Take(100);
var items = await query.ToCollectionAsync();

return items;
}
}

Because we allowed to get data from Azure Mobile for Everyone, we don’t use any keys there. But I am downloading just 100 records from our database. Later you may add one more method which will implement incremental downloading. You can use Skip(n) method there in order to skip already downloaded records: .Skip(n).Take(100).

In order to finish our work with the Shared project, I will create Assets folder there and put logo for my applications there.

Since we already implemented all business logic and our applications allow us to receive notifications, we may finish work with interface of our applications.

In case of Windows 8 application I decided to use GridView control. We need to disable all “selection” and “click” functionality and show messages and dates there. Let’s review my code:

<Page.BottomAppBar>
<CommandBar>
<AppBarButton Label="Обновить" Icon="Refresh" Click="AppBarButton_Click"></AppBarButton>
</CommandBar>
</Page.BottomAppBar>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Image Source="Assets/football.png" Height="36" HorizontalAlignment="Left" Margin="120,30,0,10"></Image>
<GridView Name="myGrid" Grid.Row="1" Padding="120,40,100,80" SelectionMode="None" Visibility="Collapsed">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Width="450" HorizontalAlignment="Left" Height="100" Background="Gray" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="{Binding __createdAt}" Style="{StaticResource CaptionTextBlockStyle}" Foreground="Green" Margin="5"></TextBlock>
<TextBlock Text="{Binding text}" Grid.Row="1" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="Wrap" Margin="5"></TextBlock>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<ProgressRing Name="progressBox" IsActive="True" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100" Grid.Row="1" Visibility="Visible"></ProgressRing>
<TextBlock Name="errorBox" TextWrapping="Wrap" Text="Что-то случилось с сетью. Попробуйте загрузить данные снова." Visibility="Collapsed"
HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center"
Grid.Row="1" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>

<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="Common">
<VisualState x:Name="Loading">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="errorBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="progressBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Visible" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="myGrid" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Loaded">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="errorBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="progressBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="myGrid" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Visible" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Error">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="errorBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Visible" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="progressBox" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="myGrid" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame Value="Collapsed" KeyTime="0"></DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>

</VisualStateManager.VisualStateGroups>
</Grid>

I know that it’s bigger than you imagined but it allows to show different parts of our interface based on different events in our application. We can divide this code in three parts.

In the first part we declared application bar control with refresh button there. I am going to use this button to allow user update interface in case user had opened application some time ago and it is still in the memory.

In the second part I declared Grid layout and some controls inside like GridView, Image and several textboxes with different messages. We are going to show GridView or massages based on situation.

In the last part I declared VisualStateManager control which allows to declare several custom states there. We will have three states:

· Loading – data is loading from Azure Mobile services;

· Loaded – data is loaded and ready to show;

· Error – we have problem with internet connection;

Depending on state, we are going to hide and show some parts of our interface.

Finally we need to implement some code, which will set state of our interface and this code will use our utility class in order to download data. I propose to use the following code inside MainPage.xaml.cs:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
LoadData();
}


private void AppBarButton_Click(object sender, RoutedEventArgs e)
{
LoadData();
}


private async void LoadData()
{
try
{
VisualStateManager.GoToState(this, "Loading", false);
var items = await DataClass.LoadData();
myGrid.ItemsSource = items;
VisualStateManager.GoToState(this, "Loaded", false);
}
catch(Exception ex)
{
VisualStateManager.GoToState(this, "Error", false);
}
}

The most important method there is LoadData. We are using of this method in order to move interface to the right state and it allows us to download and bind data as well.

In case of Windows Phone we will have the same code and XAML but I will change GridView control to ListView and I need to change some margins there. So, I will show just a piece of code with some differences there:

<ListView Name="myGrid"  Grid.Row="1" Padding="10" SelectionMode="None" >
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,10">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="{Binding __createdAt}" Style="{StaticResource ListViewItemContentTextBlockStyle }" Foreground="Green"></TextBlock>
<TextBlock Text="{Binding text}" Grid.Row="1" Style="{StaticResource ListViewItemTextBlockStyle}" TextWrapping="Wrap" Margin="0,5,0,0"></TextBlock>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Therefore, we developed applications for Windows Phone and Windows 8, which allow us to get notifications about football games using Windows Notification Service and these applications can show the latest messages as well.

image

Publishing the applications

In order to publish your applications, you need to change the icons there. It’s the hardest part for developers, so, if you are going to publish the real application, you need ask designers about icons. Right after you changed all default icons, you may create Store packages for Windows Phone and Windows 8 separately. You can make it using context menu by calling Store->Create App Package item. Of course, you need to have access to your Store account and you need to reserve applications names there but we made it in the previous post.

Some time ago, Microsoft required Privacy policy for all Windows 8 applications, which used Internet connection. In case of Windows Phone you needed to create a settings page, which allows user to switch off notifications in your application. Today, you don’t have to do it. Privacy policy is still required but just for applications, which collect and store personal data (we don’t collect anything about users). Notification settings for Windows Phone 8.1 applications will be generated automatically and user can change it in any time using Settings->notifications+actions menu item (it’s strange but your application will appear there just after the first notification only).

Therefore, you may upload your packages, fill description and other fields and submit your applications for review. Usually review takes about 2-3 days but in my case it took about 2 hours.

My applications are available here:

http://www.windowsphone.com/s?appid=ff9b0b08-0a11-4eba-9362-9a023650dcfd

http://apps.microsoft.com/windows/app/fooball-ua-messages/870b8ea4-1385-4193-ab27-9836dd216711

Written by Sergiy Baydachnyy

01/05/2015 at 7:58 PM

Posted in Microsoft Azure, Windows 8, Windows Phone

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