on Wednesday, July 3, 2013
Hello,
When we dealing with microcontrollers, the number of GPIO (General Purpose Input Output) pins is always limited and sometimes it is impossible to interface some components that desires many outputs from a microcontroller due to the unavailability of pins in the microcontroller and this may lead to change the used microcontroller to another one.
In some other cases, the microcontroller controls a very distant equipment that requires many pins to work, this will lead us to make one wear for each pin and so there is a big chance of loosing data plus there is the high price of the wires.

For this problems there are a simple solution that consists on a GPIO expander. The role of a GPIO expander is to add more GPIO pins to the microcontroller, the microcontroller then is interfacing with the expander using a serial protocols that requires few wires.

In this tutorial I used the MCP23017 which is a GPIO expander by MICROCHIP that talks with a PIC16F877 using I2C protocol.
I used mplab-x and hi tech C for code creation,and proteus ISIS for simulation:

If you want to know more about I2C visit this link.

The schematics:

The code:
I2C.C
#include "Includes.h"

void I2CInit(void){
TRISC3 = 1; /* SDA and SCL as input pin */
TRISC4 = 1; /* these pins can be configured either i/p or o/p */
SSPSTAT |= 0x80; /* Slew rate disabled */
SSPCON = 0x28; /* SSPEN = 1, I2C Master mode, clock = FOSC/(4 * (SSPADD + 1)) */
SSPADD = 0x28; /* 100Khz @ 4Mhz Fosc */
}

/*
Function: I2CStart
Return:
Arguments:
Description: Send a start condition on I2C Bus
*/
void I2CStart(){
SEN = 1; /* Start condition enabled */
while(SEN); /* automatically cleared by hardware */
/* wait for start condition to finish */
}

/*
Function: I2CStop
Return:
Arguments:
Description: Send a stop condition on I2C Bus
*/
void I2CStop(){
PEN = 1; /* Stop condition enabled */
while(PEN); /* Wait for stop condition to finish */
/* PEN automatically cleared by hardware */
}

/*
Function: I2CRestart
Return:
Arguments:
Description: Sends a repeated start condition on I2C Bus
*/
void I2CRestart(){
RSEN = 1; /* Repeated start enabled */
while(RSEN); /* wait for condition to finish */
}

/*
Function: I2CAck
Return:
Arguments:
Description: Generates acknowledge for a transfer
*/
void I2CAck(){
ACKDT = 0; /* Acknowledge data bit, 0 = ACK */
ACKEN = 1; /* Ack data enabled */
while(ACKEN); /* wait for ack data to send on bus */
}

/*
Function: I2CNck
Return:
Arguments:
Description: Generates Not-acknowledge for a transfer
*/
void I2CNak(){
ACKDT = 1; /* Acknowledge data bit, 1 = NAK */
ACKEN = 1; /* Ack data enabled */
while(ACKEN); /* wait for ack data to send on bus */
}

/*
Function: I2CWait
Return:
Arguments:
Description: wait for transfer to finish
*/
void I2C_Wait(){
while ( ( SSPCON2 & 0x1F ) || ( SSPSTAT & 0x04 ) );
/* wait for any pending transfer */
}

/*
Function: I2CSend
Return:
Arguments: dat - 8-bit data to be sent on bus
data can be either address/data byte
Description: Send 8-bit data on I2C bus
*/
void I2CSend(unsigned char dat){
SSPBUF = dat; /* Move data to SSPBUF */
while(BF); /* wait till complete data is sent from buffer */
I2C_Wait(); /* wait for any pending transfer */
}

/*
Function: I2CRead
Return: 8-bit data read from I2C bus
Arguments:
Description: read 8-bit data from I2C bus
*/
unsigned char I2CRead(void){
unsigned char temp;
/* Reception works if transfer is initiated in read mode */
RCEN = 1; /* Enable data reception */
while(!BF); /* wait for buffer full */
temp = SSPBUF; /* Read serial buffer and store in temp register */
I2C_Wait(); /* wait to check any pending transfer */
return temp; /* Return the read data from bus */
}


