Showing posts with label Embedded programming. Show all posts
Showing posts with label Embedded programming. Show all posts

Sunday, 2 June 2013

setjmp and longjmp

In short, functions setjmp and longjmp just work like label&goto instruction, except that the combination of label&goto only can be used within the same function which means you cannot goto the label outside the function. But the combination of setjmp and longjmp can be used anywhere in the whole program.

For example, we use label&goto to implement a jump function:

main()
{
     int a=1, b=2, c=0;
label:
     c=a+b;
     goto label;
     
}

Now we implement the same function using setjmp and longjmp:

typedef long jmp_buf[16];

main()
{
     int a=1, b=2, c=0;
     jmp_buff environment;
     setjmp (evironment);
     c=a+b;
     longjmp(evironment, 1);
}

So from above, we can see the jump buffer environment contains all the context around the setjmp function, so it works like label. And then the longjmp function will jump to the position where environment assigned.

The prototype of setjmp and longjmp:

int setjmp(jmp_buff env);
void longjmp(jmp_buff env, int val);

So function longjmp never return any value, because it will just jump the execution flow to setjmp position, but once jump to setjmp position, the setjmp function will return the value assigned by val which is the second parameter of longjmp function.

The first time setjmp function is called, it will always return 0. But after longjmp is executed, and jump to setjmp function, setjmp will never return 0. (Even if you set val to 0, setjmp will also return 1).

To make every thing more clearer, let's see an example from reference [1]:

  1. #include<stdio.h>  
  2. #include<setjmp.h>  
  3. jmp_buf ebuf;  
  4. int f2();  
  5. int main()  
  6.  {  
  7.        int i;  
  8.        printf("1");  
  9.        i=setjmp(ebuf);  
  10.        if(i==0)  
  11.        {  
  12.            f2();  
  13.            printf("This will not beprinted.");  
  14.        }  
  15.        printf("%d",i);  
  16.        return 0;  
  17. }  
  18. int f2()  
  19. {  
  20.        printf("2");  
  21.        longjmp(ebuf,3);  
  22. }  

The output of this example will print "1 2 3"


Reference: 
[1] http://blog.csdn.net/sunlylorn/article/details/7178575 

Tuesday, 17 April 2012

Common mistakes in C programming


Common mistakes about subfunction:

1. Formal parameter issues:
 
void GetMemory(char *p)
{
p = (char *)malloc(100);
}

void Test(void)
{
char *str = NULL;
GetMemory(str);  
strcpy(str, "hello world");
printf(str);
}
Using a pointer variable as formal parameter is dangerous, because formal parameter only passes the value. So it only pass the address. 

So when allocate memory to formal paramter or any other defined pointer variables in subfunction, it will disapear after the end of subfunction. Insteadly, we can achieve the same function by passing the pointer variable who points the pointer variable who is going to be allocated.
void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
if(*p==NULL)
printf(" Memory allocation fails!\n ");
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");  
printf(str);   
}

2. Variable life in subfunction:

char *GetMemory(void)
{  
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str= GetMemory();   
printf(str);
}

This program may not print the string "hello world", because although GetMemory function can return the address of the string, but the content has been destroyed after the end of the subfunction.

Monday, 16 April 2012

Pointer variable


Usually, pointer variables are with type difinition like char *, int *, long *, and like that. So when you want to  do some operations, compiler will use sizeof(type) as the unit. For example:


#include "stdio.h"

main()
{
    int a[3]={4, 5, 6};
    int *point1;
    point1=a;
    point1=point1+1;
    printf("%d\n", *point1);
    getchar();
}

Result: 5

However, we can use void * to define a point variable without type. But this variable cannot be operated because of the uncertain length of this variable. So before operation, you have to cast the variable to a specific type to do the operations. For example:


#include "stdio.h"

main()
{
    int a[3]={4, 5, 6};
    void *point2;

    point2=a;

    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);
    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);
    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);
    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);

    getchar();
}
Result:
1280  --- 00000101  00000000
5
1536  --- 00000110  00000000
6



Reference:
[1] C语言深度解剖读书笔记之----C语言基础测试题, http://blog.csdn.net/feitianxuxue/article/details/7334929

Tuesday, 13 March 2012

Principle of Floating point


Introduction:
Compared to fixed point arithmetic, floating point allows us to use both larger scope of integer and fraction in a expression because of the floating exponent. 
A floating point memory block is composed of sign flag, exponent(2^e) and mantissa. The format is shown below.
64-bit floating point (double)

32-bit floating point (float)


  • We need the exponent part to be signed, so the compiler will subtract the q with a bias. The calculations are shown below.
e=q-bias

