Created
August 2, 2020 00:50
-
-
Save chronopoulos/d34de9b6119d4ec052451d6afaa99e79 to your computer and use it in GitHub Desktop.
testing I2C on the STM32L1 using libopencm3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <libopencm3/stm32/rcc.h> | |
#include <libopencm3/stm32/gpio.h> | |
#include <libopencm3/stm32/usart.h> | |
#include <libopencm3/stm32/i2c.h> | |
static void clock_setup(void) { | |
rcc_clock_setup_hsi(&rcc_clock_config[2]); // 16mhz hsi raw | |
} | |
static void gpio_setup(void) { | |
rcc_periph_clock_enable(RCC_GPIOA); | |
gpio_mode_setup(GPIOA, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO5); | |
} | |
static void usart_setup(void) { | |
rcc_periph_clock_enable(RCC_USART1); | |
gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO9); | |
gpio_set_af(GPIOA, GPIO_AF7, GPIO9); | |
usart_set_baudrate(USART1, 115200); | |
usart_set_databits(USART1, 8); | |
usart_set_parity(USART1, USART_PARITY_NONE); | |
usart_set_stopbits(USART1, USART_CR2_STOPBITS_1); | |
usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE); | |
usart_set_mode(USART1, USART_MODE_TX); | |
usart_enable(USART1); | |
setbuf(stdout, NULL); // optional | |
} | |
static void i2c_setup(void) { | |
rcc_periph_clock_enable(RCC_I2C1); | |
gpio_mode_setup(GPIOB, GPIO_MODE_AF, GPIO_OTYPE_OD, GPIO8 | GPIO9); | |
gpio_set_af(GPIOB, GPIO_AF4, GPIO8 | GPIO9); | |
i2c_peripheral_disable(I2C1); | |
i2c_set_clock_frequency(I2C1, I2C_CR2_FREQ_36MHZ); | |
i2c_set_fast_mode(I2C1); | |
i2c_set_ccr(I2C1, 0x1e); | |
i2c_set_trise(I2C1, 0x0b); | |
i2c_peripheral_enable(I2C1); | |
} | |
//// | |
int main(void) { | |
int i; | |
clock_setup(); | |
gpio_setup(); | |
usart_setup(); | |
i2c_setup(); | |
while (1) { | |
// blink the LED | |
gpio_set(GPIOA, GPIO5); | |
for (i = 0; i < 1000000; i++) { | |
__asm__("nop"); | |
} | |
gpio_clear(GPIOA, GPIO5); | |
for (i = 0; i < 1000000; i++) { | |
__asm__("nop"); | |
} | |
// query an i2c address | |
i2c_send_start(I2C1); | |
i2c_send_7bit_address(I2C1, 0x18, I2C_WRITE); | |
i2c_send_stop(I2C1); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment