C++ Programming Reference Jump Starter - Renishaw ...

60
RenBED C Programming Jump Starter Page 1 C++ Programming Reference Jump Starter Written for RenBED By Jon Fuge [email protected] December 3 2013 © 2013 Renishaw plc

Transcript of C++ Programming Reference Jump Starter - Renishaw ...

RenBED C Programming Jump Starter Page 1

C++ Programming Reference Jump

Starter

Written for RenBED

By Jon Fuge [email protected] December 3 2013 © 2013 Renishaw plc

RenBED C Programming Jump Starter Page 2

Contents What is RenBed? 3 Getting Started 4 Punctuators and C++ symbols 5 Enumeration 5 Keywords 5 Constants, variables, arrays, auto, static, register, volatile and sizeof 6 Constants, variables, array and sizeof example 7 Enumeration example 7 Relational Operators 8 Assignment Operator 8 Logical operators 9 Octal, Decimal & Hexadecimal 9 Arithmetic Operators 10 Bitwise Operators 11 Digital Input And Output 12 Setting up a digital input. 13 DigitalIn PinName(PortName); 13 PinName.mode(PinMode); 13 PinName 13 Setting up a digital output. 13 DigitalOut PinName(PortName); 13 PinName 13 Driving the 7 segment displays 14 Driving the 7 segment displays example 15 printf 16 printf examples 18 scanf 19 Communicating with USB 20 USB Serial 21 USB Mouse 22 USB Keyboard 23 USB Mouse Keyboard 24 USB HID 25 USB Audio 26 USB MIDI 27 USB MSD 28 Pointers 29 typedef 29 Structure 30 #define 30 union 31 Bit Fields 32 for, do, while, break and continue 34 if, else, switch, case, default and break 35 asm 36 goto 36 UserNumber.h: 38 UserNumber.cpp: 39 main.cpp: 39 Appendix 1 How do you get an MBED account? 40 Appendix 2 Importing a Project 43 Appendix 3 Create a new project 46 Appendix 4 Adding a file 48 Appendix 5 Add an existing library to your program 50 Appendix 6 Select The Target Device 52 Appendix 7 Compile your program 54 Appendix 8 Programming RenBED 56 From Google Chrome browser... 58 From Internet Explorer browser... 59

RenBED C Programming Jump Starter Page 3

What is RenBed? RenBED is a microcontroller development board for quick prototyping of software and electronic projects. It is based ona NXP LPC11U24 microcontroller. RenBED has all you need to start developing projects and it’s compatible with thembed LPC11U24.

NXP LPC11U24 MCU o Low power ARM® Cortex™-M0 Core o 48MHz, 8KB RAM, 32KB FLASH o USB Device, 2xSPI (can be configured for two of three positions), I2C , UART, 7x 10bit ADC, GPIO

Prototyping form-factor o 40-pin 0.1" pitch DIP package, 54x26mm o 5V USB, 4.5-9.0V supply or 2.4-3.3V battery (connected to DIP40) o Built-in USB drag 'n' drop FLASH programmer o Reset & ISP (In-circuit Serial Programming) button o 2x7 segment LED displays. o Works stand alone, or plug it into bread board.

www.mbed.org Developer Website o Lightweight Online Compiler o High level C/C++ SDK o Cookbook of published libraries and projects

4.5V – 9.0V In

Not Connected

nReset

DIP2

DIP3

DIP4

DIP5

DIP6

DIP7

DIP8

MOSI

MISO

SCK

SPI

DIP9

DIP10

TX

RXSerial

DIP11

DIP12

DIP13

DIP14

DIP15

DIP16

DIP17

DIP18

DIP19

DIP20

0VDIP1

AD0

AD1

AD2

AD3

AD4

AD5

AD6

TCK

TDI

TMS

TDO

TRST

SWDIO

MOSI

MISO

SCK

SPI

P0_0

P0_9

P0_8

P1_29

P0_2

P1_27

P1_26

P1_22

P1_21

P1_20

P0_10

P0_11

P0_12

P0_13

P0_14

P0_15

P0_22

P0_21

P0_20

P1_15

P0_3

P0_19

P0_18

P0_5

P0_4

P1_25

P1_24

P1_14

P0_1

P0_17

P0_7

‐3.3V Regulated Out

5.0V USB Out

Not Connected

Not Connected

MOSI

MISO

SCK

SPI

VBUS

USB

TX

RXSerial

SDA

SCLI2C

ISP

LED MUX

DIP39

DIP38

DIP37

DIP36

DIP35

DIP34

DIP33

DIP32

DIP31

DIP30

DIP29

DIP28

DIP27

DIP26

DIP25

DIP24

DIP23

DIP22

DIP21

DIP40

Green boxes contain “must know” information.

RenBED C Programming Jump Starter Page 4

Getting Started By now you are getting a little bit more familiar with the mbed environment and are able to create your own programsin a variety of ways. If you haven’t guessed, all ‘C’ programs have a main program file called “main.cpp”, now let’slook at some “Good practice” programming techniques.

Add plenty of comments to your code. Make your code self-commenting by giving functions, variables etc. sensible names. If you have defined a constant, put its name in CAPITALS, separate words with an underscore. For variables and constants add the type (initial) as lowercase before the name. Use extra lines and spaces to make your code readable Use indents of 3 spaces per indent.

 

Okay, I’ve probably mentioned lots of new words, DON’T PANIC! These will all be explained in this document. But toensure that you are not kept entirely in the dark, let’s have a look at a program and see how those rules apply. The compiler does its own job of adding colour to the text.

Comments are green! o Single line comments start with “//” no end needs to be defined, a new line will do that for you. o Multiline comments start with “/*” and have to end with “*/”

Keywords (special built in reserved words) are blue! Compiler directives (tell the compiler how to compile the code) and numbers are shown in red! Strings (special arrays of characters used as text) are pink. Everything else is black.

The program example includes a constant and a variable, but for either to be useful, we need to be able to “operate”with them. For that purpose, C++ integrates operators. Unlike other languages whose operators are mainlykeywords, operators in C++ are mostly made of signs that are not part of the alphabet but are available in allkeyboards. This makes C++ code shorter and more international, since it relies less on English words.

/******************************************************************************** This program counts forever                                                  * *                                                                              * * Jon Fuge                                                                     * * V1.0 25/11/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" // include “mbed.h”  /* Declare global variables and constants before main() */  const char cINCREMENT = 1; // Increment step size  int main () // This is the “main” function to run. {     // local variables declared in a function.    char cMyCounter = 0; // Counter variable     for (;;) // This starts the infinite loop    {       cMyCounter = cMyCounter + cINCREMENT;    } // end of for (;;) } // end of main () 

The initial of the type has been added in lowercase before the names of variables and constants.  

The names of variables are in CamelText. 

The names of constants are in CAPITALS. 

Indents are used to make the code clear. 

Extra lines have been added to make the code readable 

Comments have been added to the end of code blocks to make them easy to identify. 

Title block makes it easy to see what’s happening. 

RenBED C Programming Jump Starter Page 5

Enumeration Enumeration is a little bit like assigning sequential numbers to a series of constants. If we wanted to assign constants to thedays of the week like SUN = 0, MON = 1, TUE = 2, etc… we could write the following code: We don’t have to start at 0, but can specify any start we want:

enum DaysOfTheWeek { SUN , MON, TUE, WED, THUR, FRI, SAT }; 

enum MonthsOfTheYear { JAN = 1, FEB, MAR, APR, MAY, JUN,\                       JUL, AUG, SEP, OCT, NOV, DEC}; 

Tip… Use \ if your code needs to go over multiple lines.

Keywords Keywords are the built in commands of ‘C++’ (blue in the editor) and are the building blocks of all programs, they are reserved words.

asm  enum  signed auto  extern  sizeof break  float  static case  for  struct char  goto  switch const  if  typedef 

continue  int  union default  long  unsigned 

do  register  void double  return  volatile else  short  while 

You cannot use keywords for variable, constant, function or procedure names.

Punctuators and C++ symbols // symbols used in C++ These are non alphanumeric symbols used to organise your C++ code to help understand how the program will beexecuted. Understanding these symbols and how they are used is essential for coding in C++.

Punctuators and symbols: Operator Operation

[ ]  Square brackets are used for single and multidimensional arrays ( )  Brackets are used to group expressions together { }  Braces indicate the start and end of a compound statement (series of statements) ,  The comma is used to separate expressions ;  Semicolon is used as a terminator for statements and also used to split expressions in a for statement :  A colon is used to indicate a labelled statement and by switch for selection statements *  * in a variable expression creates a pointer &  Gives the address of an expression (used with pointers)

“ “  Quotes are used to define “string” constants …  An Ellipsis is three dots to indicate a variable number of expressions

(type)  Type cast changes the type of an expression #  Used by compiler pre-processor ##  Used by compiler pre-processor //  // Start of a single line comment (no end symbol is required) 

/*  /* Start of a multi‐line comment,end of a multi‐line comment*/ */ 

.  Structure access (to access a member of a structure) ‐>  Indirect structure access (to access a member of a structure from a pointer)

RenBED C Programming Jump Starter Page 6

Constants, variables, arrays, auto, static, register, volatile and sizeof For constants and variables, we need to specify what type of data is to be stored, we can choose the correct type based on the range and polarity of data to be stored (see the table below).

Type Sign Size stdint.h type Range signed char  signed 8-bit int8_t -27 - (27-1)

char  unsigned 8-bit uint8_t 0 - (28-1) short  signed 16-bit int16_t -215 - (215-1)

unsigned short  unsigned 16-bit uint16_t 0 - (216-1) int  signed 32-bit int32_t -231 - (231-1)

unsigned int  unsigned 32-bit uint32_t 0 - (232-1) long long  signed 64-bit int64_t -263 - (263-1)

unsigned long long  unsigned 64-bit uint64_t 0 - (264-1) float  signed 32-bit -3.4E38 - 3.4E38 double  signed 64-bit -1.7E308 - 1.7E308

It used to be important to consider what technology of microcontroller you are using. Older microcontrollers were generally 8-bit, and could handle 8-bit numbers very well, but had to use 4 times the effort for 16-bit numbers and 8 times the effort to handle 32-bit numbers, dependent on which type of processor. We have no concerns with RenBED because it uses a powerful 32-bit ARM processor so it can handle 32-bit numbers as effortlessly as 8-bit numbers. Constants are used to store a number that will never change, one such number could be a value for PI (π), or it could be a control parameter such as, MAXIMUM_SPEED = 155. Constants are used to avoid “magic numbers” which are numbers placed with no explanation. Variables store numbers, which are modified by the program; these are particularly useful allowing your program to count and process information. Arrays can be constants or variables. An array is a group of same type data grouped sequentially and accessible by an index. Arrays start at 0, so char cDiameter[4] contains cDiameter[0], cDiameter[1], cDiameter[2], cDiameter[3].

Constant declaration Variable declaration assigned value: const float PI = 3.1415927; char cClassSize = 15;

Unassigned: - float fCircumference, fRadius;

Assigned array: const char cDIAMETER[4] = {15,18,14,17}; char cMatrix[2][3] = {{2,3,5},{7,11,13}};

Unassigned array: - char cBigMatrix[4][4][6], cSmall[4][3];

To understand how variables are stored, we consider three variables…

The picture shows how these variables are arranged in memory. 15

cClassSize:

2 3 4 5 11 13

cMatrix[0][0]:

cMatrix[0][1]:

cMatrix[0][2]:

cMatrix[1][0]:

cMatrix[1][1]:

cMatrix[1][2]:

208

sNumberOfPens:

7

sNumberOfPens gets split into two 8 bit numbers (lowest 8 bits first). If we convert 2000 into Hexadecimal, we get 0x07D0. This gets stored as 0xD0 (208 decimal) in the first location and 0x07 (7 decimal) in the second. By default all variables are auto, auto means that the variable will only exist during the life of a function or procedure, once the function has completed, the variable is lost. Although auto is a keyword, it is rarely used. static is the opposite of auto, static defines a variable as being persistent so its value is preserved once the function or procedure has exited; upon re-entry to the function, the previous variable value remains as it was. register lets you store a variable in a processor register (hardware rather than memory). This is declared in a similar way to other variables but is rarely used because the compiler automatically chooses the best optimisation for storage. volatile is the extreme opposite of const and indicates that a variable can be changed unpredictably despite observing the normal program flow. Examples could be timer registers, interrupt handler storage etc. The function sizeof returns the number of bytes used by a variable or array. sizeof is useful for determining the size of a buffer to ensure that you have not exceeded the storage capacity.

char cClassSize = 15; char cMatrix[2][3] = {{2,3,5},{7,11,13}}; short sNumberOfPens = 2000; 

Tip… Use #include “stdint.h” at the start of your code, uint8_t can be used instead of char etc to make your code more readable. 

RenBED C Programming Jump Starter Page 7

Enumeration example

