My code stops at the first iteration for the phot_val "if" statement.
/////// Code loop
void loop() {
double sound = MIC(); //Declare variable for obtaining microphone data
double phot_val;
int nreadings = 100;
int song1[N]={CN4, DN4, EN4, FN4, GN4, AN4, BN4, CN5};
int song2[M]= {RT0, RT0, CN4, DN4, CN4, FN4, EN4, RT0,CN4, DN4, CN4, GN4, FN4, RT0, CN4, CN5, AN4, FN4, EN4,DN4, RT0, AS4, AN4, FN4, GN4, FN4, RT0, RT0};
phot_val = read_analogn(2,nreadings);
Serial.print("Sound: ");Serial.println(sound); //Testing purposes, Print out sound/mic value
Serial.print("Light: ");Serial.println(phot_val,5);//Testing purposes, Print out light sensor data
if(phot_val >= .5){play_song(song1,N);} //Stops after first 100???
/// Else If statements to change RBG colors depending on sound
if(MIC() >= 30){ setColor(255, 0, 0); } //Red Color
else if(MIC() >= 35){setColor(0, 255, 0);} //Green Color
else if(MIC() >= 40){setColor(0, 0 , 255);} //Blue Color
else if(MIC() >=25){setColor(255, 255, 255);} //White Color
else if(MIC() >=25){setColor(170, 0, 255);} //White Color
else {setColor(0, 0, 0);}
}
/////// Read light sensor function
float read_analogn(int p, int n){
float sum = 0;
float avg;
int i;
float voltage;
float phot_val;
for(i=0; i<n; i++)
{
phot_val = analogRead(p);
voltage = phot_val*(5.0/1023.0);
sum += voltage;
}
avg = sum/n;
return (avg);
}
/////// Color function for RBG Leds
void setColor(int redV, int greenV, int blueV) {
analogWrite(redP, redV); //Red value for RBG
analogWrite(greenP, greenV); //Green value for RBG
analogWrite(blueP, blueV); //Blue value for RBG
}
/////// Play song function
void play_song(int song[], int n){
int isong; //Define variables
for(isong=0;isong<n;isong++){ //For loop to play the songs
tone(SPKR,song[isong]);
delay(500);
}
noTone(SPKR);
}
}
I can post more code if needed, but I have no Idea why it stop
Edit: Fixed title, and added more code of the functions.
So basically it runs tru but when "if(phot_val >= .5){play_song(song1,N);}" becomes true it stops until the song it's played entirety then it continues to read data again.
You aren't checking the value of the analog pin in the for loop so it blocks everything until the entirety of the song finishes. All you need to do is update the for loop to check the value of the input.
Replace your for loop with something like:
for(isong=0;isong<n;isong++){
tone(SPKR,song[isong]);
delay(500);
phot_val = read_analogn(2, nreadings);
if(phot_val < .5){break;} //or whatever value you want it to stop at
}
This will stop the song when your sensor goes below the threshold
I do not see any for loop , perhaps read_analogn(); is a function you declared which contains a for loop?
In that case you should check the function in order to make sure the for loop does not fall into an infinite loop , perhaps place some serial outputs in different parts of the code to see if it reaches that part , print out variables to check if different parts of the code are operating and so on.
Nevertheless it is hard to say what is happening without seeing the for loop / function which is causing the trouble so I suggest you place the functions code and the for loop itself in your question.
The first else if in your code is at this questionable location:
if(MIC() >= 30){ setColor(255, 0, 0); } //Red Color
else if(MIC() >= 35) {
// comes here only if the first call of MIC() returns less than 30
// and the second one returns 35 or more.
// ???
}
This is not an answer, but hard to read as a comment.
We are working on a Arduino project where we use different methods to change the power of three LED's making our own "RGB" lamp and the current issue is with flex resistors. The idea is to use three flex resistors to control each lamp. We used the map function with out lowest & highest value making our lowest number 0 and our highest 255.
The issue is primarily that our number fluctuate a lot and the laps flicker like crazy.
Any recommendations?
We've tried changing our mapped numbers, both max and min.
We've also played around with the code but with no success.
#include <LiquidCrystal.h>
int bend1 = A0;
int bend2 = A4;
int bend3 = A5;
int green = 6;
int red = 10;
int blue = 9;
unsigned long previous = 0;
const long interval = 500;
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
Serial.begin(9600);
Serial.println("Started");
lcd.begin(16,2);
pinMode(green, OUTPUT);
pinMode(red, OUTPUT);
pinMode(blue, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previous >= interval)
{
previous = currentMillis;
lcd.clear();
}
int value1 = analogRead(bend1);
int value2 = analogRead(bend2);
int value3 = analogRead(bend3);
value1 = map(value1, 510, 910, 0, 255);
value2 = map(value2, 490, 905, 0, 255);
value3 = map(value3, 500, 900, 0, 255);
if(value3 > 20)
{
analogWrite(blue, value3);
}
else
{
analogWrite(blue, 0);
}
if(value2 > 20)
{
analogWrite(red, value3);
}
else
{
analogWrite(red, 0);
}
if(value1 > 20)
{
analogWrite(green, value3);
}
else
{
analogWrite(green, 0);
}
lcd.setCursor(0, 0);
lcd.print("GREEN");
lcd.setCursor(7, 0);
lcd.print("RED");
lcd.setCursor(12, 0 );
lcd.print("BLUE");
lcd.setCursor(0, 1);
lcd.print(value1);
lcd.setCursor(7, 1);
lcd.print(value2);
lcd.setCursor(12, 1);
lcd.print(value3);
}
We should get the values 0,0,0 when all flex resistors are flat but instead they fluctuate from -10 ---> 90 in some cases. One of our fault might be faulty flex resistors. But we think there might be some code issues hidden also.
I am trying to obtain an increment that goes up from 0 to n, then decreases from n-1 to 0, and repeats the cycle over and over.
In this example written in Processing, I would like the background to go from black(i=0) to white(i=255) incrementally then white to black incrementally and so forth. Now I only get it to go from black to white, and then it comes back to black suddenly.
int i = 0;
void setup(){
size(640, 360);
frameRate(60);
}
void draw(){
background(i);
i++;
if(i==256){i=0;}
}
Try -
int change = 1;
void draw(){
background(i);
i = i + change;
if(i==256){change = -1;}
if(i==0){change = 1;}
}
Another way to look at this question would be: "How could I draw a triangle wave?".
I like this way cause it does not need "ifs". Some thing like this would do.
triangleWave = maxNumber - abs(incrementedVar % (2*maxNumber) - maxNumber);
Coll, isn't it?
I have this old code using this, it's not drawing the wave, but using it for size and fill color. Also there is a sine wave for comparision. Check it out:
float zigZag, toIncrement, speed =1, maxNumber = 255;
float sine, x = 270, speed2 = 1;
void setup() {
size(800, 400);
background(255);
}
void draw() {
background(255);
//triangle wave
toIncrement+=speed;
zigZag = maxNumber - abs(toIncrement % (2*maxNumber) - maxNumber);
fill(zigZag);
noStroke();
ellipse( 150, height/2+100, 50, 50);
strokeWeight(zigZag);
stroke(0);
line(100, height/2-100, 200, height/2-100);
text("triangle = " + int(zigZag), 100, height-30);
println("triangle wave value = " + zigZag);
//sine wave
x+=speed2;
sine = (1+sin(radians(x)))*(maxNumber/2);
fill(sine);
noStroke();
ellipse( 650, height/2+100, 50, 50);
strokeWeight(sine);
stroke(0);
line(600, height/2-100, 700, height/2-100);
fill(80);
text("sine = " + int(sine), 600, height-30);
}
I've currently managed to get my LED to cycle through eight colors that I've selected. Everything is working correctly, except that I want to go for a more natural feel, and would like to fade / transition from one color to the next, instead of having them just replace one another.
Here's my code so far:
int redPin = 11;
int greenPin = 10;
int bluePin = 9;
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop()
{
setColor(250, 105, 0); // Yellow
delay(1000);
setColor(250, 40, 0); // Orange
delay(1000);
setColor(255, 0, 0); // Red
delay(1000);
setColor(10, 10, 255); // Blue
delay(1000);
setColor(255, 0, 100); // Pink
delay(1000);
setColor(200, 0, 255); // Purple
delay(1000);
setColor(0, 255, 0); // Green
delay(1000);
setColor(255, 255, 255); // White
delay(1000);
}
void setColor(int red, int green, int blue)
{
analogWrite(redPin, 255-red);
analogWrite(greenPin, 255-green);
analogWrite(bluePin, 255-blue);
}
What the other answers omit about this topic is the fact that that human perception of light intensity is logarithmic, not linear. The analogWrite() routines are setting the output pin's PWM duty cycle, and are linear. So by taking the minimum duty cycle (say 0) and maximum duty cycle (say, for the sake of easy math this is 10) and dividing it into equal chunks, you will be controlling the intensitiy linearly which will not give satisfying results.
What you need to do instead is set your intensity exponentially. Let's say your maximum intensity is 255. You can generate this result by treating your intensity as a power to raise some number to. In our case, given that we are dealing with computers that like binary, powers of two are convenient. So,
2^0 =1
2^8=256
so we can have 8 intensity levels. Actually, note that out minimum is now not fully off (it is 1 not 0) and our maximum is out of range (256 not 255). So we modify the formula to be
output = 2 ^ intensity - 1
Or in code
int output = 1<<intensity - 1;
This yields values from 0 to 255 for intensity levels from 0 to 8 (inclusive), so we actually get nine levels of intensity. If you wanted smoother transitions (i.e. more levels of intensity), and still use logarithmic intensity you'll need floating-point math.
If you apply this method of calculating intensity to each channel (R, G, B) then your perception will be in accord with what your code says it should be.
As fars as how to smoothly transition between various colors, the answer depends on how you want to navigate the color space. The simplest thing to do is to think about your color space as a triangle, with R, G, and B, as the verteces:
The question then is how to navigate this triangle: you could go along the sides, from R, to G, to B. This way you will never see white (all channels fully on) or "black" (all fully off). You could think of your color space as a hexagon, with additional purple (R+B), yellow (G+B), and brown (R+G) colors, and also navigate the perimeter (again, no white or black). There are as many fading possibilities as there are ways of navigating insides these, and other figures we might think of.
When I built fading programs like this the color space and the traversal I liked was as follows: think of each channel as a binary bit, so now you have three (R, G, and B). If you think of each color as having some combination of these channels being fully on, you get 7 total colors (excluding black, but including white). Take the first of these colors, fade to it from black and back to black, and then go to the next color. Here's some code that does something like that:
int targetColor = 1;
int nIntensity = 0;
int nDirection = 1; // When direction is 1 we fade towards the color (fade IN)
// when 0 we fade towards black (fade OUT)
#define MAX_INTENSITY 8
#define MIN_INTENSITY 0
#define MAX_TARGETCOLOR 7
void loop() {
for (;;) {
// Update the intensity value
if (nDirection) {
// Direction is positive, fading towards the color
if (++nIntensity >= MAX_INTENSITY) {
// Maximum intensity reached
nIntensity = MAX_INTENSITY; // Just in case
nDirection = 0; // Now going to fade OUT
} // else : nothing to do
} else {
if (--nIntensity <= MIN_INTENSITY) {
nIntensity = MIN_INTENSITY; // Just in case
// When we get back to black, find the next target color
if (++targetColor>MAX_TARGETCOLOR)
targetColor=1; // We'll skip fading in and out of black
nDirection = 1; // Now going to fade IN
} // else: nothing to do
}
// Compute the colors
int colors[3];
for (int i=0;i<3;i++) {
// If the corresponding bit in targetColor is set, it's part of the target color
colors[i] = (targetColor & (1<<i)) ? (1<<nIntensity) -1 : 0;
}
// Set the color
setColor(colors[0], colors[1], colors[2]);
// Wait
delay(100);
}
}
It is indeed possible to fade between different colors. What I'm also usually missing in Arduino books and code on the web is, that it is possible to write C++ classes in Arduino IDE. Therefore, I'm going to show an example that fades between colors using C++ classes.
An issue that should be addressed is on which pins the analogWrite should be done to, because not all pins are capable of Pulse Width Modulation (PWM). On a Arduino device the pins that support PWM are denoted with a tilde '~'. The Arduino UNO has digital pins ~3, ~5, ~6, ~9, ~10 and ~11. And most Arduino use those pins for PWM, but check your device to be sure. You can create PWM on regular digital pins by switching your led on for 1ms and of for 1 ms this mimics 50% power on the LED. Or turn it on 3 ms and of 1 ms this mimics 75% power.
In order to fade a LED you would have to reduce/increase the PWM value and wait a bit. Youl'll have to wait a little while, because otherwise the arduino tries to fade/dim leds thousands of times per second and you won't see a fade effect, although it probably there. So you are looking for a method to gradually reduce/increase the second parameter to analogWrite( ) for three LEDs; For a more thorough explanation see for example chapter 7 of Arduino Cookbook. That book is a good read for Arduino fans anyway!
So I adapted the code from the OP to contain a 'rgb_color' class that is more or less just a container for red, green and blue values. But more importantly is the fader class. When an instance of fader is constructed the proper pins should be in the constructor red, green and blue respectively. Than the fader contains a member function void fade( const rgb_color& const rgb_color&) which will do the fading between the in and out color. By default the function will take 256 steps of 10ms from the input color to the output color. (note here due to integer divisions this doesn't really mean that each step 1/256 th, but perceputally you won't notice it).
/*
* LedBrightness sketch
* controls the brightness of LEDs on "analog" (PWM) output ports.
*/
class rgb_color {
private:
int my_r;
int my_g;
int my_b;
public:
rgb_color (int red, int green, int blue)
:
my_r(red),
my_g(green),
my_b(blue)
{
}
int r() const {return my_r;}
int b() const {return my_b;}
int g() const {return my_g;}
};
/*instances of fader can fade between two colors*/
class fader {
private:
int r_pin;
int g_pin;
int b_pin;
public:
/* construct the fader for the pins to manipulate.
* make sure these are pins that support Pulse
* width modulation (PWM), these are the digital pins
* denoted with a tilde(~) common are ~3, ~5, ~6, ~9, ~10
* and ~11 but check this on your type of arduino.
*/
fader( int red_pin, int green_pin, int blue_pin)
:
r_pin(red_pin),
g_pin(green_pin),
b_pin(blue_pin)
{
}
/*fade from rgb_in to rgb_out*/
void fade( const rgb_color& in,
const rgb_color& out,
unsigned n_steps = 256, //default take 256 steps
unsigned time = 10) //wait 10 ms per step
{
int red_diff = out.r() - in.r();
int green_diff = out.g() - in.g();
int blue_diff = out.b() - in.b();
for ( unsigned i = 0; i < n_steps; ++i){
/* output is the color that is actually written to the pins
* and output nicely fades from in to out.
*/
rgb_color output ( in.r() + i * red_diff / n_steps,
in.g() + i * green_diff / n_steps,
in.b() + i * blue_diff/ n_steps);
/*put the analog pins to the proper output.*/
analogWrite( r_pin, output.r() );
analogWrite( g_pin, output.g() );
analogWrite( b_pin, output.b() );
delay(time);
}
}
};
void setup()
{
//pins driven by analogWrite do not need to be declared as outputs
}
void loop()
{
fader f (3, 5, 6); //note OP uses 9 10 and 11
/*colors*/
rgb_color yellow( 250, 105, 0 );
rgb_color orange( 250, 40, 0 );
rgb_color red ( 255, 0, 0 );
rgb_color blue ( 10, 10, 255 );
rgb_color pink ( 255, 0, 100 );
rgb_color purple( 200, 0, 255 );
rgb_color green ( 0, 255, 0 );
rgb_color white ( 255, 255, 255 );
/*fade colors*/
f.fade( white, yellow);
f.fade( yellow, orange);
f.fade( orange, red);
f.fade( red, blue);
f.fade( blue, pink);
f.fade( pink, purple);
f.fade( purple, green);
f.fade( green, white);
}
This is probably what you are looking for. Whenever we want to shift color over the spectrum and trasition the colors in a circular and smooth motion, what we are really doing is shifting light using HUE in the HSI/HSV (Hue, Saturation, Intensity/Value) color space.
Take if you will this figure:
We will attach a value from 0-360 for hue because hue has 360 degrees of color.
A value of 0.00 - 1.00 for saturation, and a value of 0.00 -1.00 for intensity/value
Here is my circuit on the MEGA 2560:
Here is video of this code running:
<iframe width="560" height="315" src="https://www.youtube.com/embed/gGG-GndSKi0" frameborder="0" allowfullscreen></iframe>
So lets build a function that we can pass the hue value and a for loop inside our loop function to call that value 360 times to shift over the full rainbow of color.
//Define the pins we will use with our rgb led
int redPin = 9;
int greenPin = 10;
int bluePin = 11;
//define that we are using common anode leds
#define COMMON_ANODE
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
int rgb[3];
//Arduino has no prebuilt function for hsi to rgb so we make one:
void hsi_to_rgb(float H, float S, float I) {
int r, g, b;
if (H > 360) {
H = H - 360;
}
// Serial.println("H: "+String(H));
H = fmod(H, 360); // cycle H around to 0-360 degrees
H = 3.14159 * H / (float)180; // Convert to radians.
S = S > 0 ? (S < 1 ? S : 1) : 0; // clamp S and I to interval [0,1]
I = I > 0 ? (I < 1 ? I : 1) : 0;
if (H < 2.09439) {
r = 255 * I / 3 * (1 + S * cos(H) / cos(1.047196667 - H));
g = 255 * I / 3 * (1 + S * (1 - cos(H) / cos(1.047196667 - H)));
b = 255 * I / 3 * (1 - S);
} else if (H < 4.188787) {
H = H - 2.09439;
g = 255 * I / 3 * (1 + S * cos(H) / cos(1.047196667 - H));
b = 255 * I / 3 * (1 + S * (1 - cos(H) / cos(1.047196667 - H)));
r = 255 * I / 3 * (1 - S);
} else {
H = H - 4.188787;
b = 255 * I / 3 * (1 + S * cos(H) / cos(1.047196667 - H));
r = 255 * I / 3 * (1 + S * (1 - cos(H) / cos(1.047196667 - H)));
g = 255 * I / 3 * (1 - S);
}
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
}
void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
#endif
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
///here we have our main loop and the for loop to shift color
void loop()
{
//the for loop counts to 360 and because its in our control loop it will run forever
// We will use int i to increment the actual desired color
for (int i=0; i<=360;i++){
hsi_to_rgb(i,1,1);
setColor(rgb[0],rgb[1],rgb[2]);
//Changing the delay() value in milliseconds will change how fast the
//the light moves over the hue values
delay(5);
}
}
If you want to fade between colours, work in a colourspace which makes it easy and then convert back to RGB at the end.
For example, work in HSL colour space, keep S and L constant (say a fully saturated and bright colour) and then "fade" H around the circle - you'll go from red through green, blue and back to red. Convert back to RGB and then use those values for your LED drives. I used this technique for a "mood lamp" app, and other code for the colour space conversion can be found on SO.
You can simplify your code by using a struct for your color.
struct Color
{
unsigned char r;
unsigned char g;
unsigned char b;
};
Then, it is easy to have a fading function
// the old color will be modified, hence it is not given as reference
void fade(Color old, const Color& newColor)
{
// get the direction of increment first (count up or down)
// each of the inc_x will be either 1 or -1
char inc_r = (newColor.r - old.r)/abs(newColor.r-old.r); // note, that the right hand side will be sign extended to int according to the standard.
char inc_g = (newColor.g - old.g)/abs(newColor.g-old.g);
char inc_b = (newColor.g - old.g)/abs(newColor.g-old.g);
fadeOneColor(old.r, newColor.r, inc_r, old);
fadeOneColor(old.g, newColor.g, inc_g, old);
fadeOneColor(old.b, newColor.b, inc_b, old);
}
void fadeOneColor( unsigned char& col_old,
const unsigned char& col_new,
const char inc,
Color& col)
{
while(col_old != col_new)
{
col_old += inc;
SetColor(col);
delay(20);
}
}
I would like to contribute with a more user friendly answer as aids understanding of how it works.
In my example bellow I'm using common anode RGB LED.
In my project however: To set a Color to RGB LED, I send a String via HW Serial.
Command Example: RGB000255000
This Command as String is divided into 4 parts of 3 chars each.
Using the Command Example Above:
"RGB" : To filter where the Command will be executed.
"000" : The 2nd 3 Chars represent Red Value.
"255" : The 3rd 3 Chars represent Green Value.
"000" : The 4th 3 Chars represent Blue Value.
Result: This will Output Green on your LED.
See Code Bellow:
// Set your LED Pins.
const int rPin = 9;
const int gPin = 10;
const int bPin = 11;
// Set the variables that will assign a value to each Color Pin.
int rVal = 255;
int gVal = 255;
int bVal = 255;
// Fade Red Pin (In / Out).
void FadeRed(int red)
{
// When Red Value on Red Pin is Inferior to the New Value: Fade In.
if (rVal < red)
{
// Fade Out.
for (int r = rVal; r <= red; r++)
{
// Set the Variable and Pin values.
rVal = r;
analogWrite(rPin, rVal);
// Delay Slighlty (Synchronously). For Asynchronous Delay; you may try using "millis".
delay(6);
}
}
// When Red Value on Red Pin is Superior to the New Value: Fade Out.
else
{
for (int r = rVal; r >= red; r--)
{
rVal = r;
analogWrite(rPin, rVal);
delay(6);
}
}
}
// Fade Green Pin (In / Out).
void FadeGreen(int green)
{
if (gVal < green)
{
for (int g = gVal; g <= green; g++)
{
gVal = g;
analogWrite(gPin, gVal);
delay(6);
}
}
else
{
for (int g = gVal; g >= green; g--)
{
gVal = g;
analogWrite(gPin, gVal);
delay(6);
}
}
}
// Fade Blue Pin (In / Out).
void FadeBlue(int blue)
{
if (bVal < blue)
{
for (int b = bVal; b <= blue; b++)
{
bVal = b;
delay(6);
analogWrite(bPin, b);
}
}
else
{
for (int b = bVal; b >= blue; b--)
{
bVal = b;
delay(6);
analogWrite(bPin, b);
}
}
}
void FadeColor(int red, int green, int blue)
{
// Debug Only.
Serial.println("\n[+] Received Values");
Serial.println(red);
Serial.println(green);
Serial.println(blue);
// Code.
FadeRed(red);
FadeGreen(green);
FadeBlue(blue);
// Debug Only.
Serial.println("\n[+] Pin Values \n");
Serial.println(rVal);
Serial.println(gVal);
Serial.println(bVal);
}
/* Set RGB LED Color According to String Value. (i.e: RGB000000000) */
void SetColor(String color)
{
// Retrieve the New Color from String.
/* Split a String : Start Position; End Position */
String red = color.substring(3, 6); /* Get the 1st 3 Characters Corresponding to RED */
String green = color.substring(6, 9); /* Get the 2nd 3 Characters Corresponding to GREEN */
String blue = color.substring(9, 12); /* Get the Last 3 Characters Corresponding to BLUE */
int r = atoi(red.c_str());
int g = atoi(green.c_str());
int b = atoi(blue.c_str());
int redVal = 255 - r;
int grnVal = 255 - g;
int bluVal = 255 - b;
FadeColor(redVal, grnVal, bluVal);
}
void setup()
{
pinMode(rPin, OUTPUT);
pinMode(gPin, OUTPUT);
pinMode(bPin, OUTPUT);
pinMode(rPin, HIGH);
pinMode(gPin, HIGH);
pinMode(bPin, HIGH);
analogWrite(rPin, rVal);
analogWrite(gPin, gVal);
analogWrite(bPin, bVal);
}
Here's a fast linear fade between two RGB values stored in uint32_t as 0x00RRGGBB as is used in many addressable RGB pixel strips such as in NeoPixel (and is inspired by some of the code in the NeoPixel Arduino library).
It doesn't take colour space into consideration but still looks nice and smooth in practice.
uint32_t fadeColor(uint32_t const x, uint32_t const y, uint8_t const fade)
{
// boundary cases don't work with bitwise stuff below
if (fade == 0)
{
return x;
}
else if (fade == 255)
{
return y;
}
uint16_t const invFadeMod = (255 - fade) + 1;
uint16_t const fadeMod = fade + 1;
// overflows below to give right result in significant byte
uint8_t const xx[3] // r g b
{
static_cast<uint8_t>((uint8_t(x >> 16) * invFadeMod) >> 8),
static_cast<uint8_t>((uint8_t(x >> 8) * invFadeMod) >> 8),
static_cast<uint8_t>((uint8_t(x >> 0) * invFadeMod) >> 8),
};
uint8_t const yy[3] // r g b
{
static_cast<uint8_t>((uint8_t(y >> 16) * fadeMod) >> 8),
static_cast<uint8_t>((uint8_t(y >> 8)* fadeMod) >> 8),
static_cast<uint8_t>((uint8_t(y >> 0)* fadeMod) >> 8),
};
return ((uint32_t)(xx[0] + yy[0]) << 16) | ((uint32_t)(xx[1] + yy[1]) << 8) | (xx[2] + yy[2]);
}
I've tried countless times to try and get this to work. I've moved loads of it around but still, nothing works. When I press the M key, my lights are meant to change to random colours. However, they change just to white.
This is what i have...
float colorArray[100][3]; // Create an array for random colors
keyPressed function:
case 'm' | 'M':
updateLights(2);
break;
defined_to_openGL function:
for (int i = 0; i < 3; i++)
{
glPushMatrix();
glColor3f(colorArray[i][0],colorArray[i][1],colorArray[i][2]);
glTranslatef(-50*i/2,-20,0.5); // Begin the first circle at -50, -20. Then multiply by i to create a space between them.
drawLights(2.0f);
glPopMatrix();
if(i <= 3)
{
glPushMatrix();
glColor3f(colorArray[i][0],colorArray[i][1],colorArray[i][2]);
glTranslatef(-38,-20,0.5);
drawLights(2.0f);
glPopMatrix();
glPushMatrix();
glColor3f(colorArray[i][0],colorArray[i][1],colorArray[i][2]);
glTranslatef(-12,-20,0.5);
drawLights(2.0f);
glPopMatrix();
}
}
Update lights function:
{
cout << "update lights" << endl;
for(int i = 0; i < 3; i++)
{
colorArray[i][0] = rand() % 255;
colorArray[i][1] = rand() % 255;
colorArray[i][2] = rand() % 255;
glutPostRedisplay();
}
}
You are using glColor3f which accepts 3 float parameters in [0.0,1.0] for each color intensity while rand()%255 produces an output which is in [0,254].
You can either switch to glColor3ub( GLubyte red, GLubyte green, GLubyte blue) which accepts an unsigned byte (and change modulo to %256 since you are skipping a value with 255) or generate a value in [0.0,1.0]by changing your random generation to
rand()/((float)RAND_MAX+1)
but this mean that you will have to change the type of colorArray to GLFloat.