Skip to content

Instantly share code, notes, and snippets.

@dcvezzani
Last active April 30, 2018 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcvezzani/52b3a5cccb9ab4547c7a6470ce1a8431 to your computer and use it in GitHub Desktop.
Save dcvezzani/52b3a5cccb9ab4547c7a6470ce1a8431 to your computer and use it in GitHub Desktop.
My latest musings with an Arduino
#include <math.h>
/*
AnalogReadSerial
Reads an analog input on pin 0, prints the result to the Serial Monitor.
Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/AnalogReadSerial
*/
int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
int maxFadeAmount = 130;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
int readInput() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
//delay(1); // delay in between reads for stability
return sensorValue;
}
void fadeLed(float percentage) {
// set the brightness of pin 9:
Serial.println(maxFadeAmount * percentage);
analogWrite(led, (maxFadeAmount * percentage));
}
void blinkLed(float percentage) {
// set the brightness of pin 9:
analogWrite(led, brightness);
fadeAmount = maxFadeAmount * percentage * ((fadeAmount > 0) ? 1 : (-1));
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
Serial.print(brightness);
Serial.print(", ");
Serial.println(fadeAmount);
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) {
if (brightness < 0) brightness = 0;
if (brightness > 255) brightness = 255;
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
// delay(30);
}
// the loop routine runs over and over again forever:
void loop() {
int sensorValue = readInput();
if (sensorValue <= 10) {
sensorValue = 11;
//Serial.println(sensorValue);
}
float percentage = sensorValue / 1024.0;
Serial.print(percentage);
Serial.print("; ");
blinkLed(percentage);
//fadeLed(percentage);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment