spi.c

来自「SPI communications for ATmega128/ATmega2」· C语言 代码 · 共 40 行

C
40
字号
#include "spi.h"

void spi_init(void)
{
volatile unsigned char read_SPSR = 0;

      DDRB  |=  (1<<DDB0) | (1<<DDB1) | (1<<DDB2) | (1<<DDB4); //set SCK, MOSI and nSC as outputs
      PORTB |=  (1<<PB1); //set SCK high
      PORTB &= ~(1<<PB0); //set nCS low
      DDRB  &= ~(1<<DDB3); //set MISO as input
      PORTB &= ~(1<<PB3); //disable pull-up at MISO pin

      SPCR = (1<<SPE) | (1<<MSTR) | (1<<CPOL) | (1<<CPHA);
      read_SPSR = SPSR;

      for (unsigned char i = 0; i < 4; ++i)
            spi_send_byte(0xFF);

      PORTB |= (1<<PB0); //set nCS high
}


unsigned char spi_send_byte(unsigned char data)
{
volatile unsigned char read_SPSR = 0x00;
unsigned char incoming = 0x00;

      PORTB &= ~(1<<PB0); //select device

      read_SPSR = SPSR;
      SPDR = data;
      while (!(SPSR & (1<<SPIF)));
      incoming = SPDR;

      PORTB |= (1<<PB0); //set nCS high

      return incoming;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?