/******************************************************************************* * This program demonstrates the use of enumeration                             * *                                                                              * * Jon Fuge                                                                     * * V1.0 26/11/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"  enum DaysOfTheWeek { SUN , MON, TUE, WED, THUR, FRI, SAT }; enum MonthsOfTheYear { JAN = 1, FEB, MAR, APR, MAY, JUN,\                        JUL, AUG, SEP, OCT, NOV, DEC};  USBSerial serial; // Virtual serial port over USB. Use Teraterm as the interface  int main() {    wait (10); // Wait 10 seconds to connect port     serial.printf("Sunday is day %i, April is the %i month of the year\n\r", SUN, APR);     for(;;) {} // Loop forever } 

Tip… Use \ if your code needs to go over multiple lines.

Output is: Sunday is day 0, April is the 4 month of the year 

Constants, variables, array and sizeof example

/******************************************************************************* * This program demonstrates the use of constants, variables and arrays         * * Jon Fuge V1.0 25/11/2013 First issue of code                                 * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"   USBSerial serial; // Virtual serial port over USB. Use Teraterm as the interface  const float fPI = 3.1415927; // Declare a value for PI const char cDIAMETER[4] = {15,18,14,17}; // constant array of circle diameters  char cMatrix[2][3] = {{2,3,5},{7,11,13}}; // matrix array of circle diameters  int main() {    float fCircumference; // Declare local variables    wait (10); // Wait 10 seconds to connect port     fCircumference = fPI * 16; // Magic numbers should be avoided!    serial.printf("Diameter:16 Circumference:%f\n\r", fCircumference);     fCircumference = fPI * (float)cDIAMETER[2]; // accessing an array.    serial.printf("Diameter:%i Circumference:%f\n\r", cDIAMETER[2], fCircumference);     fCircumference = fPI * (float)cMatrix[0][1]; // accessing an array.    serial.printf("Diameter:%i Circumference:%f\n\r", cMatrix[0][1], fCircumference);     serial.printf("cMatrix is %i bytes\n\r", sizeof(cMatrix));     for(;;) {} // Loop forever } 

To convert a char into a float, we need to typecast it with (float).

Remember arrays start at 0!

Output is: Diameter:16 Circumference:50.265484 Diameter:14 Circumference:43.982300 Diameter:3 Circumference:9.424778 cMatrix is 6 bytes 

Tip… same type variables can be declared together when separated by commas. Note that variables and arrays can be mixed. 

char cX, cY, cColour[3];

Tip… sizeof tells you the size (in bytes) of a variable or array. 

Access a multidimensional array

RenBED C Programming Jump Starter Page 8

Assignment Operator The most common operator in C++ is the assignment operator ‘=’. We have a variable to the left of ‘=’ this is called the‘lvalue’ (left value); the number on the right is called the ‘rvalue’ (right value). The lvalue has to be a variable or aconstant. Constants can only be declared once and cannot be modified. The rvalue can be a variable, a constant or anumber or arithmetic function.

Assignment operator: Number Operation Example

=  Assign value on right to part on the left char cMyCounter = 0; // Counter variable

/******************************************************************************** This program demonstrates decimal, octal and hexadecimal                     * *                                                                              * * Jon Fuge                                                                     * * V1.0 01/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"   //Virtual serial port over USB. Use Teraterm or other terminal as the interface USBSerial serial;  int main() {    const char cRVALUE1 = 0x86; // 10000110 in binary!    char clvalue;               // Store our result here!     wait (5); // Wait 5 seconds to connect port    clvalue = cRVALUE1;    serial.printf("%X = %X\n\r", cRVALUE1, clvalue);    for(;;) {} // Loop forever } 

Output is: 86 = 86 

Relational Operators Relational operators allow you to compare two values. The comparison is done with an lvalue and an rvalue, the operator defines what comparison is to be performed; the result of the comparison is given as a Boolean value (either TRUE or FALSE). Relational operators are often used with if, while, for etc.

/******************************************************************************* * This program demonstrates decimal, octal and hexadecimal                     * * Jon Fuge                                                                     * * V1.0 01/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"   //Virtual serial port over USB. Use Teraterm or other terminal as the interface USBSerial serial;  int main() {    char cValue     = 43;   // Create 3 values     wait (5); // Wait 5 seconds to connect port    if (cValue == 43) serial.printf("cValue == 43\n\r");    if (cValue != 50) serial.printf("cValue != 50\n\r");    if (cValue > 42) serial.printf("cValue > 42\n\r");    if (cValue < 44) serial.printf("cValue > 44\n\r");    if (cValue >= 32) serial.printf("cValue >= 32\n\r");    if (cValue <= 54) serial.printf("cValue >= 54\n\r");    while(cValue == 43) {} // Loop forever } 

Relational operators: Operator Operation

== Equal to != Not Equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to

Output is: cValue == 43 cValue != 50 cValue > 42 cValue > 44 cValue >= 32 cValue >= 54 

RenBED C Programming Jump Starter Page 9

Octal, Decimal & Hexadecimal When we enter numbers into our program, we can represent them in three different bases. An example is shownbelow.

/******************************************************************************* * This program demonstrates decimal, octal and hexadecimal                     * *                                                                              * * Jon Fuge                                                                     * * V1.0 01/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"   //Virtual serial port over USB. Use Teraterm or other terminal as the interface USBSerial serial;  int main() {    char cDecimal     = 20;   // This is 20 in decimal!    char cOctal       = 020;  // This is 16 in decimal!    char cHexadecimal = 0x20; // This is 32 in decimal!     wait (5); // Wait 5 seconds to connect port    serial.printf("Display values as decimal:\n\r");    serial.printf("cDecimal = %i, cOctal = %i, cHexadecimal =%i\n\r", cDecimal, cOctal, cHexadecimal);    serial.printf("Display values as octal:\n\r");    serial.printf("cDecimal = %o, cOctal = %o, cHexadecimal =%o\n\r", cDecimal, cOctal, cHexadecimal);    serial.printf("Display values as hexadecimal:\n\r");    serial.printf("cDecimal = %X, cOctal = %X, cHexadecimal =%X\n\r", cDecimal, cOctal, cHexadecimal);    for(;;) {} // Loop forever }  Output is:

Display values as decimal: cDecimal = 20, cOctal = 16, cHexadecimal =32 Display values as octal: cDecimal = 24, cOctal = 20, cHexadecimal =40 Display values as hexadecimal: cDecimal = 14, cOctal = 10, cHexadecimal =20 

Number representations: Number Representation

20 By default, all numbers are decimal “20” 020 Lead “0” is octal, decimal “16” 0x20 Lead “0x” is hexadecimal, decimal “32”

Logical operators Are used to perform logic functions to Boolean variables and relational operators.

/******************************************************************************* * This program demonstrates decimal, octal and hexadecimal                     * * Jon Fuge                                                                     * * V1.0 01/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"   //Virtual serial port over USB. USBSerial serial;  int main() {    char cValue     = 43;   // Create 3 values     wait (5); // Wait 5 seconds to connect port    if ((cValue < 50) || (cValue > 100)) serial.printf("cValue is under 50 or over 100\n\r");    if ((cValue > 40) && (cValue < 50)) serial.printf("cValue is between 40 and 50\n\r");    if ((cValue < 50) && !(cValue == 40)) serial.printf("cValue is less than 50 and not 40\n\r");    while(cValue == 43) {} // Loop forever } 

Logical operators: Operator Operation

&& Logical AND || Logical OR ! Logical NEGATION

Output is: cValue is under 50 or over 100 cValue is between 40 and 50 cValue is less than 50 and not 40 

RenBED C Programming Jump Starter Page 10

Arithmetic Operators C++ supports the 5 basic arithmetic operators, addition, subtraction, multiplication, division and modulo (theremainder of a division between two integers). Two additional arithmetic operators have been added to increment ordecrement a variable. An arithmetic operator is often used with an assignment operator. Be careful with the order of++ or --. Arithmetic operators: Operator Operation Example

+  Addition iLValue = iRValue1 + iRValue2; ‐  Subtraction iLValue = iRValue1 ‐ iRValue2; 

*  Multiplication iLValue = iRValue1 * iRValue2; 

/  Division iLValue = iRValue1 / iRValue2; 

%  Remainder (integers only) iLValue = iRValue1 % iRValue2; 

++  Adds 1 to a variable (Increment)

iLValue = iRValue++; // ilValue = irValue; irValue increments.iLValue++; // irValue increments 

iLValue = ++iRValue; // irValue increments; ilValue = irValue. 

‐‐  Subtracts 1 from a variable (Decrement)

iLValue = iRValue‐‐; // ilValue = irValue; irValue decrements.iLValue‐‐; // irValue decrements 

iLValue = ‐‐iRValue; // irValue decrements; ilValue = irValue. 

/******************************************************************************* * This program demonstrates various arithmetic operators                       * * Jon Fuge                                                                     * * V1.0 02/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"   //Virtual serial port over USB. Use Teraterm or other terminal as the interface USBSerial serial;  int main() {    char crvalue1 = 43; // random decimal    char crvalue2 = 7;  // random decimal    int  clvalue;       // Store our result here!     wait (5); // Wait 5 seconds to connect port    clvalue = crvalue1 + crvalue2;    serial.printf("%i + %i = %i\n\r", crvalue1, crvalue2, clvalue);    clvalue = crvalue1 ‐ crvalue2;    serial.printf("%i ‐ %i = %i\n\r", crvalue1, crvalue2, clvalue);    clvalue = crvalue1 * crvalue2;    serial.printf("%i * %i = %i\n\r", crvalue1, crvalue2, clvalue);    clvalue = crvalue1 / crvalue2;    serial.printf("%i / %i = %i\n\r", crvalue1, crvalue2, clvalue);    clvalue = crvalue1 % crvalue2;    serial.printf("%i %% %i = %i\n\r\n\r", crvalue1, crvalue2, clvalue);    serial.printf("              iRValue = %i\n\r", crvalue1);    clvalue = crvalue1++;    serial.printf("iLValue = iRValue++\n\riLValue = %i, iRValue = %i\n\r\n\r", clvalue, crvalue1);    crvalue1 = 43; // reset crvalue1    serial.printf("              iRValue = %i\n\r", crvalue1);    clvalue = ++crvalue1;    serial.printf("iLValue = ++iRValue\n\riLValue = %i, iRValue = %i\n\r\n\r", clvalue, crvalue1);    crvalue1 = 43; // reset crvalue1    serial.printf("              iRValue = %i\n\r", crvalue1);    clvalue = crvalue1‐‐;    serial.printf("iLValue = iRValue‐‐\n\riLValue = %i, iRValue = %i\n\r\n\r", clvalue, crvalue1);    crvalue1 = 43; // reset crvalue1    serial.printf("              iRValue = %i\n\r", crvalue1);    clvalue = ‐‐crvalue1;    serial.printf("iLValue = ‐‐iRValue\n\riLValue = %i, iRValue = %i\n\r\n\r", clvalue, crvalue1);    for(;;) {} // Loop forever } 

Output is: 43 + 7 = 50 43 ‐ 7 = 36 43 * 7 = 301 43 / 7 = 6 43 % 7 = 1                iRValue = 43 iLValue = iRValue++ iLValue = 43, iRValue = 44                iRValue = 43 iLValue = ++iRValue iLValue = 44, iRValue = 44                iRValue = 43 iLValue = iRValue‐‐ iLValue = 43, iRValue = 42                iRValue = 43 iLValue = ‐‐iRValue iLValue = 42, iRValue = 42 

RenBED C Programming Jump Starter Page 11

Bitwise Operators Bitwise operators allow us to perform binary logic functions on variables. The implementation of the operator isexactly the same as an arithmetic operator. The numbers shown below are binary numbers which can only contain1s & 0s. The program above repeats the calculation examples.

Bitwise operators: Operator Operation Example function Result

&  AND returns 1 if both bits are 1 10000110 & 00010011 =  00000010|  OR returns 1 if either or both bits are 1 10000110 | 00010011 =  10010111^  XOR returns 1 if bits are complementary 10000110 ^ 00010011 =  10010101~  Complement (invert) each bit ~10000110 = 01111001<<  Shift left by (rvalue) bits 10000110 << 0x02 = 00011000>>  Shift right by (rvalue) bits 10000110 >> 0x02 = 00100001

/******************************************************************************* * This program demonstrates various bitwise operators                          * *                                                                              * * Jon Fuge                                                                     * * V1.0 01/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"   //Virtual serial port over USB. Use Teraterm or other terminal as the interface USBSerial serial;  int main() {    char crvalue1     = 0x86; // 10000110 in binary!    char crvalue2     = 0x13; // 00010011 in binary!    char crvalue3     = 0x02; // 00000010 in binary!    char clvalue;             // Store our result here!     wait (5); // Wait 5 seconds to connect port    clvalue = crvalue1 & crvalue2;    serial.printf("%X & %X = %X\n\r", crvalue1, crvalue2, clvalue);    clvalue = crvalue1 | crvalue2;    serial.printf("%X | %X = %X\n\r", crvalue1, crvalue2, clvalue);    clvalue = crvalue1 ^ crvalue2;    serial.printf("%X ^ %X = %X\n\r", crvalue1, crvalue2, clvalue);    clvalue = ~crvalue1;    serial.printf("~%X = %X\n\r", crvalue1, clvalue);    clvalue = crvalue1 << crvalue3;    serial.printf("%X << %X = %X\n\r", crvalue1, crvalue3, clvalue);    clvalue = crvalue1 >> crvalue3;    serial.printf("%X >> %X = %X\n\r", crvalue1, crvalue3, clvalue);     serial.printf("\n\r"); // add another blank line    for(;;) {} // Loop forever } 

Output is: 86 & 13 = 2 86 | 13 = 97 86 ^ 13 = 95 ~86 = 79 86 << 2 = 18 86 >> 2 = 21 

RenBED C Programming Jump Starter Page 12

Digital Input And Output The simplest form of Input and Output is DigitalIn and DigitalOut, these instructions require“#include  mbed.h” to be added to “main.cpp”. The library file “mbed” needs to be imported to your project.DigitalIn and DigitalOut are assigned to ports, which are determined by looking at the table below.

4.5V – 9.0V In

Not Connected

nReset

DIP2

DIP3

DIP4

DIP5

DIP6

DIP7

DIP8

MOSI

MISO

SCK

SPI

DIP9

DIP10

TX

RXSerial

DIP11

DIP12

DIP13

DIP14

DIP15

DIP16

DIP17

DIP18

DIP19

DIP20

0VDIP1

AD0

AD1

AD2

AD3

AD4

AD5

AD6

TCK

TDI

TMS

TDO

TRST

SWDIO

MOSI

MISO

SCK

SPI

P0_0

P0_9

P0_8

P1_29

P0_2

P1_27

P1_26

P1_22

P1_21

P1_20

P0_10

P0_11

P0_12

P0_13

P0_14

P0_15

P0_22

P0_21

P0_20

P1_15

P0_3

P0_19

P0_18

P0_5

P0_4

P1_25

P1_24

P1_14

P0_1

P0_17

P0_7

‐3.3V Regulated Out

5.0V USB Out

Not Connected

Not Connected

MOSI

MISO

SCK

SPI

VBUS

USB

TX

RXSerial

SDA

SCLI2C

ISP

LED MUX

DIP39

DIP38

DIP37

DIP36

DIP35

DIP34

DIP33

DIP32

DIP31

DIP30

DIP29

DIP28

DIP27

DIP26

DIP25

DIP24

DIP23

DIP22

DIP21

DIP40

The example below toggles a LED on and off when a switch is pressed, the switch is connected between DIP5 (P0_9)& 0V, and the LED with resistor is connected between DIP36 (P0_21) and 0V.

/******************************************************************************** This program demonstrates how to read a switch and toggle a LED.             * * Connect LED and resistor between to DIP36 (P0_21) and DIP1 (0V).             * * Connect switch between DIP5 (P0_9) and DIP1 (0V).                            * *                                                                              * * Jon Fuge                                                                     * * V1.0 12/11/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" // has prototypes for DigitalIn and DigitalOut  DigitalIn  mybutton(P0_9); // mybutton reads bit  9 of port 0 (DIP5). DigitalOut myled(P0_21);   // myled controls bit 21 of port 0 (DIP36).  int main() {    mybutton.mode(PullUp); // Configure pin to be a pull‐up input    for(;;) { //Create infinite loop to keep program running.       if (mybutton == 0) { // if mybutton = 0, then it has been pressed          myled = !myled; // myled will now become !myled (! means NOT).          wait(0.1); // Wait for 0.1 seconds to "debounce" the switch.          while (mybutton == 0) {} // Wait for my button to be released.       } // End of if (mybutton == 0)    } // End of for(;;) } // end of int main() 

RenBED C Programming Jump Starter Page 13

Setting up a digital output.

DigitalOut PinName(PortName); Creates a DigitalOut called PinName, which is connected to the specified PortName.

PinName When PinName is used on its own, it is used to set the output state of the pin, PinName can also be used as a function in the same way as DigitalIn which returns the level of the output as a 0 (Low), or a 1 (High).

DigitalOut myled(P0_21);   // myled controls bit 21 of port 0 (DIP36). 

myled = !myled; // myled will now become !myled (! means NOT).

Setting up a digital input.

DigitalIn PinName(PortName); Creates a DigitalIn called PinName, which is connected to the specified PortName.

PinName.mode(PinMode); Allows you to specify what type of input your digital input is. After a reset, pins P0_4 & P0_5 are configured as OpenDrain, all other pins are configured as PullUp.

PinName When PinName is used on its own, it operates as a function which returns the digital level of the input pin as a 0 (Low), or a 1 (High).

Port names and DIP pin mapping: DIP

Number PortName

DIP Number

PortName DIP

Number PortName

DIP Number

PortName

DIP1 ‐  DIP11 P1_22 DIP21 P0_7 DIP31 ‐

DIP2 ‐  DIP12 P1_21 DIP22 P0_17 DIP32 ‐

DIP3 ‐  DIP13 P1_20 DIP23 P0_1 DIP33 P0_3

DIP4 P0_0  DIP14 P0_10 DIP24 P1_14 DIP34 P1_15

DIP5 P0_9  DIP15 P0_11 DIP25 P1_24 DIP35 P0_20

DIP6 P0_8  DIP16 P0_12 DIP26 P1_25 DIP36 P0_21

DIP7 P1_29  DIP17 P0_13 DIP27 P0_4 DIP37 ‐

DIP8 P0_2  DIP18 P0_14 DIP28 P0_5 DIP38 ‐

DIP9 P1_27  DIP19 P0_15 DIP29 P0_18 DIP39 ‐

DIP10 P1_26  DIP20 P0_22 DIP30 P0_19 DIP40 ‐

Pin modes: Mode Operation PullUp  When PullUp is selected, a current of 50µA is applied to the pin pulling it high. PullDown  When PullDown is selected, a current of 50µA is applied to the pin pulling it low. PullNone  When PullNone is selected, the input is left floating so you will need to pull it high or low.

OpenDrain When PullNone is selected, the input can get a bit smelly , no actually it is like the floating input

before, but also has the ability to pull itself low so it can be used as a input/output.

DigitalIn  mybutton(P0_9); // mybutton reads bit  9 of port 0 (DIP5). 

mybutton.mode(PullUp); // Configure pin to be a pull‐up input

if (mybutton == 0) { // if mybutton = 0, then it has been pressed

RenBED C Programming Jump Starter Page 14

Driving the 7 segment displays RenBED comes supplied with two 7 segment displays and are driven by dedicated pins on the microcontroller. Eachsegment is labelled with a letter ranging from A – G and each has a decimal point (DP). For RenBED to light up one ofthe segments, it has to drive the segment low (0). In order to display numbers, a series of segments need to be lit up,the table below shows, which segments need to be lit for numbers ranging from 0 – 9.

A separate multiplexor (MUX) wire selects which display to drive, when set to 0, D5 (left) is driven, when set to 1, D6(right) is driven.

Segment drive to represent decimal numbers: Number Binary G F E D C B A

0 0000 1 0 0 0 0 0  0 1 0001 1 1 1 1 0 0  1 2 0010 0 1 0 0 1 0  0 3 0011 0 1 1 0 0 0  0 4 0100 0 0 1 1 0 0  1 5 0101 0 0 1 0 0 1  0 6 0110 0 0 0 0 0 1  0 7 0111 1 1 1 1 0 0  0 8 1000 0 0 0 0 0 0  0 9 1001 0 0 1 0 0 0  0 

Port mapping for 7 segment displays: 7 Segment Connection Microcontroller port map

MUX  P1_25A  P1_23B  P1_28C  P0_16D  P1_317  P1_13F  P1_16G  P1_19DP  P0_23

RenBED C Programming Jump Starter Page 15

Driving the 7 segment displays example

Fortunately there is a 7 segment display driver routine for RenBED available on the mbed site which is easy to use sowe don’t need to worry about mapping the segments and driving them with the appropriate pattern. Some examplecode for driving the seven segment display is shown below. To drive the displays, your project will need the libraries“mbed” and “SevenSegLed”, and we will need “#include SevenSegLed.h" and “#include mbed.h” in “main.cpp”.

/******************************************************************************* * This program demonstrates how to drive the seven segment display             * *                                                                              * * Jon Fuge                                                                     * * V1.0 13/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "SevenSegLed.h"  // Lets define some "macros" to make the code easier to read  #define mUnits D_7seg[1]     // "mUnits" will be substiuted for "D_7seg[1]" #define mTens  D_7seg[0]     // "mTens"  will be substiuted for "D_7seg[0]" #define mDot   D_dot[1]      // "mDot"   will be substiuted for "D_dot[1]"  void attimeout();            //declare prototype for timeout handler.  //configure sevensegled pin connection mapping. // //                     common type (0:anode common 1:cathode common) //                     |  display mode (0:smooth 1:hard) //                     |  |   segA   segB   segC   segD   segE   segF   segG   segP  com1  com2 SevenSegLed segmentled(0, 0, P1_23, P1_28, P0_16, P1_31, P1_13, P1_16, P1_19, P0_23, p21, P1_25);  //Define two arrays to house the data to be outputted. D_7seg can contain digits 0‐F and D_dot 0‐1. // //                   0  1   //0 = leftmost digit, 1 = rightmost digit //                   |  | uint8_t D_7seg[2] = {0, 0}; // number    (0x00:"0", ... , 0x09:"9", 0x0A:"A", ... , 0x0F:"F", other:" ") uint8_t D_dot[2]  = {0, 0}; // dotpoint. (0:off 1:on)  Ticker timeout;             //Create an instance of class Ticker called timeout.  int main() {      timeout.attach_us(&attimeout, 500000); // Set up interrupt to call attimeout() every half a second.      for(;;) {         segmentled.SevenSegLed_main(D_7seg, D_dot); // Keep the displays multiplexed.     } }  void attimeout()              //Timer interrupt routine. {     mDot = 1 ‐ mDot;     if (mDot == 1) {         mUnits++;             // This means the same as D_7seg[0] = D_7seg[0] + 1; Increment "units"         if (mUnits > 9) {     // "units" digit should be in the range 0 ‐> 9             mUnits = 0;       // Reset the "units" to 0             mTens++;          // Increment "tens" digit             if (mTens > 9) {  // "tens" digit should be in the range 0 ‐> 9                 mTens = 0;    // Reset the "tens" to 0             }         }     } } 

RenBED C Programming Jump Starter Page 16

printf printf is used quite a lot in C & C++ it is the main command for sending information to the outside world; forconvenience, all printf examples will use the USB Serial library. Printf is used to send text to the outside world, but it also has the ability to include formatted parameters. The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which areoptional and follow these specifications:

Printf parameters: Parameters start with % and are arranged in the following way.. Items held in [ ] are optional, but the specifier must always exist. Specifier Output Example d or i  Signed decimal integer 392

u  Unsigned decimal integer 7235o  Unsigned octal 610x  Unsigned hexadecimal integer 7faX  Unsigned hexadecimal integer (uppercase) 7FAf  Decimal floating point 392.65e  Scientific notation (mantissa/exponent), lowercase 3.9265e+2E  Scientific notation (mantissa/exponent), uppercase 3.9265E+2g  Use the shortest representation: %e or %f 392.65G  Use the shortest representation: %E or %F 392.65c  Character as  String of characters sample%  A % followed by another % character will write a single % to the stream. %

flags: Flags Description

‐  Left-justify within the given field width; Right justification is the default (see width sub-specifier).

+ Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.

(space)  If no sign is going to be written, a blank space is inserted before the value.

Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.

0 Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).

width: Width Description

(number) Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

%[flags][width][.precision][length]specifier

RenBED C Programming Jump Starter Page 17

In addition to printf parameters, printf also allows you to enter ASCII control characters. In order to inform printf that you want to use a control character you start an “escape sequence” with a ‘\’” slash character. The table below lists the escape sequences available.

.precision: Width Description

.number 

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E and f specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed.

.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

length: The length sub-specifier modifies the length of the data type. This is a chart showing the types used to interpret the corresponding arguments with and without length specifier (if a different type is used, the proper type promotion or conversion is performed, if allowed):

Flags Specifiers

d i u o x X f e E g G c s (none)  int unsigned int double int char* hh  signed char unsigned char h  short int unsigned short int l  long int unsigned long int int char* ll  long long int unsigned long long int j  intmax_t uintmax_t z  size_t size_t t  ptrdiff_t ptrdiff_t L  long double

Printf escape sequences: Specifier ASCII (American Standard Code for Information Interchange) ASCII Name

\a  Audible alert (bell) BEL\b  Backspace BS\t  Horizontal tab HT\n  Newline LF\v  Vertical tab VT\f  Formfeed FF\r  Carriage return CR\”  Double quote “\’  Single quote ‘\?  Question mark ?\\  Backslash /

RenBED C Programming Jump Starter Page 18

printf examples

/******************************************************************************* * This program demonstrates the use of printf parameters                       * *                                                                              * * Jon Fuge                                                                     * * V1.0 16/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"  //Virtual serial port over USB. USBSerial serial;  int main() {    wait (5);    serial.printf ("Characters: %c %c \n\r", 'a', 65);    serial.printf ("Decimals: %d %ld\n\r", 1977, 650000L);    serial.printf ("Preceding with blanks: %10d \n\r", 1977);    serial.printf ("Preceding with zeros: %010d \n\r", 1977);    serial.printf ("Some different radices: %d %x %o %#x %#o \n\r", 100, 100, 100, 100, 100);    serial.printf ("floats: %4.2f %+.0e %E \n\r", 3.1416, 3.1416, 3.1416);    serial.printf ("Width trick: %*d \n\r", 5, 10);    serial.printf ("%s \n\r", "A string");    for (;;) {}; } 

Output is: Characters: a A Decimals: 1977 650000 Preceding with blanks:       1977 Preceding with zeros: 0000001977 Some different radices: 100 64 144 0x64 0144 floats: 3.14 +3e+00 3.141600E+00 Width trick:    10 A string= 21 

/******************************************************************************* * This program demonstrates the use of printf escape sequences                 * *                                                                              * * Jon Fuge                                                                     * * V1.0 19/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"  //Virtual serial port over USB. Use Teraterm or other terminal as the interface USBSerial serial;  int main() {    wait (5);    serial.printf ("audible alert (bell) |\a|   \\a   %d\n\r" , '\a');    serial.printf ("backspace            |\b|   \\b   %d\n\r" , '\b');    serial.printf ("horizontal tab       |\t|   \\t   %d\n\r" , '\t');    serial.printf ("newline              |\n|   \\n  %d\n\r"  , '\n');    serial.printf ("vertical tab         |\n|   \\v  %d\n\r"  , '\v');    serial.printf ("formfeed             |\f|   \\f  %d\n\r"  , '\f');    serial.printf ("carriage return      |\r|   \\r  %d\n\r"  , '\r');    serial.printf ("double quote         |\"|   \\\"  %d\n\r", '\"');    serial.printf ("single quote         |\'|   \\\'  %d\n\r", '\'');    serial.printf ("question mark        |\?|   \\?  %d\n\r"  , '\?');    serial.printf ("backslash            |\\|   \\\\  %d\n\r", '\\');    for (;;) {}; } 

Output is: audible alert (bell) ||   \a   7 backspace            |   \b   8 horizontal tab       |  |   \t   9 newline              |                       |   \n  10 vertical tab         |                       |   \v  11 formfeed             |                       |   \f  12 |   \r  13eturn      | double quote         |"|   \"  34 single quote         |'|   \'  39 question mark        |?|   \?  63 backslash            |\|   \\  92 

RenBED C Programming Jump Starter Page 19

scanf scanf is used almost as much as printf and is used to get information to the outside world. scanf is used to receive text to the outside world, but it also has the ability to include formatted parameters. The format specifier can also contain sub-specifiers: flag, width and length (in that order), which are optional and follow these specifications:

Printf parameters: Parameters start with % and are arranged in the following way.. Items held in [ ] are optional, but the specifier must always exist. Specifier Output Example

d, I or u decimal integer optionally preceded by (+ or -), a 0 prefix mkes the value octal, 0x prefix makes the value hexadecimal

392 

o  octal optionally preceded by (+ or -) 610x  hexadecimal integer optionally preceded by (+ or -). 7fa or 7FA

f, e, g Decimal floating point optionally preceded by (+ or -) and optionally containing one decimal point.

392.65 or 3.9265e+2 

c  Character as  String of characters sample%  A % followed by another % character will write a single % to the stream. %

flags: Flags Description

* An optional starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument).

width  Specifies the maximum number of characters to be read in the current reading operation (optional).

length One of hh, h, l, ll, j, z, t, L (optional). This alters the expected type of the storage pointed by the corresponding argument (see below).

%[*][width][length]specifier

length: The length sub-specifier modifies the length of the data type. This is a chart showing the types used to interpret the corresponding arguments with and without length specifier (if a different type is used, the proper type promotion or conversion is performed, if allowed):

Flags Specifiers

d i u o x X f e E g G c s (none)  int unsigned int double int char* hh  signed char unsigned char h  short int unsigned short int l  long int unsigned long int int char* ll  long long int unsigned long long int j  intmax_t uintmax_t z  size_t size_t t  ptrdiff_t ptrdiff_t L  long double

RenBED C Programming Jump Starter Page 20

Communicating with USB The library USBDevice supports many protocols… The next few pages of this booklet will deal with how to use each of the USB device classes and provide examples oftheir use.

USB Protocols supported by USBDevice library: Protocol Name Usage

USB Serial The USB Serial class uses the USB interface to emulate a serial port. The RenBED is recognized by the computer as a serial port. This is a great solution to communicate easily between the microcontroller and a computer

USB Mouse The USB Mouse class allows to emulate a mouse with your RenBED. You can either chose a relative or absolute mouse. This class allows you to, move the cursor on the screen, click, scroll

USB Keyboard The USB Keyboard class allows to use RenBED as a keyboard. You can, send basic keys, send "modified keys" such as: CTRL + 'c', send media keys (Mute, Volume Up, Volume Down, next track, ...)

USB Mouse And Keyboard Achieves USB Mouse & USB Keyboard at the same time

USB HID

The USB HID (Human Interface Device) class is a great opportunity to send and receive raw data to a custom program. This allows you to design your own USB device without any specific drivers on the host side as all operating systems have a built-in HID driver.

USB Audio

The USB Audio class enables the RenBED to be recognized as an audio device. With this interface, you can receive audio packet from the computer (play music,...) and receive them over USB. For instance you connect a speaker or an I2S/I2C chip to RenBED and play the stream received from the computer.

USB MIDI Using this library, you can do things like send MIDI messages to a computer (such as to record in a sequencer, or trigger a software synthesiser) and receive messages from a computer (such as actuate things based on MIDI events).

USB MSD

The USBMSD interface is used to emulate a mass storage device over USB. You can use this class to store or load data to and from a storage chip (SDcard, flash,...). This class implements the MSD protocol and calls pure virtual functions such as disk_initialize,disk_write or disk_read to interact with a storage chip.

RenBED C Programming Jump Starter Page 21

Output is: What is your name? Jon What are you doing Jon? 

USB Serial The simplest USB class to use is the USBSerial device. USBSerial provides an easy to use interface between yourcomputer and RenBED. To use USBSerial we have to add “#include USBSerial.h" and “#include mbed.h” to “main.cpp” and Import the library files “mbed” and “USBDevice” to your project. The example below shows a very simple way to communicate with the USB virtual serial port using printf to send a message to the port, and scanf to receive a message from the port. When RenBED has connected to your computer using the USBSerial protocol for the first time, windows will try to findan existing driver without success. Follow the instructions mentioned below to install the driver: http://mbed.org/handbook/USBSerial You will require a “terminal emulator” to provide you with a window, in addition to the USB serial driver, which cancommunicate with a serial port device. For older computers Windows includes a program called “HyperTerminal” whichdoes just that, otherwise, you can download a terminal emulator called “TeraTerm” fromhttp://ttssh2.sourceforge.jp/index.html.en or “RealTerm” from http://realterm.sourceforge.net/ With the terminal emulator installed and running, press “Reset” on RenBED; you should hear Windows informing youthat the device has connected; now you can connect the terminal emulator to the appropriate serial port, look for theone called “MBED Virtual Serial Port”. Once connected, after approximately 10 seconds, RenBED will ask you whatyour name is… If this does not happen; shut down the terminal emulator, reset RenBED and try again…

/******************************************************************************** This program demonstrates how to read a string from the USB serial device    * * and write a string back to the USB serial device                             * *                                                                              * * Jon Fuge                                                                     * * V1.0 25/11/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"   //Virtual serial port over USB. Use Teraterm or other terminal as the interface USBSerial serial;  int main() {    char buf[128]; // A char array is also a string!    wait (10); // Wait 10 seconds to connect port    // Need to type a key, then enter to get a response.    serial.printf("What is your name?\n\r"); // Send message to USB serial port    serial.scanf("%s", buf); // Receive message from USB serial port    serial.printf("What are you doing %s?\n\r", buf);    for(;;) {} // Loop forever } 

Output is: What is your name? Jon What are you doing Jon? 

RenBED C Programming Jump Starter Page 22

USB Mouse USB Mouse allows you to generate signals from RenBED to emulate mouse functions on the PC. As an alternativeinput device it could be used to interface to a series of sensors to give you a greater range of control systems;however, without appropriate sensors, it could just drive some poor unsuspecting soul to the point of despair with thecode below.

/******************************************************************************* * This program moves the mouse around on the PC in a large circle              * *                                                                              * * Jon Fuge                                                                     * * V1.0 13/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBMouse.h"  #define mDegreeToRadian 3.14/180 #define RADIUS 10   USBMouse mouse;   int main() {     int16_t i16_X;     int16_t i16_Y;     int32_t i32_Angle = 0;   // set the start angle       for (;;) {         i16_X = cos((double)i32_Angle * mDegreeToRadian) * RADIUS; // calculate x offset         i16_Y = sin((double)i32_Angle * mDegreeToRadian) * RADIUS; // calculate y offset                  mouse.move(i16_X, i16_Y); // send a message to move the mouse cursor         i32_Angle += 3; // move to the next angle of annoyance         wait(0.001); // wait 1ms before we do it all again     } // loop back to for (;;) } // end main() 

RenBED C Programming Jump Starter Page 23

USB Keyboard The USBKeyboard interface is used to emulate a keyboard over the USB port. You can type strings and sendkeycodes, send keys with modifiers (e.g. CTRL + 's'), function keys and also the media control keys. As with USB Mouse, there is plenty of scope for practical jokes.

/******************************************************************************* * This program demonstrates how RenBED can operate the keyboard                * *                                                                              * * Jon Fuge                                                                     * * V1.0 13/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBKeyboard.h"   //LED segment A: NUM_LOCK //LED segment B: CAPS_LOCK //LED segment C: SCROLL_LOCK BusOut leds(P1_23, P1_28, P0_16);   USBKeyboard keyboard;   int main(void) {     for (;;) {         keyboard.mediaControl(KEY_VOLUME_DOWN); // Turn the volume down         keyboard.printf("Hello World from RenBED \r\n"); // Send a message         keyboard.keyCode('s', KEY_CTRL); // Send CTRL ‐ S         keyboard.keyCode(KEY_CAPS_LOCK); // Toggle CAPS LOCK         wait(1); // Wait for 1 second         leds = keyboard.lockStatus(); // Display LED status of keyboard     } } 

RenBED C Programming Jump Starter Page 24

USB Mouse Keyboard The USBMouseKeyboard interface is used to emulate a mouse and a keyboard at the same time over the USB port.You can get up to all the shenanigans that USB Keyboard and USB Mouse gave you but both at the same time.

/******************************************************************************* * This program demonstrates the use of mouse and keyboard concurrently         * *                                                                              * * Jon Fuge                                                                     * * V1.0 13/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBMouseKeyboard.h"   #define mDegreeToRadian 3.14/180 #define RADIUS 10  //LED segment A: NUM_LOCK //LED segment B: CAPS_LOCK //LED segment C: SCROLL_LOCK BusOut leds(P1_23, P1_28, P0_16);   //USBMouseKeyboard USBMouseKeyboard key_mouse;   int main(void) {     int16_t i16_X;     int16_t i16_Y;     int32_t i32_Angle = 0;   // set the start angle       for (;;) {         key_mouse.mediaControl(KEY_VOLUME_UP); // Turn the volume down         key_mouse.keyCode(KEY_CAPS_LOCK); // Toggle CAPS LOCK         key_mouse.keyCode(KEY_SCROLL_LOCK); // Toggle SCROLL LOCK         i16_X = cos((double)i32_Angle * mDegreeToRadian) * RADIUS; // calculate x offset         i16_Y = sin((double)i32_Angle * mDegreeToRadian) * RADIUS; // calculate y offset         key_mouse.move(i16_X, i16_Y); // send a message to move the mouse cursor         i32_Angle += 3; // move to the next angle of annoyance         wait(.1);         leds = key_mouse.lockStatus();     } } 

RenBED C Programming Jump Starter Page 25

USB HID The USBHID class can be used to send and receive messages over USB. For instance, you can define your ownprotocol and communicate between your computer and the RenBED with all capabilities of a USB communication. Touse USBHID, you need a script running on the host side (computer). For instance on a 32 bits Windows 7 machine,you can use pywinusb. The subject of USB HID requires expert programming knowledge and will not be covered further in this document.

/******************************************************************************* * This program demonstrates the use of a USB HID with descriptors              * *                                                                              * * Jon Fuge                                                                     * * V1.0 13/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBHID.h"   //We declare a USBHID device. By default input and output reports are 64 bytes long. USBHID hid(8, 8);   Serial pc(USBTX, USBRX);   //This report will contain data to be sent HID_REPORT send_report; HID_REPORT recv_report;   DigitalOut l1(LED1);   int main(void) {     send_report.length = 8;       for (;;) {                  //Fill the report         for (int i = 0; i < send_report.length; i++)             send_report.data[i] = rand() & 0xff;           //Send the report         hid.send(&send_report);           //try to read a msg         if(hid.readNB(&recv_report)) {             l1 = !l1;             for(int i = 1; i < recv_report.length; i++) {                 pc.printf("%d ", recv_report.data[i]);             }             pc.printf("\r\n");         }     } } 

RenBED C Programming Jump Starter Page 26

USB Audio The USBAudio class enables the RenBED to be recognized as an audio device. With this interface, you can receiveand send audio packets from and to a computer (play a music,...) over USB. For instance you can connect a speaker or an I2S/I2C chip to the RenBED and play the stream received from the computer.

/******************************************************************************* * This program receives audio from the PC then writes this data back to the    * * serial port                                                                  * *                                                                              * * Jon Fuge                                                                     * * V1.0 16/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBAudio.h"   Serial pc(USBTX, USBRX);   // frequency: 48 kHz #define FREQ 48000   // 1 channel: mono #define NB_CHA 1   // length of an audio packet: each ms, we receive 48 * 16bits ‐>48 * 2 bytes. #define AUDIO_LENGTH_PACKET 48 * 2 * 1   // USBAudio USBAudio audio(FREQ, NB_CHA);   int main() {     int16_t buf[AUDIO_LENGTH_PACKET/2];          for (;;) {         // read an audio packet         audio.read((uint8_t *)buf);           // print packet received         pc.printf("recv: ");         for(int i = 0; i < AUDIO_LENGTH_PACKET/2; i++) {             pc.printf("%d ", buf[i]);         }         pc.printf("\r\n");     } }  Change the default sound board

To send audio packets to the mbed, you have to change the default sound board used by the Operating system. On Windows, you can do this by clicking on:

control panel Hardware and Sound Manage audio device in the Sound section Select the Mbed Audio device and press Set default

RenBED C Programming Jump Starter Page 27

USB MIDI The USBMIDI interface can be used to send and receive MIDI messages over USB using the standard USB-MIDI protocol. Using this library, you can do things like send MIDI messages to a computer (such as to record in a sequencer, ortrigger a software synthesiser) and receive messages from a computer (such as actuate things based on MIDI events)

/******************************************************************************* * This program writes music to the PC Midi interpreter, then reads data back   * * and displays the key codes on the seven segment displays                     **                         * * Jon Fuge                                                                     * * V1.0 16/12/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBMIDI.h" #include "SevenSegLed.h"  #define mUnits D_7seg[1]     // "mUnits" will be substiuted for "D_7seg[1]" #define mTens  D_7seg[0]     // "mTens"  will be substiuted for "D_7seg[0]" #define mDot   D_dot[1]      // "mDot"   will be substiuted for "D_dot[1]"  SevenSegLed segmentled(0, 1, P1_23, P1_28, P0_16, P1_31, P1_13, P1_16, P1_19, P0_23, p21, P1_25);  uint8_t D_7seg[2] = {0, 0}; // number    (0x00:"0", ... , 0x09:"9", 0x0A:"A", ... , 0x0F:"F", other:" ") uint8_t D_dot[2]  = {0, 0}; // dotpoint. (0:off 1:on)  //USBMIDI object USBMIDI midi;  void show_message(MIDIMessage msg) {     switch (msg.type()) {         case MIDIMessage::NoteOnType:             mUnits = msg.key() % 16;             mTens = msg.key() / 16;             break;         case MIDIMessage::NoteOffType:         default:             mUnits = 0x11;             mTens = 0x11;     } }  int main() {     // call back for messages received     midi.attach(show_message);      for (;;) {         for(int i=48; i<83; i++) {     // send some messages!             midi.write(MIDIMessage::NoteOn(i));             wait(0.1);             midi.write(MIDIMessage::NoteOff(i));             wait(0.1);         }         for (;;) {             segmentled.SevenSegLed_main(D_7seg, D_dot); // Keep the displays multiplexed.         }     } } 

RenBED C Programming Jump Starter Page 28

USB MSD The USBMSD interface is used to emulate a mass storage device over USB. You can use this class to store or loaddata to and from a storage chip (SDcard, flash,...). This class implements the MSD protocol and calls pure virtualfunctions such as disk_initialize, disk_write or disk_read to interact with a storage chip.

/******************************************************************************* 

* This program conencts a SD‐Card to the RenBED board and emulates a Pen drive * 

*                                                                              * 

* Jon Fuge                                                                     * 

* V1.0 16/12/2013 First issue of code                                          * 

*******************************************************************************/ 

 

#include "mbed.h" 

#include "USBMSD_SD.h" 

  

USBMSD_SD sd(p5, p6, p7, p8); // This line does all the hard work!   int main() {     for(;;); // That's really all there is to do! } 

RenBED C Programming Jump Starter Page 29

Pointers 

Pointers are dogs, sticks or lasers, but a different type of pointer is one that points to a memory location. We declare apointer in a similar way to declaring a variable. We can see it’s a pointer because it has an * in front of the name. Although I have put pointers in an orange box (expert skills), pointers are very useful and you are encouraged to learnhow to use them. The example below shows how pointers are used.

char *ptr; // Declare a pointer to a char

/******************************************************************************** This program demonstrates the use of pointers                                * *                                                                              * * Jon Fuge                                                                     * * V1.0 25/11/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"  USBSerial serial; // Virtual serial port over USB. Use Teraterm as the interface  int main(void) {    char cBox1 = 5;    char cBox2 = 10;     // Declare two variables.    char *ptr  = &cBox1; // Declare a pointer directed to cBox1        wait (10);           // Wait 10 seconds to connect port     serial.printf("cBox1:%i, cBox2:%i, *ptr:%i\n\r", cBox1, cBox2, *ptr);     cBox2 = cBox1;       // cBox2 was 10, but is now 5    serial.printf("cBox1:%i, cBox2:%i, *ptr:%i\n\r", cBox1, cBox2, *ptr);        cBox1 = 15;          // cBox1 was 5, but is now 15    serial.printf("cBox1:%i, cBox2:%i, *ptr:%i\n\r", cBox1, cBox2, *ptr);    // cBox2 will still report 5, but *ptr now reports 15     for(;;) {}           // Loop forever } 

Output is: cBox1:5, cBox2:10, *ptr:5 cBox1:5, cBox2:5, *ptr:5 cBox1:15, cBox2:5, *ptr:15 

typedef typedef allows you to create an alias or synonym of an existing type (or types). stdint.h uses typedef to create new more readable types…

/******************************************************************************** This program demonstrates the use of structures                              * *                                                                              * * Jon Fuge                                                                     * * V1.0 25/11/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h"  typedef unsigned short myword; // Declare myword as a new type  int main() {    myword mwAddress;      // Declare variables with the new type        mwAddress = 600;     for(;;) {}             // Loop forever } 

Orange boxes contain “expert” information.

RenBED C Programming Jump Starter Page 30

Structure

structure allows you to join two or more types together to make a new type. In the example, we will create a type called “coordXY”, and show two ways to initialise it.

/******************************************************************************* 

* This program demonstrates the use of structures                              * 

* Jon Fuge V1.0 26/11/2013 First issue of code                                 * 

*******************************************************************************/ 

