10位DAC生成 100Hz左右的三角波- /* 4 MHz (needed for delay function) */
- #define F_CPU (4000000UL)
- #include <avr/io.h>
- #include <util/delay.h>
- #include <math.h>
- /* 参考电压延迟 */
- #define VREF_STARTUP_TIME (50)
- /* 低2位 */
- #define LSB_MASK (0x03)
- /* 单周期点数 */
- #define Single_Wave_Dots (400)
- /* 偏置电压 */
- #define DC_OFFSET (510)
- /* 频率 */
- #define FRE (100)
- /* 每个点延迟时间 */
- #define Bit_Period ((1000000 / FRE) / Single_Wave_Dots)
- static void tWaveInit(void);
- static void VREF_init(void);
- static void DAC0_init(void);
- static void DAC0_setVal(uint16_t value);
- /* Buffer to store the sine wave samples */
- signed int tWave[Single_Wave_Dots];
- signed int tx ;
- static void tWaveInit(void)
- {
- uint16_t i;
- for(i = 0; i < Single_Wave_Dots; i++)
- {
- if( i>99 && i <300){
- tx = 200-i ;
- }
-
- if (i >299){
- tx = i-400 ;
- }
- if (i >0 && i <100 ){
- tx = i ;
- }
- tWave[i] = DC_OFFSET + tx*5;
- }
- }
- static void VREF_init(void)
- {
- VREF.DAC0REF = VREF_REFSEL_2V048_gc /* Select the 2.048V Internal Voltage Reference for DAC */
- | VREF_ALWAYSON_bm; /* Set the Voltage Reference in Always On mode */
- /* Wait VREF start-up time */
- _delay_us(VREF_STARTUP_TIME);
- }
- static void DAC0_init(void)
- {
- /* Disable digital input buffer */
- PORTD.PIN6CTRL &= ~PORT_ISC_gm;
- PORTD.PIN6CTRL |= PORT_ISC_INPUT_DISABLE_gc;
- /* Disable pull-up resistor */
- PORTD.PIN6CTRL &= ~PORT_PULLUPEN_bm;
- DAC0.CTRLA = DAC_ENABLE_bm /* Enable DAC */
- | DAC_OUTEN_bm /* Enable output buffer */
- | DAC_RUNSTDBY_bm; /* Enable Run in Standby mode */
- }
- static void DAC0_setVal(uint16_t value)
- {
- /* Store the two LSbs in DAC0.DATAL */
- DAC0.DATAL = (value & LSB_MASK) << 6;
- /* Store the eight MSbs in DAC0.DATAH */
- DAC0.DATAH = value >> 2;
- }
- int main(void)
- {
- short tindex = 0;
-
- VREF_init();
- DAC0_init();
-
- tWaveInit();
-
- while (1)
- {
- DAC0_setVal(tWave[tindex++]);
- if(tindex == Single_Wave_Dots)
- tindex = 0;
- _delay_us(Bit_Period);
- }
- }
|