Signal generator acquisition

Hello, I would like to acquire a sinusoidal waveform generated by a waveform generator.
I would like to acquire 512 samples of a sine with a frequency of 100Hz.

I’m trying something like this but the plot is wrong. Can you help me?

#include <Wire.h>

const int inPin = 34;
const int freq=200; //2 times sine f
unsigned int sampling_period_us;
unsigned long microseconds;
double x[512];

void setup(void)
{
Serial.begin(9600); 

sampling_period_us = round(1000000*(1.0/freq));
 
}


void loop(void)
{

microseconds = micros();

for(int i=0; i<512; i++){

  x[i]=analogRead(inPin);

while(micros() - microseconds < sampling_period_us){
        //empty loop
      }
      microseconds += sampling_period_us;

Serial.println(x[i]);   
}

Don’t print in the sampling loop.

Printing takes a lot of time, especially at such a low Baud rate, and the time to print is variable, which completely invalidates the sample interval.

Sampling theory says that the sample rate frequency must be greater than twice the highest frequency in the signal

100 Hz, 10 ms per cycle. I'd want those 512 samples to be a bit more than one cycle. One cycle is 10 ms, 512 data points in 10 ms means a sampling frequency of 5120 Hz. Some 4500 Hz sounds like good to me, that's a little more than one cycle captured.

Do the printing in a separate for loop, after you acquire the data. And consider a faster baud rate. 115200 or so.

double x[512];

Make this int instead, to save space and time. The result of analogRead() is an integer.

const byte inPin = 34;
const int freq = 200; // 2 times sine f
const unsigned long sampling_period_us = round(1000000.0  / freq);

int x[512];

void setup(void)
{
  Serial.begin(9600);
}

void loop(void)
{
  for (int i = 0; i < 512; i++)
  {
    x[i] = analogRead(inPin);
    delayMicroseconds(sampling_period_us);
  }

  for (int i = 0; i < 512; i++)
  {
    Serial.println(x[i]);
  }
}