用DAC产生正弦波

 

MCU: C8051F330, Fmax: 23KHz
 
  
#include 
#include 

unsigned char sine_table[8] = { 0x80, 0xDA, 0xFF, 0xDA, 0x80, 0x25, 0x00, 0x25 }; /* 8KSPS, 0dB */
// unsigned char sine_table[8] = { 0x80, 0xAD, 0xC0, 0xAD, 0x80, 0x52, 0x3F, 0x52 }; /* 8KSPS, -6dB */

unsigned char *waveform_data = &sine_table[0];

/* for generate 1KHz sine wave, call it per 125us */ 
unsigned char waveform_output(void)
{
	unsigned char dac_value;

	dac_value = *waveform_data++;
	if (waveform_data >= &sine_table[8])
	{
	    waveform_data = &sine_table[0];
	}

	return dac_value;
}

int main()
{
    int i;

    for (i = 0; i < 16; i++)
    {
        printf("%02X\n", waveform_output());
    }

    return 0;
}
 
  
#include 
#include 
#include 
#include 

unsigned char *sine_table = NULL;

float db2liner(float dB)
{
    return pow(10, dB / 20);
}

float liner2db(float liner)
{
   return (20 * log10(liner));
}

int waveform_generate(int freq, int sps, float dB)
{
    int i;
    int table_length;
    float A;
    float value;

    table_length = sps / freq;

    sine_table = (unsigned char *)malloc(table_length);
    memset(sine_table, 0, table_length);

    A = db2liner(dB);

    for( i = 0; i < table_length; i++)
    {
        value = A * sin(2 * M_PI * i * freq / sps);
        if (value < 1.0)
        {
            sine_table[i] = (256 / 2) + value * (256 / 2);  /* add DC offset */
        }
        else
        {
            sine_table[i] = 256 - 1;
        }
    }

    return table_length;
}

int main()
{
    int i, table_length;

    /* generate 1000Hz sine wave, sample rate: 8000Hz, gain: -6dB */
    table_length = waveform_generate(1000, 8000, -6);

    printf("unsigned char sine_table[%d] = { ", table_length);
    for (i = 0; i < table_length; i++)
    {
        printf((i != table_length - 1) ? "0x%02X, " : "0x%02X ", sine_table[i]);
    }
    printf("};\n");

    free(sine_table);

    return 0;
}

你可能感兴趣的:(ARM)