oreblock.ino

/****************************************
 *                                      *
 *  oreblock.ino                        *
 *  Eric Ayars                          *
 *  4/4/12                              *
 *                                      *
 *  Minecraft ore-block night-light,    *
 *  with selectable ore type and        *
 *  "phasing" of intensity.             *
 *                                      *
 ****************************************/

#define MAGNITUDE 0.5   // size of phasing

byte Red = 8;       // Red PWM pin
byte Green = 7;     // Green PWM pin
byte Blue = 6;      // Blue PWM pin

byte BUTTON = 2;    // Button pin
byte selection;     // store current ore type

byte color[] = {255,0,0,        // redstone
                25,255,0,       // emerald
                0,0,255,        // lapis
                16,4,0,         // iron (?)
                255,115,0,      // gold
                0,255,100};     // diamond
byte R, G, B;
byte currentButton, priorButton;
byte phaseRate = 40;            // controls rate of phasing, larger=slower

void setColor(byte r,byte g,byte b) {
	// The RGB LED is common-anode, so low level at a given pin corresponds
	// to "on" for that color. Accordingly, we must invert the PWM output.
    r = 255-r;
    g = 255-g;
    b = 255-b;
    analogWrite(Red, r);
    analogWrite(Green, g);
    analogWrite(Blue, b);
}

boolean buttonPressed() {
    boolean state = 0;
    currentButton = digitalRead(BUTTON);
    if (currentButton==LOW && priorButton==HIGH) {
        // Button was just pressed, so ...
        state = 1;
    }
    priorButton = currentButton;
    return state;
}

void setup() {

    // set up the output PWM pins
    pinMode(Red, OUTPUT);
    pinMode(Green, OUTPUT);
    pinMode(Blue, OUTPUT);

    // Set up the button color-switcher
    pinMode(BUTTON, INPUT);
    digitalWrite(BUTTON, HIGH);
    priorButton = HIGH;

    // initialize random seed
    int seed = analogRead(1);
    randomSeed(seed);

    // Pick initial color
    selection = random(1024) % 6;

}

void loop() {

    // phase of pulsing effect
    byte phase = 0;
    float phi;

    // "correct" color for this ore
    R = color[selection*3];
    G = color[selection*3 +1];
    B = color[selection*3 +2];
    // "current" color for this ore
    byte r = R;
    byte g = G;
    byte b = B;
    
    while (1) {
    
        if (buttonPressed()) {
            // cycle through ore types
            selection += 1;
            if (selection > 5) selection = 0;
            break;
        }
        // Button not pressed, so carry on phasing
        phi = sin(float(phase) * 0.0246);   // sin(phase/255 *2*pi)
        phi = MAGNITUDE*phi*phi;            // sin^2 * scale factor
        r = byte(float(R)*(1.0 - phi));
        g = byte(float(G)*(1.0 - phi));
        b = byte(float(B)*(1.0 - phi));
        setColor(r,g,b);
        phase += 1;
        delay(phaseRate);
    }
}


Generated by GNU enscript 1.6.4.