Posts: 1
Joined: Thu Mar 15, 2018 9:14 pm

how can i use one button to controll 3 LEDs, plss help

Thu Mar 15, 2018 9:24 pm

if i press button 1 times, Led#1 will on
if i press button 2 time, Led#2 will on
if i press button 3 time, led #3 will on

how can i code in C

Code: Select all

include <wiringPi.h>
#include <stdio.h>

void mode1();
void mode2();
void mode3();

#define Led1 4
#define Led2 6
#define Led3 17
#define Button 12

int main(){
pinMode(Led1, OUTPUT);
pinMode(Led2, OUTPUT);
pinMode(Led3, OUTPUT);
pinMode(Button, INPUT);
pullUpDnControl(Button, PUD_UP); 
	if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
		printf("setup wiringPi failed !");
		return 1;
			int button_press = digitalRead(Button);
		if (button_press == 1){
		 if(button_press == 2){
		if (button_press == 3){
			mode3();	}	
	return 0;

void mode1(){
	digitalWrite(Led1, LOW);
	digitalWrite(Led2, HIGH);
	digitalWrite(Led3, HIGH);	
void mode2(){
	digitalWrite(Led1, HIGH);
	digitalWrite(Led2, LOW);
	digitalWrite(Led3, HIGH);	
void mode3(){
	digitalWrite(Led1, HIGH);
	digitalWrite(Led2, HIGH);
	digitalWrite(Led3, LOW);	

User avatar
[email protected]
Posts: 1998
Joined: Tue Feb 07, 2012 2:14 pm
Location: Devon, UK
Contact: Website

Re: how can i use one button to controll 3 LEDs, plss help

Fri Mar 16, 2018 12:15 pm

I'm not writing your code for you, but would just like to point out that you're calling wiringPiSetup() twice. This is an error. Even worse that you call it the first time to set bcm_gpio pin mode, wiringPiSetupGpio() then the 2nd time to set wiringPi pin mode. wiringPiSetup(); This is not going to do what you think it might do. work. Pick one way or the other.

digitalRead() returns 1 or 0. This depends on the input pin state and this depends on the way you've wired it up. It does not return a count of the number of times you push a button. You need to write code to do the counting. (and you probably need to debounce the switches too)

Gordons projects:

Return to “C/C++”