Skip to Content
Arduino Cookbook, 3rd Edition
book

Arduino Cookbook, 3rd Edition

by Michael Margolis, Brian Jepson, Nicholas Robert Weldin
April 2020
Intermediate to advanced
795 pages
17h 43m
English
O'Reilly Media, Inc.
Book available
Content preview from Arduino Cookbook, 3rd Edition

Mathematical Operations

3.0 Introduction

Almost every sketch uses mathematical operations to manipulate the value of variables. This chapter provides a brief overview of the most common mathematical operations. If you are already familiar with C or C++, you may be tempted to skip this chapter, but we suggest you review it because there are some idioms used by Arduino programmers that you may encounter even if you don’t use them yourself (such as the use of bitSet to change the value of a bit). If you are new to C and C++, see one of the C reference books mentioned in the Preface.

3.1 Adding, Subtracting, Multiplying, and Dividing

Problem

You want to perform simple math on values in your sketch. You want to control the order in which the operations are performed and you may need to handle different variable types.

Solution

Use the following code:

int myValue;
myValue = 1 + 2;  // addition
myValue = 3 - 2;  // subtraction
myValue = 3 * 2;  // multiplication
myValue = 3 / 2;  // division (the result is 1)

Discussion

Addition, subtraction, and multiplication for integers work much as you expect.

Integer division truncates the fractional remainder in the division example shown in this recipe’s Solution; myValue will equal 1 after the division (see Recipe 2.3 if your application requires fractional results):

int value =   1 + 2 * 3 + 4;

Compound statements, such as the preceding statement, may appear ambiguous, but the precedence (order) of every operator is well defined. Multiplication ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Arduino for Arduinians

Arduino for Arduinians

John Boxall
Getting Started With Arduino, 4th Edition

Getting Started With Arduino, 4th Edition

Massimo Banzi, Michael Shiloh

Publisher Resources

ISBN: 9781491903513Errata PageSupplemental Content