不韋 呂 / UIT_ADDA

Dependents:   UIT2_MovingAverage UIT2_AllpassReverb UIT2_CombReverb UIT2_FIR_LPF_Symmetry ... more

DAC_MCP4922.cpp

Committer:
MikamiUitOpen
Date:
2014-12-21
Revision:
14:6c60601c1834
Parent:
11:a764fe59d343
Child:
16:0001d3e93bee

File content as of revision 14:6c60601c1834:

//------------------------------------------------------
// Class for single DAC in MCP4922
//
// 2014/12/21, Copyright (c) 2014 MIKAMI, Naoki
//------------------------------------------------------

#include "DAC_MCP4922.hpp"

namespace Mikami
{
    DAC_MCP4922::DAC_MCP4922(DAC dac, PinName mosi, PinName sclk,
                             PinName cs, PinName ldac, int hz)
        : wcr_(dac | 0x3000), spi_(mosi, NC, sclk),
          ld_(ldac, 0), mySpi_((SPI_TypeDef*)NULL)
    {
        if ( (mosi == PA_7) || (mosi == PB_5) )  mySpi_ = SPI1;
        if ( (mosi == PB_15) || (mosi == PC_3) ) mySpi_ = SPI2;
        if ( mosi == PC_12 )                     mySpi_ = SPI3;

        // Set SPI format and bus frequency
        spi_.format(16, 0);
        spi_.frequency(hz);
            
        // timer prescaler is set same value of boud rate for SPI
        uint16_t psc = (2 << ((mySpi_->CR1 >> 3) & 0x07)) - 1;
        ss_ = new Tim4_ss(psc, 18, cs);
        
        // Set DAC to 0
        WriteDac(0);
        while (IsBusy()) {}
    }

    void DAC_MCP4922::Write(float value)
    {
        if (value < -1.0f) value = -1.0f;
        if (value >  1.0f) value =  1.0f;

        WriteDac((uint16_t)((value + 1.0f)*2047));
    }

    void DAC_MCP4922::Write(uint16_t value)
    {
        WriteDac((value > 4095) ? 4095 : value);
    }
        
    void DAC_MCP4922::Ldac()
    {
        ld_.write(0);
        ld_.write(0);   // ensure width of "L" pulse
        ld_.write(1);
    }

    void DAC_MCP4922::WriteDac(uint16_t value)
    {
        ss_->SlaveSelect();
        mySpi_->DR = value | wcr_;
    }

    void DAC_MCP4922::ScfClockTim3(uint32_t clock, PinName pin)
    {
        if ( (pin != PA_6) && (pin != PB_4) && (pin != PB_5) &&
             (pin != PC_6) && (pin != PC_7) && (pin != PC_8) && (pin != PC_9) )
        {
            fprintf(stderr, "\r\nIllegal pin name in DAC_MCP4922::ScfClockTim3()\r\n");
            while (true) {}
        }

        PwmOut clockSCF(pin);
        
        TIM3->ARR =  SystemCoreClock/clock - 1;
        TIM3->PSC = 0;
        // Set capture/compare register 2
        if ( (pin == PA_6) || (pin == PB_4) || (pin == PC_6) )
            TIM3->CCR1 = (TIM3->ARR + 1)/2;    
        if ( (pin == PB_5) || (pin == PC_7) )
            TIM3->CCR2 = (TIM3->ARR + 1)/2;    
        if (pin == PC_8)
            TIM3->CCR3 = (TIM3->ARR + 1)/2;    
        if (pin == PC_9)
            TIM3->CCR4 = (TIM3->ARR + 1)/2;    
    }
}