Programming arduino getting started with sketches pdf download






















International Consulting Limited online. This book was released on 05 March with total page pages. You will learn how to configure hardware and software, develop your own sketches, work with built-in. An updated guide to programming your own Raspberry Pi projects Learn to create inventive programs and fun games on your powerful Raspberry Pi—with no programming experience required. This practical TAB book has been revised to fully cover the new Raspberry Pi 2, including upgrades to the Raspbian operating system.

Popular All Time. If you want to make the most of the book and try out some of the experiments, then it is useful to have the following on hand:. Both are readily available for a few dollars from a hobby electronics shop such as Radio Shack. You will of course also need an Arduino Uno board. If you want to go a step further and experiment with Ethernet and the liquid crystal display LCD shield, then you will need to buy shields that are available from online stores.

See Chapters 9 and 10 for details. This book is structured to get you started in a really simple way and gradually build on what you have learned. You may, however, find yourself skipping or skimming some of the early chapters as you find the right level to enter the book. These sketches are demonstrated throughout with runnable code examples. Many Arduino users stick to C character arrays instead.

This library is beautifully easy to use, and if you have used strings in Java, you will be very at home with the Arduino String Object library. Other String Functions Table summarizes some of the more useful things that you can do with String functions.

Instead you must write data to a microSD card. The following example shows how to write a single byte of EEPROM, in this case, from the setup function: The first argument of the write function is the address in the EEPROM to which the byte should be written, and the second argument is the value to be written to that address.

EEPROM Example The following example shows a typical scenario where a value is written during the normal running of a program and then read back during startup.

The application is a door lock pro- ject using the Serial Monitor to enter codes and change the secret code. If the code had to be reset every time the Arduino started, then there would be no point in allowing the user to change the code. During the discussion that follows, certain areas of the sketch will be highlighted.

You may find it useful to run the sketch to get a feel for how it works. It does not require that you connect any extra hardware to the Arduino. The setup function contains a call to the function initializeCode. So if this is the first time that the sketch has been run, then there is no way to know what value might be left in EEPROM by a previous sketch.

You could be left with a lock, that is, a code whose value you do not know. One way around this is to create a separate sketch specifically to set the default code. This sketch would need to be installed on the Arduino before the main sketch. The down- side of this approach is there is a slim chance that the EEPROM location used to store this flag already contains it.

If so, this solution would be unacceptable if you were defining a commercial product, but here you can elect to take that risk. The stored code is only read when the Arduino resets. The Arduino utility func- tions highByte and lowByte are used to separate the parts of the int code. In the example shown in the previous section, you got around this restriction by splitting the int into two bytes in order to save and retrieve it in EEPROM.

This gives you more options, including reading and writing a Word 16 bits and blocks of memory of arbitrary size. Note that this occupies two bytes, so if you want to save another int, you specify an address of 12, not These functions allow data structures of any length space permitting to be stored and retrieved.

This is calculated here as the length of the string plus one to include the null character at the end of the string. The following sketch reads the string back in again and displays it on the Serial Mon- itor along with the string length: To read the string, a character array of size 50 is created. Because the message has a null on the end, when it is printed by the Serial Monitor, only the text expected not the full 50 characters is displayed.

It is also only guaranteed to be reliable for , write cycles before it starts suffering from amnesia. For this reason, you need to be careful not to write to it every time around a loop, for example. Using Flash An Arduino has a lot more flash memory than it does any other type of memory. This makes it a tempting place to store data, especially as flash memory does not forget when it loses power.

Having said all that, it is quite easy and safe to use flash to hold constant data that are not going to change during the running of a sketch. The easiest way to create flash-stored string constants is to use the F function that I described in an earlier section.

The syntax is repeated here as a reminder: This form only works when you are using the string constant directly in a message like this. You cannot, for example, assign the result to a char pointer. The data, however, must be constant data that will not change during the running of the sketch.

The following example illustrates how you can create an array of ints that will be stored in flash memory: By putting the PROGMEM directive in front of the array declaration, you ensure that it is only stored in flash memory. Figure Results of the Cardinfo example sketch Writing to the SD card is made easy, as the code snippet here shows: Summary In this chapter, you have learned about all aspects of memory and data storage within Ar- duino. In the next chapters, you will explore Arduino programming for various types of serial interface, starting with the I2C bus.

All the Arduino boards have at least one I2C interface to which you can attach a wide range of peripherals. Some examples are shown in Figure Figure A collection of I2C devices The three devices on the top row of Figure are all display modules from Adafruit.

You can find these modules on eBay and elsewhere for a few dollars. In the center is a real-time clock RTC module, including an I2C chip and crystal oscillator that maintains a fairly accurate time and date. Once you have set the date and time over I2C, you can read the time and date back over I2C whenever you need it. This module also includes a long-life lithium button cell that allows it to keep time, even when the module has no external power.

Figure shows a possible arrangement of two I2C components attached to an Arduino, a real-time clock RTC , and a display module. The outputs are also open-collector, which means that they require a pull-up resistor.

These resistors should be 4. If some devices on the bus use different voltages, you need to use a level converter. The various Arduino boards allocate different pins to I2C. Figure shows the timing diagram for this signal. When transmission is complete, the clock can stop and the SDA pin is returned to tri-state. The Wire Library You could, of course, generate these pulses yourself by bit banging—that is, turning digital outputs on and off in your code. To make life easier for us, however, the Arduino software includes a library called Wire that handles all the timing complexity, so we can just send and receive bytes of data.

If the Arduino were being initialized as a slave, then you would need to specify an address, 0 to , as its parameter to uniquely identify it on the I2C bus. Master Sending Data To send data to an I2C device, start by using the beginTransmission function and specify- ing the address of the I2C device on the bus that you wish to send data to: You can either send data to an I2C device one byte at a time, or you can send a char array, as shown in these two examples: Finally, at the end of the transmission, use the endTransmission function: Master Receiving Data For a master to receive data from a slave, it must first request the number of bytes it re- quires using the requestFrom function: The first argument to this function is the address of the slave from which the master wants to receive data, and the second argument is the number of bytes that the master is expecting to receive back.

The slave can return less than this, so the available function is used to determine both if data has arrived and the number of bytes received. I2C Examples Any I2C device should have an accompanying datasheet that specifies the messages that it expects to use. Sometimes you will need to use that datasheet to build your own messages to send from the Arduino and to interpret the messages that come back. Even if no fully fledged library is available, you can often find useful code snippets for the device on the Internet.

It deals with raw messages to interface an Arduino with a TEA module. These modules are available at a very low cost on the Internet and are easy to connect to an Arduino to use as an Arduino-controlled FM receiv- er. The tricky part is that the connections on these devices are set at an extremely fine pitch, so you generally need to make or buy some kind of adapter that allows you to use them with breadboard or jumper wires. Figure shows how this module can be wired to an Arduino. The datasheet specifies that the TEA expects to receive messages of five bytes.

The example code shown next is a fully working example that will tune the frequency once at startup. In practice, you need some other mechanism, such as push buttons and an LCD display, to set the frequency. This function takes a float as a parameter. This value is the frequency in MHz.

To convert a float frequency in MHz into a two-byte value that can be sent as part of the five-byte message, you need to do some math. For more information on this kind of bit manipulation, see Chapter 9. The remainder of the setFrequency function begins transmission of the I2C message to the slave with address 0x60, which is fixed for the TEA chip.

It then sends each of the 5 bytes, starting with the 2 frequency bytes. Arduino-to-Arduino Communication This second example uses two Arduinos, one acting as the I2C master and one as the slave. The master will send messages to the slave, which will, in turn, echo them to the Serial Monitor, so we can see that the communication is working. The connections for this setup are shown in Figure Both sketches are provided as examples in the Wire library. This message is then sent to the I2C slave device with the ID of 4, as specified in beginTransmission.

This parameter specifies the I2C address of the slave, which is 4. It must match the address that the master sends the message to. The sketch for the slave differs from that of the master because it uses interrupts to re- spond to the master when a message comes in. This is accomplished using the onReceive function, which is invoked like an interrupt service routine see Chapter 3. Place this in setup so the user-written function receiveEvent is invoked whenever a message comes in. The receiveEvent function is expected to have a single parameter, which indicates the number of bytes ready to be read.

In this case, this number is ignored. The while loop first reads all the available characters and echoes each character in turn. It then reads the single byte number on the end of the message and prints that to the Serial Monitor. Using println rather than write ensures that the value of the byte is displayed rather than its character value Figure Of these, the range of backpack boards for matrix and seven-segment LED displays from Adafruit are typical.

You can find out more about these colorful and interesting devices here: www. This chip also has a well-used and reliable Arduino library to simplify it and hide the actual I2C messages.

The fragments of code are, again, taken from the examples supplied with the library. If you want to see the actual I2C code, then you can open the library files and look at how they work. For example, you can find the function definition for now in RTClib. BCD splits a byte into two 4-bit nibbles yes, really.

Each nibble represents one digit of a two-digit decimal number. So the number 37 is represented in a BCD byte as The first four bits being decimal 3 and the second four bits 7. Summary In this chapter, you have learned about I2C and how to use it with an Arduino to commu- nicate with peripherals and other Arduinos. In the next chapter, we examine another type of serial bus interface that is used to com- municate with peripherals.

This interface, called 1-wire, is not as widely used as I2C, but is used in the popular DS18B20 temperature sensor. The 1-Wire stand- ard created by Dallas Semiconductor has taken this to its logical extreme by reducing the data lines used to just one. The bus is slower than I2C, and it has the interesting feature of parasitic power, which allows remote devices to be connected to a microcontroller with just two wires, GND ground , and combined power and data wire.

The 1-Wire bus standard has a much smaller range of potential devices than I2C, most manufactured by Dallas Semiconductor or Maxim. Figure Connecting a 1-Wire device to an Arduino 1-Wire is a bus, rather than a point-to-point connection, and you can chain together up to devices using the arrangement shown in Figure The microcontroller is the master and the peripherals are the slaves. This address is 64 bits in length, allowing for roughly 1.

The protocol is similar to I2C in that the bus line is switched from being an input to being an output by the master to allow two-way communication. However, rather than have separate clock and data signals, 1-Wire has just a single data line and uses long and short pulses to signify 1s and 0s. The stream of 1 and 0 pulses then follow this. You can combine these into a single command, and you can use any Arduino pin for the bus; simply supply the pin number as the parameter: In the example, the bus will be initialized on pin D10 of the Arduino.

Scanning the Bus Because each slave device on the bus is allocated a unique ID during manufacturing, you need a way to find the devices on the network.

So the master Arduino can essentially produce a list of the devices on the bus. Table lists some of the most common family codes for 1-Wire. Table Family Codes for 1-Wire Addresses The OneWire library has a search function that you can use to find all the slave devices on the bus. Figure Listing 1-Wire slave devices The search function requires an array of 8 bytes in which to put the next address that it finds. If no more devices are to be found, it will return 0.

This allows the while loop in the previous example to keep iterating until all the addresses have been displayed. The last byte of the address is actually a cyclic redundancy check CRC that ensures the integrity of the address.

Figure shows a DS18B20 chip connected to an Arduino. Note how the chip it- self is just a three pin transistor-like chip. Figure A DS18B20s connected to an Arduino The Dallas Semiconductor temperature sensor has its own library that makes request- ing the temperature and decoding the result easier. This example displays the temperature in Celsius from a single temperature sensor in the Serial Monitor window Figure Figure Displaying the temperature using a DS18B20 This example uses just one temperature sensor, but you can easily extend it to use mul- tiple sensors.

The DallasTemperature library wraps the OneWire address discovery process in the getAddress function, the second parameter of which is the index position of the sensor. To add a second sensor, you need to add a new variable for its address and then set that address using getAddress. Summary In this chapter, you learned a little about the 1-Wire bus and how to use it with the popular DS18B20 temperature sensor.

In the next chapter, we look at yet another kind of serial data interface called SPI. It is fast but uses four pins compared with the two that I2C uses. One Arduino pin must be used for SS for each peripheral on the bus.

This setup effectively addresses the right peripheral on the bus by turning all the other peripherals off. A wide range of SPI devices are available, including many of the same type of devices available for I2C. Bit Manipulation SPI interfacing tends to involve a lot of bit manipulation to get data on and off the bus. Binary and Hex You first met the concept of bits and bytes back in Chapter 4 see Figure When you are manipulating bits in a byte or word two bytes , you can use their decimal values, but converting between binary and decimal is not that easy to do in your head.

The leading zeros are optional, but providing them serves as a handy reminder that 8 bits are available. The second example uses an int to hold 16 bits. The qualifier unsigned is placed in front of int to indicate that the variable should only be used to represent positive numbers. But including the word unsigned is good practice.

When you get to 16 bits, the binary representation starts to look a bit long and unwieldy. For this reason, people often use a notation called hexadecimal, or more commonly just hex, to represent longer binary num- bers.

Hex is number base 16, which means you have the usual digits 0 to 9 but also the letters A to F that represent the decimal values 10 to That way, each four bits of a number can be represented in a single digit. Table shows the decimal, binary, and hexadecimal representations of the numbers 0 to 15 decimal.

Masking Bits A common problem when you receive data from a peripheral using any kind of connection is that the data arrives packed into bytes and not all of the bytes are needed.

Peripheral de- signers often fit as much information as they can into as few bits as possible, speeding up communication, but often at the expense of making the devices more difficult to program.

Figure shows how a byte containing multiple data can be masked to produce a number from the least significant three bits of the byte. In binary written in the normal mathematical way, the most significant bit is the leftmost bit and the least significant bit is the rightmost. After all, the rightmost is only worth 1 or 0.

The least significant bit is also sometimes referred to as bit 0, bit 1 being the next most significant bit and so on. In the example shown in Figure , the data byte has some values at the most signific- ant end that we are not interested in and only three bits at the least significant end that we want to extract as a number. Shifting Bits Another thing you will find with received data is that having masked the bits you want, those bits are not all at the least significant end of the byte.

For example, if the value of interest in the data used in Figure was between bits 5 and 3 see Figure , you need to first mask the bits of interest, as you did in the previous example, and then sift the bits three places to the right.

This may result in some bits being shifted off the end of the byte. You can accomplish this by first shifting the bits of one byte the most significant byte to one end of the int and then adding in the second byte. Figure illustrates this process. Table lists the pin assignments on the most common Arduino boards. They are used to enable a par- ticular slave just before data transmission and then disable it after communication is com- plete.

No pull-up resistors are required on any of the lines. This is for programming the USB interface. The SPI Protocol The SPI protocol is, at first sight, confusing because data is transmitted and received at the same time by both the master and the currently selected slave. Because the master sets the transmission frequency, make sure the rate is not too fast for the slave device.

It only supports Arduino-as-master scenarios. The library also only directly supports transmission of whole bytes. Unless you are using a Due, you also need to set up digital outputs for each of the SS pins to the slave devices. These outputs can be any Arduino pins. Having set them to be outputs, you need to set them to HIGH immediately because the slave select logic is inver- ted, so a LOW means the slave is selected.

The Due has extended the SPI library so you can specify one pin to be used for slave selecting, and then the library automatically sets this LOW before transmission and then HIGH after transmission is complete.

You can use this feature simply by specifying the pin to use as the only argument to SPI. The disadvantage of doing it this way, however, is that it breaks compatibility with other Arduino boards. In the examples in this chapter, all the slave select pins are controlled manually and are, therefore, suitable for all Arduino boards.

A number of utility functions allow you to configure the SPI connection. However, the defaults will normally work, so you only need to change these settings if the datasheet for the slave device leads you to believe they might need changing.

These functions are sum- marized in Table Table Configuration Functions The combined data send and receive happens in the transfer function. This function transfers a byte of data and returns the byte of data that it received during the send opera- tion.

The chip is low cost and easy to wire. Figure shows the chip wired to the Arduino using breadboard and jumper wires. The variable resistor pot is used to vary the voltage to analog input 0 between 0 and 5V. Although Serial. The chip is capable of two ADC operation modes. One mode is to compare two analog channels, and the second mode which this example uses returns the single-ended reading from the channel specified, just like an Arduino analog input.

In order for the MCP to recognize these 4 bits, we have to split them across 2 bytes. The other 2 bits in this byte are the most significant 2 bits of the analog channel number. The remaining bit of this number is in the second configuration byte as its most significant bit.

After that, the first configuration byte is sent: The analog data will not start arriving until the second configuration byte is sent. Finally, the actual bit analog reading value is calculated using the following line: Each of the 2 bytes has 5 of the 10 bytes of data in it. The first byte contains these bits in its least significant 5 bits.

All the bits apart from those 5 are masked out and shifted five positions up in the bit int. The lower byte contains the remainder of the reading in its most significant five digits. These must be masked and shifted right by three bit positions before they can also be added into the bit int.

To test this, open the Serial Monitor. You should see some data appear. The first two binary numbers are the 2 bytes from the MCP and the final decimal number is the analog reading between 0 and Figure Viewing the messages in binary Summary Interfacing with SPI when no library is available is by no means easy.

You will sometimes need to perform a little trial and error to get things going. As with any type of debugging, always start by gathering evidence and examining the data that you are receiving. You will slowly get a picture of what is happening and then be able to tailor your code to produce the desired results. This standard is a point-to-point interface rather than a bus, but nonetheless a much-used and handy mechanism for sending and receiving data.

You use it when you program your Arduino board, and you also use it to communicate with the Serial Monitor to send data back and forth to the Arduino from your computer. Serial communication, of this kind, is not a bus. It is point-to-point communication. Only two devices are involved—generally an Arduino and a peripheral.

This also includes devices origin- ally intended to be connected to the serial port of a PC. Serial Hardware Figure shows the serial hardware for the Arduino Uno. This part of the microcontroller is responsible for sending and receiving bytes of data from and to the microcontroller.

The Uno has a separate processor that acts as a USB-to-serial interface. As well as electrical differences in the serial signal, the USB bus also has a much more complicated protocol than serial and so it does a fair bit of work behind the scenes so it appears the serial port of the ATmega is communicating directly with your computer. This gives you the advantage of connecting the Tx and Rx to other electronics and still being able to program the Arduino and send data to the Serial Monitor.

Other Arduino boards have differing quantities and arrangements of serial ports. These are summarized in Table Note that the Due is alone among Arduino boards in oper- ating its serial ports at 3. For communicating over longer distances, an electrical standard called RS has been defined. Until perhaps the last decade, you could com- monly find PCs with RS serial ports.

The RS standard changes the signal levels, making them more suitable for traveling a greater distance than with TTL Serial.

Serial Protocol The Serial protocol and much of the terminology around it dates back to the early days of computer networking. Both the sender and receiver have to agree on a speed at which to exchange data. This speed, called the baud rate, is set at both ends before communication begins. The baud rate is the number of signal transitions per second, which would be the same as the number of bits per second, were it not for the fact that a byte of data may have start, end, and parity bits.

Baud rates are selected from a number of standard baud rates. The most commonly used baud rate for the Arduino is probably , which tends to be the default baud rate. There is no particularly good reason for this as the Arduino com- municates reliably at baud.

For projects that require really fast data transfer, this rate will be used. Another common rate is baud. Some peripherals such as Bluetooth serial adaptors and GPS hardware use this rate. Another rather confusing Serial connection parameter that you might encounter is a string of characters like this: 8N1.

This string means 8 bits per packet, No parity checking, and 1 stop bit. Although other combinations are possible, any device that you are likely to encounter will be 8N1. The Serial Commands The Serial commands are not contained in a library, so you do not need an include com- mand in your sketch. Start serial communication using the command Serial. If you are using a board that has more than one serial port, and if you are using the de- fault port port 0 , you just use the Serial.

If you are using one of the other ports, however, then put the number after the word Serial. For example, to start commu- nication on serial port 3 on an Arduino Due, you would write the following in your sketch: Once Serial. Your loop function can check for incoming bytes of data using the Serial.

This function returns the number of bytes available for reading. If no bytes are available, then it returns 0. The readBytes function reads available bytes into a buffer within the sketch, as op- posed to the buffer used by the UART.



0コメント

  • 1000 / 1000