Wednesday, November 16, 2016

Embedded Toolchain selection criteria's

For selecting proper toolchain for your embedded project following are the questions that you should ask to yourself:

  1. Do you prefer a commercial quality product that gets the job done, or is it more important with a free or low-cost solution that may or may not work as intended?
  2. What is the cost of project failure or delay? Does senior management accept that commercial risk, in return for a few dollars saved on tool purchase?
  3. Are powerful tool capabilities or short learning curve and ease of use of primary interest?
  4. Do you want to conform to the new open industry standards, such as the ECLIPSE IDE and the GNU gcc/gdb compiler and debugger toolchain, or rely on proprietary products with a vendor lock-in?
  5. Do you want to work in an open and thriving tools eco system (the ECLIPSE IDE with its vast Eclipse plug-in eco system comes to mind here), or is extensibility and flexibility less of an issue?
  6. Do you want a tool that only fits the needs right now, or do you want to future proof yourself with a tool that you can grow with as your needs increase over time?
  7. Do you just need a basic edit/compile/debug IDE, or are you looking for a more complete embedded development platform, with features for software quality (such as MISRA-C coding standards checking, code complexity analysis), team collaboration (version control system and bug database GUI integration), advanced debugging (hard fault crash analysis, event/data/instruction tracing, dual-core debugging, RTOS aware debugging) and so on?
  8. Do you need technical support and perhaps also training options, providing a safety net in case you run into problems?
  9. Do you need deep integration with STM32 technologies, like STM32CubeMx and ST-LINK?
While selecting Toolchain following features should looked for in feature list:

  • Event- and data tracing
  • System profiling
  • Instruction trace: record your program's execution, instruction-by-instruction
  • RTOS-aware debugging
  • Hard fault crash analysis
Following are some interesting links that I came across
http://blog.atollic.com/what-is-the-best-ide-tool-for-professional-stm32-development

Embedded Toolchain selection criteria's

For selecting proper toolchain for your embedded project following are the questions that you should ask to yourself:

  1. Do you prefer a commercial quality product that gets the job done, or is it more important with a free or low-cost solution that may or may not work as intended?
  2. What is the cost of project failure or delay? Does senior management accept that commercial risk, in return for a few dollars saved on tool purchase?
  3. Are powerful tool capabilities or short learning curve and ease of use of primary interest?
  4. Do you want to conform to the new open industry standards, such as the ECLIPSE IDE and the GNU gcc/gdb compiler and debugger toolchain, or rely on proprietary products with a vendor lock-in?
  5. Do you want to work in an open and thriving tools eco system (the ECLIPSE IDE with its vast Eclipse plug-in eco system comes to mind here), or is extensibility and flexibility less of an issue?
  6. Do you want a tool that only fits the needs right now, or do you want to future proof yourself with a tool that you can grow with as your needs increase over time?
  7. Do you just need a basic edit/compile/debug IDE, or are you looking for a more complete embedded development platform, with features for software quality (such as MISRA-C coding standards checking, code complexity analysis), team collaboration (version control system and bug database GUI integration), advanced debugging (hard fault crash analysis, event/data/instruction tracing, dual-core debugging, RTOS aware debugging) and so on?
  8. Do you need technical support and perhaps also training options, providing a safety net in case you run into problems?
  9. Do you need deep integration with STM32 technologies, like STM32CubeMx and ST-LINK?
While selecting Toolchain following features should looked for in feature list:

  • Event- and data tracing
  • System profiling
  • Instruction trace: record your program's execution, instruction-by-instruction
  • RTOS-aware debugging
  • Hard fault crash analysis
Following are some interesting links that I came across
http://blog.atollic.com/what-is-the-best-ide-tool-for-professional-stm32-development

Friday, September 23, 2016

Technologies and there purpose

ARM + DSP: Technology increase the DSP processing capability of  ARM. It is useful in applications like audio video codec implementation in handheld  devices, Motor control, Voice and handwriting  recognition, embedded control, FFT processing, Filtering techniques implementation for image processing.

Neon Co-Processor:  Single Instruction Multiple Data (SIMD) kinds of operation for faster results. Its application is mostly in multimedia format encoding and decoding

ARM VFP (hardware Floating Point Unit ): Provided hardware for double precision and single precision floating point arithmetics. Useful in applications like Automotive sector (ABS, Traction control etc.), 3D Graphics (Digital consument products), Imaging (Digital camera), Industrial (Motion control)

Jazelle: High performance, Low power and Low cost environment for ARM architecture. It improves multi-tasking performance of ARM. ARM Jazelle technology software is a full featured multi-tasking Java Virtual Machine (JVM), highly optimized to take advantage of Jazelle technology architecture extensions available in many ARM processor cores. Its basically makes ARM processor support Java in all better ways.

TrustZone: Technology build on system on-chip. Used for providing system wide security.

Thursday, September 22, 2016

Controlled variable memory assignment in a EMBEDDED system code: Example

Following is an example of writing embedded code, where you control the space allocation for the variable using different coding technique.

Code is executed on Keil uVision IDE: IDE-Version: µVision V5.20.0.39
Using simulator

C Compiler:      Armcc.exe V5.06 update 1 (build 61)
Assembler:       Armasm.exe V5.06 update 1 (build 61)
Linker/Locator:  ArmLink.exe V5.06 update 1 (build 61)

startup file used: startup_ARMCM4.s
CMSIS device system source file: system_ARMCM4.c
(Startup code are auto generated by Keil, during the project creation process)

-->user_main.c



int __main(void)
{


/******** Accessing IRAM memory address using pointers *******/

unsigned int *ptr_a = (unsigned int *)0x20000000;
unsigned int *ptr_b = (unsigned int *)0x20000010;
unsigned int *ptr_c = (unsigned int *)0x20000020;
unsigned int *ptr_d = (unisgned int *)0x20000030;
*ptr_a = 9;
*ptr_b = 3;
while (1)
{
*ptr_c = (*ptr_a) * (*ptr_b);
*ptr_d = *ptr_c - *ptr_a;
*ptr_c = *ptr_d - *ptr_a;
(*ptr_a)++;
(*ptr_b)++;
}



/******** Auto addressing assignment for variables in IRAM *******/
/*
static unsigned int a = 0x10;
static unsigned int b = 0x11;
static unsigned int c = 0x12;
static unsigned int d = 0x13;
a = 9;
b = 3;
while (1)
{
c = a * b;
d = c - a;
c = d - a;
a++;
b++;
}
*/


/******** Absolute addressing assignment for variables in IRAM *******/
/*
static unsigned int a __attribute__((at(0x20000000))) = 0x10;
static unsigned int b __attribute__((at(0x20000010))) = 0x11;
static unsigned int c __attribute__((at(0x20000020))) = 0x12;
static unsigned int d __attribute__((at(0x20000020))) = 0x13;
a = 9;
b = 3;
while (1)
{
c = a * b;
d = c - a;
c = d - a;
a++;
b++;
}
*/


/******** Inlining Embedded ARM cortexM4-F assembly code into C code *******/
/*
__asm
(
"MOVS r0, #0x10 \n"
"MOVS r1, #0x11 \n"
"MOVS r2, #0x12 \n"
"MOVS r3, #0x13 \n"
);
while(1)
{
__asm
(
"MUL r2, r0, r1 \n"
"SUBS r3, r2, r0 \n"
"SUBS r2, r3, r1 \n"
"ADDS r0, r0, #0x01 \n"
"ADDS r1, r1, #0x01 \n"
);
}
*/


}


Execute various segments of code one at a time to see the effect.
Run the code in debug mode.

Tuesday, September 20, 2016

7segment Display driver IC selection and connection



7 segment display are of type common:

  1. Common Anode
  2. Common Cathode
Display can be:
  1. Single Digit
  2. Multiple multiplexed digits
In these cases, the current to be driven through these segments and digits is more as compared to the current source/ sink capacity of micro-controller GPIO pins. Hence the drivers come in to picture.

Drivers are of types:
  1. HIGH side driver IC (UDN2981)
  2. LOW side driver IC (ULN2803)
Common anode configuration:
  1. It is better to go with LOW side driver, as the cathode of each segment can be connected to separate darlington pair inside driver IC to sink the current.
  2. At the anode side, single PNP(BC557) transistor can  be connected. In case of multiple digits, separate PNP transistors to be connected for each digit. 
  3. Base of each transistor will be controlled by GPIO through a series base resistor
  4. GPIOs will also be connected to driver input through a series current limiting resistor
Common cathode configuration:
  1. It is better to go with HIGH side driver, as the anode of each segment cab be connected to separate darlington pair inside driver IC to source the current.
  2. At the cathode side, single NPN (BC547) transistor can  be connected. In case of multiple digits, separate NPN transistors to be connected for each digit.
  3. Base of each transistor will be controlled by GPIO through a series base resistor
  4. GPIOs will also be connected to driver input through a series current limiting resistor

In both cases care to be taken:

  1. Care should be taken that only 1 digit is ON at a time.
  2. All n-digits can be displayed by maintaining high refresh rate of the display (eg. 180Hz)
  3. Based on Vce voltage and Isource/sink, the Power(Pd) dispation through every pin of driver can be estimated. Pd(W) * (degC/W) rating of the driver should be less than the Maximum junction temperature rating of  the driver. Otherwise driver IC is on the "Stairway to heaven" :)
More better option,
  1. There are also driver IC options like MAX7219, which have both the HIGH side and LOW side driver in the package. 
  2. MCU communicate to driver over SPI, sending digit to be displayed.
  3. Driver takes care of refresh rate (eg. 500Hz for 8 digits)
  4. Driver handles the intensity of digiti display (Layman terms  'brightness')
  5. MCU dont need to update all digits at all time, even if one digit in the number is to be modified.
Diagram where all options are merged into one:

Thursday, September 15, 2016

Important things to study

Curve fitting
- regression
- interpolation: Its is required in situation where we need to estimate peak of signal based on limited set of discrete values.
- Fourier approximation

Linear curve fitting: this kind of curve fitting introduces discontinuity in the curve
Polynomial curve fitting: removes discontinuity from the curve
Spline curve fitting:  sometimes polynomial curves make the curve fitting way too distorted by what is expected. In such scenarios spline is a better options. It behaves more like linear, but removes discontinuity from the curve.

Continuous wave Fourier transform
Discrete wave Fourier transform O(n^2)
Fast Fourier transform O(n. log2(n))

Why discrete FT required in practical applications?
--> Real life data is discrete. And DFT provided fast method of find frequency components. If Continuous FT is to be used, first interpolation is required to be done & then followed by CFT.

Why FFT is required is DFT is already there ?
--> FFT is even fast method of finding frequency content in the discrete data.

Where CFT is required practically?
--> Problems w


Significance of ROOT MEAN SQUARE: Its is derived from AC current. When AC current is passed through resistive load, the dissipate power will be same as the power dissipate when DC current of value equal to RMS of AC current is passed through same resistive load.

Mean
Variance
Standard deviation

IPC - POSIX Shared Memory

shmget() system call - create shared memory
shmat() system call - process that wish to access the shared memory  must attach it to their address space
shmdt() system call - when process no longer wish to access the shared memory, it can be detached from the address space using this call
shmctl() system  call - remove shared memory from system

Other processes that wish to access this shared memory must first attach to it using shmat()

---------------------------------------------------------------------------------------------
IPC_sharedmemory.c
---------------------------------------------------------------------------------------------


Wednesday, September 14, 2016

JTAG, SWD and debugWIRE: How are they different ? Its always a question ..... Let me clarify

JTAG - Joint Test Application Group
- Its used for verifying design and testing PCB after manufacturing
- Its referred as IEEE Standard 1149.1
- Standard Test Access Port and Boundary-Scan Architecture
- Programming and debugging both can be done using JTAG

Physical interface:

  1. TDI (Tets Data In)
  2. TDO (Test Data Out)
  3. TCK (Tets Clock)
  4. TMS (Test Mode Select)
  5. TRST (Test Reset)
Daisy chain way of using JTAG

Example of JTAG chain


SWD - Serial Wire Debug

Serial Wire Debug (SWD) is debug port for microcontroller where package is small, or small number of pins.
Its used mostly in ARM architecture chips
SWD is availabel as a part of Core Sight Debug access port
Compatible with all ARM processors, and any processor that uses JTAG
- Programming and debugging both can be done using SWD
Physical interface: 
  1. SWCLK (Serial Wire Clock)
  2. SWDIO (Serial Wire Data In and Out)
In case when SWD is used for JTAG based process
  1. SWCLK --> TCK
  2. SWDIO --> TMS
With SWD protocol, the debugger is connected to AMBA bus as another master, using which debugger can access ARM core system and peripheral memory

NOTE:
Ofcourse, VCC and GND need to be common between In-Circuit-Debugger/Programmer and Processor

SWO (Serial wire out) wire is used sometimes along with SWCLK and SWDIO.
Some of the programmer and debuggers like STLINK provide debugging utility like printf(), which are very useful. These utilities use SWO wire to send serial data over it to PC. But here you need to set the system clock value correctly in the serial debug viewer configuration on PC.

debugWIRE

debug WIRE is a single wire interface provide in most Atmel AVR microcontrollers.
Its even more beneficial compared to JTAG and SWD as its very useful in places where package pin count is very small. On-Chip-Debugger (OCD) is provided on silicon itself by Atmel. dW single wire is internally connected to OCD. Whenever BREAK instruction (Software breakpooint) or (Hardware breakpoint) is observed by OCD, the CPU core operation is stopped and halted. All the SRAM, Peripheral register values, IO status information is sent by OCD over dW wire to the External Debugger unit(JTAGICE3). It will convert dW information to USB so that information could be sent to PC. On PC there will be a Debug software program which will grab the data and display it. Debug software running on PC will be a part of AtmelStudio.
- Only debugging both can be done using debugWIRE
- SPI interface is used for programming where dW debug interface is used



Physical interface:
Single wire dW.
Its a alternate functionality for RESET pin of the micro controller.

Microcontroller oscillator circuit working

 Circuit consists of two parts: an inverting amplifier that supplies a voltage gain and 180° phase shift and a frequency selective feedback path. The crystal combined with Cx and Cy form a tuned PI network that tends to stabilize the frequency and supply 180° phase shift feedback path. In steady state, this circuit has an overall loop gain equal to one and an overall phase shift that is an integer multiple of 360°. Upon being energized, the loop gain must be greater than one while the voltage at XTAL grows over multiple cycles. The voltage increases until the NAND gate amplifier saturates. At first glance, the thought of using a digital NAND gate as an analog amplifier is not logical, but this is how an oscillator circuit functions.


Friday, September 2, 2016

Important specs while selecting MCU


  1. Memory architecture: Von-neumann or Harvard or Modified Harvard
  2. Instruction set architecture: RISC or CISC
  3. Operating frequency
  4. CPU operating modes
  5. Coremark benchmarking results of MCU. Or results like matrix multiplication/inverse calculation, FFT etc. related benchmarking is good to judge MCU.
  6. Application category based selection: Ultra low power, Mainstream, High performance (as in case of ST)
  7. Peripheral available on MCU
  8. Number of Timers: Basic, Genereal purpose and High resoluation
  9. Number of external interrupt lines.
  10. Number of internal interrupt lines.
  11. DMA necessary when large data transfers are important in application.
  12. CRC and MPU (memory protection unit):
    1. CRC is used while compiling teh binary and writing data to Flash. Its is then decoded using the same CRC to verify the read instruction is correct, inside CPU
    2. MPU is used mostly in RTOS level applications, where we need isolation between kernel area and user domain. This protects the kernel memory area from user code intervention
  13. FPU (Floating point unit): Its is necessary when there are many floating point multiplications and divisions in the code. This makes the code execution very fast, as compared to the software FPU implemetation (aebi_vfpu())
  14. ADC: High sampling rate, Effective number of bits (ENOB), Resolution. Also look for internal temperature compensation availability as it helps if compensation of temperature drifts in the application. 
  15. Communication peripherals: I2C, SPI, UART
  16. Analog peripheral on chip: programmable gain OPAMP, Analog COMPARATORs. These are necessary for applications where they play role in reducing cost of products, by decreasing cost of external components required.
  17. Power consumption in various modes. This is particulary important when you are dealing with portable device applications like electronic handheld device, smart watch etc.

Sunday, August 7, 2016

GPIO internal modes


Very basic thing but still very important for every Electronic engineer to understand.
Stop throwing around terms like high impedance, push pull, open drain......
First understand the meaning and then speak with confidence :)




Monday, April 25, 2016

printf, fprintf, sprintf and printk..... whats the difference ?

There are basically 3 standard "streams"

  1. stdin - standard input stream
  2. stdout - standard output stream
  3. stderr - standard error stream
fprintf(standard stream, "message");  //message is sent to the mentioned stream

printf("message"); //message is sent to stdout. so it is as good as writing fprintf(stdout, "message")

#define BUFFER_SIZE 50
char *ch_arr = (char *)malloc(sizeof(char) * BUFFER_SIZE);
sprintf(ch_arr,  "message"); //message is sent to char buffer whose pointer is passed as argument

printk(KERN_IMERG "message");  
//used to print message to kernel log file. Hence it can only be called from kernel only

IPC: Process communication using PIPE

Pipes are basically used for communicating information between two processes.



There are two types of pipes:
  1. ordinary pipe
  2. Named pipe

Ordinary Pipe:

  • simple pipes are unidirectional in nature (one-way comm)
  • two-way communication can be achieved by creating 2 pipes
  • pipe cannot be accessed from the outside the process that creates it
  • Hence it is used mostly for parent and child process communication

