Skip to content

Instantly share code, notes, and snippets.

@imudak
Created April 24, 2018 08:31
Show Gist options
  • Save imudak/4dcd3f20d3cfb5f4c37b2ccfcf486442 to your computer and use it in GitHub Desktop.
Save imudak/4dcd3f20d3cfb5f4c37b2ccfcf486442 to your computer and use it in GitHub Desktop.
PWMを自力で生成するスケッチ
/******** Sine wave parameters ********/
#define PI4 4*3.14159 // 2 sine wave cycles
#define AMP 127 // PWM Multiplication factor for the sine wave
#define OFFSET 128 // Offset shifts wave to just positive values
/******** Lookup table ********/
#define LENGTH 20 // The length of the waveform lookup table
byte wave[LENGTH]; // waveform values for PWM
const byte pulsePin = 9;
void setup() {
Serial.begin(115200);
pinMode(pulsePin, OUTPUT);
/******** Populate the waveform lookup table ********/
for (byte i = 0; i < LENGTH; i++)
{
float v = (AMP * sin(((PI4 / LENGTH) * i)));
wave[i] = byte(v + OFFSET); // Store value as integer
Serial.println(wave[i]);
}
}
void loop() {
static unsigned long lastPulseTime;
static byte i = 0;
if (micros() - lastPulseTime >= 50000ul) //20Hz
{
lastPulseTime += 50000ul;
analogWrite(pulsePin, wave[i]);
//Serial.print(i);
//Serial.print('\t');
Serial.println(wave[i]);
i++;
if (i == LENGTH - 1)
i = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment