This is 3rd tutorial in series of tutorials on STM8 microcontroller by ST Microelectronics. In this tutorial, we will learn, how to handle inputs on GPIO ports/pins of STM8S controller. We are considering only Polling method of reading inputs in this article, Interrupt method will be covered later.
Reading input on any of the STM8S GPIO pin is very straight forward. Lets take this step by step.
Step – 1 Declare the GPIO Pin/Port as Input
One has to declare any GPIO pin as input before any physical signal input can be read from that GPIO pin. To declare the GPIO pin as Input we again need to set proper bits in DDR Register of corresponding port. Table below shows different combinations of DDR, CR1 & CR2 registers in order to set any GPIO either as Input or Output and to enable or disable Pull ups and Interrupts.
In this experiment we are going to use GPIO as Input with Pull up but without Interrupts. So, for example if I want to use PE.7 as input with Pull up enabled and Interrupt disabled. I need to write corresponding bit (bit 7) in DDR register of PORTE as ’0′.
GPIOE->DDR &= ~(1<<7); // Declare PE.7 as Input
GPIOE->CR1 |= 1<<7; // PE.7 Pull Up Enabled
Now, once we have set PE.7 as Input with Internal Pull-Up, we are now ready to read the input logic status at PE.7 Pin.
Step -2 Read Pin status from IDR Register
STM8S has ODR register to write on output port and IDR register to read from input port. IDR is a read-only 8-bit register. Logical value at any bit of IDR register of a port, reflects the actual logical status of that pin of that port. For example, if Pin 7 of IDR register of GPIOE is ’0′, that means, PE.7, if configured as input is currently set to logic ’0′.
Step – 3 Schematic
Figure below shows the connections that I’ve made to experiment with Inputs. Circuit has a tactile switch connected to PE.7 and 3 LEDs connected to PC.2, PC.4 and PC.6 respectively.
Step -4 Code
Image below is main() function for input handling program. Whenever the user presses the switch at PE.7, the input pin goes low, the code has a software wait for switch debounce. As the user presses the switch, it will glow all the LED for approximately 1 second otherwise the LEDs remain off forever.
For any further help or suggestions on this article/ series, please comment your views, questions in the comment area below.
Thanks for reading!