creation and use:


  • pipe() function is used to create a pipe. This actually creates special file
  • read(), write(), close() system calls can be used to access this file
  • int file_descriptor[2] array is used as file_descriptor to access file.
    • file_descriptor[0] = read from file
    • file_descriptor[1] = write to file
  • one of the file descriptor(read/write) should be closed in the respective process to make it unidirectional. This is done to avoid Deadlock condition and exploit parallelism

Named Pipes:

  • named pipes are like FIFOs
  • created using mkfifo() system calls and opereated using open, read, write and close(0 system calls
  • they appear as files in file system once created
  • they remain as it is until they are deleted explicitly
  • multiple process on same machine can use named pipe
  • For communication over network, socket wrapper need to be used
Named pipe Example:
$mkfifo demo_fifo
$exec 3<> demo_fifo
$ls -l >&3
$cat demo_fifo

mkfifo - create named pipe
exec - to a assigned 3 as file descriptor for named pipe
$ls -l >&3  add output of ls -l to named pipe
cat - read the data from named pipe

Following is example of Ordinary pipe:
---------------------------------------------------------------------------------
linux_pipe.c
---------------------------------------------------------------------------------

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 50
#define READ_END 0
#define WRITE_END 1

int main(int argc, char *argv[]){
char write_msg[BUFFER_SIZE] = "message over pipe";
char read_msg[BUFFER_SIZE];
int file_descriptor[2];

pid_t pid;

// create pipe
if (pipe(file_descriptor) == -1){
fprintf(stderr, "ERROR: Pipe creation failed");
return 1;
}

pid = fork(); // fork process
if (pid < 0){ // process forking failure
fprintf(stderr, "ERROR: Process forking failure");
}
else if (pid == 0){ //this is child process
printf("Inside child process\n");
close(file_descriptor[WRITE_END]); //close the write end of the pipe
read(file_descriptor[READ_END], read_msg, BUFFER_SIZE); //read message from pipe. wait until message is received
printf("Read data = %s", read_msg);
close(file_descriptor[READ_END]); //close read end of the pipe
}
else { //this is parent process
sleep(5); //Too verify child waits at read() for 5sec until it receives message
close(file_descriptor[READ_END]); //close read end of the pipe
write(file_descriptor[WRITE_END], write_msg, strlen(write_msg) + 1); //writing message to pipe
printf("Task of writing message to pipe completed\n");
close(file_descriptor[WRITE_END]); //close write end of the pipe
}

return 0;
}


---------------------------------------------------------------------------------
output
---------------------------------------------------------------------------------

Inside child process

Task of writing message to pipe completed
Read data = message over pipe

Wednesday, April 20, 2016

Clarification on hierarchy.... GTK+, GDB, GLib and GNU C ibrary

GNU C Library(glibc) - wrapper around linux kernel and it communicates to kernel via system calls. Its the implementation of the C standard library.

GLib - It uses GNU C Library to use linux kernel resource. All basic & advanced data structures, thread creation, IPC related & processes can be called through GLib API. It provides Main loop functionality which is used in applications like DBus (GDBus).

GDK(GIMP Drawing Kit) - Its a drawing tool used to communicate to graphical system. It provides API using which we can communicate with display device driver  easily.

GTK+(GIMP Toolkit) Its a UI development toolkit, a level above which is used to design UI for the applications. It makes the code portable from various OS, as the code once written using GTK+, we can cross-compile it to any platform. GNOME linux GUI is built using GTK+.

Now a days, people prefer using Qt, as it provides rich set of APIs to construct beautiful UI and as well as portable from OS to OS and device to device.

IPC: Message queue with example

Message queue

Message queue is a type of inter process communication. It is used to transfer data between processes. It is asynchronous communication as in, sender can dump data in queue, and receiver can get the data out at its convenience.

Parameters of queue:

  1. Queue ID
  2. Key
  3. Message structure:
    • type
    • text

Method calls:

  1. msgget()
  2. msgsnd()
  3. msgrcv()

Applications:

  1. VxWorks and QNX encourage the use of message queue for inter-process & inter-thread communication
  2. It provides resilience functionality as the message dont get "lost" in communication in case of system failure.

Example:

Sender code - creates queue and enter message into it with a particular key
Receiver code - Access the queue, gets the message and prints the text. If while receiver process execution data is not available in queue, it waits at msgrcv(), and proceeds when it gets some data.

Shell command to view the queue IPC
$ipcs -q

*******************************
sender.c
*******************************
/*
 * sender.c
 *
 *  Created on: 19-Apr-2016
 *      Author: root
 */

//IPC_msgq_send.c

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE     128

void die(char *s)
{
  perror(s);
  exit(1);
}

struct msgbuf
{
    long    mtype;
    char    mtext[MAXSIZE];
};

main()
{
int count = 0;
//char data[3][MAXSIZE] = {"first", "second", "third"};
    int msqid;
    int msgflg = IPC_CREAT | 0666;
    key_t key;
    struct msgbuf sbuf;
    size_t buflen;

    key = 1234;

    if ((msqid = msgget(key, msgflg )) < 0)   //Get the message queue ID for the given key
      die("msgget");

    //Message Type
    sbuf.mtype = 1;

    printf("Enter a message to add to message queue : ");
    scanf("%[^\n]",sbuf.mtext);
    getchar();

    buflen = strlen(sbuf.mtext) + 1 ;

    while (count < 3){
    //*sbuf.mtext = data[count];
    //buflen = strlen(sbuf.mtext) + 1 ;
if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
{
printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buflen);
die("msgsnd");
}
else
{
printf("Message Sent\n");
}
count++;
    }
    exit(0);
}

