/* * File name: test_cap2.c * Date first: 01/08/2018 * Date last: 01/09/2018 * * Description: STM8 test program for capture on Timer2 * * Author: Richard Hodges * * Copyright (C) 2018 Richard Hodges. All rights reserved. * Permission is hereby granted for any use. * ****************************************************************************** * * This program tests the timer2 capture library by receiving serial bits * from another host and sending the capture counts back. To use this, connect * a TTL to USB adapter to pins 2 (TX) and 3 (RX) and power and ground. Be * sure to connect the USB adapter RX to STM TX and TX to RX. On the other * host, use a terminal program (eg, minicom) to send bytes and display the * capture results. * ****************************************************************************** * * Pinout: * * Pin 1, PD4: Timer2 channel 1 * Pin 2, PD5: UART TX * Pin 3, PD6: UART RX * * Pins 1 and 3 connected so that RX bytes also go to Timer2 capture. */ #include "stm8.h" #include "lib_uart.h" #include "lib_cap2.h" #include "lib_bindec.h" void setup(void); /****************************************************************************** * * Receive bits to UART, capture the bit lengths, print to UART TX */ int main() { char decimal[12]; int count; char bitct, assembled, val; setup(); uart_init(BAUD_9600); cap2_init(CAP2_16_MHZ); while (1) { while (!uart_rsize()); /* wait for UART byte */ while (uart_rsize()) { /* normally only one, but use all */ val = uart_get(); uart_puts("\r\nReceived '"); uart_put(val); uart_puts("' 0x"); bin8_hex(val, decimal); uart_puts(decimal); uart_puts("\r\n"); } bitct = 0; assembled = 0; while (cap2_count()) { count = cap2_get(); bitct++; if (bitct < 2) continue; /* throw away count before start bit */ bin16_dec(count, decimal); decimal_rlz(decimal, 4); uart_puts(decimal); uart_put(' '); count /= 1582; /* 1666 per bit +- 5% */ if (bitct == 2) count--; /* first sample, drop start bit */ while (count) { assembled >>= 1; if (bitct & 1) assembled |= 0x80; count--; } } uart_puts(" (assembled=0x"); bin8_hex(assembled, decimal); uart_puts(decimal); uart_puts(") overflow="); bin16_dec(cap2_overflow(), decimal); uart_puts(decimal); uart_puts("\r\n"); } } /****************************************************************************** * * Initial setup */ void setup(void) { CLK_CKDIVR = 0; /* clock 16mhz */ PA_DDR = 0x00; /* start with all inputs */ PA_CR1 = 0xff; /* weak pull-ups */ PA_CR2 = 0x00; /* no interrupts */ PB_DDR = 0x20; /* PB5 is LED */ PB_CR1 = 0xff; PB_CR2 = 0x00; PC_DDR = 0x00; PC_CR1 = 0xff; PC_CR2 = 0x00; PD_DDR = 0x00; PD_CR1 = 0xef; /* IMPORTANT: no pullup for PD4 */ PD_CR2 = 0x00; __asm__ ("rim"); }