⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 spi.c

📁 SPI communications for ATmega128/ATmega2560 (native SPI and UART in SPI-mode).
💻 C
字号:
#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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -