STM8S003F3P6 becomes unresponsive and can no longer be programed
Hello,
I'm writing some timer code for the STM8S003F3P6. I am using SDCC to compile it and stm8flash to flash it on to the device with a third part ST-Link V2.
I am having an issue that when I flash the device with my code it doesn't run and I can no longer write to the device. I can still read the flash memory and write to non-program memory but I seem unable to reprogram the device and I'm not sure why. This has also been hard to debug due to having limited numbers of ICs and it hard to buy more of them atm.
Below is the code I am running. It only crashes when I add timer_setcompare(adc_read()); to the main loop. adc_read() works when on its own and just returns a 16 bit value. timer_setcompare() seems to work during the init.
Does anyone have any idea why this would be bricking my devices?
---- Main.c ----
#include "adc.h"
#include "debugPort.h"
#include "stm8s.h"
#include "timer.h"
#define wfi() \
{ __asm__("wfi\n"); } /* Wait For Interrupt */
void main() {
CLK_DIVR = 0x00; // Set the frequency to 16 MHz
CLK_PCKENR1 = 0xFF; // Enable peripherals
unsigned long i = 0;
uart_init();
outMsg("\nStarting...\n");
adc_init();
PC_DDR = 0b1000000;
PC_CR1 = 0b1000000;
PC_ODR = 0b0000000;
uint16_t adc = adc_read();
timer_init();
while(1) {
timer_setcompare(adc_read());
}
}
---- Timer.c ----
#include "adc.h"
#include "stm8s.h"
#include "debugPort.h"
#include "timer.h"
#include <stdint.h>
#include <stdbool.h>
#define BitGet(x, n) (bool) (((x) >> (n)) & 1)
#define enableInterrupts() {__asm__("rim\n");}
const uint16_t tim1_prescaler = 4;
const uint16_t tim1_auto_reload = 1023;
void timer_setcompare(uint16_t compare){
TIM1_CCR1H = (compare >> 8);
TIM1_CCR1L = (compare & 0xFF);
}
void timer_init(void)
{
FLASH_DUKR = 0xAE;
FLASH_DUKR = 0x56;
FLASH_CR2 |= (1 << 7);
FLASH_NCR2 &= ~(1 << 7);
OPT2 |= (1 << 0);
NOPT2 &= ~(1 << 0);
outMsg("%X - %X\n", OPT2, NOPT2);
FLASH_IAPSR &= ~(1 << 3);
TIM1_PSCRH = (tim1_prescaler >> 8);
TIM1_PSCRL = (tim1_prescaler & 0xFF);
TIM1_ARRH = (tim1_auto_reload >> 8);
TIM1_ARRL = (tim1_auto_reload & 0xFF);
timer_setcompare(500);
TIM1_RCR = 0;
TIM1_CCER1 = 0b1; //Enable Compare
TIM1_CCER1 |= 0b01; //Active Low
TIM1_CCMR1 = 0b1000; //Enable preload
TIM1_CCMR1 |= 0b01100000; //Set PWM Mode 1
TIM1_EGR |= 0b1; // Update event for new register settings
TIM1_BKR = 0b10000000; //enable output?
TIM1_CR1 = 0b1; //Enable Timer
outMsg("Timer Start Up Done\n");
}