Выбрать главу

Having set the pin as an input, you can then read the voltage at that pin, as in this example loop function:

loop()

{

  if (digitalRead(7) == HIGH)

  {

    digitalWrite(led, LOW)

  }

}

Here, the LED will be turned off if the input at pin 7 is read as HIGH at the time it is tested. The Arduino decides whether to turn the LED on with an if statement, which starts with the if command. Immediately after the word if is a condition. In this case, the condition is (digitalRead(7) == HIGH). The double equal sign (==) tells the machine to compare the two values on either side. In this case, if pin 7 is HIGH, then the block of code surrounded by { and } after the if will run; otherwise it won’t. We have already met the code to be run if the condition is true. This is the digitalWrite command to turn the LED on.

NOTE

Lining up the { and } makes it easier to see which } belongs to which {.

STABILIZING DIGITAL INPUTS WITH PULL-UP RESISTORS

The preceding example code in assumes that the digital input is definitely either high or low. A switch connected to a digital input can only close a connection. You’ll typically connect switches in such a way that when flipped, the digital input is connected to GND (0V). While the switch’s connection is open, the digital input is said to be floating. That means the input isn’t electrically connected to anything, but a floating input can still pick up electrical noise from the circuitry around it, causing the voltage on the pin to oscillate between high and low.

This behavior is undesirable because the code could be activated unexpectedly. To prevent input pins from floating, just add a pull-up resistor (Figure C-5). We use just such a resistor in “Project 6: PIR Zombie Detector” on page 72.

When the switch is open (as shown in Figure C-5), the resistor connects the input pin to a voltage source, pulling up the voltage at the input pin to 5V and holding it there. Pressing the button to close the switch overrides the weak pulling up of the input, connecting the digital input to GND instead.

Figure C-5: Schematic for using a pull-up resistor with a digital input

Arduino inputs have built-in pull-up resistors of about 40 kΩ that you can enable as follows:

pinMode(switchPin, INPUT_PULLUP);

This example shows how you would set the pin mode of a digital input to be used with a switch using the Arduino pull-up resistor: just set the pin mode to INPUT_PULLUP rather than INPUT.

READING ANALOG INPUTS

Analog inputs allow you to measure a voltage between 0V and 5V on any of the A0 to A5 analog input pins on the Arduino. Unlike with digital inputs and outputs, you don’t need to include the pinMode command in setup when using an analog input.

You use analogRead to read the value of an analog input, and you supply the name of the pin you want to read as a parameter. Unlike digitalRead, analogRead returns a number rather than just true or false values. The returned number will be between 0 (0V) and 1,023 (5V). To convert the number into an applicable voltage, multiply the value by 5 and then divide it by 1,023, which amounts to dividing it by 204.6.

Here’s how you’d read an analog value and convert it in Arduino code:

int raw = analogRead(A0);

float volts = raw / 204.6;

The variable raw is an int (whole number) because the reading from an analog input is always a whole number. To scale the raw reading as a decimal number, the variable needs to be a float (floating point) type of variable.

WRITING TO ANALOG OUTPUTS

Digital outputs only allow you to turn a component (like an LED) on and off, but analog outputs allow you to control the level of power supplied to a component incrementally. This control allows you to, for example, control the brightness of an LED or the speed of a motor. This is used in “Project 20: Silent Haptic Communication with Arduino” on page 209 to reduce the power to the motor so that it doesn’t attract zombies by making too much noise.

Only the pins D3, D5, D6, D9, D10, or D11 are capable of being used as analog outputs. These pins are marked with a little tilde (~) beside the pin number on the Arduino.

To control an analog output, use the command analogWrite with a number between 0 and 255 as the parameter, as in the following line:

analogWrite(3, 127);

A value of 0 is 0V and fully off, while a value of 255 is 5V and fully on. In this example, we set the output of pin D3 to 127, which would be half power.

REPEATING CODE IN CONTROL LOOPS

Control loops (not to be confused with the loop function) allow you to repeat an action a set number of times or until some condition changes. There are two commands you can use for looping: for and while. You would use the for command for repeating something a fixed number of times and while for repeating something until a condition changes.

The following code makes an LED blink 10 times and then stops:

void setup() {

  pinMode(led, OUTPUT);

  for (int i = 0; i < 10; i++)

  {

    digitalWrite(led, HIGH);

    delay(1000);

    digitalWrite(led, LOW);

    delay(1000);

  }

void loop() {

}

HOW ANALOG OUTPUTS GENERATE VOLTAGES

It is tempting to think of an analog output as being capable of a voltage between 0V and 5V, and if you attach a voltmeter between an analog output pin and GND, the voltage will indeed seem to take on values between 0V and 5V as you change the parameter to analogWrite. In fact, things are a little more complex than that. This kind of output is using pulse width modulation (PWM). Figure C-6 shows what is really going on.

Figure C-6: Analog output’s pulse width modulation

An analog output pin generates 490 pulses per second with varied pulse widths. The larger the proportion of the time that the pulse stays high, the greater the power delivered to the output, and hence the brighter the LED or faster the motor.

A voltmeter reports this as a change in voltage because the voltmeter cannot respond fast enough and therefore does a kind of averaging (integration).

In this example, we place the blinking code in setup rather than loop, because loop would repeat the blink cycle immediately so the LED would not stop after 10 times.

If you wanted to keep an LED blinking as long as a button connected to a digital input was pressed, you would use a while command:

➊ while (digitalRead(9) == LOW)

   {

      digitalWrite(led, HIGH);

      delay(1000);

      digitalWrite(led, LOW);

      delay(1000);

   }

This code says that while pin 9 detects that a button is being pressed ➊, the LED should be lit.

SETTING TWO CONDITIONS WITH IF/ELSE

In “Configuring Digital Outputs” on page 251, we used an if command to tell the Arduino IDE to do something if a certain condition was met. You can also use if in conjunction with the else command to instruct the IDE to perform one set of code if the condition is true and a different set of commands if it is false. Here’s an example: