MCP4725 sinewave generator

I am using a MCP generator to genrate sinewaves, I used Adafruit exmple, it can generate it, so the circuit is no problem. But when I wrote the follow code, the device cannot generate any waves, I cannot find the problem, any body knows?

void loop(void) {
if (currentMillis - previousMillis1 >= period1) {
  uint16_t i;
  if (i>128) {
  i=0;
  }
  previousMillis1 = currentMillis;  
  dac1.setVoltage(4096.0 * (sin(2.00 * PI / 128.0 * (float)i)) , false);
  i++;
   }
}

(Code tags added by moderator. Next time, please use the </> button on the menu bar).

at least 2 problem

divide i by 128
dac1.setVoltage(4096.0 * (sin(2 * PI * i / 128.0)) , false);

need i to be persistent, so either define it outside the function or make it static within the function

Looks and reads better but here early in the AM is the same valeu as

4096.0 * (sin(2.00 * PI / 128.0 * (float)i))

Is PI build in, or st least 3.14159265358979323846 somewhere?

a7

the important issue what the i variable being dynamic

1 Like


Why the wave like this?

because sinusoids are both positive and negative

make the magnitude half of what it is (2048 and add that as an offset so that the sinusoid is from 0-(2*Magnitude)


I modified it like this:
dac2.setVoltage(2048.0 + 4096 * (sin(2.00 PI / 100.0(float)j) ) , false);
But the wave become this.

dac2.setVoltage(2048 + 2048 * (sin(2 *PI / 100.0*(float)j) ) , false);

Thank you very much!
It's been solved!

Hi, @seiyou
Can you please post your final working code so others looking for a similar solution can see it.

Thanks.. Tom... :grinning: :+1: :coffee: :australia:

... and a picture of the waveform

#include <Wire.h>
#include <Adafruit_MCP4725.h>

Adafruit_MCP4725 dac1

unsigned long previousMillis1 = 0;
const long period1 = 0;
unsigned long currentMillis = millis();

void setup(void) {
Serial.begin(9600);
dac1.begin(0x61);
}

uint16_t i;
void loop(void) {
if (currentMillis - previousMillis1 >= period1) {
if (i>50) {
i=0;
}
previousMillis1 = currentMillis;
dac1.setVoltage(2047.0 + 2047.0 * (sin(2.00 * PI / 50 * (float)i)) , false);
i++;
}
}

image

MCP4725 generating sinewaves' frequency is too low. When I increase the frequency,the waves are easily distorted. whether the MCP4275's resolution is too low? any method can resolve this problem?

Hi,
Code tags on your code would help thanks...

To add code please click this link;

Thanks.. Tom... :grinning: :+1: :coffee: :australia:

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.