📄 main.c
字号:
/*
Travis Lytle
This project takes data from an A2D via SPI and displays it via SCI to a terminal the voltage applied
in hex and in volts.
SPI A2D using AD7887 - http://www.analog.com/static/imported-files/data_sheets/AD7887.pdf
Using HCS12 S12UB board
HC12 A2D PIN
SCLK----------------CLK 8
SS------------------Chip Select 1
MOSI----------------DIN 6
MISO----------------DOUT 7
*/
#include <hidef.h> // common defines and macros
#include <mc9s12dg128.h> // derivative information
#pragma LINK_INFO DERIVATIVE "mc9s12dg128b"
#include <stdio.h>
void initSPI0(void);
uint ad7887(uchar);
void initSCI0(void);
char getChar(void), getString(char *);
void putChar(char), putString(char *);
uint a2dresult, ones, tenths, hundredths;
char volts[25];
ulong a2d, temp;
void main(void)
{
uchar ch;
initSPI0();
initSCI0();
while(1)
{
ch = getChar(); //used to check for keyboard input
if(ch == 0x20){ //checks for space key input
a2dresult = ad7887(0x21); //queries the A2D
temp = (ulong)a2dresult * 1221;
ones = temp / 1000000;
temp = (temp - (1000000* ones));
tenths = temp/100000;
temp = (temp - (100000*tenths));
hundredths = temp /10000;
sprintf(volts, "Hex:%4X Voltage:%d.%d%d", a2dresult, ones, tenths, hundredths);
putString(volts);
putString("\n\r");
}
}
}
void initSPI0(void)
{
SPI0CR1 = 0x5E; //SPI on, set to master, and clock phase bit CPOL, CPHA, SSOE on
SPI0CR2 = 0x10; //MODFEN enabled
SPI0BR = 0x77; //SPI Baud Rate
}
uint ad7887(uchar cr)
{
uchar ub, lb; //upper and lower bytes
uint ad; //upper and lower bytes in one variable
while (!(SPI0SR & 0x20));
SPI0DR = cr; //control register
while (!(SPI0SR & 0x80));
ub = SPI0DR; //recieve dummy data
while (!(SPI0SR & 0x20));
SPI0DR = cr; //control register
while (!(SPI0SR & 0x80));
lb = SPI0DR;
ad = ub <<8;
ad = ad | lb;
return ad; //return data
}
void initSCI0() {
char x;
SCI0BDH = 0x00; //Baud Rate H Byte
SCI0BDL = 26; //Baud Rate L Byte 9600 Baud
SCI0CR1 = 0x00;
SCI0CR2 = 0x0C; //TE and RE enabled
x = SCI0SR1; //status reg clears RDRF flag
x = SCI0DRL; //data reg
}
char getString(char *buf)
{
while((*buf++ = getChar()) != 0x0D){;}
*buf = 0; //terminate string with a NULL char
}
void putString(char *cx)
{
while((*cx))
{
putChar(*cx);
cx++;
}
}
/* gets a char from the serial input.
waits for RDRF flag, which is recieve data registry full*/
char getChar(void)
{
while((SCI0SR1 & 0x20) == 0x00);
return (SCI0DRL);
}
/* puts a char to the serial input.
waits for TDRE flag, which is transmit data registry empty*/
void putChar(char cx)
{
while(!(SCI0SR1 & 0x80)); //comment line out so data is sent rapidly and buffer does not get cleared
SCI0DRL = cx;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -