summaryrefslogtreecommitdiff
path: root/Colours.cpp
blob: 7ae49a2650dc47bcf41e2cdab86ece405b787a3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
 * Colours - library for managing the colours on RGB LEDs
 * Copyright 2009, 2013 Elena Grandi
 *
 * This file is part of Colours.
 *
 * Colours is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of 
 * the License, or (at your option) any later version.
 *
 * Colours is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Colours.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Arduino.h"
#include "Colours.h"

Colours::Colours(int rPin,int gPin,int bPin) {
    _initPINs(rPin,gPin,bPin);
    _invert = false;
}

Colours::Colours(int rPin,int gPin,int bPin,bool invert) {
    _initPINs(rPin,gPin,bPin);
    _invert = invert;
}

void Colours::_initPINs(int rPin,int gPin,int bPin) {
    _rPin = rPin;
    _gPin = gPin;
    _bPin = bPin;
    pinMode(_rPin,OUTPUT);
    pinMode(_gPin,OUTPUT);
    pinMode(_bPin,OUTPUT);
}

void Colours::writeRGB(unsigned char r,unsigned char g,unsigned char b) {
    if (_invert) {
        analogWrite(_rPin, 255-r);
        analogWrite(_gPin, 255-g);
        analogWrite(_bPin, 255-b);
    } else {
        analogWrite(_rPin, r);
        analogWrite(_gPin, g);
        analogWrite(_bPin, b);
    }
}

void Colours::writeHSV(unsigned int h,unsigned char s,unsigned char v) {
    h = h % 360;
    if (s==0) {
        writeRGB(v,v,v);
    } else {
        unsigned int f,p,q,t;
        f = 256*(h%60)/60;
        p = v*(256-s)/256;
        q = v*(256-f*s/256)/256;
        t = v*(256-s*(256-f)/256)/256;
        switch( (h/60) % 6 ) {
            case 0:
                writeRGB(v,t,p);
                break;
            case 1:
                writeRGB(q,v,p);
                break;
            case 2:
                writeRGB(p,v,t);
                break;
            case 3:
                writeRGB(p,q,v);
                break;
            case 4:
                writeRGB(t,p,v);
                break;
            case 5:
                writeRGB(v,p,q);
                break;
        }
    }
}