lundi 14 septembre 2015

XY Plotter with LabVIEW and STM32F4



Abstract -- the aim of this project is to design and build a XY-Plotter capable of drawing computer processed images or graphs. It details design choices, high-level control processing, and the low-level control algorithms that were used with graphical interfaces programmed in LabVIEW. The control is implemented using the Stm32F4 board 

I. Project Description :
A XY-Plotter is a robot that operates in two axes of motions ("X" and "Y") in order to draw different shapes or write a text. It is composed of two special mechanisms for raising and lowering a pen. The plotter has a hole in its base where the pen goes through. It is designed to print on either paper or any surface such as a wall. The plotter should simply be placed against the surface and the pen will draw away through the hole. Each axis is powered using a single stepper motor and belt. But, is that all what a XY-Plotter can do? Definitely not! It may be useful for young children or persons suffering from writing disabilities, such as having a broken hand; they can write using their smartphones by simply dictating texts. Modulo small changes, it can be used to place electronic components on a Printed Circuit Board (PCB).

a.High-level architecture
The figure below summarized the overall architecture of the XY-Plotter . Indeed, the user can select ether he needs to draw a mathematical curve or extract the shapes from a given picture. An additional interface simulates the robot movement (with adjustable speed) and visualizes the real-time behavior of the robot

b.XY-Plotter Mechanics
To minimize the costs, we decided to realize the XY-Plotter using two old printers. It was very difficult to adapt all the parts and have a good precision. these figures shows some different steps to build and assemble the different parts of the robot.

c. Canny Edge interface
To simplify the use of our plotter, the software application was divided into three interfaces that will be detailed in this section. This interface allows the upload of an image file, extract the shapes of the features it contains and returns the set of their coordinates as text file. This requires of course to go through several steps:
In the first step (reading the image file), the image file is opened using IMAQ ReadFile . The file format can be a standard format (BMP, TIFF, JPEG, JPEG2000, PNG, and AIPD) or a nonstandard format already defined by the user. In all cases, the read pixels are converted automatically into the image type passed by.
The second step is the shape detection. After getting the picture, we invoke the IMAQ CannyEdgeDetection, which uses a specialized edge detection method to accurately estimate the location of edges even under conditions of poor signal-to-noise ratios.
The result is a binary image. It represents a black & white converted image that can be reproduced by the robot using black ink on white paper. It is worth mentioning here that the details level of detected edges is tuneable through the use of a user fixed threshold value.
The final step is the generation of the edge points coordinates. To find the number of edge segments in an image and get the coordinates of the pixels in each segment, we used the IMAQ GetPointsOnContour function. It joins adjoining edge pixels into edge segments.
The image bellow  shows an example of segment information after detecting the Edge and generating coordinate of contour points

As aforementioned, the final job for this interface is to return a text file containing all the coordinates of the detected contour points. 




d. Curve drawer interface
As defined in the NI-LabVIEW documentation, the XY-graph is a general-purpose, Cartesian graphing object that plots multivalued functions, such as circular shapes or waveforms with a varying time base. The XY-graph displays any set of points, evenly sampled or not.
This graphing object will be used along with the LabVIEW formula interpreter supporting the standard mathematical operators (" + ", " - " , " * ", "/ ") and a very large number of mathematical functions (trigonometry functions, logarithm and exponential functions and random numbers generators).
These two LabVIEW objects are two key components for our XY-Plotter. In fact they allow us draw and visualise several plots right before printing them. They both form our so called “Curve drawer interface”


E. Printer interface and 3D-model
The XY plotter GUI shown in figure below allows the user to see a preview and reel time impression with 3d model.
After confirming , the command are send via serial connection.
the serial port would have to be selected properly for appropriate communication between computer and microcontroller. Once the communication was established, the computer was ready to send information to the microcontroller.
The idea is to send a command and wait until the device respond with ‘ok’

II.EXAMPLE OF USES :
A.drawing on paper :
We present here a simple test of our realized robot. It represents a complete built, realized and tested system. As shown in the figure, we succeeded in printing the logo of National Instrument and an arbitrary character.

B.Laser Engraver example
This robot can be easily upgraded to Laser Engraver by adding a 500mW laser engraver


In the image bellow, a list of suggested materials that can be used to engrave with laser is given, that are: wood board, colorful paper cards, dark opaque acrylic, etc. Besides, the list of possible cutter material include among others: colourful paper cards, foam papers, etc.


C.PCB example
Milling a PCB is not an easy task, especially when it is homemade, so with this robot we can add a sharp tools attached to a high performance motor  to make our PCB  more easily , faster , with high accuracy 
After uprating the XY Plotter. The CannyEdge interface do the job by extracting all the path. The Robot can print circuit-traces directly on to a carrier board
 

IIi.Other software Version using Qt
This version is under developing:






 
References
   [1]    J. TRAVIS and J. KRING. “LabVIEW for Everyone: Graphical Programming Made Easy and Fun”, National Instruments Virtual Instrumentation Series. Prentice Hall PTR, 2006.
   [2]     (2012) The Mantis robot website. [Online]. Available: http://www.mantisrobot.com/
   [3]    BLUETOOTH, S. I. G. Specification of the Bluetooth System, version 1.1. http://www. bluetooth. com, 2001.


Team members
This project is realized by Nidhal Mars, an engineering student at ENSI, “Embedded Software and Systems” specialization. It is supervised by Dr.-Ing.Mohamed Amine Abid (Researchgate / Linkedin) and Dr.-Ing.Chadlia JARAD (Researchgate / Linkedin) , associate professors at ENSI.



jeudi 10 septembre 2015

Using ultrasonic Sensor with Arduino and Stm32


1. What is an Ultrasonic Distance Sensor ?  




Ultrasonic Sensor is a popular and low cost solution for non-contact distance measurement function. It is able to measure distances from 2cm to 400cm with an accuracy of about 5mm. This module includes ultrasonic transmitter, ultrasonic receiver and its control circuit. it can be used with all most micro-controller .
HC-SR04/5 module has 4 pins :

  • VCC – 5V of the power supply
  • TRIG – Trigger Pin
  • ECHO – Echo Pin
  • GND – to ground 
TRIG and ECHO pins can be used to interface this module with a microcontroller unit.

2. How Does an Ultrasonic Sensor Work?

- Ultrasonic sensor principle
Ultrasonic sensors emit short, high-frequency sound pulses at regular intervals. These propagate in the air at the velocity of sound. If they strike an object, then they are reflected back as echo signals to the sensor, which itself computes the distance to the target based on the time-span between emitting the signal and receiving the echo.


 
- Interfacing with microcontroller 
  1. Provide TRIGGER signal, at least 10μS High Level (5V) pulse.
  2. The module will automatically transmit eight 40KHz ultrasonic burst.
  3. If there is an obstacle in-front of the module, it will reflect the ultrasonic burst.
  4. If the signal is back, ECHO output of the sensor will be in HIGH state (5V) for a duration of time taken for sending and receiving ultrasonic burst. Pulse width ranges from about 150μS to 25mS and if no obstacle is detected, the echo pulse width will be about 38ms.  
- How to Find the Range of Target ?

The image bellow explain how to calculate the range.



3. How to use it with Arduino or Stm32 : 

- Wire connection and code for Arduino
-  VCC pin to the Arduino 5v
-  GND pin to the Arduino GND
- TRG pin to the Arduino Digital pin 12
-  ECHO pin to the Arduino Digital pin 11
the code example : (source : arduinobasics.blogspot.com)
/*
 HC-SR04 Ping distance sensor:
 VCC to arduino 5v 
 GND to arduino GND
 Echo to Arduino pin 11 
 Trig to Arduino pin 12
 */


#define echoPin 11 // Echo Pin
#define trigPin 12 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

void loop() {
/* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */ 
 digitalWrite(trigPin, LOW); 
 delayMicroseconds(2); 

 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10); 
 
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 
 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;
 
 if (distance >= maximumRange || distance <= minimumRange){
 /* Send a negative number to computer and Turn LED ON 
 to indicate "out of range" */
 Serial.println("-1");
 digitalWrite(LEDPin, HIGH); 
 }
 else {
 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */
 Serial.println(distance);
 digitalWrite(LEDPin, LOW); 
 }
 
 //Delay 50ms before next reading.
 delay(50);
}
wire connection and code for Stm32f4 
-  VCC pin to the stm32f4 5v
-  GND pin to the
stm32f4 GND
- TRG pin to PD10

-  ECHO pin to PD11
You can get all project from my git account HERE 

 
#include "stm32f4_discovery.h"
#include "delay.h"

uint32_t Read_Distance(void);
void Init();

uint32_t distance ;

int main()
{  
    Init();   // initialisation de pin
    SysTick_Init(); // pour pouvoire utiliser la fonction delay :)

    while (1)
    {
    distance=Read_Distance();
    delay_nms(100);
    }
}


void Init()
{
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

    GPIO_InitTypeDef gpioStructure;
       
    gpioStructure.GPIO_Pin = GPIO_Pin_10;
    gpioStructure.GPIO_Mode = GPIO_Mode_OUT;
    gpioStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_Init(GPIOD, &gpioStructure);
    
    gpioStructure.GPIO_Pin = GPIO_Pin_11;
    gpioStructure.GPIO_Mode = GPIO_Mode_IN;
    GPIO_Init(GPIOD, &gpioStructure);
}
//Les Pins pour le Test sont PD10 (Trig) et PD11(echo) 

uint32_t Read_Distance(void)
{
          __IO uint8_t flag=0;
           __IO uint32_t disTime=0;
    GPIO_SetBits(GPIOD,GPIO_Pin_10);
    delay_nus(10);
    GPIO_ResetBits(GPIOD,GPIO_Pin_10);

  while(flag == 0)
  { 
   while(GPIO_ReadInputDataBit(GPIOD,GPIO_Pin_11) == SET)
   {
     disTime++;
     flag = 1;
   }
  
  }
    return disTime;
}
    

mercredi 9 septembre 2015

Top 4 Stm32 , Arduino and Raspberry Pi Sensors


 May be you are new in embedded system world , this article will help you to know the most popular sensors that you can use in your projects . these sensors are very helpful and can give you many ideas of robotic projects .

1.Line follower module
Line follower module based on the optical reflector TCRT5000 and LM393 amplifier. It connects to a digital input of an Arduino or compatible card. it is very useful for Robots and you can use it also on analog mode .


2. Ultrasonic sensor 
 If you are building an autonomous robot you should have this sensor . it is super easy to use with just 3 pins. 5V, GND and Signal. The effective range is from about 2 centimeters to 300 centimeters . you can find HERE an article about it .



3. Motion sensor 
A motion detector is a device that detects moving objects, particularly people. A motion detector is often integrated as a component of a system that automatically performs a task or alerts a user of motion in an area. Motion detectors form a vital component of security, automated lighting control, home control, energy efficiency, and other useful systems.

 

4. Flex sensor
When you need to detect a flex, a flex sensor is the most helpful part for you. As the sensor is flexed, the resistance across the sensor increases. It is great for detecting how much fingers are bent . 
Here is simple example of uses :


dimanche 9 août 2015

Persistence of Vision (PoV) : Clock and text displayer



This is the LED display i made, it works on the principle of Persistence of Vision (PoV).
 The Led's are turned on and off at precise intervals on different points while they are in motion such that they display the required text or time .





1. Objective:
To realize a text displayer and a clock from a single vector LEDs . These LEDs are rotating
fast enough that the human eye has the impression of watching:
- an matrix of leds in the case of a text displayer


 
- a circle of leds in the case of  clock



2. how does this system work ?
Each period, the LEDs show the same pattern in the same place . If the rotation frequency is high, the retina of the observer will have the impression that the image is fixed.

3. Design
Power supply unit:

With a continuous movement it is necessary to use two different power supplies,
So we put a 9V battery that will provide energy to the rotating part (PIC + LED) through a 5V regulator.

The motor will be powered by an external adjustable power that will allows me to choose the speed of rotation. 

 
Block of leds Management:

According to the datasheet bicolor LEDs TLUV5300, i must provide 30mA per LED,
In the worst case up to 60mA per bicolor LED.
  There will be 7 LEDs connected on a port , that is meen  i must provide 420mA in the worst case .
But
the PIC datasheet indicate that it supports 25mA per pin and 100mA per port, so i must use a circuit for  current amplification . (in my case i used ULN2003)

Schematic diagram of the control of LEDs:


System integration:

The programmed part of the system will be entrusted to PIC16F877

microcontroller   using  20MHz clock  which will be more than enough at the frequency of mechanical system (~ 10Hz).


4. Realization 

In order to prepare my printed circuit board , i use isis 7 and here is some screen shot of my work :




5. Software development   
here is exemple of solution to show time (case of clock ):
 
while (1)
{

for (j=1;j<=periode;j++) 
{
for (s1=60;s1>0;s1--)
{
if (s1!=second) /*  second desactivated    */
{
   if (s1!=minute ) /*  minute desactivated   */
    {      if ( s1 != hour)
            {
                     if (s1%5)
                        {
                          output_b(0b00000000);
                          delay_us(speed_time);
                          output_b(0b00000000);
                          delay_us(speed_time);
                          output_b(0b00000000);
                          delay_us(speed_time);
                          output_b(0b00000000);
                        }
                     else 
                     {
                          output_b(0b00000000);
                          delay_us(speed_time);
                          output_b(0b01000000);
                          delay_us(speed_time);
                          output_b(0b00000000);
                          delay_us(speed_time);
                          output_b(0b00000000);    
                      };
                }
             else          
               {
                          output_b(0b00000100);
                          delay_us(speed_time);
                          output_b(0b01001111);
                          delay_us(speed_time);
                          output_b(0b00000100);
                          delay_us(speed_time);
                          output_b(0b00000000);        
               }
     }
    else           /*  minute activated   */
    {  if ( s1 != hour)
            {
                     if (s1%5)
                        {
                          output_b(0b00001000);
                          delay_us(speed_time);
                          output_b(0b00011111);
                          delay_us(speed_time);
                          output_b(0b00001000);
                          delay_us(speed_time);
                          output_b(0b00000000);
                        }
                     else 
                     {
                          output_b(0b00001000);
                          delay_us(speed_time);
                          output_b(0b01011111);
                          delay_us(speed_time);
                          output_b(0b00001000);
                          delay_us(speed_time);
                          output_b(0b00000000);    
                      };
                }
             else          
               {
                          output_b(0b00001100);
                          delay_us(speed_time);
                          output_b(0b01011111);
                          delay_us(speed_time);
                          output_b(0b00001100);
                          delay_us(speed_time);
                          output_b(0b00000000);        
               }
      };
}
else /* second activated  */
{
    if (s1!=minute) /* minute desactivated  */
    {        if ( s1 != hour)
            {
                          output_b(0b00100000);
                          delay_us(speed_time);
                          output_b(0b11111111);
                          delay_us(speed_time);
                          output_b(0b00100000);
                          delay_us(speed_time);
                          output_b(0b00000000);  
              }
             else          
              {
                          output_b(0b00100100);
                          delay_us(speed_time);
                          output_b(0b01111111);
                          delay_us(speed_time);
                          output_b(0b00100100);
                          delay_us(speed_time);
                          output_b(0b00000000);        
              }
    }
    else   /*  minute activated   */
    {       if ( s1 != hour)
            {
                          output_b(0b00101000);
                          delay_us(speed_time);
                          output_b(0b01111111);
                          delay_us(speed_time);
                          output_b(0b00101000);
                          delay_us(speed_time);
                          output_b(0b00000000);    
            
             }
            else          
            {
                          output_b(0b00101100);
                          delay_us(speed_time);
                          output_b(0b01111111);
                          delay_us(speed_time);
                          output_b(0b00101100);
                          delay_us(speed_time);
                          output_b(0b00000000);        
             }
    };
}
 };
 };
 second++;
 if(second==60) 
 {
 minute++;
 second=0;
 };
 if(minute ==60) 
 {
 hour+=5;
 minute =0;
 };
 if(hour==60) 
 {
hour=0;
 };
 };
}

    

mardi 5 mai 2015

IOT : Routing solution for a Wireless Personal Area Network (WPAN)

This article represent a routing solution for a WPAN or WSN based on random walk algorithm . the used transceiver is spirit1 you can find its firmware with our implemented solution on my github account 

The Internet of Things (IoT), defined by the Oxford dictionary as a proposed development of the Internet in which everyday objects have network connectivity, allowing them to send and receive data, is the next big thing in embedded computing. Most of the information available on the Internet is made and added by human beings, but the IoT can change all this data collection by connected widgets. 

A boom owing to the arrival of the IoT is expected to connect a very large number of devices to the Internet. One major drawback was the limitation of 4.3 billion unique addresses posed by the IPv4 protocol. This issue was addressed with the development and subsequent adaptation of IPv6, which allows a nearly unlimited number, 2128, or approximately 3.4×1038 unique addresses. Gartner, the American research firm, predicts nearly 26 billion devices on the IoTby 2020.
It is a well known fact that wireless connectivity is a key component of the Internet of Things (IoT). Embedded systems in various disciplines, such as transportation, medical, smart grid, industrial, home and automation, are more often than not integrated with wireless connectivity called machine-to-machine (M2M) communication. These systems need not necessarily be M2M-capable, but these do include an assortment of sensors and other devices. 
The main problem of M2M solutions is the higher cost of devices that allows your system to connect to the internet. So we are interesting to minimize the cost of developing of theses technologies. 

In fact , one of the most used device for communication is the GSM modem due to it large coverage. But using this type of communication always has a cost additional for users who should pay the subscription fee. So it is very important to find a less costly solution for the deployment of M2M platform that respect the requirement.

Machine to Machine technology (M2M) 
The development of communication technologies and intelligent devices combined with enterprise computing, enabled the emergence of a new type of uses and applications: the Machine To Machine or M2M. 

M2M 
The Machine To Machine is the association of information and communications technology with intelligent and communicating objects in order to interact together without human intervention. The use of the machine-to-machine is particularly suitable for interacting with a large number of devices that can be fix or mobile. The M2M technologies facilitates the management of high number of devices. It also allows companies and organizations to develop new services in their works. 

M2M Architecture 
M2M allows a bidirectional exchange between the M2M device and the application. The received information will be processed. In many cases, M2M involves a group of identical devices interacting with an application. In some cases, the devices can‘t communicate directly with the application because of their limited capacity. In this case, a device called Gatewayis necessary to ensure the communication.

Global Architecture
Deployment architecture 
The overall architecture is used to give an overview on the various nodes of our network, from this vision, we will detail the main role of each node. Three things form basic building blocks of our M2M system. End nodes or Meter , routing Node (router) and concentrator . Each of these nodes has to have certain characteristics in order to form an effective system as explained further.  
Meter : It is the front-most node of any IoT system. In some cases, these objects could also perform dual role as sensors or input devices as well as actuators or output devices. Their main job is to collect or disseminate data (or do both). Meters need to have unique identifier in order to identify them and communicate with them effectively in large array of end-nodes in bigger M2M application. Meters can be controlled with command-control mechanism and this may be either autonomous or may be handled by the end-users directly. Typical examples of end nodes could be humidity sensor, temperature sensor, MEMs, radar vision, ultrasonic sensors, RFID readers, flow meters, cameras, GPS etc.

Router : A router is a specialized networking device allows to move data from meters that are outside the coverage to the concentrator. It is always activated so it needs to be powered by a power supply. In our application , the router can do the same job of meter and send its own information to the concentrator (or receive commands ). the router configuration is dynamic and can be changed by the concentrator in order to improve the performance of our system and get the optimal path.

Concentrator : This section does form central part of our system and can be considered as a heart of IoT or M2M solution. The main job of this node is to process the data and information received from meters or routers and transmit to further link for action which may be software application or cloud based service. It also sends the information received from application to the meters or router (configuration). Concentrators nodes provide local intelligence to the entire network of sensors and application. While heavy lifting software is based on cloud network or individual PCs, processing nodes form small computing elements in local infrastructure. These can be easily controlled with command-control mechanism by application software and mostly work on real-time basis. Its also performs encryption and decryption of data to maintain security of communication. Typically a Concentrator involves one or more microcontrollers, microprocessors, hybrid circuits, etc. and may be relatively bigger in size as compared to meters.

Topology 

Nodes operating modes allows a partial mesh topology. A mesh network is a network topology in which each node relays data for the network. All mesh nodes cooperate in the distribution of data in the network. Mesh networks can relay messages using a routing technique. With routing, the message is propagated along a path by hopping from node to node until it reaches its destination.

Detailed design 
Internal Architecture: 
 As we explained in the global architecture , our application is composed from three device (Meter , Router , Concentrator). Each device has a necessary element to do its tasks. for example the Meter need some sensors (or actuator) to collect or disseminate data while the concentrator need other device (example : GSM Modem or Wifi ) to establish an internet connection. However all device need a common element which is the transceiver to communicate together. All these additional elements will be integrated to a microcontroller. To guarantee that the system will operate autonomously and support multitasking , a state machine will be implemented to allows the parallel execution of tasks and organize the program by layer. While all device will use a common transceiver , the program will contain a common layer which are : Network , Mac_driver that will be explained later with detail. 

 In addition to these two layer , each Node has its own application layer to do its tasks. the Routing node can listen to all devices to route any packet come from meter/concentrator that are outside the coverage ofthe concentrator/meter. However , both Meter and Concentrator will accept only a packet that is destinated for them (a low level filter will be enabled).





Design of different layer
=> Mac driver layer 
The aim of this layer is to manipulate the main operation which are send or receive data. it begin with initializing the communication between the microcontroller and the transceiver and configure some parameter (modulation , band frequency , type of packet ... ). Then this layer will wait for request to send or listen for incoming data and manage Csma-ca engine.

- IDLE : This state will wait for request from the superior layer
- RX : Turn off csma-ca engine and listen for incoming data. if any data is received it will be saved on temporary buffer and the state will change to Received_data_ready
- Received_data_ready : the state will be detected by the superior layer and it means that there is new data saved in Rx buffer.
- TX : Turn on csma-ca engine and send data saved on Tx buffer to the destination address
- Wait_Tx_Flag : In this state , the machine will wait until the channel will be empty and the transmission is done.



=> Network layer 
This machine have two waiting line , one for the messages to send called Txfifo and the other for the received data called Rxfifo. Both are using First-In, First-Out algorithm.
- Message state in TxFIFO : - Empty : in this state the packet is empty and the superior layer can put its message that want to send - Ready_to_send : in this state the packet is ready to send and waiting for it turn. - Sending : this state means that the message is sending right now and waiting for acquittal
- Message state in RxFIFO : - Empty : In this state if any data is received this packet is empty and ready to save it. - Rx_msg : this state is to inform that it contain new message ready to be readed.




=> Meter application layer 
The flowchart belows models the Meter application layer. this device have to build a packet of informations periodically or eventually depending on application. Once the message is ready the machine will send it to TxFIFO of Network layer and wait for acquittal in case of need.
- BUILD_MSG : In this state the machine will wait for any interruption or period deadline to build a new packet with updated informations.
- SEND_DATA : The machine will send the ready message to the Network layer and exactly to the TxFIFO. Then if the packet need to be acquitted the machine will wait for acquittal. Else it will return to the initial state which is BUILD_MSG.
- WAIT_ACK : This state is to wait for the concentrator to send it acquittal

=> Concentrator application layer 
As we mentioned in the global architecture the role of concentrator is to process the data and information received from meters or routers and transmit to the server. in case the packet need to be acquitted the machine will support this task. 
- LISTENING : in this state the machine will listen for incoming packet from the RxFIFO (Network layer)
- SEND_DATA_TO_SERVER : In this state (after receiving new packet) the new data will be send to the server using Tcp/Ip connexion. 

- SEND_ACK : Send an acquittal for each packet in case of need.




=>Router application layer
- Principal of random walk : A random walk is a mathematical formalization of a path that consists of a succession of random steps. For example, the path traced by a molecule as it travels in a liquid or a gas, the search path of a foraging animal, the price of a fluctuating stock and the financial status of a gambler can all be modeled as random walks, although they may not be truly random in reality. The term random walk was first introduced by Karl Pearson in 1905. Random walks have been used in many fields: ecology, economics, psychology, computer science, physics, chemistry, and biology. Random walks explain the observed behaviors of many processes in these fields, and thus serve as a fundamental model for the recorded stochastic activity



Our routing algorithm is based on random walk , all routers have a threshold (probability of transmission) that is used to make a decision. In addition to the threshold the packet will have
a field called ‘prefered address’ that is used also for decision. when a packet is received , the router will analyse it to make one of the following decision : 

1- if the packet is destined for the broadcast address (0xFF) , then the router will get a random number in [0..100] (Get_Random) using its Timer and compare it to the threshold. if the random number is upper than the threshold , the packet will be forgotten. Else the router will send it to the destination after a period (WAIT) calculated using the random number (random number * 2 ms). 
2- if the field ‘prefered address’ is equal to the router address , then the packet will be routed to the destination directly (Send_Msg) 
3- if the field ‘prefered address’ is not equal to the router address Or the packet routed many time ( fixed at fifth time ) , then the message will be forgotten.


Frame format
- Application layer :
Data is used to save the information that will be send to the server. this field can be programmed by the developer which is an actor for our application
- Network layer :
Source : the address of the original device who send the packet that can be a meter or concentrator
Destination : the address of destination device that can be meter or concentrator
Preferred address : used to define a specific route and if it is equal to the broadcast address the router will forward it using its intelligent algorithm (random walk)
Sequence number of the message.
Type of the message that define if the meter need an acquittal or not. And also for the concentrator to define if it is a command or an acquittal (ACK).
Routers to count the number of router and describe the route of packet in of tests
- Mac driver layer :
Preamble (programmable field): the length of the preamble is programmable from 1 to 32 bytes. Each preamble byte is a '10101010' binary sequence.
Sync (programmable field): the length of the synchronization field is programmable (from 1 to 4 bytes). The SYNC word is programmable through registers SYNC1, SYNC2, SYNC3, and SYNC4. If the programmed sync length is 1, then only SYNC word is transmitted; if the programmed sync length is 2 then only SYNC1 and SYNC2 words are transmitted and so on.
Length (programmable/optional field): the packet length field is an optional field that is defined as the cumulative length of Address, Control, and Payload fields. It is possible to support fixed and variable packet length. In fixed mode, the field length is not used.
Destination address (programmable/optional field): when the destination address filtering is enabled in the receiver, the packet handler engine compares the destination address field of the packet received with the value of register TX_SOURCE_ADDR.
Payload (programmable/optional field): the device supports both fixed and variable payload length transmission from 0 to 65535 bytes.
CRC (programmable/optional field): There are different polynomials CRC: 8 bits, 16 bits (2 polynomials are available) and 24 bits. When the CRC automatic filtering is enabled, the received packet is discarded automatically when the CRC check fails.
 




Hardware environment

Host device: STM32L151 Discovery
The choice of STM32L151 DISCOVERY as host device is based on many reasons. This device extend the ultra-low-power concept with no compromise on performance, using the Cortex-M3 core and a flexible CPU clock from 32 kHz up to 32 MHz. As well as the dynamic run and low-power run modes, two additional ultra-low-power modes bring you very low power consumption while keeping an RTC, backup register content and low-voltage detector. The STM32L151/152 devices are designed for medical, industrial and consumer applications and feature an onboard fast 12-bit 1 MSPS ADC, USB 2.0 FS and capacitive touch sensing. To reduce application cost and design, the STM32L151/152 offer an integrated LCD driver with up to 8 x 40 segments.



SPIRIT1 Low data rate, low power Sub 1GHz transceiver
The SPIRIT1 is a very low-power RF transceiver, intended for RF wireless applications in the sub-1 GHz band. It uses a very small number of discrete external components and integrates a configurable baseband modem, which supports data management, modulation, and demodulation. The data management handles the data in the proprietary fully programmable packet format also allows the M-Bus standard compliance format (all performance classes). However, the SPIRIT1 can perform cyclic redundancy checks on the data as well as FEC encoding/decoding on the packets. The SPIRIT1 provides an optional automatic acknowledgement, retransmission, and timeout protocol engine in order to reduce overall system costs by handling all the high-speed link layer operations. Moreover, the SPIRIT1 supports an embedded CSMA/CA engine. An AES 128-bit encryption co-processor is available for secure data transfer. The SPIRIT1 fully supports antenna diversity with an integrated antenna switching control algorithm. Transmitted/received data bytes are buffered in two different three-level FIFOs (TX FIFO and RX FIFO), accessible via the SPI interface for host processing.
The SP1ML-868 and SP1ML-915 
To simplify our development and test task , we used The SP1ML-868 and SP1ML-915. They are ultra-low power & fully integrated RF modules operating respectively in the 868 MHz SRD and 915 MHz ISM bands. The SP1ML module is a compact-size module, integrating an on-board antenna with easy-to use interface, allowing users to easily add wireless connectivity in designs and reducing time to-market. These modules are based on the SPIRIT1 RF sub-GHz transceiver (with integrated SMPS), STM32L1 microcontroller, integrated filter/balun and chip antenna. The UART host interface allows simple connection to an external microcontroller with a standard firmware, allowing AT commands to facilitate RF configuration, data transmission and reception, using simple point-topoint communication. Selected STM32L1 GPIO and peripherals are available for interfacing to external devices in the user application. Advanced features of the SPIRIT1 radio are also accessible. The serial wire debug interface (SWD) is also available. The modules are CE compliant and FCC certified (FCC ID S9NSP1ML)




Different tests 
Main program 
The figure belows shows our main program with the different type of device. The infinite loop is organized and contain the routine of all layers. The developer can easily select the type of device and modify on it.
 

Test of Csma-CA engine 

CSMA mode is used in order to avoid collisions when attempting to access the communication channel.The figure belows  shows the different devices used to evaluate the Csma-CA engine. These devices are Meter (A) which is used to send a packet and a concentrator (B) to receive it. A sniffer (D) is used for testing the transmission. A noise generator device (C) is used to generate a continuous wave in order to occupy the channel to permit the validation of the CSMA feature enabled on the Meter device of this example. The result shown in figure belows was perfect and the Meter (A) send its packet only after we turned off the noise generator device (C).




Test of Meter , router and concentrator 
- Test of two meters with concentrator In this test we used two meters and one concentrator. these meters are sending their packets periodically. The figure shows the result of this test. At the first the meter that have 0x20 as address send a packet (1) that need an acquittal. then the concentrator will send for it a packet (2) that it type is acquittal. the same scenario will be repeated (3+4) for meter with address equal to 0x30 


- Test of meter router and concentrator 
In this case we introduced a router device with one meters and one concentrator. The figure shows the result of this test. At the first the meter send a packet (1) that need an acquittal and has 0xFF (broadcast address) as preferred route. So the router will forward (2) it using its intelligent algorithm (Random walk) and add it address in routers field. Then the concentrator will receive the message and send (3) it acquittal (ACK). Finally the router will forward the packet again (4) , but this time to the meter.


References : 
[1] ST Micoelectronis Spirit1 Low data rate, low power sub-1GHz transceiver (11-02-2015) 
[2] Data sheet SPIRIT1 RF, DM00047607 (18-2-2013) 
[3] Data sheet SP1ML, DM00133214 (27-2-2015) [B5] St WIRELESS M-BUS IN SMART GRID SCENARIO [B6] Data sheet STM32L151x6/8/B (30-Jan-2015)
[4]http ://emcu.it/WirelessMBUS/Wireless_M-BUS_Solutions_and_more (27/07/2015) 
[5] http://electronicsofthings.com (01-08-2015) 

This project is realized by Nidhal Mars, an engineering student at ENSI, “Embedded Software and Systems” specialization through a summer internship (2015) .
This article is extracted from my report. For any needs feel free to contact me .