要求单片机A的按钮控制单片机B的LED亮灭
发送端
/*
* RX.c
*
* Created: 2016/3/19 15:24:34
* Author: Jon.Wei
*/
#include <io.h>
#include "delay.h"
#define uint unsigned int
#define uchar unsigned char
uchar key;
void SPI_MasterInit(void)
{
/* 设置 MOSI 和 SCK 为输出,其他为输入 */
DDRB = (1<<5)|(1<<7);
/* 使能 SPI 主机模式,设置时钟速率为 fck/16 */
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}
void SPI_MasterTransmit(uchar cData)
{
/* 启动数据传输 */
SPDR = cData;
/* 等待传输结束 */
while(!(SPSR & (1<<SPIF)))
;
}
void main(void)
{
DDRA=0x00;
PORTA=0xff;
SPI_MasterInit();
while (1)
{
key=PINA.0;
SPI_MasterTransmit(key);
delay_ms(200);
}
}
接收端
/*
* tx.c
*
* Created: 2016/3/19 15:38:06
* Author: Jon.Wei
*/
#include <io.h>
#include "delay.h"
#define uint unsigned int
#define uchar unsigned char
void SPI_SlaveInit(void)
{
/* 设置 MISO 为输出,其他为输入 */
DDRB = (1<<6);
/* 使能 SPI */
SPCR = (1<<SPE);
}
uchar SPI_SlaveReceive(void)
{
/* 等待接收结束 */
while(!(SPSR & (1<<SPIF)))
;
/* 返回数据 */
return SPDR;
}
void main(void)
{
DDRC=0xff;
PORTC=0xff;
SPI_SlaveInit();
while (1)
{
PORTC.0=SPI_SlaveReceive();
delay_ms(100);
}
}
|