Mechatronics geek blog

المواضيع الرئيسيه للميكاترونكس

Physical System Modeling , Sensors and Actuators ,Signals and Systems , Computers and Logic Systems AND Software and Data Acquisition

أردوينو

شرح للأردوينو يأخذك من مستوي المبتديء إلي المحترف

لغات البرمجه

C ,C++ ,C# ,Python ,Java ...

الانظمه المدمجه

AVR,PIC, ARM CORTEX ..., RTOS, Automotive Protocoles ( CAN - LIN - ...)

Solid Works

العديد من شروحات السوليد وركس تأخذك من مستوي المبتديء إلي مستوي المحترف

Saturday, April 27, 2019

Sorting Algorithms

Sorting Algorithms:
---------------------------
1- Selection Sort
2- Bubble Sort
3- Merge Sort
============================================================
1- Selection Sort: 
- Time Complexity : O(N^2)
---------------------------------------
void swap(int*ele1,int*ele2)
{
int temp;
temp=*ele1;
*ele1=*ele2;
*ele2=temp;
}

/*
in this code: the use of mini variable is to determine the index of the smallest number in the array first then we swap after the inner loop finishes. Without the mini variable, we have to move the swap function into the inner loop and swap whenever the condition is true and that takes more time!
*/
void selectSortElements(int*arr,int size)
{
int i,j,mini;
for(i=0;i<size-1;i++)
{

mini=i;

/* The inner for loop is used to determine the index of the smallest element in the array */
for(j=i+1;j<size;j++)
{
if(arr[j]<arr[mini])
{
mini=j;
}
}
swap(&arr[i],&arr[mini]);
}
}

=================================================
2-Bubble Sort:-
--------------------

void bubbleSort(int*arr , int size)
{
    int i,j;

    for(i=0;i<size-1;i++)
    {
        for(j=0;j<size-i-1;j++)
        {
            if( arr[j]>arr[j+1])
            {
                 swap(&arr[j],&arr[j+1]);
             }   
         }
    }
}

The above function always runs O(n^2) time even if the array is sorted.It can be optimized by stopping the algorithm if inner loop didn’t cause any swap.

The optimized version of bubble sort:
---------------------------------------------------

void bubbleSort(int*arr, int size)
{
int i , sortFlag=0;
while(!sortFlag)
{
sortFlag=1;
for(i=size-1;i>=0;i--)
{
if(arr[i]<arr[i-1])
{
swap(&arr[i],&arr[i-1]);
sortFlag=0;
}
}
}
}

NOTES:
========
Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
=========================================================
Merge Sort:
------------------

Perfectly explained: https://www.geeksforgeeks.org/merge-sort/









Searching Algorithm

Searching Algorithms:
---------------------------
1-Sequential Search
2- Binary Search
----------------------------------------------------------
1- Sequential Search:
    -Searching in an array of N.
    -Time complexity: O(N)

int sequentialSearch (int * arr, int size, int data)
{
       int index= -1;
       int i;
       for(i=0;i<size;i++)
       {
          if(arr[i] == data)
          {
           return i; /* Once the data is found return the index and exit the function*/
           }
         }
       return index;
}

===================================================================
2- Binary Search: is applied on "Sorted data" 
    - Data must be sorted.
    - Time Complexity: O(log N)

int binarySearch(int*arr, int size ; int data)
{
int low=0;
int high=size-1;
while(low<=high)
{
mid=(low+high)/2;
if(data>arr[mid])
{
low=mid+1
}
else if(data<arr[mid])
{
high=mid-1;
}
else
{
return mid;
}
return -1;
}

---------------------------------------------------
The same Function using Recursion:

int recBinarySearch(int*arr,int low , int high,int data)
{
int mid=(high+low)/2;
if(low>highh)
{
return -1;
}
if(arr[mid] < data)
{
  low=mid+1;
return recBinarySearch(arr,low,high,data);
}
else if (arr[mid] > data)
{
  high=mid-1;
return recBinarySearch(arr,low,high,data);
}
else
return mid;
}
============================================================










Matrices (mathematics)

Matrices Addition and Subtraction:-
=============================
************************************************************************
Rule:
You can only Add or subtract two matrices only and only if they have the same number of rows and columns and the result will have the same number of rows and columns.

***************************************************************************
Addition or subtraction is performed between the two elements that have the same location.

Ex:

[ 5      4              [ 9      -3               [ (9+5)    (4-3)                  [14       1
   -1    6         +     8      2         =       (-1+8)   (6+2)          =        7         8
    0     7 ]               -6    1 ]                (0-6)      (7+1) ]                -6          8 ]


Pointers Questions

1- Print an array after removing duplicating numbers in it?
Solution:
https://github.com/AmrHRAbdeen/C-Programming/blob/master/RemoveDuplicatedValues.c
===================================================================
2- Find 2 Elements in the Array such that the difference between them is the Largest?
Solution:
https://github.com/AmrHRAbdeen/C-Programming/blob/master/MaxDiffInArray.c
===================================================================
3- Find the One repeated number in an Array and print number of repetition?
Solution:
https://github.com/AmrHRAbdeen/C-Programming/blob/master/findOneRepeatedValue.c
===================================================================
4- perform Cyclic Swapping on an array of 3 Elements?
Solution:
https://github.com/AmrHRAbdeen/C-Programming/blob/master/cyclicSwap.c
===================================================================
5- Adding Two Matrices
Solution:
https://github.com/AmrHRAbdeen/C-Programming/blob/master/AddingMatrices.c
===================================================================

Monday, April 15, 2019

Building Process and Critical Sections || Part(2)

Building process (Part 2):
--------------------------------
in case the variable is used repeatedly in the code and its value is not changing during the code, The compiler optimizer has the option to store it in a General purpose register (GPR) or cache it in a cache memory if exists to reduce execution time.

Ex:

var =40;
while(var==40)
{
..
..
..
}

Here, the compiler will solve this line while(var==40) to
1- Read Var from its Virtual Memory Address (or from a GPR if cached in a GPR or cache memory)
2- Compare Var to 40
3- Jump if Equal.

is caching always useful?

*No , Not really!

let's say we have that code snippet:
-------------------------------------------
var =40;
while(var==40)
{
..
..
..
}
----
ISR()
{
 var =10;
}

As we discussed earlier, the compiler will divide while condition to 3 steps. so, Let's imagine that while the CPU executes the read operation of var variable that is stored in a GPR ( as the compiler decided to cache it as it's used repeatedly in the code) , an ISR is fired modifying the value of var variable in RAM ,but CPU doesn't sense that change as var value is already cached in one of its GPRs! and that's a PROBLEM!

so we need to tell the compiler NEVER cache this variable as here we introduce volatile modifier.

Volatile Modifier: tells the compiler optimizer to NOT cache this variable. as its value may be changed in the future. 

When to use volatile Modifier?
------------------------------------------
1) Any variable is defined inside an ISR should be defined as volatile.
2) Any Variable is changed by HW.

Example:-
---------------
Registers Addresses => #define PINA *((volatile u8*)0x31) 
as PINA is an 8-bit register is modified by HardWare as PINA is updated when there's input voltage to the microcontroller.

It's a good practice to use volatile modifier whenever we define registers addresses.
3) Shared variable in multi-threading programming (OS tasks).


Tuesday, April 9, 2019

Analog to Digital Converter (ADC)

Analog to Digital Converter (ADC):
-----------------------------------------------
used to convert Analog signals to digital value.

Types of ADC:
==============
1- Ramp Counter ADC:-
--------------------------------
The idea behind this type of ADCs is that:
The Counter is Enabled by Zero (Active LOW). When the desired signal (Vin) > DAC output(which is a voltage too) the comparator output is Zero (0) Enabling the timer to continue to count.  When the desired signal is equal to the DAC output, the comparator output is 1 disabling the counter from counting. The last value in the Counter is the digital representation of the analog signal.
-------------------------------------------------------------------------------------------------------------------
The step size is the voltage difference between one digital level (i.e. 0001) and the next one (i.e. 0010 or 0000).

step size = Vref. / (2^Resolution) 

(2^Resolution) referred to Number of levels (Quantization).

Ex:
  Vref.=5Volt. in 2 bit ADC so Step = 5/2^2=5/4=1.25 Volt
so ADC will have 4 different digital values(4 Levels) corresponding to analog signals of (0 , 1.25 , 2.5 , 3.75 , 5 Volt)

*Rem:
DAC is unable to produce its Vref. (Max. Voltage) as it is saturated at (Vmax-Step) which means the last level (digital representation) will be the same for  (Vmax-Step) to (Vmax).

Analog Value = Digital Representation * Step

Ex: ADC , Vref = 5V , Resolution:8 Bit , Digital Value = 1111 1111

Analog Value = 255 * (5/256) = 4.9804 Volt => ( 5 - 0.0195 ) => (Vmax.-Step)

*Note:
---------
-Increasing ADC resolution means increasing ADC accuracy.
-Increasing Vref. means increasing measurement range.

Vref. Calculations:
------------------------
Vref is determined according to:

1- Max. Volt. will be measured from a sensor/transducer should be less than or equal Vref. of an ADC.
2- Generated Error in measurement. as when a sensor generates a max. volt of 2 is used with 2 bit ADC with Vref. =5 this will make a step of ( 5/4)=1.25 volt. which means that the ADC will only sense 0 and 1.25 Volt of the sensor ! which means a high error in reading the sensor's reading.But, if the same ADC is used with Vref. =2Volt that makes the Step=2/4=0.5 volt so the ADC will sense the 4 levels for the sensor's reading (0,0.5,1.5,2)!
-----------------------------------------------------------------------------------------------------------------
Problems with Ramp. Counter ADC:-
----------------------------------------------------
1- Increasing counter clock will increase the error in reading the digital representation as the counter will continue to count above the desired digital representation as a result of the delay between moving the digital representation from counter to DAC to convert it to an analog signal to be compared with the desired signal.

2- Increasing counter clock will decrease conversion time and as a result conversion time is not constant.

======================================================================
2- Successive Approximation ADC (SAR ADC) :-
-------------------------------------------------------------
It has 3 main Components:
---------------------------------
1- SAR "Successive Approximation Register"
2- Comparator
3- Control Unit


The main idea depends  on :
if Analog Volt. (DAC Output) > Vin so the corresponding bit is cleared otherwise it's kept as 1.

Steps: (Assuming: 8 Bit SAR ADC , Step Size=10 mV, Vin=1Volt.):-
------------------------------------------------------------------------------------
1- Starts with binary 1000 0000 (128 in decimal)=> Analog Volt = 128 * 10 mV = 1.28 Volt.  > Vin
   so bit 7 is cleared(dropped).
2- 0100 0000 (64 in decimal) => Analog Volt = 64 * 10 mV=640 mV < Vin so bit 6 kept as 1.
3- 0110 0000 (96 in decimal) => Analog Volt=96*10 mV=960 mV < Vin so bit 5 kept as 1.
4- 0111 0000 (112 in decimal) => Analog Volt= 112*10mV=1.12 V > Vin so bit 4 is cleared.
5- 0110 1000 (108 in decimal) => Analog Volt=108*10mV=1.08V > Vin so it 3 is cleared.
6- 0110 0100 (100 in decimal) => Analog Volt=100*10mV=1V = Vin so bit 2 is kept as 1.
7- 0110 0110 (102 in decimal) => Analog Vol=102*10mV=1.02mV > Vin so bit 1 is cleared.
8- 0110 0101 (101 in decimal) => Analog Vol=101*10mV=1.01 mV > Vin so it 1 is cleared.
9- 0110 0100 is the final representation of 1Volt. input.

Result After 8 Clock Cycles:
-------------------------------------
so 1 Volt = > 0110 0100
--------------------------------------

Advantages:
------------------
Conversion  time is constant.


Comparison between Ramp. Counter ADC and SAR ADC:
---------------------------------------------------------------------------
3- Flash ADC
----------------------
4- Integrator ADC
-------------------------



Watchdog Timer

Watchdog Timer:-
-----------------------

-is a countdown timer used to reset the microcontroller after a specific timeout. The microcontroller should kick the Watchdog timer by resetting its value preventing it from reaching Zero.

- One should adjust the watchdog timer to guarantee that a specific code will be executed is a specific time period less than the watchdog period. At the end of that piece of code, one should disable the watchdog timer or reload it with a new value.

*To measure the execution time of a specific function we can use the oscilloscope to determine its switching time (context switch and context restore) by setting a pin high before calling it and clearing it again after returning to main function (That method is the most accurate method as it takes in consideration the Hardware delay and experience the real world/HW.)

Watchdog Conditions:
-----------------------------
1- Has a separate clock (Works on its own clock)
2- Has disable Sequence.

NOTE:-
-------------
We need to keep the Watchdog sleep by refilling it with a new value and preventing it from reaching Zero, hence preventing the microcontroller form resetting.


Watchdog in AVR (ATmega32):-
-------------------------------------------








Test Code:
-----------------
https://github.com/AmrHRAbdeen/ATmega32_Projects/tree/master/WatchDogTimer



Monday, April 8, 2019

Embedded C From 12 to 2 - Episode 1

Embedded C From 12 to 2 - Episode 1


Saturday, April 6, 2019

IOT_Notes

Found in iTi_First_Sketch (Back)

Tuesday, April 2, 2019

Memory Sections

Memory Sections (Common Sections)
-----------------------------------------------

RAM:
1- .Stack section
2- .Heap section
3- .BSS section (Block Started by Symbol)
4- .Data

ROM:
1- .ISR Vector or .Vectors or .intVVector or .IVT
2- .rodata (Read Only data)
3- .romdata or .data
4- .text
==============================================
Example:
------------
uint32 x ; /*Uninitialized Global Variable stored in .bss section in RAM  and initialized with ZERO "According C Standard"*/

uint32 y=7; /*Initialized Global Variable stored in .data section in ROM (which means it has a specific location in .data section in ROM with value 7 but there's no label for it ) then it will be moved to .data section in RAM during run time with its label y and its value 7 */

const uint32 Z=100; /*Constant initialized global variable stored in .rodata section in ROM*/

void main(void)
{
uint32 A=10; /*Local variable stored in .stack section in RAM during runtime*/

/********Note: Static local variables will be treated as Global Variables********/

static uint32 B=20; /*Static local variable initialized with 20 and stored in .data section in ROM (which means it has a specific location in .data section in ROM with value 20 but there's no label for it ) then it will be moved to .data section in RAM during run time with its label B and its value 20 */

static uint32 F; /*Uninitialized static local Variable stored in .bss section in RAM  and initialized with ZERO "According C Standard"*/


const uint32 N=20;/*constant local variable stored in .stack section in RAM you can not change its value directly but you can define a pointer to it and change its value by dereferencing that pointer*/


static const uint32 M=200; /*static constant local variable .rodata section in ROM*/

}



















Monday, April 1, 2019

Generate Sine Wave using ATmega32

Sine wave Equation:

y=sin(x) ; where x is  the angle in radian. in a whole circle there are 2*PI radians . This means x varies from 0 to 2*3.14(PI) [0,6.28] => Half circle [0,+3.14] Other half [0,-3.14]

As sin may be negative we need to handle this situation by shifting the 0 to 127 ( 127 is our new ZERO line) anything above 127 would be +ve and anything below 127 would be -ve.

One more thing, The output of sine is from -1 to +1 so we need to scale it up by multiplying it with 127 So the Final Equation is:

                                      y=127+(127*sin(x))

Now, we need to divide the sine wave to points that will be plotted :

x=0;
for(i=0;i<100;i++)
{
   myArr[i]= 127+(127*sin(x));
   x=x+0.0628; /* as in whole circle there are 6.28 radians so 0.0628 is 1/100 of 6.28 as we need 100 points */
}