- Programming Arduino Getting Started with Sketches Book Description:
- Outsourcing Services
- Programming Arduino Getting Started with Sketches by Simon Monk E-Book
- Programming Arduino: Getting Started with Sketches (2nd ed.)
- Programming Arduino Getting Started with Sketches (9780071784221): Simon Monk
Programming Arduino Getting Started With ichwarmaorourbia.tk About the Author Simon Monk has a bachelor's degree in cybernetics and computer science and a . Programming Arduino Getting Started with Sketches. Pages · with Sketches. Simon Monk He has been an. Getting Started in Currency Trading: Winning in Today's Forex Market Download Book (PDF, KB). Book . Written by hobbyist and electronics guru Simon Monk, Programming Arduino": Getting Started with Sketches, Second Edition, features easy-to-follow.
|Language:||English, Arabic, Dutch|
|ePub File Size:||29.80 MB|
|PDF File Size:||11.19 MB|
|Distribution:||Free* [*Registration Required]|
Programming Arduino: Getting Started with Sketches, Second Edition Book Details Author: Simon Monk Pages: Binding: Paperback. Read Programming Arduino PDF - Getting Started with Sketches, Second Edition by Simon Monk New Harbinger Publications | Program. [PDF] Programming Arduino Getting Started with Sketches Edition by Simon Monk . In this practical guide, electronics guru Simon Monk takes you under the .
Table of Contents A. Dedication B. About the Author C. Preface D. Acknowledgments E. Introduction 1. This Is Arduino 2.
Getting Started 3. C Language Basics 4.
Programming Arduino Getting Started with Sketches Book Description:
Functions 5. Arrays and Strings 6. Input and Output 7.
The Standard Arduino Library 8. Data Storage 9. Displays You can read the connection names next to the connectors. The first is Reset. This does the same thing as the Reset button on the Arduino. Rather like rebooting a PC, using the Reset connector resets the microcontroller so that it begins its program from the start.
To reset the microcontroller with the Reset connector, you momentarily set this pin low connecting it to 0V. The rest of the pins in this section just provide different voltages 3.
GND, or ground, just means zero volts. It is the reference voltage to which all other voltages on the board are relative. Analog Inputs The six pins labeled as Analog In A0 to A5 can be used to measure the voltage connected to them so that the value can be used in a sketch. Note that they measure a voltage and not a current. Only a tiny current will ever flow into them and down to ground because they have a very large internal resistance.
That is, the pin having a large internal resistance only allows a tiny current to flow into the pin. Although these inputs are labeled as analog, and are analog inputs by default, these connections can also be used as digital inputs or outputs. Digital Connections We now switch to the top connector and start on the right-hand side in Figure Here we find pins labeled Digital 0 to These can be used as either inputs or outputs.
When used as outputs, they behave rather like the power supply voltages discussed earlier in this section, except that these are all 5V and can be turned on or off from your sketch. So, if you turn them on from your sketch they will be at 5V, and if you turn them off they will be at 0V.
As with the power supply connectors, you must be careful not to exceed their maximum current capabilities. The first two of these connections 0 and 1 are also labeled RX and TX, for receive and transmit. These connections are reserved for use in communication and are indirectly the receive and transmit connections for your USB link to your computer.
These digital connections can supply 40 mA milliamps at 5V. That is more than enough to light a standard LED, but not enough to drive an electric motor directly. Microcontroller Continuing our tour of the Arduino board, the microcontroller chip itself is the black rectangular device with 28 pins. This is fitted into a dual inline DIL socket so that it can be easily replaced. The pin microcontroller chip used on the Arduino Uno board is the ATmega Figure is a block diagram showing the main features of this device.
The heart—or, perhaps more appropriately, the brain—of the device is the central processing unit CPU. It controls everything that goes on within the device. It fetches program instructions stored in the flash memory and executes them.
This might involve fetching data from working memory RAM , changing it, and then putting it back. Or, it may mean changing one of the digital outputs from 0V to 5V.
Whereas the flash memory is intended for storing program instructions from sketches , the EEPROM is used to store data that you do not want to lose in the event of a reset or the power being turned off. Figure ATmega block diagram Other Components Above the microcontroller is a small, silver, rectangular component. This is a quartz crystal oscillator. It ticks 16 million times a second, and on each of those ticks, the microcontroller can perform one operation—addition, subtraction, or another mathematical operation.
To the right of the crystal is the Reset switch. Clicking on this switch sends a logic pulse to the Reset pin of the microcontroller, causing the microcontroller to start its program afresh and clear its memory. Note that any program stored on the device will be retained, because this is kept in non- volatile flash memory—that is, memory that remembers even when the device is not powered. To the right of the Reset button is the Serial Programming Connector. It offers another means of programming the Arduino without using the USB port.
Because we do have a USB connection and software that makes it convenient to use, we will not avail ourselves of this feature. This chip converts the signal levels used by the USB standard to levels that can be used directly by the Arduino board.
The Origins of Arduino Arduino was originally developed as an aid for teaching students. It was subsequently in developed commercially by Massimo Banzi and David Cuartielles.
It has since gone on to become enormously successful with makers, students, and artists for its ease of use and durability. Another key factor in its success is that all the designs for Arduino are freely available under a Creative Commons license.
This has allowed many lower-cost alternatives to the boards to appear. Many big retailers sell only the official boards, which are nicely packaged and of high quality.
Yet another reason for the success of Arduino is that it is not limited to microcontroller boards. There are a huge number of Arduino-compatible shield boards that plug directly into the top of an Arduino board. Because shields are available for almost every conceivable application, you often can avoid using a soldering iron and instead plug together shields that can be stacked one upon another.
The following are just a few of the most popular shields: Indeed, this is by far the most used of the Arduino boards, but the boards are all programmed using the same language and largely have the same connections to the outside world, so you can easily use a different board.
Uno, Duemilanove, and Diecimila The Arduino Uno is the latest incarnation of the most popular series of Arduino boards. The series includes the Diecimila Italian for 10, and the Duemilanove Italian for Figure shows an Arduino clone.
By now you may have guessed that Arduino is an Italian invention. These older boards look very similar to the Arduino Uno. They both have the same connectors and a USB socket and are generally compatible with each other. The most significant difference between the Uno and the earlier boards is that the Uno uses a different USB chip.
Programming Arduino Getting Started with Sketches by Simon Monk E-Book
This does not affect how you use the board, but it does make installation of the Arduino software easier and allows higher speeds of communication with the computer. The Uno can also supply more current on its 3. The earlier boards will have either an ATmega or ATmega The ATmega has more memory, but unless you are creating a large sketch, this will make no difference.
It boasts a huge collection of input output ports, but cleverly adds these as extra connectors at one end of the board, allowing it to remain pin-compatible with the Arduino Uno and all the shields available for Arduino.
It uses a processor with more input output pins, the ATmega, which is a surface mount chip that is fixed permanently to the board. So, unlike with the Uno and similar boards, you cannot replace the processor if you accidentally damage it.
The extra connectors are arranged at the end of the board. Extra features provided by the Mega include the following: If you fit pins to it, it can just plug into the breadboard as if it were a chip. This allows the device to even be programmed wirelessly. The Arduino Bluetooth is not a cheap board, and it is often cheaper to attach a third-party Bluetooth module to a regular Arduino Uno. Lilypad The Lilypad Figure is a tiny, thin Arduino board that can be stitched into clothing for applications that have become known as wearable computing.
The Lilypad does not have a USB connection, and you must use a separate adaptor to program it. It has an exceptionally beautiful design.
However, the range of Arduino boards constantly changes, so for a complete and up-to-date picture of the Arduino family, see the official Arduino website list at www. Arduino Clones and Variants Unofficial boards fall into two categories. Some just take the standard open source hardware designs of Arduino and build a cheaper one.
Some names you can search for boards of this nature include the following: New variants are appearing all the time, and far too many exist to mention them all. However, the following are some of the more interesting and popular variants: Powering Up When you download an Arduino board, it is usually preinstalled with a sample Blink program that will make the little built-in light-emitting diode LED flash.
The LED marked L is wired up to one of the digital input output sockets on the board. It is connected to digital pin This limits pin 13 to being the one used as an output. However, the LED uses only a small amount of current, so you can still connect other things to that connector.
All you need to do to get your Arduino up and running is supply it with some power. The easiest way to do this is to plug in it into the USB port on your computer. This is the same type of lead that is normally used to connect a computer to a printer. New Arduino boards come with this Blink sketch already installed so that you can verify that the board works. Installing the Software To be able to install new sketches onto your Arduino board, you need to do more than supply power to it over the USB.
You need to install the Arduino software Figure Full and comprehensive instructions for installing this software on Windows, Linux, and Mac computers can be found at the Arduino website www.
Once you have successfully installed the Arduino software and, depending on your platform, USB drivers, you should now be able to upload a program to the Arduino board. When you start the Arduino application on your computer, it opens with an empty sketch.
Fortunately, the application ships with a wide range of useful examples. So from the File menu, open the Blink example as shown in Figure Figure The Blink sketch You now need to transfer or upload that sketch to your Arduino board.
So plug your Arduino board into your computer using the USB lead. The Arduino board will probably already be flashing, as the boards are generally shipped with the Blink sketch already installed.
Before you can upload a sketch, you must tell the Arduino application what type of board you are using and which serial port you are connected to. Figures and show how you do this from the Tools menu. Now click on the Upload icon in the toolbar. This is shown highlighted in Figure After you click the button, there is a short pause while the sketch is compiled and then the transfer begins. If this did not work, then check your serial and board type settings.
Figure shows the modified sketch with the changes highlighted. Figure Uploading the sketch Click on the Upload button again. Then, once the sketch has uploaded, you should see your LED start to blink twice as fast as it did before.
Congratulations, you are now ready to start programming your Arduino. You can open them and copy parts from one to another. You will not normally use Open because the Arduino application has the concept of a Sketchbook where all your sketches are kept carefully organized into folders. You gain access to the Sketchbook from the File menu. As you have just installed the Arduino application for the first time, your Sketchbook will be empty until you create some sketches.
As you have seen, the Arduino application comes with a selection of example sketches that can be very useful. Accept the default location, but change the filename to MyBlink, as shown in Figure Now if you go to the File menu and then click on Sketches, you will see MyBlink as one of the sketches listed. I suggest that now is the time to download this file and unzip it into the Arduino folder that contains the sketches. In other words, when you have unzipped the folder, there should be two folders in your Arduino folder: The Programming Arduino folder will contain all the sketches, numbered according to chapter, so that sketch , for example, is sketch 1 of Chapter 3.
Figure Saving a copy of Blink These sketches will not appear in your Sketchbook menu until you quit the Arduino application and restart it. Do so now. Then your Sketchbook menu should look similar to that shown in Figure In the next chapter, we will look at some of the basic principles of the C language that the Arduino uses and start writing some code.
In this chapter, you get to understand the basics of the C language. You will use what you learn here in every sketch you develop as an Arduino programmer. To get the most out of Arduino, you need to understand these fundamentals. Programming It is not uncommon for people to speak more than one language. In fact, the more you learn, the easier it seems to learn spoken languages as you start to find common patterns of grammar and vocabulary. The same is true of programming languages.
So, if you have used any other programming language, you will quickly pick up C. The good news is that the vocabulary of a programming language is far smaller than that of a spoken language, and because you write it rather than say it, the dictionary can always be at hand whenever you need to look things up.
Also, the grammar and syntax of a programming language are extremely regular, and once you come to grips with a few simple concepts, learning more quickly becomes second nature. It is best to think of a program—or a sketch, as programs are called in Arduino—as a list of instructions to be carried out in the order that they are written down. For example, suppose you were to write the following: These three lines would each do something.
The first line would set the output of pin 13 to HIGH. The second line would simply wait for milliseconds half a second and then the third line would turn the LED back off again.
So these three lines would achieve the goal of making the LED blink once. These are both part of what is termed the syntax of the language. Most languages require you to be extremely precise about syntax, and one of the main rules is that names for things have to be a single word. That is, they cannot include spaces. So, digitalWrite is the name for something.
Not only do you have to avoid spaces in names, but also names are case sensitive. So you must write digitalWrite, not DigitalWrite or Digitalwrite. These two pieces of information are called arguments, which are said to be passed to a function when it is called.
The parameters for a function must be enclosed in parentheses and separated by commas.
However, you can sprinkle space characters within the parentheses if you want. If the function only has one argument, then there is no need for a comma.
Notice how each line ends with a semicolon. It would be more logical if they were periods, because the semicolon marks the end of one command, a bit like the end of a sentence. In the next section, you will find out a bit more about what happens when you press the Upload button on the Arduino integrated development environment IDE. Then you will be able to start trying out a few examples.
What Is a Programming Language? It is perhaps a little surprising that we can get to Chapter 3 in a book about programming without defining exactly what a programming language is.
We can recognize an Arduino sketch and probably have a rough idea of what it is trying to do, but we need to look a bit deeper into how some programming language code goes from being words on a page to something that does something real, like turn an LED on and off. Figure summarizes the process involved from typing code into the Arduino IDE to running the sketch on the board.
This is not as straightforward as simply taking the text that you typed into the editor and moving it to the Arduino board. The first step is to do something called compilation. This takes the code you have written and translates it into machine code—the binary language that the Arduino understands. A side-effect of compiling the code is that it is checked to make sure that it conforms to the rules of the C language.
This text is not C. Ciao does not name a type.
This time we will try compiling a sketch with no code at all in it see Figure This time, the compiler is telling you that your sketch does not have setup or loop functions. The Arduino IDE has looked at your efforts at writing code and found them to be acceptable. The IDE is also telling you that the maximum size is 32, bytes, so you still have lots of room to make your sketch bigger.
There are some new things here. For example, there is the word void and some curly braces. Figure A sketch that will compile The line void setup means that you are defining a function called setup. In Arduino, some functions are already defined for you, such as digitalWrite and delay, whereas you must or can define others for yourself.
The important thing to understand is that here you are not calling setup or loop like you would call digitalWrite, but you are actually creating these functions so that the Arduino system itself can call them. This is a difficult concept to grasp, but one way to think of it is as being similar to a definition in a legal document.
Programming Arduino: Getting Started with Sketches (2nd ed.)
Functions work much like such definitions. You define a function that you or the system itself can then use elsewhere in your sketches. Going back to void, these two functions setup and loop do not return a value as some functions do, so you have to say that they are void, using the void keyword. If you imagine a function called sin that performed the trigonometric function of that name, then this function would return a value.
The value returned to use from the call would be the sin of the angle passed as its argument. After the special keyword void comes the name of the function and then parentheses to contain any arguments.
In this case, there are no arguments, but we still have to include the parentheses there. There is no semicolon after the closing parenthesis because we are defining a function rather than calling it, so we need to say what will happen when something does call the function.
Those things that are to happen when the function is called must be placed between curly braces. Curly braces and the code in between them are known as a block of code, and this is a concept that you will meet again later. Note that although you do have to define both the functions setup and loop, you do not actually have to put any lines of code in them.
However, failing to add code will make your sketch a little dull. The reason that Arduino has the two functions setup and loop is to separate the things that only need to be done once, when the Arduino starts running its sketch, from the things that have to keep happening continuously. The function setup will just be run once when the sketch starts. Add the lines to your sketch so that it appears as follows and then upload them to your board: The setup function itself calls two built-in functions, pinMode and digitalWrite.
You already know about digitalWrite, but pinMode is new. The function pinMode sets a particular pin to be either an input or an output. So, turning the LED on is actually a two-stage process.
First, you have to set pin 13 to be an output, and second, you need to set that output to be high 5V. When you run this sketch, on your board you will see that the LED comes on and stays on. You can leave the pinMode call in the setup function because you only need to call it once. The project would still work if you moved it into the loop, but there is no need and it is a good programming habit to do things only once if you only need to do them once. So modify your sketch so that it looks like this: Run this sketch and see what happens.
It may not be quite what you were expecting. The LED is basically on all the time. Hmm, why should this be? Try stepping through the sketch a line at a time in your head: Run setup and set pin 13 to be an output.
Run loop and set pin 13 to high LED on. Delay for half a second. Set pin 13 to low LED off. Run loop again, going back to step 2, and set pin 13 to high LED on. The problem lies between steps 4 and 5. What is happening is that the LED is being turned off, but the very next thing that happens is that it gets turned on again. This happens so quickly that it appears that the LED is on all the time. The microcontroller chip on the Arduino can perform 16 million instructions per second.
So, our LED will only be off for a few millionths of a second. To fix the problem, you need to add another delay after you turn the LED off. Your code should now look like this: Try again and your LED should blink away merrily once per second.
You can download them from http: Variables In this Blink example, you use pin 13 and have to refer to it in three places. If you decided to use a different pin, then you would have to change the code in three places. Similarly, if you wanted to change the rate of blinking, controlled by the argument to delay, you would have to change to some other number in more than one place.
Variables can be thought of as giving a name to a number. Actually, they can be a lot more powerful than this, but for now, you will use them for this purpose. When defining a variable in C, you have to specify the type of the variable. We want our variables to be whole numbers, which in C are called ints. So to define a variable called ledPin with a value of 13, you need to write the following: Notice that because ledPin is a name, the same rules apply as those of function names.
So, there cannot be any spaces. The convention is to start variables with a lowercase letter and begin each new word with an uppercase letter. We have also sneaked in another variable called delayPeriod. Everywhere in the sketch where you used to refer to 13, you now refer to ledPin, and everywhere you used to refer to , you now refer to delayPeriod. Try changing it to and running the sketch on your Arduino board. There are other cunning things that you can do with variables.
To do this, all you need to do is to add something to the delayPeriod variable each time that you do a blink. Modify the sketch by adding the single line at the end of the loop function so that it appears, as in the following listing, and then run the sketch on the Arduino board. Press the Reset button and see it start from a fast rate of flashing again.
Your Arduino is doing arithmetic now. Every time that loop is called, it will do the normal flash of the LED, but then it will add to the variable delayPeriod. We will come back to arithmetic shortly, but first you need a better way than a flashing LED to see what the Arduino is up to.
Experiments in C You need a way to test your experiments in C. One way is to put the C that you want to test out into the setup function, evaluate them on the Arduino, and then have the Arduino display any output back to something called the Serial Monitor, as shown in Figures and You access it by clicking on the rightmost icon in the toolbar.
Its purpose is to act as a communication channel between your computer and the Arduino. You can type a message in the text entry area at the top of the Serial Monitor and when you press Return or click Send, it will send that message to the Arduino.
Also if the Arduino has anything to say, this message will appear in the Serial Monitor. In both cases, the information is sent through the USB link. Figure Writing C in setup Figure The Serial Monitor As you would expect, there is a built-in function that you can use in your sketches to send a message back to the Serial Monitor. It is called Serial. This information is usually a variable. Numeric Variables and Arithmetic The last thing you did was add the following line to your blinking sketch to increase the blinking period steadily: The equals sign does something called assignment.
That is, it assigns a new value to a variable, and the value it is given is determined by what comes after the equals sign and before the semicolon. In this case, the new value to be given to the delayPeriod variable is the old value of delayPeriod plus Figure shows what you should see in the Serial Monitor after this code runs.
To take a slightly more complex example, the formula for converting a temperature in degrees Centigrade into degrees Fahrenheit is to multiply it by 5, divide by 9, and then add So you could write that in a sketch like this: First, note the following line: When we write such a line, we are actually doing two things: We are declaring an int variable called degC, and we are saying that its initial value will be Alternatively, you could separate these two things and write the following: You must declare any variable just once, essentially telling the compiler what type of variable it is —in this case, int.
However, you can assign the variable a value as many times as you want: So, in the Centigrade to Fahrenheit example, you are defining the variable degC and giving it an initial value of 20, but when you define degF, it does not get an initial value. Its value gets assigned on the next line, according to the conversion formula, before being sent to the Serial Monitor for you to see. This is in accordance with the usual use of arithmetic. However, sometimes it makes it clearer to use parentheses in the expressions.
So, for example, you could write the following: The expressions that you write can be as long and complex as you need them to be, and in addition to the usual arithmetic operators, there are other less commonly used operators and a big collection of various mathematical functions that are available to you.
You will learn about these later. Commands The C language has a number of built-in commands. In this section, we explore some of these and see how they can be of use in your sketches. What if you only want to execute part of a sketch if some condition is true?
At the moment, it will gradually get slower and slower until each blink is lasting hours. To do this, you must use an if command; the modified sketch is as follows.
Try it out. The if command looks a little like a function definition, but this resemblance is only superficial. The word in the parenthesis is not an argument; it is what is called a condition. So in this case, the condition is that the variable delayPeriod has a value that is greater than 3, If this is true, then the commands inside the curly braces will be executed.
In this case, the code sets the value of delayPeriod back to If the condition is not true, then the Arduino will just continue on with the next thing. Running through the sequence of events in your head will help you understand what is going on. So, here is what happens: Arduino runs setup and initializes the LED pin to be an output. Arduino starts running loop.
The LED turns on. A delay occurs. The LED turns off. Add to the delayPeriod. If the delay period is greater than 3, set it back to Go back to step 2. It is one example of what are called comparison operators. These operators are summarized in the following table: There is another form of if that allows you to do one thing if the condition is true and another if it is false. We will use this in some practical examples later in the book.
You already know one way of doing this, using the loop function. As soon as all the commands in the loop function have been run, it will start again automatically. However, sometimes you need more control than that. You could do that by just repeating the same code over and over again in your loop function, like this: But this requires a lot of typing and there are several much better ways to do this.
The sketch to accomplish this with a for loop is, as you can see, a lot shorter and easier to maintain than the previous example: The for loop looks a bit like a function that takes three arguments, although here those arguments are separated by semicolons rather than the usual commas. This is just a quirk of the C language. The compiler will soon tell you when you get it wrong. The first thing in the parentheses after for is a variable declaration.
This specifies a variable to be used as a counter variable and gives it an initial value—in this case, 0. The second part is a condition that must be true for you to stay in the loop. In this case, you will stay in the loop as long as i is less than 20, but as soon as i is 20 or more, the program will stop doing the things inside the loop.
The final part is what to do every time you have done all the things in the loop. In this case, that is to increment i by 1 so that it can, after 20 trips around the loop, cease to be less than and cause the program to exit the loop. Try entering this code and running it. The only way to get familiar with the syntax and all that pesky punctuation is to type it in and have the compiler tell you when you have done something wrong. Eventually it will all start to make sense.
One potential downside of this approach is that the loop function is going to take a long time. This is not a problem for this sketch, because all it is doing is flashing an LED. But often, the loop function in a sketch will also be checking that keys have been pressed or that serial communications have been received. If the processor is busy inside a for loop, it will not be able to do this. Generally, it is a good idea to make the loop function run as fast as possible so that it can be run as frequently as possible.
The following sketch shows how to achieve this: You may have noticed the following line: This is just C shorthand for the following: In fact, for some applications, even this is too slow, and purists would say that you should not use delay at all. The best solution depends on the application. You can accomplish the same thing as the preceding for example using a while command as follows: The expression in parentheses after while must be true to stay in the loop.
When it is no longer true, then the sketch continues running the commands after the final curly brace. The define Directive For constant values like pin assignments that do not change during the running of a sketch, there is an alternative to using a variable. You can use a command called define that allows you to associate a value with a name.
Everywhere that this name appears in your sketch, the value will be substituted before the sketch is compiled. As an example, you could define a pin assignment for a LED like this: This is because it is not actually part of the C language itself; but is called a pre-compiler directive that is run before compilation. It is something to consider if memory is at a premium. Conclusion This chapter has got you started with C. You also worked out how to use if and for commands to control the order in which your commands are executed, and learned a little about making an Arduino do some arithmetic.
In the next chapter, you will look more closely at functions. The chapter will also introduce the variable types other than the int type that you used in this chapter.
The reason that you need to be able to write your own functions is that as sketches start to get a little complicated, then your setup and loop functions will grow and grow until they are long and complicated and it becomes difficult to see how they work. The biggest problem in software development of any sort is managing complexity. The best programmers write software that is easy to look at and understand and requires very little in the way of explanation.
Functions are a key tool in creating easy-to-understand sketches that can be changed without difficulty or risk of the whole thing falling into a crumpled mess. What Is a Function? A function is a little like a program within a program. You can use it to wrap up some little thing that you want to do.
A function that you define can be called from anywhere in your sketch and contains its own variables and its own list of commands. When the commands have been run, execution returns to the point just after wherever it was in the code that called the function. By way of an example, code that flashes a light-emitting diode LED is a prime example of some code that should be put in a function. So, all we have really done here is to move the four lines of code that flash the LED from the middle of the for loop to be in a function of their own called flash.
Now you can make the LED flash any time you like by just calling the new function by writing flash. Note the empty parentheses after the function name. This indicates that the function does not take any parameters. The delay value that it uses is set by the same delayPeriod function that you used before. Parameters When dividing your sketch up into functions, it is often worth thinking about what service a function could provide.
In the case of flash, this is fairly obvious. Read through the following code and then I will explain just how parameters work in a little more detail. Now, if we look at our loop function, it has only two lines in it. We have moved the bulk of the work off to the flash function. Notice how when we call flash we now supply it with two arguments in parentheses.
Where we define the function at the bottom of the sketch, we have to declare the type of variable in the parameters. In this case, they are both ints. We are in fact defining new variables. However, these variables numFlashes and d can only be used within the flash function. This is a good function because it wraps up everything you need in order to flash an LED.
The only information that it needs from outside of the function is to which pin the LED is attached. If you wanted, you could make this a parameter too—something that would be well worth doing if you had more than one LED attached to your Arduino.
Global, Local, and Static Variables As was mentioned before, parameters to a function can be used only inside that function. So, if you wrote the following code, you would get an error: On the other hand, suppose you wrote this: This code would not result in a compilation error.
However, you need to be careful, because you now actually have two variables called x and they can each have different values. The one that you declared on the first line is called a global variable. It is called global because it can be used anywhere you like in the program, including inside any functions. The parameter x is said to shadow the global variable of the same name. This can lead to some confusion when trying to debug a project. In addition to defining parameters, you can also define variables that are not parameters but are just for use within a function.
These are called local variables. For example: The local variable timesToFlash will only exist while the function is running. As soon as the function has finished its last command, it will disappear. This means that local variables are not accessible from anywhere in your program other than in the function in which they are defined. So, for instance, the following example will cause an error: Seasoned programmers generally treat global variables with suspicion.
The reason is that they go against the principal of encapsulation. The idea of encapsulation is that you should wrap up in a package everything that has to do with a particular feature. Sometimes there is a perfectly legitimate reason for this. Other times, people use them in a lazy way when it would be far more appropriate to pass parameters.
In our examples so far, ledPin is a good use of a global variable. Actually, ledPin is really a constant, because although you may change it and then recompile your sketch, you are unlikely to allow the variable to change while the sketch is actually running.
For this reason, you may prefer to use the define command we described in Chapter 3. Another feature of local variables is that their value is initialized every time the function is run. This is nowhere more true and often inconvenient than in the loop function of an Arduino sketch.
Sketch is based on the sketch , but attempts to use a local variable instead of the global variable to count the number of flashes. This sketch is broken. It will not work, because every time loop is run, the variable count will be given the value 0 again, so count will never reach 20 and the LED will just keep flashing forever. The whole reason that we made count a global in the first place was so that its value would not be reset. The only place that we use count is in the loop function, so this is where it should be placed.
Fortunately, there is a mechanism in C that gets around this conundrum. It is the keyword static. When you use the keyword static in front of a variable declaration in a function, it has the effect of initializing the variable only the first time that the function is run. Sketch shows this in operation: Return Values Computer science, as an academic discipline, has as its parents mathematics and engineering.
This heritage lingers on in many of the names associated with programming. The word function is itself a mathematical term. In mathematics, the input to the function the argument completely determines the output. We have written functions that take an input, but none that give us back a value.
If a function returns a value, then you specify a return type. The function definition now starts with int rather than void to indicate that the function will return an int to whatever calls it.
This might be a bit of code that looks like this: Any non-void function has to have a return statement in it. If you do not put one in, the compiler will tell you that it is missing. You can have more than one return in the same function. This might arise if you have an if statement with alternative actions based on some condition. Some programmers frown on this, but if your functions are small as all functions should be , then this practice will not be a problem.
The value after return can be an expression; it does not have to just be the name of a variable. So you could compress the preceding example into the following: If the expression being returned is more than just a variable name, then it should be enclosed in parentheses as in the preceding example.
Other Variable Types All our examples of variables so far have been int variables. This is by far the most commonly used variable type, but there are some others that you should be aware of. This variable type represents floating point numbers—that is, numbers that may have a decimal point in them, such as 1.
You need this variable type when whole numbers are just not precise enough. Note the following formula: But if f is an int, then the value will be truncated to The problem becomes even worse if we are not careful of the order in which we evaluate things. For instance, suppose that we did the division first, as follows: Then in normal math terms, the result would still be For circumstances like this, we can use floats.
In the following example, our temperature conversion function is rewritten to use floats: Notice how we have added. This ensures that the compiler knows to treat them as floats rather than ints. They have a value that is either true or false. In the C language, Boolean is spelled with a lowercase b, but in general use, Boolean has an uppercase initial letter, as it is named after the mathematician George Boole, who invented the Boolean logic that is crucial to computer science. You may not realize it, but you have already met Boolean values when we were looking at the if command.
You can define Boolean variables and use them as follows: Boolean values can be manipulated using Boolean operators.
So, similar to how you can perform arithmetic on numbers, you can also perform operations on Boolean values. Figure shows truth tables for the and and or operators. From the truth tables in Figure , you can see that for and, if both A and B are true, then the result will be true; otherwise, the result will be false.
On the other hand, with the or operator, if either A or B or both A and B are true, then the result will be true. The result will be false only if neither A nor B is true. In addition to and and or, there is the not operator, written as!.
Programming Arduino Getting Started with Sketches (9780071784221): Simon Monk
Figure Truth tables You can combine these operators into Boolean expressions in your if statements, as the following example illustrates: Other Data Types As you have seen, the int and occasionally the float data types are fine for most situations; however, some other numeric types can be useful under some circumstances.
In an Arduino sketch, the int type uses 16 bits binary digits. Other data types available to you are summarized in Table This table is provided mainly for reference. You will use some of these other types as you progress through the book. Table Data Types in C One thing to consider is that if data types exceed their range, then strange things happen.
So, if you have a byte variable with in it and you add 1 to it, you get 0. Until you are completely comfortable with these different data types, I would recommend sticking to int, as it works for pretty much everything. Coding Style The C compiler does not really care about how you lay out your code. For all it cares, you can write everything on a single line with semicolons between each statement.
However, well-laid-out, neat code is much easier to read and maintain than poorly laid-out code. In this sense, reading code is just like reading a book: Formatting is important. To some extent, formatting is a matter of personal taste. No one likes to think that he has bad taste, so arguments about how code should look can become personal.
The C language has a de facto standard that has evolved over the years, and this book is generally faithful to that standard. Indentation In the example sketches that you have seen, you can see that we often indent the program code from the left margin. So, for example when defining a void function, the void keyword is at the left margin, as is the opening curly brace on the next line, but then all the text within the curly braces is indented.
The amount of indentation does not really matter. Some people use two spaces, some four. You can also press Tab to indent. In this book, we use two spaces for indentation.
If you were to have an if statement inside a function definition, then once again you would add two more spaces for the lines within the curly braces of the if command, as in the following example: You might include another if inside the first if, which would add yet another level of indentation, making six spaces from the left margin.
Opening Braces There are two schools of thought as to where to put the first curly brace in a function definition, if statement, or for loop. One way is to place the curly brace on the line after the rest of the command, as we have in all the examples so far, or put it on the same line, like this: This style is most commonly used in the Java programming language, which shares much of the same syntax as C.
I prefer the first form, which seems to be the form most commonly used in the Arduino world. Thus the following example will compile without a problem: This will work, but good luck trying to read it. Where assignments are made, some people will write the following: But others will write the following: Which of these two styles you use really does not matter, but it is a good idea to be consistent.
I use the first form. Comments Comments are text that is kept in your sketch along with all the real program code, but which actually performs no programming function whatsoever. The sole purpose of comments is to be a reminder to you or others as to why the code is written as it is. A comment line may also be used to present a title. The compiler will completely ignore any text that is marked as being a comment.
We have included comments as titles at the top of many of the sketches in the book so far. There are two forms of syntax for comments: In this book, I mostly stick to the single-line comment format. Good comments help explain what is happening in a sketch or how to use the sketch.
They are useful if others are going to use your sketch, but equally useful to yourself when you are looking at a sketch that you have not worked on for a few weeks.
Some people are told in programming courses that the more comments, the better. Most seasoned programmers will tell you that well-written code requires very little in the way of comments because it is self-explanatory. You should use comments for the following reasons: Programmers often put todos in their code to remind themselves of something they need to do later. The following are not good examples of reasons you should use comments: Conclusion This has been a bit of a theoretical chapter.
You have had to absorb some new abstract concepts concerned with organizing our sketches into functions and adopting a style of programming that will save you time in the long run. In the next chapter, you can start to apply some of what you have learned and look at better ways of structuring your data and using text strings.
Now our attention is going to turn to the data that you use in your sketches. I can strongly recommend it to anyone who finds themselves bitten by the programming bug. It also captures the idea that to write a good program, you need to think about both the algorithm what you do and the structure of the data you use.
Arrays Arrays are a way of containing a list of values. The variables that you have met so far have contained only a single value, usually an int. By contrast, an array contains a list of values, and you can access any one of those values by its position in the list. C, in common with the majority of programming languages, begins its index positions at 0 rather than 1. This means that the first element is actually element zero. Morse code used to be a vital method of communication in the 19th and 20th centuries.
Because of its coding of letters as a series of long and short dots, Morse code can be sent over telegraph wires, over a radio link, and using signaling lights.As with using an output, you need to tell the Arduino in the setup function that you are going to use a pin as an input.
Because of its coding of letters as a series of long and short dots, Morse code can be sent over telegraph wires, over a radio link, and using signaling lights. In this case, the new value to be given to the delayPeriod variable is the old value of delayPeriod plus This function returns the number of bytes of data in the buffer that are waiting for you to read.
Actually, they can be a lot more powerful than this, but for now, you will use them for this purpose.
- COMPREHENSIVE CHEMISTRY TEXTBOOK PDF
- LAURA LEE GUHRKE THE CHARADE PDF
- LIGHT EMERGING PDF
- CHAIM POTOK THE CHOSEN EBOOK
- EL DILEMA DEL INNOVADOR PDF
- ULTIMATE IQ TEST BOOK
- UTA HAGEN RESPECT FOR ACTING PDF
- CCNA 4.1 GUIA COMPLETO DE ESTUDO EPUB DOWNLOAD
- THE BOOK OF ATRUS
- BUSINESS STANDARD PDF
- COGNITIVE PSYCHOLOGY A STUDENTS HANDBOOK PDF
- DENTAL ASSISTANT EBOOK