Got blue, red and yellow lights that each can turn ON independently of one another. Using operators, structs, etc. how to obtain the current color, if having: Red & Blue is purple, Blue and Yellow is green and Yellow & Red is Orange. This is not a homework.

Dani AI

Generated

For : treat each lamp as a single bit in a mask, combine them with bitwise OR, and map the 3-bit value to a name. That keeps the logic simple, fast and easy to extend. was right to ask for your code; below is a minimal, copy-pasteable pattern you can adapt to your I/O layer. is also right — how you read the lamps (GPIO, serial, etc.) affects debouncing and sampling, so keep that part separate from the color logic.

#include <stdint.h>

enum LightFlags {
    LIGHT_RED    = 1 << 0,  /* 0b001 */
    LIGHT_BLUE   = 1 << 1,  /* 0b010 */
    LIGHT_YELLOW = 1 << 2   /* 0b100 */
};

static const char *color_name[8] = {
    "None",    /* 0 */
    "Red",     /* 1 */
    "Blue",    /* 2 */
    "Purple",  /* 3 = Red+Blue */
    "Yellow",  /* 4 */
    "Orange",  /* 5 = Red+Yellow */
    "Green",   /* 6 = Blue+Yellow */
    "Mixed"    /* 7 = all three */
};

const char *get_color_name(uint8_t mask) {
    return color_name[mask & 0x07]; /* mask guards extra bits */
}

Practical tips: build the mask from your input pins (e.g. (read_red()?LIGHT_RED:0) | ...), validate inputs, and debounce physical switches. Use unsigned types for bit logic and guard array access with mask & 0x07. If perceived colors depend on brightness or LED color profiles (additive vs subtractive mixing), tweak the strings or add HSV/brightness logic instead. If you post the I/O code you have, more targeted fixes (debounce code, interrupt vs polling, thread safety) can be suggested.

Recommended Answers

All 4 Replies

While not homework this doesn't appear to be the place for "give me code." Supply your work so far and where you are stuck.

A good deal.

How you code this depends upon how the lights are integrated into the system. If directly connected to I/O ports of the computer, then you would use io-in and io-out instructions to read or set their states (on or off). If other such as serial ports, the problem is a bit more complicated but not too difficult. What you have posted so far is useless for us to help you.

commented: Lights += 1; +11
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.