31
EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Embed Size (px)

Citation preview

Page 1: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

EMS1EP Lecture 7Program Structure and Serial I/O

Dr. Robert Ross

Page 2: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Overview (what you should learn today)

• Program structure:– Flow diagrams– Functions– Comments– Libraries for other functionality

• Serial I/O:– Baud rates– Sending data from Arduino– Receiving data with Arduino

• Data Types

Page 3: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Program Structure

• Sometimes people try to write everything in the main loop() function

• Bad design practice:– OK for very small amounts of code– Hard to read– Difficult to see the flow of code – the big picture

Page 4: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Flow diagrams

• As programs get more complex it is good to design them on paper first before writing the code– Saves time– Detect errors earlier– Good to refer back to later for quick understanding

• Flow diagrams are one good design on paper technique for designing algorithms

• Another way – pseudo code

Page 5: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Flow diagram

Start or End Processing

Logical Decision

Page 6: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Flow diagram – Flash LED

int ledPin = 10;void setup() {

pinMode(ledPin, OUTPUT);}

void loop() { digitalWrite(ledPin, LOW); //LED ON delay(1000); // Wait 1S

digitalWrite(ledPin, HIGH); // LED OFF

delay(1000); // Wait 1S

}

Setup Pins

Set LED ON

Delay

Set LED OFF

Delay

Page 7: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Flow diagram – Button controlled LED

Setup Pins

Set LED ON

Set LED OFF

Is button pressed?

int ledPin = 10;int buttonPin = 9;void setup() {

pinMode(ledPin, OUTPUT);pinMode(buttonPin, INPUT);

}

void loop() {

if (LOW == digitalRead(buttonPin)){digitalWrite(ledPin, LOW);

}else{

digitalWrite(ledPin, HIGH);}

}

Page 8: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Flow diagram class exercise

• Solve the following problem using a flow diagram to develop the algorithm– Create a 3 bit counter– If a button is pressed the counter should count

down– If the button isn’t pressed the counter should

count up

Page 9: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Functions

• Functions are blocks of code that can be reused• Also called procedures in some languages• Typically have a specific function or purpose• May be implementations of one of the blocks from

the flow diagram• Advantages:

– Reuse -> reliability– Hides implementation -> Easier to read code– Separates functional blocks

Page 10: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Functions

• To use functions they need to be called• We can pass data to functions (the functions

may need this data to compute a result)• We can receive data from functions – this is

the functions return result• Functions are written outside your loop()

(normally underneath) and can be called from within the loop or from other functions

Page 11: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Functions• General form of a function:return_type function_name(arg_type arg_name, ... ){

statements;}

• return_type: The type of the data that will be returned (eg. char, unsigned int, signed int ect). If the function has no return value, then use: void

• function_name: What you call your function (eg. dly123)• arg_type: The type of data supplied as arguments (eg. int,

char). If there are no arguments, then use: void• arg_name: The names of the arguments (eg. test_value)

Page 12: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Example Function

void flashLED5Times(){int counter = 5;

while(counter > 0){digitalWrite(LED1,LOW); //LED ONdelay(500);digitalWrite(LED1,HIGH); //LED OFFdelay(500);counter--;

}}

Page 13: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Example Function

int factorial(int factorial_order){int factorial_result = 1;

while(factorial_order > 0){factorial_result *= factorial_order;factorial_order--;

}

return factorial_result;}

Page 14: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Comments

• Comments are parts of the codes which the compiler ignores• Comments are there for the programmers benefit

• Types of comments:– Inline comments: Start with // and go until the end of the line– Block comments: Start with /* end with */ and may go over multiple

lines

• Use comments to clarify any code which isn’t clear• Use a block comment to describe what each of your functions

does

Page 15: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Function Comments/* func: flashLED5Times * desc: When called this function flashes an LED 5 times. * For each flash the LED is on for 500ms and off for 500ms * param: no parameters * result: no return value*/void flashLED5Times(){

int counter = 5;while(counter > 0){

digitalWrite(LED1,LOW); //LED ONdelay(500);digitalWrite(LED1,HIGH); //LED OFFdelay(500);counter--;

}}

Page 16: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Other libraries

• People have written lots of libraries to interface with many different devices

• These are included in the Arduino software and allow for quick programs to be developed

• Later on we will use a servo library to allow us to interface servo motors with the Ardiuno

Page 17: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Serial Comm: Intro

• In first lecture brief examples of sending “hello world” to the computer from the Arduino

• Much more that we can do with it– Sending strings– Sending data or variable values– Receiving characters from the PC

Page 18: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Serial Comms: baud rate

• Need to choose a baud rate (or data rate)• Specifies the amount of bits per second (bps)

that will be sent• Needs to be the same at both the sender and

the receiver• Standard values:

– 2400, 4800, 9600, 19200

Page 19: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Serial Comms: baud rate

• Choosing the baud rate will depend on how much data you need to send

• Slower baud rate tends to be more reliable – less corruption

• Faster baud – can send more data in fixed time• Each time a character (8 bits) is sent a start and stop

bit is also sent• For 2400baud -> 2400 / (8+2) = 240 characters per

second that can be sent (not very many)• Often default is 9600 baud

Page 20: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Serial Comms: Arduino -> PC

• Before serial data can be sent it first needs to be setup

• One line of code in the setup() function– Serial.begin(<baud rate>);– baud rate = 4800, 9600, 19200 ect.

• Make sure you set the same baud rate on the PC end

Page 21: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Serial Comms: Arduino -> PC• Use Serial.print(<data to print>) to send the data

to the PC• Can be strings or values:

Serial.print(“Hello there”);Serial.print(counterValue);Serial.println(“Test123”); //Prints a newline character to go to the next line in the terminal

//Function can be overloaded to transmit data in different formats

Serial.print(counterValue,DEC); //Decimal Serial.print(counterValue,HEX); //HexSerial.print(counterValue,OCT); //OctalSerial.print(counterValue,BIN); //Binary

Page 22: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Serial Comms: Arduino -> PCClass Exercise

• Write code to output the following data to a terminal using a loop and a variable which is decremented:

Count Down TimerCount=5Count=4Count=3Count=2Count=1Count finished

Page 23: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Serial Comms: Terminal Programs

• The terminal is where received data can be viewed and sent from on the PC

• Data is all transmitted over the USB port• In the Arduino IDE use the “Serial Monitor”

Page 24: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Serial Comms: Terminal Programs

• Lots of other terminal programs are around – some of which have more functionality (eg. Strings can be stored and send or encoded for specific protocols)

• Windows generally comes with HyperTerm• A decent free terminal with lots of features is RealTerm

Page 25: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Serial Comms: PC -> Arduino

• PC can also send data to the Arduino to make it do thingsIf(Serial.available()){

//If there is at least 1 character receivedchar c = Serial.read();if(‘a’ == c){ //If the character was an ‘a’

//Do something }

}

Page 26: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

ASCII – Data format

• Data sent as ASCII characters• If you want to use numbers – need to convert them from

ASCII to decimal (subtract 0x30)

Page 27: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Serial Comms: Class exercise

• Write code to mirror back anything that is typed on the terminal

• The Arduino should receive the terminal character and send it back again

Page 28: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Data Types

• Different data types are different sizes• C has the following standard data types:

• These data types can be modified using key words to change their size and the way they store data (how these modify are compiler dependent)

Data Type Size (Bits) Range of Valueschar 8 -128 to 127int 16 -32768 to +32767long int 32 -2147483648 to + 2147483647float 32 3.4x10-38 to 3.4x10+38

double 64 1.7x10-308 to 1.7x10+308

Page 29: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Data Type Modifiers: (signed/unsigned)

• Signed number have both a positive and negative number (for 2’s complement signed numbers the top bit is a signed bit)

• Unsigned numbers are only positive • Eg:

– signed char (range -128 to 127)– unsigned char (range: 0 to 255)– signed int (range -32768 to +32767)– unsigned int (range 0 to +65535)

• How to calculate: (based on n bits)– signed: range -2n-1 to (2n-1)-1– unsigned: range 0 to (2n)-1

Page 30: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Declaring Data types//Characterschar char1 = 0; //Same as signed charactersigned char char2 = 0; //Signed characterunsigned char char3 = 0; //Unsigned character

//Integersint i1 = 0; //Same as signed integersigned int i2 = 0; //Signed integerunsigned int i3 = 0; //Unsigned integer

float f1 = 5.221 //For floating point numbers

double d1 = 5212025.122 //Large floating point numbers

Page 31: EMS1EP Lecture 7 Program Structure and Serial I/O Dr. Robert Ross

Summary(What you learnt in this session)

• Functions are good as they logically break up program functionality and improve reliablity

• Comments are your friend (along with anyone trying to read your code afterwards)

• Sending serial data can be useful for debugging and communicating with the PC

• Lots of different data types available to you – use them carefully