04 – class notes, 7 Sep 2017 — Arduino Analog
Boring Bits
My office hours are noon to 3 this Friday (8 Sep) but I can come in at 11 if that works around a time conflict, just drop me email.
Arduino Documentation
The Arduino tutorial pages are a great resource. In the Arduino IDE, go to File->Examples and you’ll find example sketches for, well, almost everything in Arduino.
Analog vs. Digital
In the previous class we talked about analog vs digital. Digital only has to states: on or off, open or closed, or in the Arduino, 0 volts or 5 volts. We use pull-down resistors to force digital inputs to be 0 if they are not 5 volts.
Analog has a range between the states of digital. A door can be half-open, a class can have final grades instead of being pass/fail, a party can range from quiet to loud depending on the people and the music.
Reading Analog Signals
Arduino Uno has six analog input pins labeled A0 to A5 that can read voltages between 0 and 5V. Use analogRead() to read a pin, it will return a value between 0 (for no voltage) and 1023 (for around 5V).
The Arduino documentation has good circuit diagrams for setting up a potentiometer (or “pot”) and a photoresistor to be read on an analog input. For now, only read analog signals powered by the Arduino 5V pin, outside signals might release the magic smoke from your Arduino.
To test your hardware, use the smallest sketch possible to read the analog input and write the information to the console:
// the value of dialPin. It's not something we would want to change,
// but making it "const" prevents us from doing it by accident
const int dialPin = 0;
void setup() {
pinMode(dialPin, INPUT);
// set up the serial console that we used in class
Serial.begin(115200);
}
void loop() {
lightValue = analogRead(dialPin);
Serial.println(lightValue);
}
Writing Analog
When we read analog we get values from 0 to 1023 from pins A0 thru A5, however when we write analog we can only write from 0 to 255 and we can only use certain pins for output, which pin varies by the type of Arduino board.
int ledValue = 0;
void setup() {
pinMode (ledPin, OUTPUT);
}
void loop() {
ledValue = ledValue + 1;
// a good example of using an if statement.
// the max value for analogWrite is 255, so if ledValue
// is over 255, reset it to 0
if (ledValue > 255) {
ledValue = 0;
}
analogWrite(ledPin, ledValue );
// the delay() statement can cause real problems in your actual script. While
// the delay is happening, the arduino does nothing, it's like hitting "pause"
// on a music player.
delay(20);
}