#include "mbed.h" 

#include "USBSerial.h" 

 

struct coordXY { int iX; int iY; }; // Define a new structure  

int main() {    USBSerial serial; // Virtual serial port over USB. Use Teraterm as the interface 

   coordXY Position1, Position2;      // Declare variables with the new structure 

    

   wait (10);             // Wait 10 seconds to connect port 

 

   Position1.iX = 1;      // Sets Position1.iX only 

   Position1.iY = 2;      // Sets Position1.iY only 

   Position2.iX = 9;      // Sets Position2.iX only 

   Position2.iY = 6;      // Sets Position2.iY only 

   serial.printf("Position1.iX:%i, Position1.iY:%i\n\r", Position1.iX, Position1.iY); 

 

   Position1 = Position2; // Directly load Position1 from Position2 

   serial.printf("Position1.iX:%i, Position1.iY:%i\n\r", Position1.iX, Position1.iY); 

 

   for(;;) {}             // Loop forever } 

Output is: Position1.iX:1, Position1.iY:2 Position1.iX:9, Position1.iY:6 

#define #define lets you make a macro which substitutes a set of commands for just one.

/******************************************************************************* 

* This program demonstrates the use of #define                                 * 

* Jon Fuge V1.0 26/11/2013 First issue of code                                 * 

*******************************************************************************/ 

#include "mbed.h" #include "USBSerial.h"  #define Position1 Position.iX = 1; Position.iY = 2 // without parameters #define SetPosition(NewX, NewY) Position.iX = NewX; Position.iY = NewY // with parameters  struct coordXY { int iX; int iY; }; // Define a new structure  int main() {    USBSerial serial;      // Virtual serial port over USB. Use Teraterm as the interface    coordXY Position;      // Declare variable with the new structure        wait (10);             // Wait 10 seconds to connect port     Position1;             // Sets Position to Position1    serial.printf("Position.iX:%i, Position.iY:%i\n\r", Position.iX, Position.iY);     SetPosition( 9, 6 );   // Directly load Position1 from Position2    serial.printf("Position.iX:%i, Position.iY:%i\n\r", Position.iX, Position.iY);     for(;;) {}             // Loop forever } 

Output is: Position1.iX:1, Position1.iY:2 Position1.iX:9, Position1.iY:6 

RenBED C Programming Jump Starter Page 31

union 

union is a collection of variables of different types much like structure, however, unlike structure, all of the different types are stored in the same memory location. union can provide efficient memory usage by sharing a memory location with many variables, but can also be put to good use by converting data types. Word occupies the same space as Lo & Hi.

Word16‐bit number

Lo Hi2 x 8‐bit numbers

Writing to Word changes the values of Lo & Hi and vice-versa.

/*******************************************************************************

* This program demonstrates the use of union                                   * 

* Word occupies the same memory space as Lo,Hi allowing conversion between     * 

* 16‐bit numbers and two 8‐bit numbers                                         * 

*                                                                              * 

* Jon Fuge                                                                     * 

* V1.0 25/11/2013 First issue of code                                          * 

*******************************************************************************/ 

 

#include "mbed.h" 

#include "USBSerial.h" 

  

union uWord16 // Declare a new union { 

   uint16_t Word; // Word occupies two bytes 

   struct // this structure occupies the same space as Word 

   { 

      // ARM is little endian and stores the low byte first, then the high byte 

      uint8_t Lo, Hi; // Lo and Hi occupy one byte each 

   }; 

}; 

 

USBSerial serial; //Virtual serial port over USB. Use Teraterm as the interface 

 

int main() { 

   uWord16 Converter; // Declare Converter as a variable of type uWord16 

     

   Converter.Word = 0x1234; // load Word with a recognisable number 

 

   wait (10); // Wait 10 seconds to connect port 

    

   serial.printf("uiWord=%X\n\r", Converter.Word); 

   serial.printf("cHighByte=%X\n\r", Converter.Hi); 

   serial.printf("cLowByte=%X\n\r", Converter.Lo); 

 

   for(;;) {} // Loop forever 

} Output is: uiWord=1234 cHighByte=12 cLowByte=34 

RenBED C Programming Jump Starter Page 32

Bit Fields We have a value stored in a variable cMyNumber of type char and we want to know if it is odd or even. char is made up of 8 binary bits. Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0 128 64 32 16 8 4 2 1 From the table, we can see that if the number is odd, “Bit0” must be 1, if it is even, “Bit0” must be 0. This code does indeed work and generates the expected result that 53 is an odd number, but we need to do a bitwise AND calculation to determine if it is odd or even. The second example looks like there is more code, but it is more readable, and produces efficient code.

/******************************************************************************** This program demonstrates determines if a number is odd or even              * * Jon Fuge V1.0 26/11/2013 First issue of code                                 * *******************************************************************************/ #include "mbed.h" #include "USBSerial.h"   USBSerial serial; //Virtual serial port over USB. Use Teraterm as the interface  int main() {    char cMyNumber = 53; // Set it to an odd number     wait (10); // Wait 10 seconds to connect port        if ((cMyNumber & 0x01) == 1)       serial.printf("%i is odd\n\r", cMyNumber);    else       serial.printf("%i is even\n\r", cMyNumber);     for(;;) {} // Loop forever } 

/******************************************************************************** This program demonstrates determines if a number is odd or even              * * Jon Fuge V1.0 26/11/2013 First issue of code                                 * *******************************************************************************/ #include "mbed.h" #include "USBSerial.h"  union byte // Define new type “byte” {     char Byte; // Use this to map a byte     struct {        char Odd:    1; // this is the same as Bit0        char Others: 7; // Just fill the rest of the bits     }; };  USBSerial serial; // Virtual serial port over USB. Use Teraterm as the interface  int main() {    byte cMyNumber;      // Declare variable cMyNumber    cMyNumber.Byte = 53; // Set it to an odd number     wait (10); // Wait 10 seconds to connect port        if (cMyNumber.Odd == 1)       serial.printf("%i is odd\n\r", cMyNumber.Byte);    else       serial.printf("%i is even\n\r", cMyNumber.Byte);     for(;;) {} // Loop forever } 

Output is: 53 is odd 

Output is: 53 is odd 

RenBED C Programming Jump Starter Page 33

On the previous page we saw we mapped a char to access Bit0 as an odd indicator; the next bit of code takes it to the next level defining all bits in a byte for convenient access. The last piece of code has not added any revelations, but it does provide a few useful definitions so you can nowaccess each individual bit in a byte, which is a feature that is often used in embedded systems.

