How can I run two loops simultaneously on an Arduino Uno? I'm new to Arduino and I have two devices that I'm trying to control:


A RGB LED light strip that can change colors
A light sensor that can detect the ambient light level


What I'd like to do is have the LED strip continuously cycle through a rainbow of colors, and the light sensor will adjust the brightness of the LED strip based on the ambient light level. Here are the two pieces of code by themselves, which I've tested in isolation and confirmed that they work properly:

LED strip:

j = (j + 1) % 256; // current iteration of the light cycle

// set the strip color
for(int i=0; i&lt; strip.numPixels(); i++) {
  strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) &amp; 255));
}

// display the new colors and wait 20ms before the next cycle
strip.show();
delay(20);


Light sensor:

sensors_event_t event;
tsl.getEvent(&amp;event); // get a light measurement
strip.setBrightness(event.light); // set the brightness of the LED strip


The problem is that the light sensor takes anywhere from 100ms to 600ms to get a reading, and tsl.getEvent(&amp;event) is a blocking call, so the end result is that the LED strip updates way too slowly. I would need to run the two side by side so that the light sensor read does not block the LED strip update. Any idea how I can accomplish this?
You can make the sensor return data faster by lowering it's accuracy.

tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS);      /* fast but low resolution */


You can also modify the library to not power-down the sensor after each reading. Just open TSL2561.cpp, find the getFullLuminosity function, and comment out the line reading disable(); and the 12 lines reading switch (_integration){ ... }

Another solution is, to have the pixels update every 20ms using a timer. You can have the timer, interrupt the main loop every 20ms and update the pixel values. 

(I can't really help you with timers, as I myself set the registers for my timers, and ISRs directly, which isn't for beginners. But there are probably libraries for it, to make it more user friendly.)