Created
August 16, 2025 18:07
-
-
Save jpf91/1ebf9d73ac21032b7d4231f9d8f216b8 to your computer and use it in GitHub Desktop.
Sample a 50Hz sine and get the amplitude
This file contains hidden or 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
| // Code fixed and idea taken from https://www.mikrocontroller.net/topic/211730#2100553 | |
| import std; | |
| // Simulate a sinus in mV, with 1200 mV offset, 50 Hz frequency, sampled at 1 kHz | |
| uint32_t measureMV() | |
| { | |
| static int pos = 0; | |
| return cast(uint32_t)(1200 + 200 * sin(2 * PI * (pos++) * 50.0 / 1000.0)); | |
| } | |
| // 18 Bit | |
| int32_t tabAmp = (1 << 18); | |
| int32_t[20] sinTab, cosTab; | |
| // Up to 12 + log2(1000) = 22 bit | |
| int32_t sinSum, cosSum; | |
| size_t phaseIdx = 0; | |
| size_t frameIdx = 0; | |
| void onTimer() | |
| { | |
| // < 12 bit | |
| int32_t sample = cast(int32_t) measureMV(); | |
| // 12bit * 18 bit => 30 bit / 18 bit => 12 bit | |
| int32_t sinPart = (sample * sinTab[phaseIdx]) / tabAmp; | |
| int32_t cosPart = (sample * cosTab[phaseIdx]) / tabAmp; | |
| sinSum += sinPart; | |
| cosSum += cosPart; | |
| // Count up the table phase | |
| phaseIdx++; | |
| if (phaseIdx == 20) | |
| phaseIdx = 0; | |
| // Result every 1s | |
| frameIdx++; | |
| if (frameIdx == 1000) | |
| { | |
| onResult(sinSum, cosSum); | |
| // Reset average value | |
| sinSum = 0; | |
| cosSum = 0; | |
| frameIdx = 0; | |
| } | |
| } | |
| void onResult(int32_t sinSum, int32_t cosSum) | |
| { | |
| double cosSumD = cast(double) cosSum; | |
| double sinSumD = cast(double) sinSum; | |
| double result = 2 * sqrt(sinSumD * sinSumD + cosSumD * cosSumD) / 1000.0; | |
| writeln(result); | |
| } | |
| void main() | |
| { | |
| for (size_t i = 0; i < 20; i++) | |
| { | |
| sinTab[i] = cast(int32_t)(tabAmp * sin(2 * PI * i / 20.0)); | |
| cosTab[i] = cast(int32_t)(tabAmp * cos(2 * PI * i / 20.0)); | |
| } | |
| writeln(sinTab); | |
| writeln(cosTab); | |
| for (size_t i = 0; i < 1000; i++) | |
| onTimer(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment