|
การใช้งาน PIC18F4520 กับ MCP4922 DAC 12 บิต
PIC18F4520 การใช้งานโมดูล MSSP ในโหมด SPI ควบคุมไอซี MCP4922 (12-Bit DAC
with SPI Interface) ไอซีสร้างแรงดันอะนาลอกความละเอียด 12 บิต (0 ถึง 4095) เชื่อมต่อแบบ
SPI โดยอาศัย spi.h ควบคุมไอซี MCP4922
เพื่อสร้างแรงดันอะนาลอก
1 : //-----------------------------------------------:
2 : // File : MCP4922.c
3 : // Purpose : MSSP (SPI Mode)
4 : // Author : Prajin Palangsantikul
5 : // Compiler : MPLAB C18 Compiler
6 : // Target : PIC18Fxxxx
7 : //-----------------------------------------------:
8 : #include "p18cxxx.h" // Device config form Project
9 : #include "delays.h" // PIC18
cycle-count delay routines
10 :#include "spi.h"
// SPI Functions
11 :
12 : //-------------------------------------------:Configuration Bits
13 : // HS Oscillator Selection, Watchdog Timer OFF
14 : #pragma config OSC = HS, WDT = OFF
15 : // Low Voltage Programming : Disabled
16 : #pragma config LVP = OFF
17 :
18 : #define CFG_DACA 0x3000 //0b0011 000000000000
19 : #define CFG_DACB 0xB000 //0b1011 000000000000
20 :
21 : #define SET_SCK TRISCbits.TRISC3
22 : #define SET_SDO TRISCbits.TRISC5
23 : #define SET_CS TRISAbits.TRISA0
24 : #define DAC_CS LATAbits.LATA0
25 :
26 : //-----------------------------------------------:delay for 1 ms
27 : void delay_ms(unsigned int ms)
28 : {
29 : for (;ms>0;ms--)
30 : {
31 : Delay1KTCYx(5); // Delay of 1 ms
32 : }
33 : }
34 :
35 : //-----------------------------------------------:Write DAC
36 : void write_dac(int data)
37 : {
38 : DAC_CS =
0;
// Enable Chip
39 : while(WriteSPI(data>>8)); // Write High Byte
40 : while(WriteSPI(data)); // Write
Low Byte
41 : DAC_CS =
1;
// Disable Chip
42 : }
43 :
44 : //-----------------------------------------------:Main
45 : void main (void)
46 : {
47 : int dac_a = 100;
48 : int dac_b = 4095;
49 :
50 : PORTA = 0; // Clear PORTA
register
51 : LATA = 0; // Clear LATA
register
52 : PORTC = 0; // Clear PORTC
register
53 : LATC = 0; // Clear LATC
register
54 :
55 : SET_SDO = 0; // Set RC5/SDO, RC3/SCK
56 : SET_SCK = 0;
57 : SET_CS = 0; // Set CS output
58 :
59 : // SPI Configure
60 : OpenSPI(SPI_FOSC_16, // SPI Master mode, clock = Fosc/16
61 :
MODE_00, // Setting for SPI bus Mode 0,0
62 :
SMPEND); // Input data sample at end of data
out
63 :
64 : write_dac(CFG_DACA|dac_a); // Write Vouta
65 : write_dac(CFG_DACB|dac_b); // Write Voutb
66 :
67 : while (1)
68 : {
69 : write_dac(CFG_DACA|dac_a); // Write Vouta
70 : write_dac(CFG_DACB|dac_b); // Write Voutb
71 :
delay_ms(100);
// Delay 0.1s
72 : dac_a +=
100;
// Increment 100
73 : dac_b -=
100;
// Decrement 100
74 : if (dac_a >
4095) // Check
dec_a
75 : dac_a =
100;
// Set to 100
76 : if (dac_b <
0)
// Chec dec_b
77 : dac_b =
4095;
// Set to 0
78 : }
79 : }
|