AVR Embedded Tutorial - SPI MCP4922/de

From Lazarus wiki
Jump to navigationJump to search

Template:Translate

12Bit DAC MCP4922 über SPI ansteuern.

Vorwort

Dieser Code ist für einen Atmega328/Arduino mit 16MHz und MCP4922.


Die folgenden Funktionen, sind in folgenden Tutorials beschrieben:

Beschreibung

Dieses Beispiel zeigt, wie man den DAC MCP4922 über SPI ansteuert.

Funktionen für die Beschreibung von 74HC595 Schieberegister

Konstanten

Pins welche an PORTB für SPI benötigt werden.

type
  TSPIGPIO = bitpacked record
    p0, p1, SlaveSelect, MOSI, MISO, Clock, p6, p7: boolean;
  end;

var
  SPI_PORT: TSPIGPIO absolute PORTB;
  SPI_DDR:  TSPIGPIO absolute DDRB;

SPI Funktionen

SPI initialisieren

procedure SPIInit;
begin
  // SPI-Port auf Ausgabe
  SPI_DDR.MOSI := True;
  SPI_DDR.Clock := True;
  SPI_DDR.SlaveSelect := True;

  SPCR := ((1 shl SPE) or (0 shl SPIE) or (0 shl DORD) or (1 shl MSTR) or (0 shl CPOL) or (0 shl CPHA) or (%01 shl SPR));
  SPSR := (1 shl SPI2X);  // SCK x 2 auf 1 MHZ
end;

SPI schreiben

procedure SPIWrite(p: PByte; len: byte);
var
  i: byte;
begin
  SPI_Port.SlaveSelect := False;
  for i := len - 1 downto 0 do begin
    SPDR := p[i];
    while (SPSR and (1 shl SPIF)) = 0 do begin
    end;
  end;
  SPI_Port.SlaveSelect := True;
end;

MCP4922 Funktionen

Bit-Belegung des MCP4922:

Bit Bezeichnung Beschreibung
15 A/B: DACA or DACB Selection bit 0 = Write to DACA
1 = Write to DACB
14 BUF: Vref Input Buffer Controlbit 0 = Unbuffered
1 = Buffered
13 GA:Output Gain Selection bit 0 = 2x (VOUT = 2 * VREF * D / 4096)
1 = 1x (VOUT = VREF * D / 4096)
12 SHDN: Output Shutdown Control bit 0 = Shutdown the selected DAC channel. Analog output is not available at the channel that was shut down. VOUT pin is connected to 500 kOhm(typical)
1 = Active mode operation. VOUT is available.
11:0 D11:D0: DAC Input Data bits. Bit x is ignored.


Ausgabe an DAC

procedure MCP4922sendValue(Value: UInt16; Channel: Byte);
type
  TADC = bitpacked record
    Value: 0..4095; // Bit 0-11
    ShutDown,       // Bit 12
    Gain,           // Bit 13
    VRef,           // Bit 14
    DAC: 0..1;      // Bit 15 
  end;

begin
  with TADC(Value) do begin
    ShutDown := 1;
    Gain     := 1;
    VRef     := 0;
    Dac      := Channel;
  end;

  SPIWrite(@Value, 2);
end;

Beispiel

Dieses Beispiel zeigt die Ausgabe von 2 Analogwerten aus dem DAC. 2 LEDs am Analog blinken abwechslungsweise, wobei der Übergang sehr sanft ist.

Konstanten und Variablen

Eine Zähl-Variable die auf 4095 hochzählt.

var
  z: Int16;

Hauptprogramm

Abwechselnd einen Wert in DAC 0& 1 schrieben.

begin
  // SPI initialisieren.
  SPIInit; 

  repeat
    for z := 0 to 4095 do begin
      MCP4922sendValue(4095 - z, 0);
      MCP4922sendValue(z, 1);
    end;
  until 1 = 2;
end.

Siehe auch

Autor: Mathias