Created
April 24, 2018 08:31
-
-
Save imudak/4dcd3f20d3cfb5f4c37b2ccfcf486442 to your computer and use it in GitHub Desktop.
PWMを自力で生成するスケッチ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******** 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