Skip to main content
2 of 4
added 232 characters in body
Majenko
  • 105.9k
  • 5
  • 82
  • 139

Arduino UNO coding problem voltage varying

I was wondering if anyone could help me... I am using and Arduino UNO and and I am doing my code in the Arduino IDE and I am trying to implement the code so that the output voltage can be varied from 0 - 5 volts using 2 pushbuttons. I want to be able to increment the voltage by +0.5 volts from 0-5 volts everytime I push ButtonA and I want to decement the voltage by -0.5 volts from 5-0V eveytime I push ButtonB.

Example: (push ButtonA) : output voltage 0.5 : (push ButtonA) : output voltage 1.0 etc.

So far when I upload my code the LED as my test for output just flickers between 2 - 4 volts. Can anyone tell me what I am doing wrong I am not that good at coding so any help would be awesome.

Here is my code...

int PWMPin = 6; // output pin supporting PWM  
int buttonApin = 9; // buttonA to pin 9 PWM  
int buttonBpin = 10; // buttonB to pin 10 PWM  
float value = 0; // read the value at 0 
int fadeValue = value; 
int counter = 0; 
 
void setup()   
{  
  Serial.begin(9600); //initialize serial communication at 9600 baud 
  pinMode(buttonApin, INPUT);   
  pinMode(buttonBpin, INPUT);  
  pinMode(PWMPin, OUTPUT);  
}  
void loop()   
{   
    int port = analogRead(0);  
    port = map(port, 0, 10, 0, 255);  
    analogWrite(6, port);   
    
  {  
  if (digitalRead(buttonApin) == LOW, counter)   
  {   
    if (counter <= 10)   
    {   
       counter = 10;   
    }   
   
  // fade from min to max in increments of 25.5 points: basically (0.5 volts)   
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5)    
    counter = fadeValue;   
    digitalWrite(PWMPin, fadeValue);   
     
    // sets the value (range from 0 to 255):   
   Serial.println(PWMPin);   
   analogWrite(PWMPin, fadeValue);    
   delay(100);      
  }    
  }   
     
  {    
    if (digitalRead(buttonBpin) == LOW, counter)   
  {   
    if (counter <= 0)   
    {   
       counter = 0;   
    }   
  // fade from max to min in increments of 25.5 points: basically (0.5 volts)   
  for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=25.5)    
    counter = fadeValue;   
    digitalWrite(PWMPin, fadeValue);   
     
  // sets the value (range from 0 to 255):   
  analogWrite(PWMPin, fadeValue);    
  delay(100);     
  }  
  }    
}