2018-05-10 05:43 AM
Hi.
I was trying to write a code to use my keypad, but I face a problem. Because I'm new in using standard libraries I didn't face a similar problem when I was using registers(in LPC series).
#define COLUMN_PIN_1 GPIO_PIN_4
#define COLUMN_PIN_2 GPIO_PIN_5#define COLUMN_PIN_3 GPIO_PIN_4#define COLUMN_PIN_4 GPIO_PIN_2#define COLUMN_PORT_1 GPIOB
#define COLUMN_PORT_2 GPIOB#define COLUMN_PORT_3 GPIOF#define COLUMN_PORT_4 GPIOAfor(j=1;j<5;j++)
{
if(GPIO_ReadInputPin(COLUMN_PORT_j,COLUMN_PIN_j))return (4*(i-1)+j-1); delay_ms(50);}In this code, I thought that the amount of the j will be replaced and for example when j is 1 COLUMN_PORT_j is COLUMN_PORT_1.
What should I do to achieve this purpose?
2018-05-10 06:04 AM
The answer isn't too simple. Read a good C book if you want.
Alternatively you can put those parameters in an array and go from there.
See this for example.
2018-05-10 06:38 AM
Never do this. #define is processed at compile time and is just replace a piece of text by another.
Create a structure which contains the port and the pin position (and maybe even the result of your loop calc ?)
Then create a const array of these, with an index you can sweep them through.
With sizeof() you can avoid using absolute index numbers for your loop. This will take few bytes of flash...
2018-05-10 07:54 AM
>>In this code, I thought that the amount of the j will be replaced and for example when j is 1 COLUMN_PORT_j is COLUMN_PORT_1.
That's really not how the pre-processor works.
ST has an example of this type of usage
/** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Private_Variables STM32F4 DISCOVERY LOW LEVEL Private Variables
* @{ */GPIO_TypeDef* GPIO_PORT[LEDn] = {LED4_GPIO_PORT, LED3_GPIO_PORT, LED5_GPIO_PORT, LED6_GPIO_PORT};const uint16_t GPIO_PIN[LEDn] = {LED4_PIN, LED3_PIN, LED5_PIN, LED6_PIN};There are inefficient macro approaches, but these rely on the optimizer to strip the dead code paths
/*!
* \brief GPIOs Macro */#define RCC_GPIO_CLK_ENABLE( __GPIO_PORT__ ) \
do { \ switch( __GPIO_PORT__) \ { \ case GPIOA_BASE: __HAL_RCC_GPIOA_CLK_ENABLE(); break; \ case GPIOB_BASE: __HAL_RCC_GPIOB_CLK_ENABLE(); break; \ case GPIOC_BASE: __HAL_RCC_GPIOC_CLK_ENABLE(); break; \ case GPIOD_BASE: __HAL_RCC_GPIOD_CLK_ENABLE(); break; \ case GPIOH_BASE: default: __HAL_RCC_GPIOH_CLK_ENABLE(); \ } \ } while(0)2018-05-10 10:13 AM
Do you know any good source for C?I searched but there are so many and I got confused which would be the best.
2018-05-10 10:36 AM
I'd start with K&R, its a pretty much foundational text to understand what's going on and the expectations, other teaching/training books are a matter of personal style and approach to learning.
https://en.wikipedia.org/wiki/The_C_Programming_Language
2018-05-10 12:24 PM
Keep in mind the embedded constrains which don't necessarity show up in the C language books.
Flash size, RAM size, stack and heap, interrupts, HW registers, ease of step by step debugging.