hirenvaja
Newbie level 2
here is my code
Code C - [expand] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 #define sbi(port,bit) port |= (1<<bit) #define cbi(port,bit) port &= ~(1<<bit) #define cb(port,bit) port & (1<<bit) void clock_setup(); void spi_master_setup(); void spi_tx(unsigned char tx); void gpio_init(); void spi_enable(); void clock_setup() { sbi(RCC->APB2ENR,12); //enable clock for SPI1 sbi(RCC->AHB1ENR,0); //enable clock for GPIOA } void spi_master_setup() { cbi(SPI1->CR1,15); //spi 2 line unidirection full duplex sbi(SPI1->CR1,2); //spi1 in master mode cbi(SPI1->CR1,11); //SPI1 in 8 bit data format sbi(SPI1->CR1,1); //CPOL=1 clock polarity 1 when idle sbi(SPI1->CR1,0); //CPHA=1 second clock transition is the first data capture edge cbi(SPI1->CR1,9); //NSS software slave management--------------- SPI1->CR1 &= ~((1<<3) | (1<<4) | (1<<5)); //000 for prescaler fpclk/2 cbi(SPI1->CR1,7); //MSB first } void gpio_init() { GPIOA->MODER |= ((1<<11) | (1<<13) | (1<<15)); //set A5,A6,A7 as alternate function mode GPIOA->OTYPER &= ~((1<<5) | (1<<6) | (1<<7)); //output type pushpull GPIOA->OSPEEDR &= ~((1<<10) | (1<<11) | (1<<12) | (1<<13) | (1<<14) | (1<<15)); //output speed GPIOA->AFR[0] |= ((1<<20) | (1<<22)); //select AF5 for SPI_SCK GPIOA->AFR[0] |= ((1<<24) | (1<<26)); //select AF5 for SPI_MISO GPIOA->AFR[0] |= ((1<<28) | (1<<30)); //select AF5 for SPI_MISO sbi(GPIOA->MODER,0); //set 0th bit to set GPIOA_0 as output mode cbi(GPIOA->OTYPER,0); //Push-pull GPIOA->OSPEEDR &= ~((1<<0) | (1<<1)); //low speed sbi(GPIOA->ODR,0); } void spi_enable() { sbi(SPI1->CR1,6); } void spi_tx(unsigned char tx) { cbi(GPIOA->ODR,0); tx=SPI1->DR; while(!(cb(SPI1->SR,1))); SPI1->DR = tx; sbi(GPIOA->ODR,0); } void delayf(unsigned int x); int main() { unsigned char tx=0; clock_setup(); spi_master_setup(); gpio_init(); spi_enable(); while(1) { tx++; spi_tx(tx); delayf(10); } } void delayf(unsigned int x) { unsigned int i,j; for(i=0;i<x;i++) { for(j=0;j<1000;j++); } }
Last edited by a moderator: