This is the fourth day of my participation in the August Text Challenge.More challenges in August

STM8 microcontroller has its own buzzer drive function, but the buzzer refers to the passive buzzer, rather than the common active buzzer.

Passive buzzer, simple understanding is that there is no internal power supply circuit, direct current, the buzzer will not ring. It must be driven with a 2-5khz square wave signal to make it sing.

Active buzzer internal power supply circuit, direct supply of direct current, the buzzer will sound. Because an active buzzer has a vibrating source inside it, it can sound as long as there is a voltage. Therefore, active buzzers are more expensive than passive buzzers.

STM8 BEEP pin is the drive pin of passive buzzer. This pin is connected to a triode to drive the passive buzzer directly.

Specific functions of buzzer pins:

There are three steps to enable the buzzer:

  1. The value of BEEPDIV[4:0] is determined according to the method described above to calibrate the frequency of the LS clock;
  2. Select output frequencies of 1 kHz, 2 kHz or 4 kHz by writing BEEPSEL[1:0] bits of BEEP_CSR;
  3. Set the BEEPEN bit of BEEP_CSR to enable the CLOCK source of LS.

There is only one register to operate on:

Buzzer driving circuit diagram is as follows:

The following code is implemented:

#include "stm8s103f3p.h"
// The BEEP port is initialized
void GPIO_Init(void)
{
  PB_DDR|=0x20;         / / PB5 output
  PB_CR1|=0x20;         //PB5 push-pull output
}
main()
{
    GPIO_Init();
    BEEP_CSR=0x00;
    BEEP_CSR |= (1<<5);  // Enable the buzzer function
    BEEP_CSR |=0x0E;     F =128/(8*(XX+2)) XX is the set value
   //BEEP_CSR=0x2e; //0E 1K 06 2K 1E 500HZ
	 while(1) {}}Copy the code

Buzzer operation is very simple, first set BEEP port as the normal IO output, then set BEEPEN in the BEEP_CSR register to 1, the buzzer function is enabled.

At this time, the buzzer can ring. If you want to change the driving frequency of the buzzer, you can change the frequency by setting the BEEPSEL bit of the BEEP_CSR register. If the frequency is not what you want, you can also change the fractional frequency by setting the BEEPDIV bit, so as to adjust the frequency to the range you want.

Some STM8 series MCU to use BEEP function, also need to set the option word. However, STM8S003 microcontroller is used here, and there is no need to set the option word. If you need to set the option word, you can directly set it in the STVP download software.

Open the STVP burn software, switch to the OPTION BYTE page, and then set the OPTION BYTE through AFR0– AFR7.