The number the format above represents is:
Here you must remember it is 1.M which is we call "significant figure" (有效数字). So when you do the some arithmetics, you have to ensure you shif the number to keep there is a "1" in the left of ".".

Precision of floating point:

Because the significant digits(有效数字) only have sizeof(M) bits, so the precision of floating point is only 2^(-sizeof(M)-1) (here we have a virtual bit). When a number is smaller than this precision, it will not be represented any more.

On the other hand, if the number exceeds 2^(sizeof(M)+1), its precision cannot be guaranteed anymore, which is also because the significant digits(有效数字) have limited bits (sizeof(M)). If a number exceeds the those significant digits, there is no enough room for the extra precision which will be missed. An example about this is shown below.

     #include <stdio.h>


     main()
     {
         int x;
         float y;

         x=1;
         while (x>0)
         {
             y=x+1;
             x=y;
         }

     }

This program will never end, because x will never overflow. When x exceeds the significant 
digits(有效数字), y cannot increase anymore. So this program will be stuck at x=16777216 (2^24).

The arithmetic (addition & subtraction) of floating point:
Here we talk about how to do addition and subtraction of floating point. As we know when we want dto do addition or subtraction of numbers with exponent, we have to align the exponent first. The floating point calculation needs the same operation.

So here we use shift on mantissa and increase on exponent to solve this problem. We start from the smaller number. When we shift the mantissa 1 bit to left, we increase the exponent by 1, until the exponent is equal to the bigger number. 

For example, we try to add 100.0 with 0.25 whose formats are "0 10000101 10010000000000000000000" and "0 01111101 00000000000000000000000" respectively. 

Then we start to shift 0.25:

0 01111101 00000000000000000000000 (original number)
0 01111110 10000000000000000000000 (right shift 1)
0 01111111 01000000000000000000000 (right shift 2)
0 10000000 00100000000000000000000 (right shift 3)
0 10000001 00010000000000000000000 (right shift 4)
0 10000010 00001000000000000000000 (right shift 5)
0 10000011 00000100000000000000000 (right shift 6)
0 10000100 00000010000000000000000 (right shift 7)
0 10000101 00000001000000000000000 (right shift 8)

Then we add 0 10000101 10010000000000000000000 with 0 10000101 00000001000000000000000.

                 0 10000101 10010000000000000000000
+ 0 10000101 00000001000000000000000
-----------------------------------------------------------
                 0 10000101 10010001000000000000000
                                           ||
                                     100.25



References:
[1] Chapter 7 -- floating point arithmetic, http://pages.cs.wisc.edu/~smoler/x86text/lect.notes/arith.flpt.html

Magic of union


"union" is very useful C type which allows you to share the same memory block when using different types of variables. Although, the types of variable is different, but the content of the memory they share is the same. So by this way you can "read" the content by using shift and "&" operator if the content is formated and assigned by compiler.

Anyway, just remember "union" makes its members share the same memory block, and the size of memory block depends on the longest member.

The following is an example to show how to use "union" to transfer floating point to binary.

#include <stdio.h>

union ufloat /*here we share the unsigned integer and float variable in the same location*/
{
     float f;
     unsigned int i;
};
void print_float(float a)
{
     char bin[32]={0};
     char index=0;
     int tmp;
     ufloat u1;

     u1.f=a;
     tmp = u1.i; /*here we get the decimal conversion of float variable*/
    
     for(unsigned int j=1;j>0;j<<=1)
     bin[index++]=(tmp&j)?1:0; /*here we convert the decimal number into binary*/
     printf("output: %d ", bin[31]);
     for(char j=30;j>=0;j--)
     {
          printf("%d",bin[j]);
          if(j==27 || j==23 || j==19 || j==15
             || j==11 || j==7 || j==3)
          printf(" ");
     }
     printf("\n");
}
int main()
{
     float x=1.5;
     print_float(x);
     return 0;
}

Results:
output: 0 0111 1111 1000 0000 0000 0000 0000 000

Tuesday, 14 February 2012

The differences between array and pointer


In fact, the name of array and pointer are totally different stuff. 
The name of array represents a certain kind of data structure of array.
For example, when you declare an array with "char amessage[]= "now is the time" ". Then declare a pointer with "char *pmessage="now is the time"".
Then array amessage is built as a data structure which contains the whole copy of string "now is the time". However pointer pmessage just contains the address of the string literal.


So the size of amessage is 16, however the size of pmessage is only 4.
But why sometimes the name of array can be used as pointer?
This is because of the compiler. When the compiler finds that the name of array appears in the right of a statement without index, the compiler will make it act as pointer - something like &amessage. 
But whatever the name of array is not pointer after all, so it cannot appear in the left of statement.

