AVR

SPI master

작성자 임베디드코리아 작성일17-10-11 12:12 조회2,662회 댓글0건
#define F_CPU 14745600UL

//1. baud rate를 선택
#define USART_BAUDRATE 115200

//2.시스템 클록과 원하는 baud rate를 이용하여 UBRR 값을 계산한다.
#define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

#include <avr/io.h>
#include <stdio.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <string.h>

unsigned char SPI_Tx(unsigned char Data);
void usartInit();
void print_udr(unsigned data);
void init_SPI_master();
void init_interrupt(void);

unsigned char *str;

int main(void){
usartInit();
init_SPI_master();
init_interrupt();
PORTB &= ~(1<<PORTB0);

print_udr(SPI_Tx('a'));
print_udr(SPI_Tx('b'));
print_udr(SPI_Tx('c'));
print_udr(SPI_Tx('d'));

PORTB |= 1<<PORTB0;

while(1){}
}

void init_interrupt(){
cli();
_delay_ms(2);
SPCR |= ((1<<SPE)|(1<<SPIE));
sei();
_delay_ms(2);
}

void usartInit(){
//3. UBRR0은 16비트 레지스터이기 때문에 8비트씩 나누어서 넣어야 한다.
UBRR0H = (uint8_t)(UBRR_VALUE>>8);
UBRR0L = (uint8_t) UBRR_VALUE;

//4. USART 설정
UCSR0C |= (1<<UCSZ00)|(1<<UCSZ01); //Charecter size : 8비트
UCSR0C &= ~(1<<USBS0); //stop  bit : 1비트
UCSR0C &= ~((1<<UPM01)|(1<<UPM00)); // no parity mode

//5. 송수신을 가능하게 한다.
UCSR0B=(1<<RXEN0)|(1<<TXEN0);
}
void print_udr(unsigned data){
while(!(UCSR0A&(1<<UDRE0)));
UDR0 = data;
_delay_ms(2);
}
void init_SPI_master(){
DDRB |= ((1<<PORTB1)|(1<<PORTB2)|(1<<PORTB0));
DDRB &= ~(1<<PORTB3);
SPCR |= 1<<MSTR;
SPCR |= (1<<SPR0);
}
unsigned char SPI_Tx(unsigned char Data){
SPDR = Data;
while(!(SPSR & (1<<SPIF)));
_delay_ms(2);
return SPDR;
}
ISR(SPI_STC_vect){}