I'm new to Arduino coding and have been looking at a lot of references to help me, and while I have been able to get LEDs to light up from a code in an Arduino Uno, I am unable to get the Arduino to send a signal through an LED when i try to give an input. Ive used analog and digital reads and differing inputs but nothing is working.
//define pins for the red LED
#define RED_LED 6
#define RED_input 5
//initial brightness for red LED
int Routput = 0;
//initialized variables
int i = 0;
int red_val = 0;
void setup() {
//set up pins to output.
pinMode(RED_input, INPUT);
pinMode(RED_LED, OUTPUT);
for(i=0; i<20; i++){
readInput();
delay(100);
displayOutput();
delay(100);
}
}
void readInput(){
red_val = 0;
Routput = 0;
red_val = digitalRead(RED_input);
if(red_val = 0){
Routput = 0;
}else{
Routput = 255;
}
}
void displayOutput(){
analogWrite(RED_LED, Routput);
analogWrite(RED_LED, 0);
}
void loop(){
}
I fiddled a lot with different variables and names and it hasn't worked so I'm open to any suggestions.
I notice you have your RED_input pinmode set to INPUT rather than INPUT_PULLUP. How is your input wired?
I would recommend getting rid of the for loop and read your input and display your output in the loop() function.
void loop() {
readInput();
displayOutput();
}
You attempted to do a comparison "if (red_val = 0)". A comparison is done with == like "if (red_val == 0)".
void readInput(){
red_val = 0;
Routput = 0;
red_val = digitalRead(RED_input);
if(red_val = 0){
Routput = 0;
}else{
Routput = 255;
}
}
If you do turn the LED on here you will turn it off so fast you won't see it.
void displayOutput(){
analogWrite(RED_LED, Routput);
analogWrite(RED_LED, 0);
}
Thank you for the feedback! So currently I have 5V set to A5, and an LED in series with a resistor wired to ground from output 6 all on the Arduino.
All I am trying to do currently is have the LED turn on when i plug in the 5V to A5 and turn off when I remove it, I plan having several inputs to the same number of outputs eventually, but wanted to learn on one I/O first so I deal with one section instead of many.
Your displayOutput() should just write Routput. You've already decided in your input routine whether Routput should be ON (255) or OFF (0).
And your input pin is DIGITAL pin 5 NOT A5. Different pins. If you leave it using pinMode INPUT and you expect it to be active when it is high(5V) you need a pull-down resistor (about 10K) between the pin and ground to stop it floating and make sure the pin normally stays low.
Steve