PropWare
3.0.0.229
C++ objects and CMake build system for Parallax Propeller
Simple-Libraries
Learn
Simple Libraries
Convert
libspi_adc
spi_adc.c
1
/* spi_adc.c
2
* Use Serial Peripheral Interface to communicate with
3
* an MCP3202 to measure voltage across channels 0 and 1 to ground.
4
*
5
* Don't forget to double check your hardware, and post problems
6
* on the Parallax forums!
7
*
8
* Written by Andrew Enright
9
*/
10
#include "spi_adc.h"
// Include MCP3002.h, which includes simpletools.h
11
#include "
simpletools.h
"
12
13
//int MCP3002_init(int mosi, int miso, int clk, int csin, float vref)
14
//float MCP3002_getVolts(int ch);
15
16
17
18
float
MCP3202_getVolts(
int
ch,
int
mosi,
int
miso,
int
clk,
int
csin
,
float
vref) {
19
return
spi_adc(ch,mosi,miso,clk,
csin
,vref,12);
20
}
21
22
float
MCP3002_getVolts(
int
ch,
int
mosi,
int
miso,
int
clk,
int
csin
,
float
vref) {
23
return
spi_adc(ch,mosi,miso,clk,
csin
,vref,10);
24
}
25
26
float
spi_adc(
int
ch,
int
mosi,
int
miso,
int
clk,
int
csin
,
float
vref,
int
bits) {
27
if
(vref < 0) {
28
print
(
"Error! Float Vref = %f, should not be <= 0\n"
, vref);
29
}
else
{
30
short
bitsIn = 0b0000000000000000;
31
int
CS_ADC=
csin
, SCK=clk, MISO=miso, MOSI=mosi;
// DO = MOSI, DI = MISO
32
float
VREF = vref;
33
high
(CS_ADC);
34
low
(CS_ADC);
// CS_ADC low selects chip
35
//boot sequence: start, sgl/diff (1 for single-ended mode), odd/sign (channel in single-ended mode), msbf
36
if
(ch == 0){
37
shift_out
(MOSI, SCK,
MSBFIRST
, 4, 0b1101);
// Send "read channel 0 single-ended"
38
}
else
{
39
shift_out
(MOSI, SCK,
MSBFIRST
, 4, 0b1111);
// Send "read channel 1 single-ended"
40
}
41
bitsIn =
shift_in
(MISO,SCK,
MSBPOST
,bits);
42
float
volts = bitsIn * VREF / (pow(2,bits));
// 1024: 2^10, it's a 10-bit ADC after all.
43
high
(CS_ADC);
44
usleep(5);
45
shift_out
(MOSI, SCK,
MSBFIRST
, 1, 0b1);
46
return
volts;
47
}
48
return
-99.99;
49
}
50
shift_out
void shift_out(int pinDat, int pinClk, int mode, int bits, int value)
Send data to a synchronous serial device.
Definition:
shiftOut.c:19
low
void low(int pin)
Set an I/O pin to output-low.
Definition:
low.c:19
simpletools.h
This library provides convenient functions for a variety of microcontroller I/O, timing,...
print
int print(const char *format,...) __attribute__((format(printf
Print format "..." args to the default simple terminal device. The output is limited to 256 bytes.
shift_in
int shift_in(int pinDat, int pinClk, int mode, int bits)
Receive data from a synchronous serial device.
Definition:
shiftIn.c:20
MSBFIRST
#define MSBFIRST
For use with shift_out. Stands for most significant bit first.
Definition:
simpletools.h:417
csin
double complex csin(double complex z)
Complex sine function.
high
void high(int pin)
Set an I/O pin to output-high.
Definition:
high.c:19
MSBPOST
#define MSBPOST
For use with shift_in. Stands for most significant bit first, post-clock.
Definition:
simpletools.h:395
Generated on Fri May 20 2022 16:48:04 for PropWare by
1.8.17