Cortex-M3 development experience (a): The application function pointer

Cortex-M3 development experience (a): The application function pointer

In learning C language syntax, learned a function pointer. It is to use a pointer to a function (in real terms is a function address). Then by calling the function pointer. At that time, after completing a look ignorant force, it is not to understand the principles, but I do not know what's the use? Direct calls can not you do? Why engage in these tasks are more demanding and more bells and whistles.

Later we found that the function pointer is also the scene of the application!

IIC IIC simulation and hardware call

When I developed, I encountered such a problem.

IIC protocol either analog can also use the built-in hardware. So there is a problem, I think some chip hardware IIC is not easy, I want to use simulation. But these switches is more trouble. All functions must be modified IIC device called again (C language does not support the function of the same name). In this way more trouble. With macro definition of it, the code becomes bloated, each local calls will require #if ... # else ... # endif.

At this time, I thought of function pointers. I need to use analog IIC, IIC points to the function of simulation. When required hardware IIC, it points to the function of the hardware IIC. This is not can it? Rush to try!

typedef uint8_t (IIC_SEND)(uint8_t, uint8_t, uint8_t);
typedef uint8_t (IIC_READ)(uint8_t, uint8_t, uint8_t);

uint8_t Simulate_iic_send(uint8_t addr, uint8_t wbuffer, uint8_t length)
{
    //模拟IIC发送时序
}

uint8_t Hardware_iic_send(uint8_t addr, uint8_t wbuffer, uint8_t length)
{
    //硬件IIC发送实现
}


IIC_SEND fiic_send = Simulate_iic_send;
IIC_SEND fiic_send = Hardware_iic_send;

In this case, I can at initialization, confirm using analog hardware IIC or IIC. In fact, the pointer may be modified during operation, switch between different modes (but not necessary).

Extension : Or we can now IIC slave mode, IIC host mode can also be made in this way.

to sum up

  1. Function pointer can be used in situations of uncertainty need to call a function, you can modify the pointer to.
  2. Function pointer make the code easier portability. In our example, we only need to change the function can be achieved, the application layer just call pointer.
  3. Being only think of these, the latter with better applications will continue to update.

Guess you like

Origin www.cnblogs.com/Oushangrong/p/11014528.html