Skip to content

Instantly share code, notes, and snippets.

@montyanderson
Created May 19, 2015 19:08
Show Gist options
  • Save montyanderson/6549155030799986318b to your computer and use it in GitHub Desktop.
Save montyanderson/6549155030799986318b to your computer and use it in GitHub Desktop.
int pwmPin = 9; // output pin supporting PWM
int inPin = 3; // voltage connected to analog pin 3, e.g. a potentiometer
int val = 0; // variable to store the read value
float volt = 0; // variable to hold the voltage read
float analogToVolt(int val) {
return (5.0 * val) / 1023;
}
int voltToPWM(float volt) {
return 255 * (volt / 5);
}
void setup() {
pinMode(pwmPin, OUTPUT); // sets the pin as output
Serial.begin(9600);
}
void loop() {
volt = analogToVolt(analogRead(inPin));
val = voltToPWM(volt);
analogWrite(pwmPin, val);
Serial.print(val);
Serial.print(", ");
Serial.println(volt);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment