Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

C Programming for the Pc the Mac and the Arduino Microcontroller System
C Programming for the Pc the Mac and the Arduino Microcontroller System
C Programming for the Pc the Mac and the Arduino Microcontroller System
Ebook448 pages6 hours

C Programming for the Pc the Mac and the Arduino Microcontroller System

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Many systems today use the C programming language as it is available for most computers This book looks at how to produce C programs to execute on a PC or a MAC computer. It also looks at the Arduino UNO micro controller and describes how to write C programs usng the Arduino 'wired' C functions as well as using standard ANSI C with direct access to the micro controller registers of the Ardunio UNO. This can lead to improved efficiency of the programs. Most of the Hardware available in the Arduino micro controller is described, and programs provided showing how to control and use them. There is a chapter on how to create your own programs and also how to change a program created to execute on the Arduino so that it can run on a different micro controller, such as the Microchip PIC. This allows the Arduino to be used as a rapid prototype system. The book also contains many working program examples with additional workshop exercises for the reader to study.
LanguageEnglish
Release dateNov 12, 2013
ISBN9781491880517
C Programming for the Pc the Mac and the Arduino Microcontroller System
Author

Peter D Minns

The author is a Lecturer at Northumbria University in the Department of Physics and Electrical Engineering where he has taught Electronics and Computer programming for the last 33 years. He obtained his BSc(H) in Electrical & Electronics in 1978 at the then Newcastle Polythechnic. His PhD was in the investigation of Electrical Power System Distance Protection using Parallel computing which he obtained in 1992. This involved using the programming language occam and the Transputer. His main interests have been in Finite State Machine design using synchrounous and asynchronous technoques, as well as Petri Nets. In addition he has developed microcontroller based system using assembly and C/C++ programming. He has programmed PC's, MAC, and many different microcontrollers in Assembly Language, as well as using C, C++, Pascal and occam programming languages. He lives near Newcastle Upon Tyne with his wife Kathleen and enjoyes Walking, Driving and listerning to Classical and contemory music.

Related to C Programming for the Pc the Mac and the Arduino Microcontroller System

Related ebooks

Programming For You

View More

Related articles

Reviews for C Programming for the Pc the Mac and the Arduino Microcontroller System

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    C Programming for the Pc the Mac and the Arduino Microcontroller System - Peter D Minns

    Contents

    Preface

    About the Author

    Acknowledgments And Permissions

    Chapter 1: Introduction to C

    1.1 Introduction

    1.2 History of C:

    1.3 Structure of a C program:

    1.4 The first C program?

    1.5 Compiling and Building an executable C program

    1.6 Data Types in C

    1.7 Operations:

    1.8 Input and Output  in C:

    1.9 Format Strings:

    1.10 Escape_sequences:

    1.11 Summary

    Chapter 2: Conditional Constructs in C

    2.1 Introduction

    2.2 The if else clause:

    2.3 The ifelse else if arrangement:

    2.4 The switch-case statement: An alternative to if-else, but with limitations.

    2.5 Loops in C

    2.5.1 while :

    2.5.2 do while:

    2.5.3 The for statement:

    2.6 Summary

    Chapter 3: Array, Strings and Structures in C

    3.1 Introduction

    3.2 Arrays in C

    3.3 Character arrays or strings in C:

    3.4 Boundary Violation:

    3.5 Strings in C

    3.6 Pre-Defined String Functions

    3.7 The NULL Terminator

    3.8 Structures in C

    3.9 Summary

    Chapter 4: Pointers in C—the way to access memory by address

    4.1 Introduction

    4.2 Pointer use in C

    4.3 The use of (*ptr)++ and ptr++.

    4.4 Initializing Pointers:

    4.5 Pointer Offsets:

    4.6 Points to note about pointer arrays:

    4.7 Allocating memory for pointers  malloc()

    4.8 Pointer Base types:

    4.9 Casts

    4.10 Summary

    Chapter 5: Using Sub-Programs in C – The C Function

    5.1 Introduction

    5.2 C Functions:

    5.3 Pass by value.

    5.4 Pass by reference.

    5.5 Advanced Topic – Pointers to C functions:

    5.6 Using Arrays as arguments in a C function

    5.7 Summary

    Chapter 6: File Handling in C

    6.1 Introduction

    6.2 Dealing with file Errors:

    6.3 Sequential File Access:

    6.4 Summary of file access:

    Chapter 7: Embedded Systems programming in C Using Arduino ‘Wired’ Functions

    7.1 Introduction

    7.2 The Arduino system

    7.3 The Arduino™ Circuit Board

    7.4 The Arduino IDE Development Software

    7.5 Arduino Atmel microcontroller Pin out and related Arduino Pins

    7.6 Basic Structure of an Arduino Program

    7.7 Where is main()?

    7.8 Things you need to know when first connecting your Arduino to the PC or MAC

    7.9 Finding out what is happening in your program as it executes

    7.10 How does the switch work

    7.11 A more Complex Program example:  Control of a Spin Motor and Pump sytem:

    7.12 Controlling Motor speed with analogWrite()

    7.13 The Arduino Analogue to Digital Converter (ADC).

    7.14 Theory of the ADC system

    7.15 A Simple Lamp Dimmer

    7.16 Summary:

    References:

    Chapter 8: Programming the Arduino using ANSI C

    8.1 Introduction

    8.2 Access to the ATmega328P microcontroller registers

    8.3 A Look at register port DDRD

    8.4 How to set up pointers to access the ATmega328 registers

    8.5 AND Bit masking

    8.6 Turning output bits on and off

    8.7 What if you want to turn bits on and off one at a time?

    8.8 ADC and PWM signals?

    8.9 Using the ADC in the ATmeg328 microcontroller  

    8.10 How to use the ADC

    8.11 Using the PWM output of the ATmeg328P microcontroller

    8.12 Program for the PWM mode:

    8.13 The SPI Interface

    8.14 A complete SPI program for the Master Arduino:

    8.15 Testing a single Arduino SPI interface

    8.16 Universal Synchronous/Asynchronous Receiver/Transmitter (USART) interface

    8.17 The USART Protocol

    8.18 USART Registers:

    8.19 A Test program to check the working of the USART

    8.20 Making use of EEPROM on the ATmega328 microcontroller

    8.21 The EEPROM registers

    8.22 A Program example to write and read EEPROM memory

    8.23 Summary:

    Chapter 9: Interrupts in C using the Arduino

    9.1 Introduction

    9.2 What does an interrupt do:

    9.3 Using the ‘Wired’ interrupts with the Arduino IDE

    9.4 The ATmega 8 Interrupt System

    9.5 Interrupt Priority Table for the ATmega328 microcontroller:

    9.6 The registers associated with interrupt enable/disable

    9.7 The Timer/Counter2 used with interrupts to perform ADC conversions at fixed time intervals

    9.8 The complete C program follows:

    9.9 Using Global memory with interrupts

    9.10 A further note on interrupt priority

    9.11 Using the Timers to produce a Priority Scheme

    9.12 Summary

    Chapter 10: Program Development

    10.1 Introduction

    10.2 Pseudo Language

    10.3 Taking the Program Specification and using it to Develop a Program

    10.4 State Machine style program format

    10.5 Summary:

    Chapter 11: Using a Liquid Crystal display (LCD) with the Arduino

    11.1 Introduction

    11.2 LCD Data Modes

    11.3 Command and Data Modes

    11.4 The Command function:

    11.5 The Data Function:

    11.6 LCD Initialisation:

    11.7 The String LCD function:

    11.8 A complete LCD Demonstration Program

    11.9 Summary:

    Chapter 12: Programming the Microchip PIC range of microcontrollers in C

    12.1 Introduction

    12.2 A typical PIC based System

    12.3 Using_The_PIC_Timer

    12.4 Comparing the PIC Timer0 with the equivalent Atmel ATmega328

    12.5 The registers to control the PIC ADC are:

    12.6 Summary

    Chapter 13: Workshop Programs for each Chapter

    Introduction:

    Chapter 1: Introduction to C Programming Basic Output and Input with C

    Further work for Chapter 1 Incremental/decremental, bitwise statements and Priority of C assignment calculations in C

    Chapter 2: C Constructs if/else, switch case, while,  do while, and for loop.

    Chapter 2: Developing your own C programs.

    Chapter 3: Using Arrays and Strings in a C program

    Chapter 4: Pointers in C

    Chapter 5: C Functions

    Chapter 6: Saving data to a file, and loading data from a file in C

    Chapter7: An Arduino Program:

    Chapter: 8 An Arduino Program using ANSI C.

    Chapter 9: An Arduino program using the Interrupts

    Chapter 10: Development of a complete Arduino program using ANSI C.

    Chapter 11 An Arduino program using the LCD Display.

    Chapter 12: An example program using the PIC.

    Appendix A: Number Systems

    Appendix B: Arduino ‘Wired’ Function Summary: With permission of Arduino Team www.arduino.cc.

    Appendix C: Some Register Addresses for the ATmega328P

    Appendix D: The Arduino Schematic Circuit Diagram:

    Appendix E: The Quincy C/C++ Programming IDE

    Appendix F: Tutorial on using XCODE for command line Programs  

    Parallel programming on the Arduino

    Preface

    This book has been developed as a first course in C programming. It makes use of existing C development tools that are freely available on the web and allow for the development of C programs that can be executed on a Personal Computer (PC) or Apple MAC Computer (MAC).   In addition later chapters cover the use of the Arduino Embedded microcontroller board that can be programmed from a PC or MAC computer.

    The first 6 chapters cover the main aspects of the language such as basic input and output, variable types, arrays and strings, pointers and file handling.

    For programming in C on a PC there are a number of Free C programming platforms.  A simple to learn and use one is the Quincy 2005 C/C++ programming Integrated Development Environment (IDE).  Despite its name this is a serious C programming IDE that makes use of the MinGW gcc  compiler and gdb debug tools.  Quincy was originally developed by Al Stevens, a C/C++ program developer and contributer to the Dr DOBBS magazine. Quincy is now under development at coder@codecutter.net.   For the MAC computer there is XCODE from Apple Computers (also Free).

    This is a very good C/C++ development IDE.  The book contains an appendix Tutorial on each.

    Chapters 7 to 11 are about using C to program the Arduino.  The Arduino is an ‘Open Source’ microcontroller based system designed to allow both novice and professionals to develop ‘Embedded’ computer systems.  This is cheap, simple to use and has a wide following.  The Arduino is introduced and the reader shown how quite complex programs can be developed using the Arduino IDE.  This is used to develop a number of C programs that make use of the Arduino ‘wired’ C functions.  These ‘wired’ C functions have been designed to make it easy to develop quite complex programs that would otherwise require much more understanding of the microcontroller underling hardware.  

    In a later chapter the idea of ANSI C (American National Standard Institute C) is introduced and used with the Arduino IDE to develop C programs that can directly access the hardware registers of the Arduino.  This makes it possible to ‘fine tune’ the Arduino microcontroller so that the underling hardware of the microcontroller can be used more efficiently.

    Most microcontrollers come with integrated hardware peripherals such as Analogue to Digital Converters (ADC) to convert real time analogue signals (Temperature for example) into digital form so they can be used in a C program, Timers units to keep accurate time and count external events, Serial hardware to allow information to be passed between the Arduino and a PC/MAC computer, and Long term data storage devices.  These are all investigated and ANSI C programs developed to control all these peripheral devices.  Indeed, these programs can be used to test a particular Arduino board for correct working, as well as being used for further development.  All the programs have been tested and work.

    Chapter 11 covers the use of a Liquid Crystal Display (LCD) with the Arduino as well as some ideas to overcome limited port bits on an Arduino UNO board.

    Finally the idea of using the Arduino to develop an application, then translate the C program code to execute on a different microcontroller is discussed.  The PIC microcontroller is introduced and program translation from an Arduino to a PIC microcontroller are looked into, both from the hardware and software point of view.

    Due to the ‘Open Source’ aspect of the Arduino  it is possible to develop an application to execute on the Arduino and develop your own hardware version of the Arduino board.  However you must acknowledge that your own version of the Arduino board is based on the Arduino.  The software to download C programs to the Arduino microcontroller (ATmega328) is available from www.arduino.cc so it is possible to buy ATmega328 microcontrollers and program them from the Arduino IDE.  In this way a new product can be developed that has particular requirements, for example adequate electrical interference protection.  Recent publicity seems to suggest that some organizations are starting to consider this idea as a possible way of getting new designs to market in the shortest possible time, by using the Arduino as a prototyping platform.

    One exciting development is the new Arduino DUE, based on an ARM 32 bit microcontroller.  This can be used to develop C programs that can include Digital Signal Processing (DSP) capability.  While this book does not cover the Arduino DUE, the ideas in the book will prepare the reader who has some experience of DSP work to move in that direction.  This opens up applications containing Digital Signal Processing, Artificial Neural Networks, and Genetic Algorithms to name a few.

    It is recommended that the reader buy an arduino board so that he/she can run the programs in the embedded chapters 7 onwards. These are very cheap (approx £23) and very robust.  The PIC programs can be executed in MPLABX with it’s simulator and cheap PIC programmers can be obtained to allow these to execute on actual PIC microcontrollers.  There is also a number of Arduino Simulators becoming available.  Try www.virtronics.com.au

    for a simple to use simulator.

    Description of the chapters in the book:

    Chapter 1:  This introduces the reader to the C programming language basics and provides a basis for the following chapters of the book.

    Chapter 2:  Introduces some of the conditional constructs of the C language with example program fragments showing their use.

    Chapter 3:  Arrays and strings are introduced with examples of use.

    Chapter 4:  Pointers are a way to allow the programmer to access memory and are much used else were in the book (chapter 8).  It contains examples of where they can be used.

    Chapter 5:  Sub-programs or C functions are commonly used in C programs and can make programs look less complex by careful use in a program.  The chapter looks at the different ways in which they can be use.

    Chapter 6:  Programs designed to execute on a PC or MAC computer often need to store date produced by the program into a file on a Disk media (Hard Drive, USB drives).  The chapter looks at the way that this is achieved.

    The following chapters make use of the Arduino Embedded microcontroller:

    Chapter 7:  The Arduino is introduced and shows how its IDE can be used with the pre-defined ‘wired’ C functions to control input and output from/to the real world.  The chapter also looks at how to write C programs using these ‘wired’ functions to obtain analogue signals from the outside world, and control light dimmers, as well as sending and receiving serial data.

    Chapter 8:  In this chapter the reader learns how to produce ANSI ‘standard’ C programs.  This allows the user to be able to ‘fine tune’ the  program in order to obtain the best performance from the Arduino.  This leads on to allow a program written to execute on the Arduino to be altered so that it can execute on a different microcontroller.  In this book the Microchip PIC is considered in Chapter 12 however other microcontrollers, such as ARM processosrs could be possible targets.

    Chapter 9:  The Arduino supports a range of interrupts to allow programs to deal with real time events.  The interrupt mechanism is described and examples of how to use interrupt are covered, with program examples using both the ‘wired’ C functions and ANSI C with direct access to the ATmega registers that control interrupts.

    Chapter10: Program Development.  This short chapter describes two methods that can be used to develop programs that help to break down the programs into manageable parts.

    Chapter 11 Using a generic Liquid Crystal Display (LCD) with the Arduino.  Describes the connection details for interfacing an LCD to the Arduino as well as showing how the LCD can be controller from the Arduino.  The chapter also describes how the pin limitations of the Adruino UNO can be expanded to accommodate additional I.O. capability.

    Chapter 12:  In this chapter the generic basics of the Microchip PIC are described and some examples given showing how former programs developed to execute on the Arduino can be changed to execute on a PIC microcontroller.  There are limitations to this, and these are described.

    Chapter 13 : Workshops for each chapter: This section of the book is a collection of programs aimed to help the reader to understand C programs.  Some of the programs can be developed further by the reader and used in his/her own designs.  All the programs have been tested and work on an Arduino UNO.  The reader should try these programs after reading each chapter.

    There are a number of useful Appendices:

    Appendix A: Binary and Hexadecimal Number Systems.

    Appendix B: Arduino ‘wired’ Function summary.

    Appendix C: Some useful Atmel ATMega328 microcontroller registers and their addresses.

    Appendix D: The Arduino Schematic Circuit Diagram.  This is an ‘Open Architecture’ that  is common to all the Arduino range of boards.

    Appendix E: A tutorial on how to use the Quincy C/C++ Programming IDE.

    Appendix F: A tutorial on how to use the XCODE C/C++ Programming IDE in Command line mode.

    Dr Peter D Minns BSc(h)., Ph.D.,  CENG MIET.

    Northumbria University

    Dept. Physics and Electrical Engineering

    Newcastle upon Tyne

    NE1 8ST.

    About the Author

    Peter Minns is a Senior Lecturer at Northumbria University in the Department of Physics and Electrical Engineering where he has worked for the last 33 years.  Prior to this he worked as a Design and Development Engineer, first at Plessey Telecommunications Ltd, then at Reyrolle Protection Ltd.

    He obtained a BSc(h) degree in Electrical & Electronic Engineering at the then Newcastle Polytechnic in 1978.  In 1992 he obtained a PhD.  This was an investigation into Development of a Power System Distance Protection Fault Detector using Parallel Computing.  This involved using the Programming Language Occam and the Transputer¹.

    Over the years he has taught Electrical and Electronic Engineering to Engineering undergraduates as well as post graduate students.  His main interests are in Finite State Machine design using Synchronous, Asynchronous and Petri Nets, as well as Microcontroller based Embedded system design using a wide range of microprocessors and microcontrollers.  Dr Minns has worked with Basic, Fortran, Pascal, C, C++, Java, and occam as well as Assembly Language programming  on the PC, the PIC, and a number of other microprocessors and micro controllers.

    He lives near Newcastle upon Tyne with his Wife Kathleen and enjoys Walking, Driving and listening to Classical and contempory music and reading.

    Acknowledgments And Permissions

    The Author would like to thank all those who have helped in the development of this book, including the many students who have provided feedback on the undergraduate studies in C programming over the years.

    Those who have helped in the proof reading of the book.

    The Editors with there kind suggestions

    I wish to acknowledge the Arduino™

    Team: Massimo Banzi, David Mettis, Tom Igoe, Gainluca Martino and David Cuetielles. In addtion Nidha Syed, for advice and permission to use information from the Arduino web site. Arduino is a trademark—see trademark@arduino.cc for more information. Also thanks to ‘Crossroads’, and Andrew Craig on the Arduino Forum site.

    The people at Apple for their work on the Xcode C/C++ development IDE, a great program to work with.  The Appendix F is compiled from experience using the Xcode IDE.

    The people at ATMEL for their kind permission to use data sheet content and diagrams for the ATmega328 microcontroller used in the Arduino UNO used in this book.  Specifically the Tables in chapter 8 to 11 relate to ATMEL registers from the Data sheet of the ATmega328 with permission from ATMEL.  Also Figure 12.5, and Figure 12.6 are also from the ATMEL ATmega328 Data Sheets.

    Microchip Technology for their free MPLAB software and broad range of PIC microcontrollers.

    Al Stevens for his original work on the Quincy C/C++ IDE.  The appendix E is compiled from experience using the Quincy IDE.

    Crystalfonz America Incorporated for the LCD information (simplified) in Chapter 11.

    Amanda Ghassaei for her three Timer interrupt program in chapter 9.

    All those people who have contributed programs for the Arduino system beyond the Arduino Team.

    Fritzing.org software for the development of Arduino schematic diagrams and Printed Circuit Boards (PCB).They have a numbers of Arduino shield PCB for development of’ the users prototypes.  They also offer a PCB manufacturing service for a price.

    A lot of the programs using the Arduino made use of the E Block system of modules manufactured by Matrix Multimedia Ltd of Halifax West Yorkshire England.  The E Block system consists of LED modules, Switch modules, LCD modules and a host of other sensor modules. Try www.matrixmultimedia.com Many thanks to John Dobson, the MD of Matrix Multimedia.

    And lastly, but by no means least my wife Kathleen for her understanding and patience during the many hours I spent working on this book.

    Chapter 1: Introduction to C

    1.1 Introduction

    C is a general purpose, structured programming language.  Its instructions consist of terms that resemble algebraic expressions, augmented by certain English keywords such as if, else, for, do, and while.  In this respect C resembles other high level languages such as Pascal, and Fortran.  C also, however, contains certain additional features that allow it to be used at lower levels, closer to the machine language of the computer.

    C has a relatively small instruction set, 32 keywords in the most common versions of the language, but these can be argument with extensive library functions that can be built upon by the programmer.

    One of the attractive features of the C language is that it can compile to produce very compact executable code. This allows it to be used to program microcontrollers, which typically have small amounts of memory.

    C compilers are commonly available for a large number of computers and microcontrollers.  This has lead to the widespread use of the language throughout the computing and engineering community.

    1.2 History of C:

    C was first developed by Dennis Ritchie and Brian Kerighan at Bell Telephone Laboratories Inc (now AT&T Bell  Laboratories) in the 1970s.  C was largely confined to Bell Labs until1978, when Brian Kerighan and  Dennis Ritchie published a definitive description of the language, The C Programming Language, Prentice-Hall, 1978.  This version is now referred to as K&R C.

    Over the years, a number of commercial versions of C have evolved, each with their own enhancements, which have made the language less than portable.  In an attempt to create a standard, the American National Standards Institute [ANSI] have produced a standard that most commercial organizations now follow, so C is back on track as a portable language between computers and microcontrollers.  Versions of C that conform to the ANSI standard are known as ANSI C.  But beware, most C compilers that are ANSI compatible also have special features added, that are not ANSI compatible.  To produce ANSI compatible code, you should not use these special features.

    Before starting to look at C programs it is assumed that the reader is familiar with both the Binary and Hexdecimal number systems.  To help readers that have not used these number systems for some time, or are unfamiliar with such number systems, Appendix A provides a brief summary.

    1.3 Structure of a C program:

    Every C program consists of

    One or more functions, one of which must be called main.  Additional function definitions may follow main.

    Each function must contain:

    •      A function heading, which consists of the function name, followed by an optional list of arguments enclosed in parentheses that may be passed into the function.

    •      A list of argument declarations, if arguments are included in the heading.

    •      A compound statement, which comprises the remainder of the function.

    Each compound statement is enclosed within a pair of braces, i.e., { and }.

    The braces may contain combinations of elementary statements, called expression statements, and other compound statements.  In this way, compound statements may be nested within one another.  

    Each expression statement must end with a semicolon, i.e., ;.

    Comments, or remarks, may appear anywhere in the program, as long as they are placed within the delimiters /* and */.

    i.e.,  /* this is a comment */

    // This is a C++ style comment line.  It only extends to the end of the current line.

    Some recent C compilers can support the C++ comment line which uses // at the beginning of a line that is to be a comment.  For example, the Ardunio IDE, xcode, netbean and MPLABX support both /*  */ and //.  However if a C program is selected (as apposed to a C++ program) in Quincy the C program will not support the // comment style.

    It is advisable not to use the C++ style of comment in C programs as it will make them no longer portable.  However some of the C programs in this book do make use of the // comment form.

    Comments can play an important part in the documentation of a program.

    Since all C programs must have their variables declared prior to using them (in common with all structured programming languages), frequently used variables, and references to pre-declared C functions that may be used within a program, can be contained within a separate header file.

    Header files can then be combined into a program by calling them with an #include statement.  A common header file that should be included in most C programs is the one called stdio.h (all header files have the file extension

    Enjoying the preview?
    Page 1 of 1