310 likes | 467 Views
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 .
E N D
EMS1EP Lecture 7Program 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
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
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
Flow diagram Processing Start or End Logical Decision
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 Flow diagram – Flash LED
Flow diagram – Button controlled LED Setup Pins Is button pressed? Set LED ON Set LED OFF 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); } }
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 Flow diagram class exercise
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
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
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)
Example Function voidflashLED5Times(){ int counter = 5; while(counter > 0){ digitalWrite(LED1,LOW); //LED ON delay(500); digitalWrite(LED1,HIGH); //LED OFF delay(500); counter--; } }
Example Function int factorial(int factorial_order){ int factorial_result = 1; while(factorial_order > 0){ factorial_result *= factorial_order; factorial_order--; } return factorial_result; }
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 Comments
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 */ voidflashLED5Times(){ int counter = 5; while(counter > 0){ digitalWrite(LED1,LOW); //LED ON delay(500); digitalWrite(LED1,HIGH); //LED OFF delay(500); counter--; } }
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
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
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
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
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 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); //Hex Serial.print(counterValue,OCT); //Octal Serial.print(counterValue,BIN); //Binary Serial Comms: Arduino -> PC
Write code to output the following data to a terminal using a loop and a variable which is decremented: Count Down Timer Count=5 Count=4 Count=3 Count=2 Count=1 Count finished Serial Comms: Arduino -> PCClass Exercise
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” Serial Comms: Terminal Programs
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
PC can also send data to the Arduino to make it do things If(Serial.available()){ //If there is at least 1 character received char c = Serial.read(); if(‘a’ == c){ //If the character was an ‘a’ //Do something } } Serial Comms: PC -> Arduino
ASCII – Data format • Data sent as ASCII characters • If you want to use numbers – need to convert them from ASCII to decimal (subtract 0x30)
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
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 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
Declaring Data types //Characters char char1 = 0; //Same as signed character signed char char2 = 0; //Signed character unsigned char char3 = 0; //Unsigned character //Integers int i1 = 0; //Same as signed integer signed int i2 = 0; //Signed integer unsigned int i3 = 0; //Unsigned integer float f1 = 5.221//For floating point numbers double d1 = 5212025.122 //Large floating point numbers
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