Example Code for Arduino-Output a Triangle Wave

How to use Arduino and the MCP4725 DAC module to output a triangle wave, providing detailed hardware and software setup instructions, sample code, and guidance on adjusting waveform parameters such as amplitude, frequency, DC offset, and duty cycle.

Hardware Preparation

Software Preparation

Wiring Diagram


Other Preparation Work

  • Set the I2C address to 0x60 with the ADDR switch. For I2C address 0x61, you need to modify the first parameter of the DAC.init () function in the code below.
  • Open Arduino IDE, upload the following sample code to the Arduino UNO, and use a oscilloscope to measure the output voltage of VOUT.
  • The user can modify the parameter in DAC.outputTriangle () to change the amplitude, frequency, DC offset and duty cycle of the triangular wave.

Sample Code

/*
 * file OutputVoltage.ino
 *
 * @ https://github.com/DFRobot/DFRobot_MCP4725
 *
 * connect MCP4725 I2C interface with your board (please reference board compatibility)
 *
 * Output a constant voltage value and print through the serial port.
 *
 * Copyright   [DFRobot](https://www.dfrobot.com), 2016
 * Copyright   GNU Lesser General Public License
 *
 * version  V1.0
 * date  2018-1-25
 */
#include "DFRobot_MCP4725.h"
#define  REF_VOLTAGE    5000

DFRobot_MCP4725 DAC;

void setup(void) {
  Serial.begin(115200);
  /* MCP4725A0_address is 0x60 or 0x61
   * MCP4725A0_IIC_Address0 -->0x60
   * MCP4725A0_IIC_Address1 -->0x61
   */
  DAC.init(MCP4725A0_IIC_Address0, REF_VOLTAGE);
}

void loop(void) {
  /*Output amplitude 5000mv, frequency 10HZ,
   *the rise of the entire cycle accounted for 50% of the DC offset 0mv triangular wave.
   */
  DAC.outputTriangle(5000,10,0,50);
}

Result

  • A full triangular wave of 5V (peak-to-peak), 10Hz, duty cycle of 50% without DC bias can be observed

Additional Information

/**
   * @fn outputTriangle
   * @brief  Output a sine wave.    
   * @param  amp amp value, output triangular wave amplitude range 0-5000mv
   * @param  freq freq value, output the triangle wave frequency
   * @param  offset offset value, output the DC offset of the triangle wave
   * @param  dutyCycle dutyCycle value, set the rising percentage of the triangle wave as a percentage of the entire cycle.
   * @n      Value range 0-100 (0 for only the decline of 100, only the rise of paragraph)
   * @return None
   */
  void outputTriangle(uint16_t amp, uint16_t freq, uint16_t offset, uint8_t dutyCycle);

  • Change the dutyCycle to 0 while the other parameters remain the same. That is "DAC.outputTriangle (5000,10,0,0)", which can generate a 10Hz sawtooth wave of 5V in amplitude.

Was this article helpful?

TOP