/******************************************************************************** This program demonstrates determines if a number is odd or even              * * Jon Fuge V1.0 26/11/2013 First issue of code                                 * *******************************************************************************/ #include "mbed.h" 

#include "USBSerial.h" 

 

union byte // Define new type “byte” { 

    char Byte; // Use this to map a byte     struct {        char Bit0: 1; // map individual 

       char Bit1: 1; // bits onto the 

       char Bit2: 1; // mapped byte. 

       char Bit3: 1; 

       char Bit4: 1; 

       char Bit5: 1; 

       char Bit6: 1; 

       char Bit7: 1; 

    }; 

}; 

 

USBSerial serial; // Virtual serial port over USB. Use Teraterm as the interface 

 

int main() { 

   byte cMyNumber;      // Declare variable cMyNumber 

   cMyNumber.Byte = 53; // Set it to an odd number 

 

   wait (10); // Wait 10 seconds to connect port 

    

   if (cMyNumber.Bit0 == 1) 

      serial.printf("%i is odd\n\r", cMyNumber.Byte); 

   else 

      serial.printf("%i is even\n\r", cMyNumber.Byte); 

 

   for(;;) {} // Loop forever 

} Output is: 53 is odd 

RenBED C Programming Jump Starter Page 34

for, do, while, break and continue // different types of loop A loop is used to perform a repetitive set of statements, there are three types of loops, which can be performed in C++which are similar but have small, but important differences.

continue Continue allows you to skip to the next continuation condition for a while, do, or for statement.

/****************************** *This program demonstrates the* *use of for, continue and     * *break.                       * *Jon Fuge                     * *V1.0 2/12/2013 First issue   * ******************************/ #include "mbed.h" #include "USBSerial.h"  #define Send serial.printf  int cValue[6] = {23, 54, 0,\                  19, ‐1, 33}; USBSerial serial;  int main() {    char cI = 0;    wait (5); // Wait 5s    for (cI = 0; cI < 6; cI ++) 

   { 

      if (cValue[cI] == 0) 

         continue; // skip on 0 

      if (cValue[cI] == ‐1) 

         break; // stop on ‐1 

      Send("%i,", cValue[cI]); 

   } 

   for (;;) {} // Loop forever 

 

 

Initialise

Condition

Code block

Increment

Rest of code

/*******************************This program demonstrates the* *use of for, continue and     * *break.                       * *Jon Fuge                     * *V1.0 2/12/2013 First issue   * ******************************/ #include "mbed.h" #include "USBSerial.h"  #define Send serial.printf  int cValue[6] = {23, 54, 0,\                  19, ‐1, 33}; USBSerial serial;  int main() {    char cI = 0;    wait (5); // Wait 5s    do {       if (cValue[cI] == 0) 

      { 

         cI ++; 

         continue; // skip on 0 

      } 

      if (cValue[cI] == ‐1) 

         break; // stop on ‐1 

      Send("%i,", cValue[cI]); 

      cI ++; 

   } while (cI < 6); 

   for (;;) {} // Loop forever 

 

 

Code block

Rest of code

Condition

/*******************************This program demonstrates the* *use of for, continue and     * *break.                       * *Jon Fuge                     * *V1.0 2/12/2013 First issue   * ******************************/ #include "mbed.h" #include "USBSerial.h"  #define Send serial.printf  int cValue[6] = {23, 54, 0,\                  19, ‐1, 33}; USBSerial serial;  int main() {    char cI = 0;    wait (5); // Wait 5s    while (cI < 6) {       if (cValue[cI] == 0) 

      { 

         cI ++; 

         continue; // skip on 0 

      } 

      if (cValue[cI] == ‐1) 

         break; // stop on ‐1 

      Send("%i,", cValue[cI]); 

      cI ++; 

   }; 

   for (;;) {} // Loop forever 

 

 

Code block

Rest of code

Condition

Output is: 23,54,19, 

while (Condition) { Code block } Rest of code Tests before!

do { Code block } while (Condition) Rest of code Tests after!

For( Initialise; Condition; Increment) { Code block } Rest of code

Tests before!

break allows you to exit a while, do, or for statement.

continue allows you to skip to the next loop of a while, do, or for statement.

Output is: 23,54,19, 

Output is: 23,54,19, 

RenBED C Programming Jump Starter Page 35

if, else, switch, case, default and break // types of conditional statements                                             switch can be used to replace a series of sequential ifs, however, if can evaluate more than just “Equal to” as can be seen in the table of “Relational operators” below; also, “Relational operators” can be linked to make more powerful conditions with “Logical operators”

/****************************** *This program determines if   * *the temperature is just right* *cold, too cold, warm or too  * *warm using “if”              * *Jon Fuge                     * *V1.0 2/12/2013 First issue   * ******************************/ #include "mbed.h" #include "USBSerial.h"  #define Send serial.printf  USBSerial serial;  // Declare constants 

const char cCOLD   =     23; const char cJUST_RIGHT = 24; const char cWARM =       25;  // declare prototype for GetTemperature. char GetTemperature(void);  int main() {    char cTemperature = GetTemperature();  

   wait (5); // Wait 5 seconds to connect    if (cTemperature == cCOLD) { 

      Send("Cold\n\r"); 

   } else { 

      if (cTemperature == cWARM) { 

         Send("Warm\n\r"); 

      } else { 

         if (cTemperature == cJUST_RIGHT) { 

            Send("Just right\n\r"); 

         } else { 

            Send("Too hot or too cold\n\r"); 

   } } 

 char GetTemperature(void) {    return (cJUST_RIGHT); } 

/****************************** *This program determines if   * *the temperature is just right* *cold, too cold, warm or too  * *warm using “switch           * *Jon Fuge                     * *V1.0 2/12/2013 First issue   * ******************************/ #include "mbed.h" #include "USBSerial.h"  #define Send serial.printf  USBSerial serial;  // Declare constants 

const char cCOLD   =     23; const char cJUST_RIGHT = 24; const char cWARM =       25;  // declare prototype for GetTemperature. char GetTemperature(void);  int main() {    char cTemperature = GetTemperature();  

   wait (5); // Wait 5 seconds to connect    switch (cTemperature) { 

      case cCOLD:       Send("Cold\n\r"); 

                        break; 

      case cWARM:       Send("Warm\n\r"); 

                        break; 

      case cJUST_RIGHT: Send("Just right\n\r"); 

                        break; 

      default:          Send("Too hot or too\ 

                             cold\n\r"); 

   } } 

 char GetTemperature(void) {    return (cJUST_RIGHT); } 

Relational operators: Operator Operation

==  Equal to !=  Not Equal to >  Greater than <  Less than >=  Greater than or equal to <=  Less than or equal to

Logical operators: Operator Operation

&& Logical AND || Logical OR ! Logical NEGATION

break exits the switch statement.

RenBED C Programming Jump Starter Page 36

goto goto allows you to interrupt the normal processing of your code and jump to another location. the use of goto is frowned upon and leads to difficult to read and manage code so is generally not used except as an error trap to interrupt the normal flow of a program. The use of goto falls into a similar category as asm, its use should be avoided at all costs and doing so will lead to more readable code which can be re-used.

/******************************************************************************* 

* This program demonstrates the use of goto                                    * 

*                                                                              * 

* Jon Fuge                                                                     * 

* V1.0 3/12/2013 First issue of code                                           * 

*******************************************************************************/ 

#include "USBSerial.h"  int main() {    BadLabel:     // code would go here 

   goto BadLabel; }

asm asm lets you add assembly language to your code for “hand” optimised code. asm requires an expert knowledge of theprocessor and is rarely used. The use of in-line assembly language is frowned upon because this stops your code from being “transportable” so a largeamount of effort would be required to transfer the code to another processor; it also makes the code difficult to read bymost programmers. If anyone suggests using “machine code” or “assembly language”, please offer them a nice sweet cup of tea and sit downand reminisce about the “good old days” with them, they will probably want to discuss the obvious benefits of punchedcard for data storage and the use of dekatrons as a debugger. If they still think there is a need for machine code due tousing an 8 bit processor and slow clocks, it would be a good time to share the benefits of a modern ARM processor.

/******************************************************************************* 

* This program demonstrates the use of asm                                     * 

* no actual in‐line assembly code has been added, only the structure of the    * 

* use of asm has been shown.                                                   * 

*                                                                              * 

* Jon Fuge                                                                     * 

* V1.0 3/12/2013 First issue of code                                           * 

*******************************************************************************/ 

int main() {    asm     { 

      // assembly code 

   } 

RenBED C Programming Jump Starter Page 37

Functions, procedures, void & return // help you write better code Functions and procedures are very similar in the way that they operate and are defined, their use is essential forwriting good ‘C’ code, and you can also benefit by being able to re-use functions and procedures elsewhere in yourcode and even use them again in other programs. Every program has at least 1 function. The difference between functions and procedures is that a function has a type before its declaration so it can returna value when it terminates. Procedures have a void before the declaration meaning it does not return a value. Procedures and functions can have parameters passed to them. To pass a parameter, we add the type and name ofthe parameter between the brackets; if we want to add more parameters we do so by separating them with commas.

int main ()

/******************************************************************************* * This program demonstrates the use of functions and procedures                * * Jon Fuge V1.0 26/11/2013 First issue of code                                 * *******************************************************************************/ #include "mbed.h" #include "USBSerial.h"  // Prototype functions and procedures are always declared before main! int GetNumberFromUser(void);  // Get the value from the user int SquareNumber(int iX);      // Get the square of x void SendSquareToUser(int iX); // Output our square to the user  USBSerial serial; // Virtual serial port over USB. Use Teraterm as the interface  int main() {    int UserNumber;    int SquareUserNumber;        wait (5); // Wait 5 seconds to connect port        for(;;) // start an endless loop.    {       UserNumber = GetNumberFromUser();         SquareUserNumber = SquareNumber(UserNumber);       SendSquareToUser(SquareUserNumber);    } }  int GetNumberFromUser(void) {    char buf[128]; // A char array is also a string!    for (;;) { // Keep looping until we get a valid number       serial.printf("Enter a number between 0 & 9:\r\n");       serial.scanf("%s", buf); // Receive message from USB serial port       if ((buf[0] >= '0') && (buf[0] <= '9')) // We can only process single digit numbers       {          serial.printf("%c is a great choice!\r\n", buf[0]);          return (buf[0] ‐ '0'); // Convert number from ASCII to decimal       }       serial.printf("I didn't like that, try again!\r\n");    } }  int SquareNumber(int iX) {    return (iX*iX); // return the value of x*x (x squared). }  void SendSquareToUser(int iX) {    serial.printf("The square is %i\r\n", iX); } 

A function returns a value,  a  procedure doesn’t. 

Tip… Use tabs or 3 spaces to indent your code making it more readable.

Output is: Enter a number between 0 & 9: 5 is a great choice! The square is 25 

RenBED C Programming Jump Starter Page 38

Modules, headers and re-use // help you write better code Dividing your program into multiple files or modules is a good practise to learn; this will help you produce code whichis more maintainable by keeping similar and dependent functions together and give you the chance to build up alibrary of useful functions which you can use in future programs. Modules can be divided into two parts, the header is stored in a .h file which contains all the public parts such asmacros, typedef’s, function prototypes and constants. The private parts of a module are stored in a .cpp file.

Header Files It is very common for headers to include other headers which can lead to problems when multiple instances of thesame definition exist; this can be overcome by the addition of the following code … The body of the header is only seen by the compiler if UNIQUE_MACRO_NAME is not defined, then it is immediatelydefined. To demonstrate the use of modules and how easy they are to create, we will look at the example on the previous page introducing functions and procedures splitting the original “main.c” file into three new files “UserNumber.h”, “UserNumber.cpp” and a cut down version of our original “main.c”. Although this example does not yield any reusable functions, it does demonstrate how we could use the files “UserNumber.h” and “UserNumber.cpp” again in future programs by copying the header and .cpp file into a new program and using #include "UserNumber.h" to reference them… 

UserNumber.h:

/******************************************************************************* 

* This is an example header file                                               * 

*                                                                              * 

* Jon Fuge                                                                     * 

* V1.0 3/12/2013 First issue of code                                           * 

*******************************************************************************/ 

#ifndef UNIQUE_MACRO_NAME #define UNIQUE_MACRO_NAME  

  // Add the body of your header here 

 

#endif 

/******************************************************************************* 

* This header groups the user / number handling functions                      * 

*                                                                              * 

* Jon Fuge                                                                     * 

* V1.0 3/12/2013 First issue of code                                           * 

*******************************************************************************/ 

#ifndef USERNUMBER #define USERNUMBER    int GetNumberFromUser(void);   // Get the value from the user    int SquareNumber(int iX);      // Get the square of x    void SendSquareToUser(int iX); // Output our square to the user #endif 

RenBED C Programming Jump Starter Page 39

UserNumber.cpp:

main.cpp:

/******************************************************************************* * This file contains the functions and procedures prototyped in UserNumber.h   * * Jon Fuge                                                                     * * V1.0 3/12/2013 First issue of code                                           * *******************************************************************************/  #include "mbed.h" #include "USBSerial.h"  USBSerial serial; // Virtual serial port over USB. Use Teraterm as the interface  int GetNumberFromUser(void) {    char buf[128]; // A char array is also a string!    for (;;) { // Keep looping until we get a valid number       serial.printf("Enter a number between 0 & 9:\r\n");       serial.scanf("%s", buf); // Receive message from USB serial port       if ((buf[0] >= '0') && (buf[0] <= '9')) // We can only process single digit numbers       {          serial.printf("%c is a great choice!\r\n", buf[0]);          return (buf[0] ‐ '0'); // Convert number from ASCII to decimal       }       serial.printf("I didn't like that, try again!\r\n");    } }  int SquareNumber(int iX) {    return (iX*iX); // return the value of x*x (x squared). }  void SendSquareToUser(int iX) {    serial.printf("The square is %i\r\n", iX); } 

/******************************************************************************* * This program demonstrates the use of functions, procedures and modules       * * Jon Fuge                                                                     * * V1.0 3/12/2013 First issue of code                                           * *******************************************************************************/  #include "mbed.h" #include "UserNumber.h"  

int main() {    wait (5); // Wait 5 seconds to connect port        int UserNumber;    int SquareUserNumber;        for(;;) // start an endless loop.    {       UserNumber = GetNumberFromUser();         SquareUserNumber = SquareNumber(UserNumber);       SendSquareToUser(SquareUserNumber);    } } 

RenBED C Programming Jump Starter Page 40

Appendix 1 How do you get an MBED account? Open up Internet explorer (or other web browser) type www.mbed.org

To create your first account, click "Login or Signup"

RenBED C Programming Jump Starter Page 41

Now Press "Signup"

Enter your details...

RenBED C Programming Jump Starter Page 42

Providing all has gone well, you have now created an mbed account, if not, please repeat the steps.

RenBED C Programming Jump Starter Page 43

Appendix 2 Importing a Project Log into www.mbed.org and click onto "Compiler", you will see something similar to below.

If you have not previously opened a project, you can click on "import a program" (in the middle of the screen);

otherwise, you can click on the "import button". Tip: if using internet explorer, pressing the F11 button will make this full screen giving you the maximum available space to use.

RenBED C Programming Jump Starter Page 44

For this example, we will choose the program "mbed_blinky"; however, you can select one that suits your requirements. Click on the name in the list so it is highlighted and the program details are displayed (Tip,

clicking on the next to “mbed_blinky” will bookmark it to make it easy to find in the future). Click "Import"

You will be given a window to edit the program details, we’ll leave it set to the defaults, click the “Import” button

RenBED C Programming Jump Starter Page 45

“Main.cpp” is the main program that is compiled for the project, click on it to bring up the code.

For this workshop, we’ll change the output pin from “LED1” to use DIP36 on RenBED (P0_21) Edit Line 3 and replace “LED1” with “P0_21”.

For a new account, you probably do not have a device selected; the compiler will need to know this so your program can be compiled into a form that RenBED can use.

RenBED C Programming Jump Starter Page 46

Appendix 3 Create a new project Log into www.mbed.org and click onto "Compiler", you will see something similar to below.

If you have not previously opened a project you can click on "create a new one" (in the middle of the screen); otherwise, you can click on the "New" button (if you are asked, you want a new program. A useful tip (if using internet explorer, pressing the F11 button will make this full screen giving you the maximum available space to use).

RenBED C Programming Jump Starter Page 47

Change the Template to "Empty Program" if it’s not already there; I'll call this "ReadButton"

Your empty project has been created, and it is just that, empty!

RenBED C Programming Jump Starter Page 48

Appendix 4 Adding a file Let us add a file to write our first program. Click the "V" to the right of the "New" button and click on "New

File...” In the create new file box, enter the file name "main.cpp" then click OK.

Once created, click on "main.cpp" to bring up the editor window.

RenBED C Programming Jump Starter Page 49

For this example, we will read a button and toggle an LED, to do this copy the program below and paste or

type it into the "main.cpp" editor window.

Now we have the code entered, but we need to add the “mbed.h” library to our program or it will not compile.

/******************************************************************************** This program demonstrates how to read a switch and toggle a LED.             * * Connect LED and resistor between to DIP36 (P0_21) and DIP1 (0V).             * * Connect switch between DIP5 (P0_9) and DIP1 (0V).                            * *                                                                              * * Jon Fuge                                                                     * * V1.0 12/11/2013 First issue of code                                          * *******************************************************************************/  #include "mbed.h" // has prototypes for DigitalIn and DigitalOut  DigitalIn  mybutton(P0_9); // mybutton reads bit  9 of port 0 (DIP5). DigitalOut myled(P0_21);   // myled controls bit 21 of port 0 (DIP36).  int main() {    mybutton.mode(PullUp); // Configure pin to be a pull‐up input    for(;;) { //Create infinite loop to keep program running.       if (mybutton == 0) { // if mybutton = 0, then it has been pressed          myled = !myled; // myled will now become !myled (! means NOT).          wait(0.1); // Wait for 0.1 seconds to "debounce" the switch.          while (mybutton == 0) {} // Wait for my button to be released.       } // End of if (mybutton == 0)    } // End of for(;;) } // end of int main() 

RenBED C Programming Jump Starter Page 50

Appendix 5 Add an existing library to your program

Click “Import”, in the window, click on the “Libraries” tab, then type “mbed.h” (or whatever library you want) in “Search criteria …” and click the “Search” button.

The top “mbed” file with thousands of previous imports is the one we want to use. Click on “mbed” to highlight it, then click “Import!”. (Tip, we are likely to use this library often, by clicking on the � next to “mbed” will bookmark it to make it easy to find in the future).

Click “Import”, in the window, Leave Import name as “mbed”, Target Path should be “ReadButton”.

RenBED C Programming Jump Starter Page 51

You will see that “mbed” brings in many files, we can make the screen easier to read by clicking the “-“ to the left of

the “mbed” folder icon.

If you have not already done so, you will need to select a target device.

RenBED C Programming Jump Starter Page 52

Appendix 6 Select The Target Device To select what device we are going to use, you need to know what platform you are going to use. To know which platform to use, the following will help... For RenBED, use mbed 11U24. Now click on the top right "No device selected" statement.

Click "Add a device"

RenBED C Programming Jump Starter Page 53

Now click on "mbed LPC11U24"

Click "Add to mbed Compiler"

Return to the compiler by clicking “Compiler” at the top right of the screen.

RenBED C Programming Jump Starter Page 54

Appendix 7 Compile your program With the target selected, click on "main.cpp" to open the program window.

Now you can compile your first program... Click "Compile" in the middle of the top buttons.

RenBED C Programming Jump Starter Page 55

If everything has gone well, your file will be downloaded and the compile status will be updated with a success

message. If there are any errors in your code they will be identified in the bottom window, double clicking on any message will take you to the specific line in your code which has caused the problem; correct all problems and re-try compiling.

Well done, you are now set up to use mbed and have compiled your program!

RenBED C Programming Jump Starter Page 56

Appendix 8 Programming RenBED

You will have completed the above steps and compiled your project, you should either be prompted for a place to save your ".bin" file, or it has gone off to the downloads folder.

Before you can do anything, you will need to connect RenBED to your PC. o Connect RenBED to your PC using the USB lead. o Put RenBED into "Programming mode", press the left button with "ISP" next to it, a yellow LED will

illuminate.

o Your PC will recognize RenBED as a USB pen drive with the label "CRP DISABLD". Make a note of the drive letter, for me it is "O:"

RenBED C Programming Jump Starter Page 57

o Navigate to the RenBED drive, and delete the "firmware.bin" file that is there.

RenBED C Programming Jump Starter Page 58

If your internet browser is asking you to save the ".bin" file in a location, navigate to the now empty RenBED drive and save the file there.

You have now programmed RenBED with your program, to start the program running press the right button "Reset".

If your browser has saved the ".bin" file to the "downloads" folder, you will need to copy the file from there. o Click on the browser window, then press CTRL-J.

FromGoogleChromebrowser...

o Click "Open downloads folder"

RenBED C Programming Jump Starter Page 59

FromInternetExplorerbrowser...

Click the destination folder under "Location"

RenBED C Programming Jump Starter Page 60

My downloaded files are saved to “Jon” on my Z: drive. Copy "mbed_blinky_LPC11U24.bin" by dragging it onto "CRP_DISABLD (O:)", you drive might have a different

location / letter. There is no need to rename the ".bin" file; this will be done for you by RenBED. If you encounter any problems (most likely, disk is full) it is likely that you have not deleted the "firmware.bin"

file stored on RenBED, you will need to do this before you can copy a new file. You have now programmed RenBED with your program, to start the program running press the right button

"Reset". Providing all has gone well, your LED will now flash.