This is 4th tutorial for STM8 Microcontrollers. This post will give you a basic idea on using STM8 internal ADC.
All STM8 family devices feature 10/12 bit ADC as peripheral. ADC can be used in single or continuous conversion mode. This example code is tested on STM8S003F3P6 and STM8S105C6T6 controller but ideally it should work for every STM8 controller.
Experiment description
Schematic below shows the connections that I made in order to test the working of ADC peripheral. I wrote a simple code to change the LED blinking frequency according to the analog voltage input at Analog Channel 3 (PD2) of STM8S000F3P6. LED is connected to PD3 in source mode.
Code
#include "stm8s.h" void myDelay(unsigned int value) { unsigned int i,j; for(i=0;i<1000;i++) { for(j=0;j<value;j++); } } void GPIO_Config(void) { GPIOD->DDR |= 1<<3; //PD.3 as output GPIOD->CR1 |= 1<<3; //push pull output } unsigned int readADC1(unsigned int channel) { unsigned int val=0; //using ADC in single conversion mode ADC1->CSR |= ((0x0F)&channel); // select channel ADC1->CR2 |= (1<<3); // Right Aligned Data ADC1->CR1 |= (1<<0); // ADC ON ADC1->CR1 |= (1<<0); // ADC Start Conversion while(((ADC1->CSR)&(1<<7))== 0); // Wait till EOC val |= (unsigned int)ADC1->DRL; val |= (unsigned int)ADC1->DRH<<8; ADC1->CR1 &= ~(1<<0); // ADC Stop Conversion val &= 0x03ff; return (val); } int main(void) { unsigned int stepNos; GPIO_Config(); while(1) { stepNos=readADC1(3); GPIOD->ODR |= (1<<); // PD.0 = 1, LED ON myDelay(stepNos); GPIOD->ODR &= ~(1<<3); // PD.0 = 0, LED Off myDelay(stepNos); } }