*******************************
receiver.c
*******************************
/*
 * receiver.c
 *
 *  Created on: 19-Apr-2016
 *      Author: root
 */

//IPC_msgq_rcv.c

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE     128

void die(char *s)
{
  perror(s);
  exit(1);
}

typedef struct msgbuf
{
    long    mtype;
    char    mtext[MAXSIZE];
} ;


main()
{
    int msqid;
    key_t key;
    struct msgbuf rcvbuffer;

    key = 1234;

    if ((msqid = msgget(key, 0666)) < 0)
      die("msgget()");


     //Receive an answer of message type 1.
    if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
      die("msgrcv");

    printf("%s\n", rcvbuffer.mtext);
    exit(0);
}

--------------------------------------------------------------------------------------------------

OUTPUT:

$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    


$./sender
Enter a message to add to message queue : text data to trasmit
Message Sent
Message Sent
Message Sent

$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    
0x000004d2 0          root       666        63           3           

$./receiver
text data to trasmit

$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    
0x000004d2 0          root       666        42           2           

$./receiver
text data to trasmit

$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    
0x000004d2 0          root       666        21           1           

$./receiver
text data to trasmit

$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    
0x000004d2 0          root       666        0            0           


Monday, March 7, 2016

ADC parameter understanding

ADC - Analog to digital converter

  1. Resolution: no. of bits (8/10/12/... bits)
  2. Input clock frequency (MHz)
  3. Pre scalar
  4. Sampling frequency
  5. Channels
  6. Single / Differential channel
  7. Vref (Reference voltage)
  8. VDD (Supply voltage)
Example: if input locking frequency for ADC is 18MHz
Prescalar values varying from 1, 2, 4, 8 to 64

Clock frequency = Input clock frequency / Prescalar
Sampling frequency = Clock Frequency / No. of clock required for single conversion

No. of clock required for single conversion = No. of bits + x
x = varies from ADC to ADC. But is usually 3 to 5 bits

So, in our case, if its a 12-bit ADC and x=6 and prescalar = 1
then, 
Clock frequency  = 18MHz;
Sampling frequency = 18MHz/18 = 1Msps (1 mega samples per second)

EOC (End of conversion) line signal is present in each ADC and can be used as interrupt for ADC ISR.



If no of channels are more, then Time required for signal conversion further increases. In our case, if 8-channels are used, then

Conversion frequency = Sampling frequency / No. of channels

Resolution is achieved over the 0V to Vref range
Vref max limit = VDD
Usually minimum limit is also mentioned (Eg. 1.1V)

Successive Approximation Register(SAR) ADC:
In SAR, register of bits equal to no. of bits of ADC is used.
By using binary search pattern, it goes through all bits toggling from MSB to LSB and providing digital input to internal DAC. DAC generates the Analog voltage respectively which is used to compare with the input analog signal at the analog comparator stage. Sampled value is held until the complete conversion process is not complete. Once the conversion is complete, EOC signal is generated.


Voltage step = Vref / 2 ^ No. of adc bits
Hence,
Quantisation error range = +/- (Voltage step / 2)

ADC types:
  1. Successive approximation ADC (Sample and Hold type)
  2. Sigma delta ADC
DAC types:
  1. R-2R ladder

Sample and Hold (S/H) OR Track and Hold:
These are usually used for high conversion rate (i.e. high Msps) application. There are two steps in SAR ADC.: Sample and Conversion.



SAR ADC goes through following states for every iteration:



  1. Track mode: Here the output signal follows the input signal. "Slew rate" defines the signal following characteristic of the sampling capacitor.
  2. Track to Hold mode: Here the input is captured and kept constant. "Transient Settling Time" is an important parameter to onsider. Usually it is mentioned as "Sample time (ts)" in datasheet.
  3. Hold mode: Now the charge on the Capacitor Ch is held almost constant, during the conversion to digital value n-bit. Here, "Droop rate" is important parameter. It defines the charge holding capacity of the smapling capacitor.
  4. Hold to Track mode: Here the output signal starts following the input signal. "Acquisition Time" defines the time required for output signal to start following the input signal.
Hence, min. time for whole sample and hold cycle  (Tconv)=
Min.Sample time (Transient Settling time) + Approximation time + Acquisition Time

Max. sampling rate = 1/ Tconv

 - Sampling time is adjustable.
 - ADC clock frequency is usually variable
 - Hence, sampling rate (Ksps/ Msps) can be varied.

Manufacturers:

Most of the applications require ADC along with the processor to process the data.
There are requirements to fit these in small space. So usually we look for a MCU with good ADC functionality. In these cases, as per my experience, ST Microelectronics (STM32F302RB) provides the best solutions, in small cost. 
There are two or more ADCs inside the MCU. These ADC have excellent sampling rates around 5Msps in this case. There is special modes called "Dual interleaved" mode, where the both ADCs can be used to sample the same channel, With this, sampling rate can be doubles like around 10Msps. That's too great to get in cost of  2.5$ USD.
NOTE: Here you are suggested to use on board DMA for interleaved mode operation



Friday, February 26, 2016

C - structures, initialized and uninitialized variables


  1. Structure alignment
  2. Trailing structure padding
  3. Trailing padding in bit fields


Following is the best link to study "C Structures"

Lost art of C structure packing: http://www.catb.org/esr/structure-packing/

Initialized and uninitialized variables:

All local variables & pointers are "uninitialized"
Local variables declared as "static" are initialized to zero or NULL

All global variables & pointers are initialized

Difference between global variable and static global variable:

  • Normal global variable can be used in other C files by use of "extern"
  • Static global variable cannot be used outside the file
Multiple file C project:
  1. Architecture of such project should be like
    1. user_main.c
    2. user_header.h
    3. file1.c
    4. file1.h
    5. file2.c
    6. file2.h
    7. file3.c
    8. file3.h
  2. Variables declared by individual c file (file1.c, file2.c file3.c) should be defined in c files itself
  3. Variable declarations should be included as part of header files(file1.h file2.h file3.h) as "extern" if these varaibles are needed outside the c file.
  4. user_header.h should include all these header files(file1.h file2.h file3.h) in it, so as get access of all variables defined the source files(file1.c, file2.c file3.c)
  5. In case of functions, function definition in c files & function prototype in header files
Multiple file C project is best for situations where
  • You want to group methods depending on there functionality. And you are the one whole and sole developer for the project. Where you don't have to share any of your code to others.
Shared objects:
  • Situations where you have to share your code to others, but you want to keep your code functionality hidden
  • The executable prepared by using shared object is small in size, but needs the .so or .dll at the time of compilation and execution
  • The application(exe) is already prepared that uses shared object & we need to optimize the algorithm inside the dll with same function prototype, then we just need to compile new shared object and replace the old. By this exe doesn't need to be recompiled.
  • These techniques of modularization of code by shared objects is used for most softwares installed on PC
  • Code Architectures come into play as, the function prototypes need to be design as part of  main source code with lot of future vision and modular scope in mind. Hence to be a code architect, you need to have lot of experience at first.
  • If we need to link new shared object to exe, then the exe need to be recompiled with new dll linked to it.
Static objects:
  • Executable prepared with static linking, the size is larger as compared to shared object
  • They are with .a extensions in Linux
  • When a executable is prepared with linking to these object file, it is called static linking
  • The concept is used in preparing mobile application eg. Apple applications, where the rule is to prepare app with static linking, if it is intended to be available on AppStore
  • It provides security kind of feature, as at runtime exe doesn't depends on any external file like in case of shared objects
At runtime, the memory allocation (RAM) takes place in almost the same size in shared object and static linking. Just a difference of few bytes, as in shared objects the address of calling the function from required .so/.dll comes into picture
Plugins:
They are basically shared objects only, just the extension names are different.

Tuesday, February 23, 2016

Function pointer use & What are callback functions ??

Function pointers are basically used in callback function, to call a particular function when a event occurs.
Callback functions are ISR(interrupt service routines) when it comes to non-os based embedded systems.

Example of using funtion pointer in C program:

---------------------
user_main.c
---------------------
*
 * user_main.c
 *
 *  Created on: 23-Feb-2016
 *      Author: root
 */


#include <stdio.h>
#include <user_include.h>

int main(int argc, char *argv[]){
Demo d;
d.input_string = "Jon snow";
d.print_data_pointer = data_print_1;
printer_function(&d);
d.print_data_pointer = data_print_2;
printer_function(&d);
return 0;
}


void data_print_1(char *inp){
printf("\n You Know Nothing,... %s ", inp);
}

void data_print_2(char *inp){
printf("\n You know everything, ... %s", inp);
}

void printer_function(Demo *temp){
temp->print_data_pointer(temp->input_string);
}


----------------------
user_include.h
----------------------
/*
 * user_include.h
 *
 *  Created on: 23-Feb-2016
 *      Author: root
 */

#ifndef USER_INCLUDE_H_
#define USER_INCLUDE_H_

/*
 * typedef
 */
typedef signed char int8;
typedef unsigned char uint8;
typedef signed int int32;
typedef unsigned int uint32;

typedef struct{
void (*print_data_pointer)(char *);
char *input_string;
}Demo;

/*
 * Function declaration
 */
void data_print_1(char *);
void data_print_2(char *);
void printer_function(Demo *);

#endif /* USER_INCLUDE_H_ */


****** OUTPUT ******
You Know Nothing,... Jon snow 
You know everything, ... Jon snow

Monday, February 22, 2016

Latch and Flip flop difference

Flip flops are used to store informaion

Category:
  1. Asynchronous/Transparent flipflops (Latch)
  2. Synchronous fliplfops
Types:
  1. SR (Set Reset)
  2. D (Data or delay)
  3. T (Toggle)
  4. JK
Underneath hardware:
  1. NOR based (eg. SR latch)
  2. NAND based (eg. SR' latch)
Methods of describing
  • Characteristic table / Truth table
R
S
Q(next)
Action
0
0
Q
Hold state
0
1
1
Set
1
0
0
Reset
1
1
0
Not allowed as Q = Q’ = 0

  • Excitation table
Q
R
S
Q(next)
0
x
0
0
0
0
1
1
1
1
0
0
1
0
x
1

Latches and flip-flops are the basic elements for storing information. One latch or flip-flop can store one bit of information. The main difference between latches and flip-flops is that for latches, their outputs are constantly affected by their inputs as long as the enable signal is asserted. In other words, when they are enabled, their content changes immediately when their inputs change. Flip-flops, on the other hand, have their content change only either at the rising or falling edge of the enable signal. This enable signal is usually the controlling clock signal. After the rising or falling edge of the clock, the flip-flop content remains constant even if the input changes.



NOTE:

  1. When the device is latch/Gate we define it by Truth table
  2. When the device is flip-flop we define it by Excitation table
States of output:
  1. HIGH
  2. LOW
  3. No change
  4. Indeterminate
  5. Race around
State of Input:
  1. HIGH
  2. LOW
  3. Don't care


RS flipflop (mostly used as LATCH)

R
S
Q
Q’
Comment
0
0
0
1
No Change
0
1
1
0
Q Change to 1 as ‘S’ is 1 (Set State)
0
0
1
0
No Change
0
0
1
0
No Change
1
0
0
1
Q Change to 0 as ‘R’ is 1 (Reset State)
0
0
0
1
No change
1
1
0
0
Not allowed. In this state Q = Q’
0
0
?
?
If both R and S change from 11 to 00 then its indeterminate state

SR flipflop is the basic building block for computer memories

D-flipflop (mostly used as LATCH)
Major drawback of SR latch (indeterminate state and Not allowed state) are overcome by D-flipflop
D-Type-edge-trig-symbol.gif
D is a synchronous input
S' and R' are asynchronous inputs

JK-flipflop (mostly a flipflop +ve edged or -ve edged)
JK-MS-symbol.giftable-5-4-1.gif


J
K
Q(next)
Q’(next)
Action
0
0
Q
Q
Hold state
0
1
J
K
J
1
0
J
K
K
1
1
Q’
Q
Toggle

PROFILE

My photo
India
Design Engineer ( IFM Engineering Private Limited )

Followers