Mikroelektronika MIKROE-350 Fiche De Données

Page de 526
Library Example
The code demonstrates how to use SPI library functions for communication between
SPI module of the MCU and Microchip's MCP4921 12-bit D/A converter
program SPI
' DAC module connections
dim Chip_Select as sbit at PORTB.B0
Chip_Select_Direction 
as sbit at DDRB.B0
' End DAC module connections
dim value as word
sub procedure InitMain()
DDA0_bit = 0                        ' Set PA0 pin as input
DDA1_bit = 0                        ' Set PA1 pin as input
Chip_Select = 1                     ' Deselect DAC
Chip_Select_Direction = 1            ' Set CS# pin as Output
SPI1_Init()                         ' Initialize SPI1 module
end sub
' DAC increments (0..4095) --> output voltage (0..Vref)
sub procedure DAC_Output(dim valueDAC as word)
dim temp as byte
Chip_Select = 0                        ' Select DAC chip
' Send High Byte
temp = 
word(valueDAC >> 8) and 0x0F    ' Store valueDAC[11..8] to
temp[3..0]
temp = temp or 0x30 ' Define DAC setting, see MCP4921 datasheet
SPI1_Write(temp)                       ' Send high byte via SPI
' Send Low Byte
temp = valueDAC     ' Store valueDAC[7..0] to temp[7..0]
SPI1_Write(temp)    ' Send low byte via SPI
Chip_Select = 1                        ' Deselect DAC chip
end sub
main:
InitMain()         ' Perform main initialization
value = 2048       ' When program starts, DAC gives
'   the output in the mid-range
while TRUE                             ' Endless loop
if  ((PINA0_bit)  and (value < 4095)) then ' If PA0 button is
pressed
Inc(value)                             '   increment value
else
365
MIKROELEKTRONIKA
- SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
Libraries
mikroBasic PRO for AVR
CHAPTER 6