Thursday 15 December 2016

microcontroller - C coding design - function pointers?


I have a PIC18F46K22 and program it with the XC8 compiler. In the end, I'll have a system like a pc with stdin and stdout. So in the main loop there will be a function which is checking if there is new input. If there's input, a function will be called accordingly. So for example when I input an A on stdin, the PIC will run a function like function_A instead of function_B which is called when I input a B.


When the PIC is done with the function, I want that the new input is sent to the function. So when pressing A opens the RS232 transmitter, from that moment every input will be sent over RS232. In the end the project is a stand-alone text editor. So when pressing A opens the file system, from that moment you aren't text editing anymore but looking through a list of files. That means that pressing Up and Down means something different than in the text-editing environment.


I've done a lot thinking on how to program this in C. I thought this up last night and would like to know if it's possible and if so, how. What I want to do is:



  • The main function calls a function like function_A

  • function_A changes a global variable function_addr to the address pointer of function in_function_A

  • From that moment, main calls the function at function_addr when there is new input.



So what I'd need is a main function which checks if function_addr is zero. If it is, a 'normal' function should be called, like function_A. If it isn't, the function at function_addr should be called. I also need a function_A which changes the function_addr to a pointer to in_function_A.


Note: when the filesystem function should be closed, is_function_A should just change function_addr to 0.


So basically my question is how can I



  • Get the address of a function (and store it in a variable)

  • Call a function at a specified address



Answer



A function


int f(int x){ .. }


Get the address of a function (and store it in a variable)


int (*fp)(int) = f;

Call a function at a specified address


int x = (*fp)( 12 );

No comments:

Post a Comment

arduino - Can I use TI's cc2541 BLE as micro controller to perform operations/ processing instead of ATmega328P AU to save cost?

I am using arduino pro mini (which contains Atmega328p AU ) along with cc2541(HM-10) to process and transfer data over BLE to smartphone. I...