📄 mcp3208.c
字号:
#include <avr/io.h>
#include "mcp3208.h"
void MCP3208_spiDelay(unsigned int NOPcount)
{
unsigned int n;
for(n=0;n<=NOPcount;n++)
{
asm volatile ("nop" ::);
}
}
void MCP3208_spiInit(void)
{
// Set MOSI, SCK and ENB output, all other input
DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK)|(1<<DD_SS); // set DD_SS to output
// Enable SPI, Master, set clock rate fclk/64
// Setup (Falling) Sample (Rising) SPI set mode 3
// CPOL=1 : CPHA=1
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR1)|(0<<SPR0)|(1<<CPOL)|(1<<CPHA);
PORT_SPI |= (1<<(PIN_CS)); //setbitHigh CS Pin
PORT_SPI |= (1<<(PIN_MOSI)); //setbitHigh MOSI Pin
PORT_SPI |= (1<<(PIN_CLK)); //setbitHigh CLK Pin
}
unsigned char MCP3208_spiWrite(char cData)
{
// Start transmission
SPDR = cData;
// Wait for transmission complete
while (!(SPSR & (1<<SPIF)))
;
return SPDR;
}
unsigned int MCP3208_spiRead(unsigned char AD_type,unsigned char ADchanel)
{
unsigned char tempHigh,tempLow,tempADtype,dumyData;
PORT_SPI &= ~(1<<(PIN_CS)); //setbitLow CS Pin
MCP3208_spiDelay(delayCount );
tempADtype = (AD_type & 0x01) << 1 ;
tempLow = (ADchanel & 0x03) << 6;
tempHigh = (ADchanel & 0x04) >> 2;
tempHigh |= (0x04)|(tempADtype); // 0x04 --> startBit
dumyData = MCP3208_spiWrite(tempHigh); // Write control HighByte return not care
gReciveHighByte = MCP3208_spiWrite(tempLow); // Write control LowByte return A/D-MSB data
gReciveLowByte = MCP3208_spiWrite(0x00); // Write Null byte 0x00 return A/D-LSB data
MCP3208_spiDelay(delayCount );
PORT_SPI |= (1<<(PIN_CS)); //setbitHigh CS Pin
return (((gReciveHighByte & 0x0F)<<8)|gReciveLowByte); // return 16bit variable (12bit A/D data)
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -