JSON libraries

 JSON libraries
1.frozen 
Output JSON objects in C as JSON formatted strings and parse 
JSON formatted strings back into the C presentation of 
the JSON objects.
FEATUES:
• C and C++ complaint portable.
• Several extra format specifiers supported.
JSON token:
This stucture contains-
Pointer pointing to beginning of the value.
Value length 
Type of the token
Token types are string,number,true,false,null,
object start, object end,array start and array end.
API’s:
• json_scanf
Scans json string directly into c/c++ variables.
• json_printf
Print c/c++ variables directly into output stream.
• json_setf
Modifies existing json_string.
• json_fread
Reads json from a file.
• json_fprintf
Writes json to a file.
• json_scanf_array_elem
Scan array element with given path and index
• json_printf_array
prints contiguous C arrays.
References:https://github.com/cesanta/frozen
SIZE of object file is 42 kBytes.
2.JSMN
Minimalistic JSON parser in C.
FEATURES:
Compatible with C89
Single head library
easily integrated into resource limited or
emb projects
API contains only 2 functions.
JSON token:
This structure contains-
type
start position in JSON data string
end position in JSON data string
size
Token types are-object,array,string,
primitive(number/boolean/true-false/null)
API’s:
•  jsmn_init
Create JSON parser over array of tokens.
•  jsmn_parse
Parses JSON data string into array of tokens,
each describing JSON object.
References:https://github.com/zserge/jsmn
SIZE of object file is upto 26 kBytes.
3.JSON-C
JSON-C implements referrence counting object that 
allows you to easily construct JSON objects in c,
output them as JSON formatted strings and parse 
JSON formatted strings back into c 
representation of JSON objects.
FEATURES:
JSON token:
Token types are boolean,double,int,object,array,string.
API’s:
• json_object_to_json_string
Stringify object to JSON format grabbing the 
shared ownership of object.
• json_object_get
Increament reference count of json_object.
• json_object_put
Decrement reference count of json_object,and free 
it if reaches to zero.
• json_object_userdata_to_json_string
Copy the userdata string to over the 
destination buffer.
• json_object_new_array
Create a new empty json_object of type 
json_type_array.
• json_object_get_array
Get the arraylist of json_object of type 
json_type_array.
• json_object_array_add
Add an element to the end of json_object 
of type json_type_array.
• json_obect_array_put_idx
Insert or replace an element at a specified 
index of the array.
• json_object_array_get_idx
Get the element at specifies index of the 
array.
All these functions for array are also defined for 
following json_types- 
boolean,double,int,int64,object .
References:https://github.com/json-c/json-c
SIZE of object file is upto 300 kBytes.

Modbus Master Stack On ATSAME54 With RTOS

In previous post we discussed about how to port modbus slave stack on ATSAME54. This post we will discuss on how to port modbus master stack on SAME microcontroller. You can download example freemodbus master stack for reference from FreeModbus. We have referred the ‘AT91SAM7X_FREETROS’ example project. You can follow the steps from previous post for creating directory of project files. Instead of modbus slave stack, add modbus master stack. In addition, We are using FreeRTOS in our project. So In top level directory we have added FreeRTOS V9.0.0 . Please refer to modifications in port specific files described in previous post.

So lets begin with issues while port modbus master stack on SAME, Without an operating systems there are normally no queues available. In case of modbus stack without using RTOS, the queue sending and receiving functions are implemented using a static variable which is set to TRUE when an event is posted. The receive function checks the variable and if TRUE returns the previously stored event. But in case of an RTOS the functions should use a real event queue. We Changed the function xMBPortEventPost() to post an event to a queue. This function will be called from an ISR so we have used xMBPortEventPostFromISR() API for that. This is the interrupt safe version of xMBPortEventPost() provided in FreeRTOS.

We changd the function xMBPortEventGet( ) to retrieve an event from that queue . The function should block until an event has been posted to the queue.

Like this we are calling xQueueCreateStatic() API from vQueueCreate and vQueueDelete() API from vMBPEventDelete .

Next step is to define the functions vMBPEnterCritical( ) and vMBPExitCritical( ) in file portother.c. A switch to another task cannot occur between the calls to vMBPEnterCritical and vMBPExitCritical . Only interrupts whose logical priority is above the value assigned to the configMAX_SYSCALL_INTERRUPT_PRIORITY constant can execute in critical section and interrupts are not permitted to call FreeRTOS API functions. In FreeRTOS there are API’s portENTER_CRITICAL() and portEXIT_CRITICAL() which we have used respectively in above two functions.

Note that if we are calling portENTER_CRITICAL() and portEXIT_CRITICAL() functions from ISR, the following assertion will get fail: configASSERT((portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK) == 0);

If you are also stuck here, means you are calling these APIs from ISR. In FreeRTOS there are interrupt safe APIs which can be used inside ISR. So here in this case we found following two interrupt safe versions for above functions:

portSET_INTERRUPT_MASK_FROM_ISR() and portCLEAR_INTERRUPT_MASK_FROM_ISR()

Use thses APIs where the function is called from ISR:

In main function, we created two tasks using xTaskCreateStatic() API from FreeRTOS , one is application task and another is for modbus task .

TESTING ON SIMULATOR:

We have now created the modbus master workpace. For testing it, we have to run the modbus slave program on PC side. We are developing the stack on linux system. For this system we found out the Diagslave Modbus Slave Simulator . Install it in your system then execute ‘linux_x86-64/diagslave -h’ It will show the options you can configure. We executed simulator by giving the following command:

After running modbus master program, the simulator showing this output:

Happy to help you during your port modbus master stack on SAME controllers.

Port Modbus Slave Stack On ATSAME54

We are referring modbus server stack implementation for SAM3X and We want to port it on SAME54P20A. First we have downloaded the example project for SAME54P20A which is using Usart_Asynchrnous module from Atmel START. Then create new top level directory for project files. Following files needs modification while porting, they are present in sub directory named ‘port’ which will contain all port specific files,

  • portserial.c
  • porttimer.c
  • portevent.c
  • portother.c
  • port.h

Atmel start project is having makefile in sub-directory ‘gcc’. Add these port specific files paths in makefile. Then add modbus stack folder to top level directory which is having all the modbus specific functions. For compilation we hav to add these all file paths in makefile which is in gcc directory. We have to first check the ‘port.h’ file whether it is suitable for our platform. If not ,then we have to define platform specific functions for serial interface,timer driver.

portserial.c: In this file there are functions for initializing USART, enabling and disabling USART module, enabling and disabling the receiver and transmitter. For enabling and disabling transmitter and receiver, we need to use corresponding low level API’s of ATSAME54P20A from ‘hri’ folder. The reference code for ATSAm3S:

Changes we have to do for ATSAME54:

In reference program for SAM3X they are using vUSARTHandler() interrupt handler in which they are checking for Rx or Tx interrupt invoked according to that respective xMBPortSerialGetByte(), xMBPortSerialPutByte() functions are called.

For SAME54P20A, there is an API- ‘usart_async_register_callback()’ so instead of ‘vUSARTHandler’, we have to create two different interrupt service routines one is for Rx interrupt and another for Tx interrupt.

portimer.c: The modbus protocol stack requires timer for detection of end of the frame. There are API’s available in SAME54P20A timer driver for initializing ,enabling and disabling the timer. For SAM3X they are using timer interrupt function TCX_IRQHANDLER() which is calling pxMBPortCBTimerExpired() function.

For ATSAME54P20A, there is timer task structure. So instead of using timer_handler we have to initialize timer structure which is having callback function in which we will call ‘pxMBPortCBTimerExpired()’ function.

If you are using FreeRTOS in your project then you need to modify ‘portevent.c’, We are not using rtos in our project so will not discuss on updating portevent functions. In next section we will update on it.

Ceedling Unit Testing With ATSAME54

This post is continuation of previous post on how to mock local variable in ceedling, please check out previous post before continuing with this article. Another issue is having to add all the microchip files.

When CMock gets a hold of the header file it looks at all the functions defined there and generates several mock functions for each.

In one program, we are dealing with 4 pins of microcontroller. The pin numbers and its functions are defined in file ‘atmel_start_pins.h’ which is included in our project. But inside this file there are definitions for all the pins and ‘hal.gpio.h’ file is included. Inside ‘hal.gpio.h’ file, another files are included. The original atmel_start_pins.h file is like below, We need only 4 pins from this file:

The function under test is :

Solution:

Instead of wasting memory we can create our own file ‘atmel_start_pins.h’ for unit testing. The file will contain The function declarations we want to mock and only the required data.

In above function INPUT_ENTER_KEY,INPUT_BACK_KEY etc are having values as follwing :

These PB_1,PB_2,PB_3,PB_4 are defined in file ‘atmel_start_pins.h’. So we can create our own ‘atmel_start_pins.h’ file which is having only requied data .The new file is like:

Now we can mock this required function and interfaces. We can just assign any numbers for PB_1,PB_2,PB_3,PB_4 . Pass these pin numbers in test cases.

we able to unit test without memory wastage.

Local Variable In Ceedling Unit Testing

Unit testing is code that calls some other code to check if it performing as expected.Ceedling is a build system specifically designed for running unit tests in c. Unity and CMock are open source tools for testing c.Ceedling has feature of automatic generation of mock.

  • Unity is a unit test framework.
  • CMock creates the fake versions of other modules.Using these fake versions we can verify whether our module is working correctly or not.
  • Ceedling include unit test framework(Unity) and Mocking framework(CMock).
  • It requires Ruby to run and it uses GCC to build each test.
  • Ceedling comes with a command line tool that can be used to generate the project.

‘Ceedling’ is open source tool used in unit testing, in our project which involves embedded system development we are using ‘ceedling’ framework. There are other unit test frameworks like google gTest but they are more suited for application software written high level languages like c++. Being embedded system software written in ‘C’ language we are using ‘Ceedling’ for our unit testing.

Issue:

I was testing function for one module which is using the modbus APIs defined in modbus.c file. For ceedling unit testing I mocked low level APIs like modbus_read_registers() and modbus_write_register().

In our code we defined function int _readModbusRegister( ) and function int _writeModbusRegister() inside which mobus_read/write_registers APIs were used :

This image has an empty alt attribute; its file name is read_Modbus_func1.jpg

The function under test is:

In above function I need to test all the possible conditions for different value of ‘drvStatus’ variable. But ‘drvStatus’ is local variable. How can I mock the local variable in Ceedling?? We cannot directly mock local variable using Ceedling. So in this case if we made our mock function modbus_read_registers() return 1 then user defined function _readModbusRegister() will always return ‘regValue’ as zero. Because right now we are testing the code without using hardware. So always ‘drvStatus’ variable will become zero and code will not get execute further. And we cannot change the value of drvStatus with this conditions.

Solution :

In ‘Ceedling’ generally we have to mock API but for getting different value for local variable ‘drvStatus’ in this case we have to mock the function which is returning value to local variable, i.e. in this case we will mock ‘_readModbusRegister()’. The actual function which we need to mock is always returning the register value. So add these two user defined function declarations to a file and add this file prefixing _mock .Ceedling will automatically create the mock versions of given functions.

When we mock the function whose definition is present we have to comment that definition otherwise ceedling will throw error for ‘ found multiple definitions’. I commented the definitions for these two mocked functions. Now I can use these _readModbusRegister_ExpectAndReturn() function with any return value and can generate test case for every possible condition. Like in first test case we are returning 8 to ‘drivestatus’ .

Here in second test case we can return 16 to ‘drivestatus variable’.

Like this we can change value of local variable.

Ceedling Unit Testing

Unit testing is code that calls some other code to check if it performing as expected.Ceedling is a build system specifically designed for running unit tests in c. Unity and CMock are open source tools for testing c.Ceedling has feature of automatic generation of mock.

  • Unity is a unit test framework.
  • CMock creates the fake versions of other modules.Using these fake versions we can verify whether our module is working correctly or not.
  • Ceedling include unit test framework(Unity) and Mocking framework(CMock).
  • It requires Ruby to run and it uses GCC to build each test.
  • Ceedling comes with a command line tool that can be used to generate the project.

Check out details on how to mock local variable in ceedling, and Ceedling Unit Testing With ATSAME54 Micro-controller.

Python for Beginners

Python is a programming language.Python can be used on a server to create web applications.

“Hello, World!” Program:

print(“Hello, World!”);

output:Hello world

In this program, we have used the built-in print() function to print Hello, world! string.

Variables and Literals:

Unlike other programming languages, Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

a = 5
print(“a =”, 5)

output:a = 5

Operators:

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

x = 20
y = 30

print(‘addition=’, x+y)

Output: addition= 18

in above program instead of + operator we also use *,,/,% etc.

Get Input from User:

In Python, you can use input() function to take input from user. For example:

inputString = input('Enter a sentence:')
print('The inputted string is:', inputString)

Python Comments:

There are 3 ways of creating comments in Python.

# This is a comment
  """This is a multiline comment.""" 
  '''This is also a  multilin

If … Else:

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

a = 33
b = 200
if b > a:
  print(“b is greater than a”)

output:b is greater than a

While Loop:

With the while loop we can execute a set of statements as long as a condition is true.

i = 1
while i < 6:
  print(i)
  i += 1

output:1 2 3 4 5 6

For Loop:

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

fruits = [“apple”, “banana”, “cherry”]
for x in fruits:
  print(x)

Python Data Structures:

1.Lists

A list is a collection which is ordered and changeable. In Python lists are written with square brackets.

list1 = [“mayuri”, “soni”, “pooja”, “priya”]

print(list1[0])

ouput:mayuri

2.Tuples:

A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.

tuple= (“mayuri”,”nikita”,”manasi”)
print(ltuple[0])

output:mayuri

3.Sets:

A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.

set = {1, 2, 3}
print(set)

output:1,2,3

4.Dictionaries:

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.

my_dict = {1: ‘apple’, 2: ‘ball’}

Python range():

range() returns an immutable sequence of numbers between the given start integer to the stop integer.

numbers = range(1, 6)

print(list(numbers)) # Output: [1, 2, 3, 4, 5]
print(tuple(numbers)) # Output: (1, 2, 3, 4, 5)
print(set(numbers)) # Output: {1, 2, 3, 4, 5}

Classes and Objects:

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a “blueprint” for creating objects.

The __init__() Function:

All classes have a function called __init__(), which is always executed when the class is being initiated.

The self parameter is a reference to the class itself, and is used to access variables that belongs to the class.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person(“John”, 36)

print(p1.name)
print(p1.age)

output:john 36

Functions:

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

def my_function():
  print(“Hello from a function”)

output:Hello from a fuction

my_function()

File Handling:

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

a.txt=

hello mayuri

f = open(“a.txt”, “r”)
print(f.read())

f = open(“a.txt”, “a”)

f.write(“new line added”)

output:a.txt=hello mayuri new line added

Exception Handling:

a = [5, 6, 7]
try:
print “Fourth element = %d” %(a[3])

except IndexError:
print(“error”)

output:error

Elevators

From several 100 years back , elevators were created that are for water driven mechanism.In 18’s new invented elevators were created that for lifting high weight materials.

Depending upon applications now modifications are happening in elevators.

 

Elevators are convenient way for vertical Transportation in safer mode.Also it saves time and energy efficiently.

It has capacity to bare high weight materials.shortly it acts as carrier for transportation.

In world-wide there are several manufactures for elevators.Depending upon applications they are manipulating features included it.

Top manufacturers of Elevators from Pune

1.Orbitech Elevators.
2.Tower Elevators.
3.Force Technologies.
4.Avicon Elevators pvt ltd.
5.Idea elevators company.
6.Escon elevators.
7.OTIS Elevators co ltd.
8.Escon Elevators.

Types of Elevator

  1. Roped hydraulic elevator.
  2. Prematic vaccum elevator.
  3. Counterweight chain drive elevator.
  4. Traction drive elevator.

Working of elevator

Basic structure of elevator

1)Counterweight:

  • By exerting opposite force it provides balance & stability to lift.
  • lifting load efficiently & saves energy.

2)Electric motor:

  • In previous times Dc motors were using because RPM was easy to control & cheaper but worst torque characteristics hence lots of jerk and poor speed regulation.
  • Now days 3 phase induction are using because of long life and high rigid structure easy to control torque and RPM.

Parameters considering while designing lift

  • No. of people require lift service.
  • Handling capacity of lift.
  • Facilities and services required for it.
  • Calculation of RTT(Round trip time).

Round trip time:

Average time required by each lift.

Also sum of time required in following process:

Handling capacity can be calculated by

H=(300*Q*100)/(P*T)

Q->Average number of passengers.

P->Total population handled during peak morning.

T->Waiting time.

Switching of an elevator :

Elevator

Elevator is nothing but one or more cars which are metal boxes which rise up and down for vertical transport of people or goods.

Parts:

  • Car(metal boxes)
  • Counterweight
  • Electric motor ,Braking system
  • Strong metal cables and pulleys
  • Control System
  • Switches and Sensors
  • Safety system
Basic diagram of elevator system

It uses motor for hoisting the car. For vertical movement it uses strong metal cables and pulleys. There are different types of elevators based upon different factors like technologies used,application,speed,hoist mechanism used,whether it carries people or good ,control system used,etc. Two types of elevators that are most commonly used in residential and commercial buildings are: Traction elevators and Hydraulic elevators.For high speed and high rising modern buildings,traction elevators are used.Traction elevators are also energy efficient because it uses counterweights to balance cars weight so requires less energy as compared to hydraulic elevators.At every floor there is display system which is showing the current direction of elevator and floor number at which the elevator is. In hospital like places where there can be an emergency for transport,we can implement elevator control system which will respond immediately when emergency switch is pressed. When emergency switch will be pressed,the elevator comes to requested floor and serves the request as interrupt.

Function of each part:

CAR  –  It is a type of vertical transport equipment that efficiently moves people or goods between floors of building.It is mounted on shaft.It can be of passenger service type or goods service type. Inside car there is keypad user interface for selecting destination floor.

There are two sets of elevator doors- Doors on the car and doors opening in elevator shaft.The car doors have clutch mechanism which will unlock the outer door to open. So outer door can open only when there is elevator at that floor.This avoids opening of outer doors in empty elevator shaft.There are main 2 types of doors manual and automatic.In automatic type doors it can be center opening door or double opening door.

COUNTERWEIGHT – Counterweight is used for balancing the weight of car.Car is pulled up by steel ropes in traction elevators.Sometimes one car is used as counterweight for another car i.e. balancing weights of each other.Using counterweight,there will be less force required for pulling the car hence less strain on cables.

ELECTRIC MOTOR BRAKING SYSTEM- Depending upon type of elevator we can use any actuator .Latest design use 3 phase induction motor with variable frequency drive electric control.For hoisting of a car it is placed above top floor of the building. There are two types of brakes for elevator system.One is for stopping the elevator at required floor and another one is for emergency like power failure or cable break-down or malfunctioning.Braking system uses combination of electrical and mechanical switches.

CONTROL SYSTEM – There are main two types of control -Manual control i.e. switches operated by pulling respective ropes.Relay-controlled elevator system was common until 1980’s.But now a days microprocessor based elevator systems are industry standards.

There are 3 types elevator controls can be implemented:

  • Selective Collective operation
  • Constant pressure operation
  • Non-Selective Collective operation
  • In selective collective operation,elevator responds to the requests along same path. Requests along opposite path will be added to the list .It reverses the direction and then serves the requests along opposite path. In constant pressure operation, the button must have pressure maintained for movement of elevator. Once pressure is removed,elevator will stop at that point. In non-selective collective operation, the elevator will respond to the calls sequentially i.e.order in which it comes.

SWITCHES AND SENSORS – Inside car there is a keypad for selecting the floor number .There is a floor button at every floor for requesting the elevator service.User can call the elevator by pressing the floor button. There are arrival sensors places at the top and bottom of car. Arrival sensors consist of reed switches which are electromagnetic switches activated my magnet.Magnet is placed at every floor and metal rods are connected to car. Respective reed switches get activated when comes near magnet and this sensors output is given to controller by which we will get to know the status of elevator i.e. at which floor elevator is. More sensors used in elevator are: Overload sensor for overload protection,current sensor,limit switches,level sensor etc.In elevator doors, infrared sensors are used for detecting obstacle between doors.

SAFETY SYSTEM-  Elevators are designed with several safety systems that keep them in position.If elevator control system detects that car is speeding downwards or upwards,it jams the metal brake from underneath the car into the guide rails on shaft. In case of power failure,electro-mechanical brakes will get activated.

Flowchart