MCP23017.C
#include "MCP23017.h"
#include "I2C.h"

void MCP23017_write(unsigned char reg, unsigned char data){
I2CInit();
I2CStart();
I2CSend(DE_ADD_WRITE);
I2CSend(reg);
I2CSend(data);
I2CStop();
}

unsigned char MCP23017_read(unsigned char reg){
unsigned char Rxbyte;
I2CStart();
I2CSend(DE_ADD_WRITE);
I2CSend(GP_PINS_A);
I2CRestart();
I2CSend(DE_ADD_READ);
Rxbyte= I2CRead();
I2CStop();
}

void MCP23017_IO(unsigned char PortA_IO, unsigned char PortB_IO){
MCP23017_write(GPB_A,PortA_IO);
MCP23017_write(GPB_B,PortB_IO);
}





on Sunday, April 14, 2013
DMA stands for direct memory access, this can be used one data needed to be transferred from place to another as it is for example from RAM to FLASH memory, from I2C, SPI or ADC to memory.
The DMA controller replaces the CPU in data transfer operation so the CPU can be freed to do other tasks.
DMA can be useful when there is critical data to receive and the user wants to see all data, even using the interrupt I/O there still time wasted while context switching, this can be elure with DMA.
The STM32 microcontroller has 2 DMA Controllers (DMA1, DMA2) and there are connected to the peripheral and memory through channels.
In the following example, I will illustrate the use of DMA with ADC.



#include "stm32f4xx.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_adc.h"
#include "stm32f4xx_dma.h"


#define ADC3_DR_ADDRESS ((uint32_t)0x4001224C)

/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
__IO uint32_t ADC3ConvertedValue = 0;
void config(){
ADC_InitTypeDef ADC_InitStructure;
ADC_CommonInitTypeDef ADC_CommonInitStructure;
DMA_InitTypeDef DMA_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;

/* Enable ADC3, DMA2 and GPIO clocks ****************************************/
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2 | RCC_AHB1Periph_GPIOC, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC3, ENABLE);

/* DMA2 Stream0 channel2 configuration **************************************/
DMA_InitStructure.DMA_Channel = DMA_Channel_2;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)ADC3_DR_ADDRESS;
DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)&ADC3ConvertedValue;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;
DMA_InitStructure.DMA_BufferSize = 1;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Disable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull;
DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
DMA_Init(DMA2_Stream0, &DMA_InitStructure);
DMA_Cmd(DMA2_Stream0, ENABLE);

/* Configure ADC3 Channel7 pin as analog input ******************************/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
GPIO_Init(GPIOC, &GPIO_InitStructure);

/* ADC Common Init **********************************************************/
ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div2;
ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;
ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
ADC_CommonInit(&ADC_CommonInitStructure);

/* ADC3 Init ****************************************************************/
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC1;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfConversion = 1;
ADC_Init(ADC3, &ADC_InitStructure);

/* ADC3 regular channel7 configuration *************************************/
ADC_RegularChannelConfig(ADC3, ADC_Channel_10, 1, ADC_SampleTime_3Cycles);

/* Enable DMA request after last transfer (Single-ADC mode) */
ADC_DMARequestAfterLastTransferCmd(ADC3, ENABLE);

/* Enable ADC3 DMA */
ADC_DMACmd(ADC3, ENABLE);

/* Enable ADC3 */
ADC_Cmd(ADC3, ENABLE);

}
int main(void)
{
config();
ADC_SoftwareStartConv(ADC3);
while(1)
{
}
}
on Saturday, April 6, 2013
In many embedded projects, we have to deal with signals directly from nature, like temperature, pressure, current, etc... Theses signals are analog by default and in most of cases we use sensors that converts these analog signals to analog electrical voltage to be injected in the microcontroller to do some work.
Unfortunately, microcontrollers are digital and just can't deal with analog signals so these signals must be converted again to digital signals that is comprehensible by the microcontroller.

For this purpose, microcontroller's manufacturers usually incorporate an ADC into the microcontroller. ADC is actually stands for Analog to Digital Converter. This module is omnipresent in most of microcontrollers.

I'm going to use the STM32F4 discovery board to interface an analog input provided by a potentiometer and visualize the received data with the watch feature while debugging the program.

#include "stm32f4xx_adc.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"

int ConvertedValue = 0; //Converted value readed from ADC


void adc_configure(){
ADC_InitTypeDef ADC_init_structure; //Structure for adc confguration
GPIO_InitTypeDef GPIO_initStructre; //Structure for analog input pin
//Clock configuration
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE);//The ADC1 is connected the APB2 peripheral bus thus we will use its clock source
RCC_AHB1PeriphClockCmd(RCC_AHB1ENR_GPIOCEN,ENABLE);//Clock for the ADC port!! Do not forget about this one ;)
//Analog pin configuration
GPIO_initStructre.GPIO_Pin = GPIO_Pin_0;//The channel 10 is connected to PC0
GPIO_initStructre.GPIO_Mode = GPIO_Mode_AN; //The PC0 pin is configured in analog mode
GPIO_initStructre.GPIO_PuPd = GPIO_PuPd_NOPULL; //We don't need any pull up or pull down
GPIO_Init(GPIOC,&GPIO_initStructre);//Affecting the port with the initialization structure configuration
//ADC structure configuration
ADC_DeInit();
ADC_init_structure.ADC_DataAlign = ADC_DataAlign_Right;//data converted will be shifted to right
ADC_init_structure.ADC_Resolution = ADC_Resolution_12b;//Input voltage is converted into a 12bit number giving a maximum value of 4096
ADC_init_structure.ADC_ContinuousConvMode = ENABLE; //the conversion is continuous, the input data is converted more than once
ADC_init_structure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC1;// conversion is synchronous with TIM1 and CC1 (actually I'm not sure about this one :/)
ADC_init_structure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;//no trigger for conversion
ADC_init_structure.ADC_NbrOfConversion = 1;//I think this one is clear :p
ADC_init_structure.ADC_ScanConvMode = DISABLE;//The scan is configured in one channel
ADC_Init(ADC1,&ADC_init_structure);//Initialize ADC with the previous configuration
//Enable ADC conversion
ADC_Cmd(ADC1,ENABLE);
//Select the channel to be read from
ADC_RegularChannelConfig(ADC1,ADC_Channel_10,1,ADC_SampleTime_144Cycles);
}
int adc_convert(){
ADC_SoftwareStartConv(ADC1);//Start the conversion
while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC));//Processing the conversion
return ADC_GetConversionValue(ADC1); //Return the converted data
}
int main(void){
adc_configure();//Start configuration
while(1){//loop while the board is working
ConvertedValue = adc_convert();//Read the ADC converted value
}
}


on Saturday, March 16, 2013
In this tutorial I'm going to show you one of the most used IP in any ST microcontroller the GPIO. What you need to know witch could be obvious to some that we are actually going to program the microcontroller in the board and not the board!!

The microcontroller of the STM32F4DISCOVERY board is STM32F407VGT ==> Datasheet

I'm using coocox for developing and it's an eclipse based IDE very friendly and intuitive.

The GPIO IP:
As I said it stands for Gneral purpose Input Output,
Each of the GPIO pins can be configured by software as output (push-pull or open-drain,
with or without pull-up or pull-down), as input (floating, with or without pull-up or pull-down)
or as peripheral alternate function. Most of the GPIO pins are shared with digital or analog
alternate functions. All GPIOs are high-current-capable and have speed selection to better
manage internal noise, power consumption and electromagnetic emission.
The I/O configuration can be locked if needed by following a specific sequence in order to
avoid spurious writing to the I/Os registers.
Fast I/O handling allowing maximum I/O toggling up to 84 MHz.
(From datasheet)

There are 5 GPIOs in the STM32 microcontroller (GPIOA,GPIOB,GPIOC,GPIOD,GPIOE) every GPIO has 16 configurable pin and each has 7 registers:
Two are used to configure the sixteen port bits individually, (CRL,CRH)
two are used to read/write the sixteen port bits in parallel, (ODR,IDR)
two are used to set/reset the sixteen port bits individually, (BSRR,BRR)
and one is used to implement a “locking sequence” that is intended to prevent rogue code from accidentally modifying the port configuration (LCKR)

First start new project choose chip (ST-STM32F407VG) . Later on the repositry window will appear, we will do some blinking so we definitely need the GPIO, click on the GPIO check box, RCC, CMSIS boot and M4 CMSIS Core are automatically checked.



In the project tree double click on main.c

GPIO as output :

What are we going to do is to make the leds embedded on the board to blink together every 1sec but to do so we need to know to witch pin and witch GPIO these leds are connected in our STM32F4DISCOVERY board.

According to the board schematics in pag 6
The leds are connected to (PD12/PD13/PD14/PD15) the GPIO used is then GPIOD and the pins are (12, 13, 14, 15)

So what we need to do is explained in the following flowchart:

The program is :
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"

GPIO_InitTypeDef GPIO_InitStructure;

void Delay(__IO uint32_t nCount);
/**
* @brief GPIO pin toggle program
* @param None
* @retval None
*/
void main(void)
{
/* GPIOD Periph clock enable */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

/* Configure PD12, PD13, PD14 and PD15 in output pushpull mode */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13| GPIO_Pin_14| GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &GPIO_InitStructure);

while (1)
{
/* LEDZ on */
GPIO_SetBits(GPIOD, GPIO_Pin_12|GPIO_Pin_13|GPIO_Pin_14|GPIO_Pin_15);
/* Insert delay */
Delay(0xFFFFF);
/* LEDZ off */
GPIO_ResetBits(GPIOD, GPIO_Pin_12|GPIO_Pin_13|GPIO_Pin_14|GPIO_Pin_15);
/* Insert delay */
Delay(0xFFFFF);
}
}

/**
* @brief Delay Function.
* @param nCount:specifies the Delay time length.
* @retval None
*/
void Delay(__IO uint32_t nCount)
{
while(nCount--)
{
}
}

GPIO as INPUT : 
Say that we need to read input from the outside world like buttons or switches we have to use the GPIO too.
In this case we are going to read the embedded button in the STM32F4DISCOVERY board.
 According to the board schematics this button is connected to the PA0 (GPIOA, pin 0).
What are we going to do is to set the leds on when the button is set and resetting them when the button is not set.

But we need to configure the GPIOA and the pin 0 as input before we can read data from it.

The program :


#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"

GPIO_InitTypeDef GPIO_InitStructure_Button;
GPIO_InitTypeDef GPIO_InitStructure;

void main(){
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//for buttons

RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

/* Configure PD12, PD13, PD14 and PD15 in output pushpull mode */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13| GPIO_Pin_14| GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &GPIO_InitStructure);
GPIO_InitStructure_Button.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure_Button.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure_Button.GPIO_Speed = GPIO_Speed_50MHz;

GPIO_Init(GPIOA,&GPIO_InitStructure_Button);
int i;
while(1){
i = GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0);
GPIO_WriteBit(GPIOD,GPIO_Pin_12|GPIO_Pin_13|GPIO_Pin_14|GPIO_Pin_15,i);
}
}







I got my STM32F4DISCOVERY board a few days ago and I'm so excited to try it.
This board is definitely one and unique board made by st for amateurs and professional to discover easily and with pleasure the strength of the STM32F4 series.

The board is really rich with features (copy past from the STM32F4DISCOVERY datasheet)
  1. STM32F407VGT6 microcontroller featuring 32-bit ARM Cortex-M4F core, 1 MB Flash, 192 KB RAM in an LQFP100 package
  2. On-board ST-LINK/V2 with selection mode switch to use the kit as a standalone ST-LINK/V2 (with SWD connector for programming and debugging)
  3. Board power supply: through USB bus or from an external 5 V supply voltage
  4. External application power supply: 3 V and 5 V
  5.  LIS302DL, ST MEMS motion sensor, 3-axis digital output accelerometer (Amazing !!!)
  6.   MP45DT02, ST MEMS audio sensor, omni-directional digital microphone
  7. CS43L22, audio DAC with integrated class D speaker driver
  8. Eight LEDs:LD1 (red/green) for USB communicationLD2 (red) for 3.3 V power onFour user LEDs, LD3 (orange), LD4 (green), LD5 (red) and LD6 (blue)2 USB OTG LEDs LD7 (green) VBus and LD8 (red) over-current
  9. Two push buttons (user and reset)
  10.  USB OTG FS with micro-AB connector (amazing for a microcontroller) 
  11. Extension header for all LQFP100 I/Os for quick connection to prototyping board and easy probing


This board can be used in many application with its DSP it can solve complex Digital signal functions used in filter computing plus it has the FPU (Floating point unit) that allows the STM32F4 to deal with floats up to 10exp-18 precision and that would be very useful in application that needs media processing or precision calculations.

I will post some tutorials talking about my experience with board.

Cheers ;)










on Sunday, February 17, 2013
So what's wrong with Tunisia!! with such great talents spread all over the world with such an honorable history with such immense agriculture potential Tunisia falls in its greatness.
So many talents so many good minds so many charismatic people and so many diversity but it seems that all of this positive line qualities Tunisia doesn't seems to get use of it, but instead this diversity this democracy is just dividing us more and more.
About 12 million person are living now in Tunisia, but even with this relatively small number of population we have more than 200 categories of Tunisian people, salfi, nahthawi, cpr, pdp, joumhouri, masar, ili m3a te2sisii willi mouch m3ehom welli me3inouch bech itabe3,.....
It seems that our diversity is playing against us. It seems that our qualities is our enemies.
It seems that democracy is not the solution.
on Friday, February 8, 2013


The need of static power supply

The need of power voltage supply is mandatory in any mechatronic application. For mobile mechatronic applications like robots, the power voltage supplier must be embedded with the application this can deliver many drawback like for example autonomy.
But when dealing with static mechatronic projects we can just get rid of the battery and use directly the domestic AC power supplier. because this supplier can deliver energy 24/7 with one drawback that this energy must be calibrated to be used in static mechatronic application witch are usually need a DC supply voltage.
In this article I'm going to show you how to create you own DC power supply.

Specifications 

INPUT : 220 V AC
OUTPUT: 5V DC / 1.5A

Principal functions:

 Our board change the 220V AC into 5V DC with a maximum operating current of 1.5A

Current protection : 


we need to protect the board from unpredictable current variation from the power supply or potential shunt that could be very dangerous and can harm our system. The obvious solution is to use a fuse.
The maximum needed current for mini mechatronic applications is 1A with a tolerance of 500mA so any current that exceeds 1.5A would be considered as dangerous to the board and the fuse must interfere. The choice is then a fuse with a normal operating current = 1.5A.


Galvanic isolation and Voltage decreasing

This part of the board is mainly responsible for decreasing the alternative voltage from 220V to 12V alternative current.
For this purpose we need a 220v 12V transformer that can assure both of the functions

Wave rectification


This part of the board is probably the most important, In fact in this part the alternative energy is transformed to a direct one. we need to eliminate the negative part of the wave or replace it with a positive wave.
For this purpose we need a full wave rectifier composed by 4 1N4001 Diodes:

Filtering and smoothing

The rectified wave still need to be more smoothed so I have to fill the gaps between the waves. To do so we need to add a capacitor that able to store voltage and release it in time to fill the gaps.
The specifications needed for our board are :
Vin :regulator input = 12V / Operating current = 1A
C = I * detlta(T)/delta(V) = 3333µF we take it as 4700µf or 2200µF

Voltage regulation

At this step we have a decent 12V DC but it's not really stable and we need to get the 5V DC To feed the electronics. For this purpose we have to add a 5V voltage regulator that can transform 12V to a stable 5v DC. The perfect choice is LM7805 witch is a 5V DC/DC regulator that is capable of supporting up to 1A witch is acceptable for the usual applications. It's recommended to add another filtering capacitor of 10mF in the output of the regulator to assure stabilization.


Integration of the hole design with Altium designer: