So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By Noob Person
#64436 Hi,

I was recently taking a look at the Espressif TCP Client sample code and I saw callback functions being registered(http://espressif.com/en/support/explore/sample-codes).

What exactly does this mean and why exactly do callbacks need to be registered? Also, is this something that's specifically done for the ESP8266?
User avatar
By daniel_ezsbc
#64448
What exactly does this mean and why exactly do callbacks need to be registered?


A callback is simply a ( parameterless ) function that is called after an event occurs. It relieves the programmer from knowing all the details about handling the even. Callbacks are commonly used in event driven programming and in interrupt handlers.

Think of the example of a user of a gui clicking on a button with the mouse. Instead of knowing all the details of how to find that the button was clicked on a certain position on screen and that it was a single left click instead of a right click with the control key held down, the writer of the callback only needs to know that the appropriate event happened. The details are handled by 'magic' in the writer of the mouse handler.

In the mouse example there would, in principle, be multiple callbacks. One for a left click, one for a right click and some for clicks with keys held down. Alternatively the callback function can receive parameters to tell it what happened. The callback runs immediately 'after' the event happened.

The callback functions have to be registered to let the code know which function to call after the event occurred. 'Registration' is simply the process of providing a name for the function to deal with the event.

Callbacks are a great way to avoid polling loops. It is an even better way of changing behavior depending on history (state we're in). As the state changes you change the event behavior by registering a new callback for an event that needs to be handled differently from previous states. Think 'right click menus' changing depending on whether you are drawing a line, circle or an arrow.

Callbacks are common in event driven programming and very common in CAD, CAM programs to allow users to customize the behavior of the main gui.

Hope this helps