-
-
Save mrcodetastic/2474e472558f3cd69e76f1464c6d4640 to your computer and use it in GitHub Desktop.
Convert LED brightness to PWM value based on CIE 1931 curve.
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
// Generate lookup table for converting between perceived LED brightness and PWM | |
// Adapted from: https://jared.geek.nz/2013/feb/linear-led-pwm | |
// See also: https://ledshield.wordpress.com/2012/11/13/led-brightness-to-your-eye-gamma-correction-no/ | |
#include <iostream> | |
#include <cmath> | |
#include <iomanip> | |
constexpr int TABLE_SIZE = 256; // Number of steps (brightness) | |
constexpr int RESOLUTION = 1 << 8; // PWM resolution (8-bit = 256) | |
// CIE 1931 brightness curve function | |
double cie1931(double L) { | |
L *= 100; | |
if (L <= 8) | |
return L / 902.3; | |
else | |
return std::pow((L + 16) / 116, 3); | |
} | |
int main() { | |
uint16_t CIE[TABLE_SIZE]; | |
// Compute values | |
for (int i = 0; i < TABLE_SIZE; ++i) { | |
CIE[i] = static_cast<uint16_t>(std::round(cie1931(static_cast<double>(i) / (TABLE_SIZE - 1)) * (RESOLUTION - 1))); | |
} | |
// Print the table | |
std::cout << "const uint16_t CIE[" << TABLE_SIZE << "] = {"; | |
for (int i = 0; i < TABLE_SIZE; ++i) { | |
if (i % 16 == 0) std::cout << "\n "; | |
std::cout << std::setw(5) << CIE[i] << ","; | |
} | |
std::cout << "\n};\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
returns the following: