HEADER FILE
#ifndef SPI_H
#define SPI_H
#include <8052.h>
#define SPI_SS P2_7
#define SPI_READ 0x03
#define SPI_WRITE 0x02
#define SPI_WRDI 0x04
#define SPI_WREN 0x06
#define SPI_RDSR 0x05
/* SPI Special Function Registers */
__sfr __at(0XD5) SPCR;
__sfr __at(0XAA) SPSR;
__sfr __at(0X86) SPDAT;
void spi_init();
char spi_tx_rx(char val);
void spi_write_enable();
void spi_write(char val, char addr);
char spi_read(char addr);
#endif
LIBRARY FILE
#include <8052.h>
#include "spi.h"
#include "string.h"
#define SPI_SS P2_7
void spi_init()
{
SPI_SS = 1;
SPSR = 0;
SPCR = 0x5c;
}
char spi_tx_rx(char val)
{
SPDAT = val; /* send data out spi port */
while (!(SPSR & 0x80)); /* wait for transfer to complete */
SPSR = 0;
return SPDAT;
}
void spi_write_enable()
{
SPI_SS = 0;
spi_tx_rx(SPI_WREN);
SPI_SS = 1;
delay(10);
}
void spi_write(char val, char addr)
{
spi_write_enable();
SPI_SS = 0;
spi_tx_rx(SPI_WRITE);
spi_tx_rx(addr);
spi_tx_rx(val);
SPI_SS = 1;
delay(10);
}
char spi_read(char addr)
{
char ret;
SPI_SS = 0;
spi_tx_rx(SPI_READ);
spi_tx_rx(addr);
ret = spi_tx_rx(0);
SPI_SS = 1;
return ret;
}
#ifndef SPI_H
#define SPI_H
#include <8052.h>
#define SPI_SS P2_7
#define SPI_READ 0x03
#define SPI_WRITE 0x02
#define SPI_WRDI 0x04
#define SPI_WREN 0x06
#define SPI_RDSR 0x05
/* SPI Special Function Registers */
__sfr __at(0XD5) SPCR;
__sfr __at(0XAA) SPSR;
__sfr __at(0X86) SPDAT;
void spi_init();
char spi_tx_rx(char val);
void spi_write_enable();
void spi_write(char val, char addr);
char spi_read(char addr);
#endif
LIBRARY FILE
#include <8052.h>
#include "spi.h"
#include "string.h"
#define SPI_SS P2_7
void spi_init()
{
SPI_SS = 1;
SPSR = 0;
SPCR = 0x5c;
}
char spi_tx_rx(char val)
{
SPDAT = val; /* send data out spi port */
while (!(SPSR & 0x80)); /* wait for transfer to complete */
SPSR = 0;
return SPDAT;
}
void spi_write_enable()
{
SPI_SS = 0;
spi_tx_rx(SPI_WREN);
SPI_SS = 1;
delay(10);
}
void spi_write(char val, char addr)
{
spi_write_enable();
SPI_SS = 0;
spi_tx_rx(SPI_WRITE);
spi_tx_rx(addr);
spi_tx_rx(val);
SPI_SS = 1;
delay(10);
}
char spi_read(char addr)
{
char ret;
SPI_SS = 0;
spi_tx_rx(SPI_READ);
spi_tx_rx(addr);
ret = spi_tx_rx(0);
SPI_SS = 1;
return ret;
}
No comments:
Post a Comment