Compile the following code, you can also get the conclusion we talked above.
#include <string.h>
#include <iostream.h>
int main (int argc, char* argv[])
{
     char str[10];
     char *pStr = str;
     cout << sizeof(str) <<endl;
     cout << sizeof(pStr) <<endl;
     return 0;
}

However, when the name of array appears as formal parameter in subfunctions, it becomes a pointer, because we are not supposed to declare a large formal parameter, or a parameter which is fixed with some value. So from these points, pointer is the best choice.

Summary:
  • The name of array is not pointer, it is just a data structure.
  • The name of array cannot appear in the left of statement.
  • When the the name of array appears as formal parameter in subfunctions, it becomes pointer.



References: 
[2] 在C语言中"指针和数组等价"到底是什么意思? http://c-faq-chn.sourceforge.net/ccfaq/node78.html

Sunday, 12 February 2012

Software Requirement Specification


Software Requirement Specification

What is SRS and its usages?

SRS (Software Requirements Specification) is used to describe the behavior of a system. SRS should include functional requirements and non-functional requirements. Funcational requirements tell you about what the software is used for and how it interact with users. Non-functional requirements tells how good the software should perform. Basically, it is some constrains imposed on the design and implementation (Remember every system has constraints, otherwise you will be able to do anything you want, that is unreasonable. So when you try to do something in life, find the constraints. This is not just about software development, it is pratical for everything). Take game development as an example. Functional requirement should think about what kind game it is, how to play it, how the players operate the console, etc. And non-functional requirements should consider how much footprint will be used, how the performance, the reliability (it should not go to crash frequently during playing), etc.
So SRS can be used as the guidance during the whole development period. It can be used as the basis of testing.

How to form a good requirements statement?

A good requirement should contain: Capabilities, Conditions, Constraints. 
However in the beginning, maybe you did not have an overall understanding of the system, so you can just state some capabilities, but as the progress carries on, you must complete the statements with conditions and constraints, otherwise the program cannot proceed.
  • Here ca pabilities are used to describe what the embedded system shall or must do.
  • Conditions are measurable qualitative or quantitative attributes and characteristics associated with the capability.One thing you need to know is when you implement one function. It must be associated with numbers or options. For example, when you design a blockbreaker game, you cannot just say I need to design blocks, panel and ball. You should say how many and how big blocks are, and the size of panel and ball, etc. Otherwise it is unrealizable.
  • Constraints is some limitations imposed on the requirements by circumstances, force or compulsion. It is something makes you design software in a limited environment, where you cannot do whatever you want. You should always be aware of these constraints when you design. For example, when you design a blockbreaker game, you should say these blocks should exist in a limited size of screen.
How to obtain requirements?

1, Getting Inputs
Get inputs from customers, environment and technical community.
Cusomers can provide:

  • Concept of operations/system concepts. Here we can know how the user operate the machine.
  • Marketing specifications
  • Request for proposals
  • External interfaces
    • Computer to computer
    • User to computer
    • Computer to sensors and actuators
    • Computer to data links
  • Feedback
Enviroment camn provide:
  • Political influence. For example, some countries may not allow some services, or they may require that the language on device have to be their local language.
  • Market influence
    • Market needs
    • Distribution and accessibility
    • Competition
  • Standards and Technical policies influence
  • Cultural influence. For example, you design a game in Iran, when players win, you put a THUMB UP picture in the end, they will kick your ass.
  • Organizational influence
Technical community can provide technical feedback from various perspectives:
  • Desgin
  • Implementation
  • Integration
  • Test
  • Manufacturing
  • Deployment
  • Operations
  • Maintenance
2, Identify and Analyze Requirements
Then we need to identify and analyze the requirements from inputs. Here you can discuss with customers, do surveys, observations, reverse engineering, simulations or prototyping, etc to identify and analyze the requirements. The goal of requirements analysis is:
  • Identify implicit requirements from the inputs and derive further requirements.
  • Identify mis-match or inconsistencies between requirements.
  • Identify missing requirements for further discussions with customers.
  • Identify missing requirements for further discussions with customers.
  • Identify workflow, patterns of behavior, attributes, system modes, data flow or capacity.
Techniques to analyze requirements:
- Scenario Analysis (Try to imagine scenario how users will use the system, and how the system response to users):
  • Very effective in systems involving some form of external stimuli (system interacting with some users)
  • Can be expressed in terms of use cases, sequence diagrams, flow charts, activity diagram, statecharts.
  • Starts with customers describing typical use scenarios.
  • Proceeds to consider different users or actors involved in the use of the system.
  • Exception scenarios are conceptualized, using various entry points in the typical use scenarios and asking "What if".
- Functional Analysis (analyze the functions the system contains, and try to analyze each function):
  • Very effective in analyzeing the inernals of the system
  • Very useful for autonomous and embedded control systems analysis
  • Often represented using function diagrams, data flow diagrams, control flow diagrams and even entity relationship diagrams
  • Starts with the interfaces and identify functions
  • Trace the data flows and event flows, to understand how data and event flows are handled
In most cases, scenario analysis and functional analysis are combined together to do requirements analysis. Scenario analysis is used when we design interfaces which need to interact with users, because here designers and customers can imagine how the user will operate it. And functional analysis is good for analyzing the internal functions of system: how many modules the system is composed of, how the data flow is passed. Functional analysis is for designers' perspectives. There are functional analysis examples from answering machine:

   
Function diagram
Data flow diagram
Event flow diagram
3, Organize and Review Requirements
When you finish all the requirement analysis, then organize well the requirements and make sure the requirements are:
  • Requirements are well-organized
  • Well formed. Follow the rules of capability, condition and constraints.
  • Readable.
    • Use a data dictionary to explain unique terminologies
    • Write with the customers or reviewers in mind
  • Testable. Keep testing of the software in mind, to make sure the test team can understand the testing tasks clearly, which can help the test team to test the system. Don't put them in a terrible situation where they think what the hell should I do holding the requirement specification document.


References: 
[1] List of system quality attributes, http://en.wikipedia.org/wiki/List_of_system_quality_attributes
[2] IEEE Recommended Practice for Software Requirements Specifications

Wednesday, 1 February 2012

Programming tricks


  1. Swap the contents of two registers.
    XOR R0, R1
    XOR R1, R0
    XOR R0, R1

    Remember "1" in result means differences, while "0" means same. However when the number apears in operation of XOR, "1" means reverse and "0" means keep.
  2. To judge if two numbers are equal, we can also use XOR.
    XOR R0, R1
    If the result is 0, then R0 and R1 are equal. Otherwise they are not.
  3. Struct type allows the specification of elements of a structure into a fixed number of bits.
    struct fivebits
    {
        unsigned int flag : 1; 
    // act as switch, on (1) or off (0)
        signed int num   : 4; // number ranges from -8...7
                                : 3; // empty 3 bits used to align to 8bits, this is necessary for manipulation
    }

Friday, 27 January 2012

Byte Alignment


Byte Alignment, actually is designed for realizing the convenience of memory addressing, to improve the speed of addressing. To understand it, we gonna talk about the difference between using Byte Alignment and non-Byte Alignment:

struct A { 
    char c; 
    int i; 
}; 
struct A a;

We use the structure above to explain the function of Byte Alignment. Without Byte Alignemnt, the address of variable c is 0x00, and the address of i is 0x01. If the addressing scope  of cpu is 4 bytes, we will need two read cycles to get i. Variable c need a read cycle to be read, however variable i need two read cycle to be read because there are three bytes of i in 0x01, 0x02, 0x03 which are read in the variable c read cycle. So when the cpu read the 0x04, it has to connect the three bytes 0x01, 0x02, 0x03. As we see, we need two read bytes to get i, it is low efficient.
However, if we set the byte alignment=4, problem will be solved, because by doing this, we make 0x01, 0x02, 0x03 in vain and set 0x04 as the address of variable i. And variable i can be read for just one cycle. Although three bytes have been wasted, we improve the efficience of addressing.

Sunday, 22 January 2012

Make ARM program using IAR Embedded Workbench IDE


Build a project: Project -> Create New Project.
After create a project, you can programm C code in file window. When you finish programming, you need to configure the project first.
Open project option: Project -> Options.
In the General Options category, you can configure the type of Processor Core or Chip Device. And click the third tab Code under  sub category C/C++ Compiler, you can set the Processor mode: Arm or Thumb.

In the Debugger category, you can set the Diver for Simulator, J-Link, J-Trace, Third-Party Driver or something else.
If the Driver above, you choose Third-Party Driver, then in Debugger -> Third-Party Driver, you can choose the path of the Third-Party Driver.

After the configuration, you can compile and make the C code. Then click the button "Download and Debug", must beware not "Debug without Downloading".
Once entering Debug mode, you can see Register, Memory, and the most important item Disassembly in the View option. (Here beware again that before entering Debug mode, you cannot click button "Debug without Downloading", it has to be "Download and Debug").

Chapter 3 — The Molt

(This story is written by me and I will be posting it on Royal Road. Profile: https://www.royalroad.com/profile/1129550/fictions) Six fifty ...