SAMA5D27-SOM1-EK1开发板按键控LED的C代码故障排查求助
Hey there, let's figure out why your LEDs aren't lighting up even though key events are working correctly. I've spotted a few critical issues in your code and setup that are likely causing this:
1. Mismatched Key Code Handling
Looking at your event output, the key code being detected is 260, but your eval_keycode function only handles BTN_LEFT (code 272) and BTN_RIGHT (code 273). That means when you press the key, the code never enters any of the switch cases—so no LED state changes ever happen!
Fix:
First, confirm exactly which key code your button is sending. You can either:
- Run
cat /proc/bus/input/devicesin the terminal to find the input event0 device and its associated key codes, or - Add a debug print inside the event loop to log every received code:
if (ev[yalv].type == EV_KEY) { printf("%ld.%06ld ", ev[yalv].time.tv_sec, ev[yalv].time.tv_usec); printf("type %d code %d value %d\n", ev[yalv].type, ev[yalv].code, ev[yalv].value); // Add this debug line printf("DEBUG: Key code received: %d\n", ev[yalv].code); if (ev[yalv].value == 0) eval_keycode(ev[yalv].code); }
Then update the switch cases in eval_keycode to match your actual key code. For example, if your button uses code 260:
void eval_keycode(int code) { static int red_state = 0; static int green_state = 0; switch (code) { case 260: // Use your actual key code here printf("Button pressed\n"); red_state = red_state ? 0 : 1; change_led_state(LED_PATH "/" red "/brightness", red_state); break; // Add a case for a second button if needed } }
2. Key Event Trigger Timing
Your code currently only calls eval_keycode when ev[yalv].value == 0—that's the release event of the button. If you want the LED to toggle when the button is pressed, change the condition to check for value == 1:
if (ev[yalv].value == 1) // Trigger on key press instead of release eval_keycode(ev[yalv].code);
3. Verify LED SysFS Setup
- Check LED Node Names: Make sure the LED nodes under
/sys/class/ledsare actually namedredandgreen. Runls /sys/class/ledsin the terminal to see the real node names—they might be something likeled0,led1, oruser_ledinstead. If they don't match, update theredandgreenmacros in your code. - Run as Root: Accessing sysfs LED nodes requires root privileges. Make sure you run your program with
sudo(e.g.,sudo ./your_program). If you see the errorsimplekey: unable to access ledin the output, this is definitely a permission issue.
4. Manual LED Test
To rule out hardware or device tree issues, manually control the LEDs from the terminal:
# First disable automatic triggers echo none > /sys/class/leds/red/trigger echo none > /sys/class/leds/green/trigger # Turn red LED on echo 1 > /sys/class/leds/red/brightness # Turn it off echo 0 > /sys/class/leds/red/brightness
If the LED doesn't respond to these commands, the problem is outside your code—check your hardware connections or the device tree configuration for the SAMA5D27 board.
内容的提问来源于stack exchange,提问作者gaston

