Friday, January 4, 2019

Battle Tank toy project using Raspberry Pi

Tank chassis driven by DC brushed motors 260.  Web server running on Raspberry Pi, so it can be controlled from web browser over internet.

Project on GitHub Link.



Friday, May 15, 2015

Upgrading JFFS2 Filesystem from linux

For embedded systems field upgrade of software application and BSP is common requirement. Updating U-boot and uImage (linux kernel) is fairly easy but upgrading filesystem from linux is bit tricky. You can-not erase the filesystem partition containing filesystem image, upgrade images and mtd-utils because it will turn your system to brick. This situation may arise if you have limited flash and can not afford to create separate partition for storing upgrade images. If you want to use most of the flash for filesystem and also store upgrade images in the same filesystem partition, here is a way to do so

A useful trick is to make use of linux implementation of traditional shared memory. This method is however neither failsafe and nor atomic. It can still brick the board if there is any sort of interruption (power failure ) while upgrading. Since it is easy and fast, so worth giving a shot. Suppose the latest filesystem image 'rootfs.jffs2' is placed in 'update' directory under 'opt'. Copy it to /dev/shm

# cp /opt/update/rootfs.jffs2 /dev/shm

Copy all the utils, needed for upgrade to shared memory too

cp  /usr/sbin/flash_erase /dev/shm/
cp  /usr/sbin/flashcp /dev/shm/
cp  /sbin/reboot /dev/shm/

Erase the partition where jffs2 filesystem resides, in my case it is mtd0 of size 29 Mb.

/dev/shm/flash_erase /dev/mtd0 0 232
/dev/shm/flashcp -v /dev/shm/rootfs.jffs2 /dev/mtd0
/dev/shm/reboot


One can also try to upgrade filesystem from u-boot using fsload but unfortunately, it was not able to load large filesystem properly.


Tuesday, July 1, 2014

Uses of Union in C

A union is a special data type available in C/C++ that enable user to store different data types in the same memory location. User can define a union with many members, but only one member can contain a value at any given time. Union thus provide an efficient way of using the same memory location for multiple types. Unions are quite similar to the structures in C but there is difference in memory allocation, memory required to store a union variable is the memory required for largest element of an union. Whereas, to store a structure variables, memory required is the sum of memory size of all members.

Union data type is quite useful in C. Unions in C are used for type-safe polymorphism. In C++'s use of classes & inheritance make the need of Union redundant.

Because of above mentioned properties Unions are mostly used for


1. Creating own Variant type

A variant can be thought of as a container that can hold a variable of almost any data type be it a numeric, float, string, or even an entire array. To create your own variant type, a union can be encapsulated within a structure along with a discriminator that indicates which of the fields of the union are valid. 
 typedef enum {EMPTY, CHAR, INT, UINT, FLOAT, DOUBLE, PTR} ValueType; 
 struct variant_t {
    int mType;
    union {
        char charVal;
        int intVal;
        unsigned int uintVal;
        float floatVal;
        double doubleVal;
        void* ptrVal;
    };
};

it can be then used as,
/* Read a value to the variant from some record */
void getData(struct variant_t* v, int variantType)
{
v->mType = (ValueType)variantType;
switch(v->mType)
{
case CHAR:
v->charVal = ReadData(fptr);
break;
case DOUBLE:
v->doubleVal = ReadData(fptr);
break;
}

2. In embedded systems.
In the embedded realm, each bit of a register may mean different things. In such scenarios a union of a 1 byte char and a structure with 8 separate 1 bit bit-fields , allows you to either change one bit or the entire byte.
Similar examples can be found in many networking APIs for IPv4 address like
union ipv4Addr {
  unsigned  ipAddress;
  char      octets[4];
};

3. To cast pointer to an int and vice-versa
In the embedded realm, mostly the size of a pointer and an int are same. This is because both of them can fit into a CPU register. So if you want to store a value at a particular memory location, you can do something like this
typedef union {
   int i;
   int* iptr;
 }intptr;

 intptr p;

 p.i = 256;
 *(p.iptr)=5; /* put 5 a location 256 */ 

 when we set p.i = 256; both the members of union has value 256, since each member share same location.


 An example C code build using VS2010 IDE can be downloaded from here. In this code a student record in "data.txt" file is read and stored in linked list. Each node of list has a union to store student information. The requirement is that, at a time user want to display only one of either name, roll number, grades or result. So depending on what user want to display, data is stored in Node that store a only a particular type ( Variant ) and display only that particular type of data.

Sunday, June 8, 2014

Head First C++ code for PizzaStore : Abstract Factory Pattern

After Factory method, Chapter 4 in the Head First Design Patterns book explains Abstract Factory design pattern.

" The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. "

Both Factory Method and Abstract Factory create objects but the key differences are :

  1. Factory Method create objects through inheritance, that is you need to extend a class and override a factory method. Whereas Abstract Factory create through object composition, it provide an abstract type for creating a family of products. Subclasses of this type create products. To use the Abstract Factory , you instantiate one and pass it into some code that is written against the abstract type.
  2. Factory Method is to just create one Product and each subclass is to decides which concrete class of Product to instantiate. Whereas Abstract Factory provides an abstract interface for creating a family of Products.
  3. Methods to create products in an Abstract Factory are often implemented with a Factory Method!
In the example code PizzaIngredientFactory is implemented as an Abstract Factory because we need to create family of Products ( the ingredients). PizzaIngredientFactory provides an abstract interface for creating a family of products. The subclasses as 'NYPizzaIngredientFactory' uses factory method like 'createDough()' in an Abstract Factory pattern.

Here is the class diagram of PizzaStoreV2






























The c++ code is build using VS2010 IDE. You can download code from here.


Wednesday, June 4, 2014

Head First C++ code for PizzaStore : A Factory Method Pattern

Chapter 4 in the Head First Design Patterns book explains Factory Method design pattern. As we learned in previous posts to "encapsulate what varies", we can apply same technique to "encapsulate the code that create objects". When you have code that create objects or instantiates concrete classes, then it can be an area of frequent change.

We create objects by using new operator but there is more to making objects than just using new operator. As per design principle 2 we should "Program to an interface, not an implementation". Why ? Because if code is written to an interface, then it will work with any new classes implementing that interface through polymorphism. When I say interface here then in C++ there is no clear distinction between interface and abstract class, unlike in C# and Java. To get a fair idea of interfaces and abstract classes in C++, you can refer stackoverflow discussions here and here. Generally speaking interface can also refer to a function's signature.
Whenever you see "new", think "concrete". When you use "new" you are certainly instantiating a concrete class, so that's an implementation and not an interface. When you have a code that makes use of lots of concrete classes then it will be prone to bugs because code may have to be changed as new concrete classes are added. So code will not be "closed for modifications" and hence violate our design principle 4 discussed in last post.
Anywhere in a code if you use "new", you'll be holding a reference to a concrete class, you should be using a Factory method to get around that! Factory method can be defined as

" The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."

The 'interface' above is factory 'method'. A factory method handles object creation and encapsulates it in a subclass. This decouples the client code in the superclass from the object creation code in the subclass. A factory method looks like

        abstract Product factoryMethod(String type)

A factory method returns a Product that is typically used within methods defined in the superclass. Client is actually code in superclass, factoryMethod isolates the client code from knowing what kind of concrete Product is actually created.

In the example code the PizzaStore class is the Creator class that contains the implementations for all of the methods to manipulate products, except for the factory method. The abstract factoryMethod ( createPizza(string) ) is what all Creater subclasses must implement ( ChicagoPizzaStore, NYPizzaStore ). The Concrete Creater( ChicagoPizzaStore, NYPizzaStore ) implements the factoryMethod(), which is the method that actually produce Products.
Pizza is the Product and all concrete products ( NYStyleCheesePizza, ChicagoStyleCheesePizza ... ) must implement the same interface so that the classes which use the products can refer to the interface not the Concrete Product ( NYStyleCheesePizza, ChicagoStyleCheesePizza etc. ).

Here is the class diagram of PizzaStore


















The c++ code is build using VS2010 IDE. You can download code from here.

Monday, June 2, 2014

Head First C++ code for StarbuzzCoffee : A Decorator Pattern

The third chapter in the Head First Design Patterns book explains another fundamental design principle that forms the basis of Decorator design pattern. The fourth design principle can be summed as

"Classes should be open for extension, but closed for modification."

The example code in Chapter 3 the Decorator Pattern provide Java Implementation of StarBuzzCoffee billing application. I tried to write similar code in C++ that explains the Decorator Pattern used in the program.
Inheriting from Base class that implements a lot of methods is not a good idea, as some of sub-classes might not need all the functionality (methods) of Base class. Also it violates design principle 2 explained in previous post.
Inheriting behavior by sub classing, set the behavior statically at compile time. And all sub-classes must inherit the same behavior. If object's behavior is extended through composition (has-a), then it can be extended dynamically at a runtime.
It is possible to add multiple new responsibilities to objects through this technique (composition), including responsibilities that were not even thought of by the designer of the superclass. And we don't have to touch their code! By dynamically composing objects, new functionality can be added by writing new code than altering existing code. This reduces chances of introducing Bugs.

Decorator pattern provides an alternative to sub-classing for extending behavior, it attaches additional responsibilities to an object dynamically. Decorators need the same "interface" as the component they wrap because they need to stand up in place of the component.
In the example code we subclass the abstract class Beverage in order to have correct type, not to inherit its behavior. The behavior is acquired by composing objects together. Decorators change the behavior of their components by adding new functionality that they achieve by wrapping the component of same type ( Since Decorator extends the same Base class as components they wrap).
Here CondimentDecorator class provides decorator interface that will wrap the objects of type Beverage ( Sub-classed from), that is why Condiment inherit from same abstract class Beverage, but it inherits from Beverage to get type so that it can wrap beverages. The behavior will be extended by composition dynamically as CondimentDecorator store reference to Beverage.

Here is the class diagram of StarBuzzCoffee




















The c++ code is build using VS2010 IDE. You can download code from here.

Saturday, May 31, 2014

Head First C++ code for Duck Simulator : A Strategy Pattern

The very first chapter in the awesome Head First Design Patterns book explains 3 fundamental design principle that forms the basis of Strategy design pattern. These principles are

  1. Identify the aspect of your application that vary and separate them from what stays the same.
  2. Program to an interface, not an implementation.
  3. Favor composition over inheritance.
The example code in Chapter 1 Intro to Design Patterns provide Java Implementation of Duck Simulator. I tried to write similar code in C++ that explains the Strategy Pattern used in the program. The behaviors of a duck that can vary (  Fly Behavior, Quack Behavior ) are encapsulated as family of classes and the non varying part ie Duck Class is base class for different types of ducks ( principle 1). Duck acts as client and make use of encapsulated family of behaviors/algorithms. This particular design is Strategy pattern and it defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that uses it.

Here is the class diagram of SimUDuck simulator

The c++ code is build using VS2010 IDE. You can download code from here.