phase shift 180 deg

In this example I am shifting the phase, it is working ok for 90 deg, for 180 deg there are distortions of sine wave.
The question - how to shift 180 deg withouth distortions ?

val1[i] = sin_zero + amp * sin(stp * i);  //0 deg, 
val2[i] = sin_zero + amp * cos(stp * i); // 90 deg, ok
val3[i] = sin_zero + amp * asin(stp * i); // 180 deg, distortions

Try using an op amp. Your signal attaches to the - input, the output will be 180 out of phase compared to the input

asin is for arcsin.

you could use

sin_zero - amp * sin(stp * i);

or

sin_zero + amp * sin(stp * i + PI);

if you define PI, maybe in math.h it is?

Here is an example sketch to phase shift a sin wave 90 and 180 deg (select 115200 in Plotter Serial):

const uint16_t SinSize = 256;  // A power of 2
double sine[SinSize];

void setup() {

  Serial.begin(115200);

  sine[0] = 0.0000;
  for (int i=0; i<SinSize; i++) {
    sine[i] = 200 * (sinf(i * 2 * PI / (SinSize-1)));
  }
}

void loop() {
  uint32_t var;
  static uint16_t i;

  delay(5);
  i = (i + 1) & 0b11111111;         // Discard all bits above SinSize
  Serial.print((int)sine[i]);       // Print waveform

  Serial.print(" ");                // print a blanck
  var = (i + SinSize/4) & 0b11111111;
  Serial.print((int)sine[var]);     // Print waveform

  Serial.print(" ");                // print a blanck
  var = (var + SinSize/2) & 0b11111111;
  Serial.println((int)sine[var]);   // Println waveform

}

alto777:
sin_zero - amp * sin(stp * i);

Thanks, this is working.

Thanks ard, I will use that also, for learning.

noweare, I know analog electronics, I want to replace it by programming.

ard

What determines the frequency of this generator, can it work at 10 kHz ?

ard uses a delay(5), that's the main thing that takes time in the loop so this generates ~200 Hz, did that math in my head so check.

Remove the delay(5) and you'll see the max frequency this scheme can attain - slightly faster if you strip out the Serail.stuff. Toggle a LED in the loop() to see the frequency / 2 as a square wave. Obviously any work you do with the sine table values will slow you down, that is lower the frequency.

If you want predictable and constant frequencies it will take another scheme, interrupt driven timing would be one way.

The big win is stashing the sin values, then using offset indexing to get phase shifted values from one table. Nice with a power of two, automatic modular arithmetic!

Thanks for explanation, I will try that. For square wave I have a simple program but there is a small problem, look at my new topic.

"The pin problem"

Well I realize now that the frequency through the loop will mean the number of samples per second, so the sin wave you'd get from, say, an D/A conversion would be that frequency divided by the table size.

Google "edgar synth arduino" for a different way to use tables for waveform generation.

a7