2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Similar documents
T H E I N T E R A C T I V E S H E L L

Variables and Data Representation

Grade 6 Math Circles November 6 & Relations, Functions, and Morphisms

CS102: Variables and Expressions

Memory Addressing, Binary, and Hexadecimal Review

printf( Please enter another number: ); scanf( %d, &num2);

Intro. Scheme Basics. scm> 5 5. scm>

1.7 Limit of a Function

Lab 01 Arduino 程式設計實驗. Essential Arduino Programming and Digital Signal Process

OrbBasic Lesson 1 Goto and Variables: Student Guide

CSE / ENGR 142 Programming I

OrbBasic 1: Student Guide

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Binary, Hexadecimal and Octal number system

Programming with Python

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

3. Simple Types, Variables, and Constants

These are notes for the third lecture; if statements and loops.

Variables and Functions. ROBOTC Software

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

Text Input and Conditionals

Variables and Constants

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

If Statements, For Loops, Functions

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Topic. Section 4.1 (3, 4)

Expressions and Casting

Table of Laplace Transforms

Here are a couple of warnings to my students who may be here to get a copy of what happened on a day that you missed.

Post Experiment Interview Questions

[ the academy_of_code] Senior Beginners

Arduino IDE Friday, 26 October 2018

Repetition Through Recursion

Procedures, Parameters, Values and Variables. Steven R. Bagley

CS 64 Week 0 Lecture 1. Kyle Dewey

FILE ORGANIZATION. GETTING STARTED PAGE 02 Prerequisites What You Will Learn

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

PYTHON YEAR 10 RESOURCE. Practical 01: Printing to the Shell KS3. Integrated Development Environment

Number Systems MA1S1. Tristan McLoughlin. November 27, 2013

Exercise: Inventing Language

Computer Science 324 Computer Architecture Mount Holyoke College Fall Topic Notes: Bits and Bytes and Numbers

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Topic 3: Fractions. Topic 1 Integers. Topic 2 Decimals. Topic 3 Fractions. Topic 4 Ratios. Topic 5 Percentages. Topic 6 Algebra

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Lesson 4. Objective: Compare and classify quadrilaterals. Lesson Suggested Lesson Structure. Multiply by 4 (8 minutes)

SPRITES Moving Two At the Same Using Game State

(Refer Slide Time: 00:23)

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

How to approach a computational problem

RIS shading Series #2 Meet The Plugins

Introduction. What is Max?

CIS 45, The Introduction. What is a database? What is data? What is information?

COPYRIGHTED MATERIAL. Getting Started with Google Analytics. P a r t

CS2630: Computer Organization Homework 1 Bits, bytes, and memory organization Due January 25, 2017, 11:59pm

Note. The above image and many others are courtesy of - this is a wonderful resource for designing circuits.

MA 1128: Lecture 02 1/22/2018

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

ENGR 40M Project 3c: Switch debouncing

CMSC 201 Computer Science I for Majors

C++ Reference NYU Digital Electronics Lab Fall 2016

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Lesson 2A Data. Data Types, Variables, Constants, Naming Rules, Limits. A Lesson in Java Programming

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Recursively Enumerable Languages, Turing Machines, and Decidability

MySQL: an application

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Maciej Sobieraj. Lecture 1

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That

CSE 120. Computer Science Principles

Lesson 5: LDR Control

First Java Program - Output to the Screen

Lesson 8: Simon - Arrays

Make a Guessing Game with Python

4. Java Project Design, Input Methods

Here are some of the more basic curves that we ll need to know how to do as well as limits on the parameter if they are required.

Topic Notes: Bits and Bytes and Numbers

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

Introduction to Counting, Some Basic Principles

Abstract. Chapter 6 Writing a Program. Overview. Writing a program: Strategy. Building a program. Bjarne Stroustrup

BB4W. KS3 Programming Workbook INTRODUCTION TO. BBC BASIC for Windows. Name: Class:

4.7 Approximate Integration

Robert Ragan s TOP 3

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Lesson 1. Introduction to Programming OBJECTIVES

This is a book about using Visual Basic for Applications (VBA), which is a

CITS2401 Computer Analysis & Visualisation

The Dynamic Typing Interlude

CS354 gdb Tutorial Written by Chris Feilbach

Pointers in C/C++ 1 Memory Addresses 2

Adding content to your Blackboard 9.1 class

Lab # 02. Basic Elements of C++ _ Part1

AN INTRODUCTION PROGRAMMING. Simon Long

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

n! = 1 * 2 * 3 * 4 * * (n-1) * n

Variables, expressions and statements

Repetition CSC 121 Fall 2014 Howard Rosenthal

Ex: If you use a program to record sales, you will want to remember data:

Transcription:

Remembering numbers (and other stuff)... Let s talk about one of the most important things in any programming language. It s called a variable. Don t let the name scare you. What it does is really simple. A variable is like a post-it note or a scrap of paper you can use to remember a number. Imagine you have a task where you need to remember how many birds, squirrels, and dinosaurs you see outside your window during the week. I track my own count of birds, squirrels, and dinosaurs using post-it notes stuck to my window. Each note is labeled: birds, squirrels, and dinosaurs. Then I keep track of each count on the corresponding post-it note. Computers keep track of numbers in a similar way, except instead of using post-it notes, they use spaces in their memory. A variable is just a way to name a certain spot in memory so you can store a number in that memory space, then use that number again later. You can name a variable almost anything you want. Normally you ll pick a name that makes sense and relates to whatever you plan to store in the variable. In this case, birds makes sense if you are counting how many birds you ve seen this week. You could keep track of birds using a variable named lostsocks, but that wouldn t make much sense, though lostsocks would still work. Lets consider this example... birds = 10; This puts the number 10 inside the variable named birds. This line of code will remove whatever was previously stored in the memory space named birds and replace it with the number 10. This is also sometimes called an assignment, as in, the number 10 is assigned to the birds variable. Experienced programmers would call the equals sign an assignment operator, but you don t need to remember that for now. You can also store the results of math in a variable. Let s consider this example... birds = 10; //birds now holds 10 birds = 2 + 3; //birds now holds 5 The second line adds 2 and 3, then takes the result of that addition and puts it back in birds. The previous value of 10 is erased and replaced by the new value of 5. You can also use the variable itself in the math if you want. This is often very useful, for example, if you re counting something. In the next example, we give birds a starting value. In the second line, we use whatever is already in the variable and do some math on it, then put the result back in the variable. birds = 10; //birds now holds 10 birds = birds + 1; //birds now holds 11 The second line takes what ever value is already present in birds, then adds 1 to it, then takes the result and puts it back in birds.

Declaring variables... Before you can actually use a variable for the first time, you have to tell the program ahead of time that you plan to use it. This tells the processor to automatically reserve a space in memory to hold the value you will eventually place inside the variable. This process of telling the program that you plan to use a variable is called declaring the variable. Kind of like, if you were going to count jelly beans, you may get a scrap of paper and label it jellybeans before you actually use it to count your beans. You only declare each variable one time. int jellybeans; //this declares the variable jellybeans This is how you declare a variable. You need to do this for every variable your program uses. A variable declaration needs at least two things. The first part is the type of variable. There are many different types of variables that can be declared depending on what you plan to store in the variable. The first part of the declaration ( int in this case) is the type of variable you are declaring, and the second part ( jellybeans in this case) is the name you are giving to the variable. The int variable type stands for integer. This is a very flexible variable type and is commonly used within Arduino code projects. The int variable type can store any whole number between -32,768 and 32,767. You can NOT store decimal numbers in an int type. (More on that later). You can name a variable almost anything you want as long as you follow a few simple rules. 1. Variable names can include upper case letters, lower case letters, digits (0 to 9), and the underscore (_) character. No other characters or symbols are allowed. 2. Variables must begin with a letter or the underscore _ character. You can not begin a variable name with a number. If you really need to begin a variable name with a number, it is customary to place an underscore first followed by the number. 3. No spaces are allowed in the variable name. All characters and numbers must be run together with no spaces. To create a variable out of several words, it is customary to run the words together and capitalize the first letter of each word, with the first word always using all lower-case letters. 4. Variable names can be up to 31 characters long. (They can be longer in some cases, but as a general rule, try to keep it to 31 or less to guarantee your code can be understood by the compiler that turns it into machine language). 5. The variable cannot be named any reserved words. These are special words that mean something special to Arduino such as break. If you type the name of a variable and it changes color on the screen, that is a good clue that it is probably a reserved word and cannot be used. You can still incorporate reserved words in the name as long as it s not an exact match to a reserved word. For example you could name a variable breakpoint, but you can not name it break by itself because the word break means something special.

Initial value of a variable... Every variable has a value stored in it, even if you have just declared it. Normally this will be zero, but there s no guarantee of this. In many cases, you will want your program to set a variable to some meaningful value before it is used. If you plan to use your variable to store the reading from a light sensor - the initial value doesn t really matter because you re going to read the sensor before using the value, which will erase whatever value it started with. But in other cases, like counting how many dinosaurs you ve seen this week, you ll probably want it to begin with some specific known value, like 0. You can give the variable an initial value at the same time you declare it if you want. This is optional, but considered good practice. int loopcount = 0; //declare loopcount and initialize it to 0 This statement declares the variable and also specifically tells the program what its initial value should be. A working example... Lets have a look at working example. This is similar to the examples you ve already seen. It declares the variable loopcount and makes sure it is set to a starting value of 0. Then the loop() function begins. Each time the program goes through loop, loopcount is increased by 1. It makes sense that we named it loopcount because that is exactly what we are storing in the variable. (That is, a count of how many times the loop() function runs). # include WinkStuff.h void loop(){ void setup(){ Motors(200,100); //Arc to the right hardwarebegin(); delay(3000); //wait 3 seconds } Motors(100,200); //Spin to the left delay(3000); //wait 3 seconds int loopcount = 0; } void loop(){ loopcount = loopcount + 1; //add 1 to loopcount } //end of loop() Declares the variable loopcount, sets it equal to 0. Add 1 to loopcount every time the program goes through the loop() function. Wink_Ch06Vars_Ex01 If you actually load this onto Wink, it won t look like he s doing anything, but he is really using all his brain power to count loops as fast as he can. In the next lesson we ll show you how to print these values to your computer screen so you can see what he s thinking. This is just a simple example to show you how a variable can be used.

A few factoids about variables... Here are a few other random tidbits about variables. Roll Over: A variable will roll over if you try to give it a value outside the range it can store. For example, if you populate a variable with the highest number it can store, then add one to it, the value will roll over and become the lowest value it can store. This works the same in the negative direction. If you are ever working with a program and the variables seem to be giving you very strange numbers, this could be the cause. The C language will not prevent you from rolling over a variable. It is happy to let you make the mistake. int x; x = -32768; x = x - 1; // x now contains 32,767 - rolls over in neg. direction x = 32767; x = x + 1; // x now contains -32,768 - rolls over Source: Official Arduino Website https://www.arduino.cc/en/reference/int Memory Limits: You may already be wondering how many variables you can declare. This really depends on how much memory you have available on the processor you are using. Wink has 2 KB of RAM memory (that is, about 2000 bytes). Each int variable requires 2 bytes, so you could theoretically use 1000 different int variables in your program. However, Arduino, as well as Wink s background code (inside WinkStuff.h) claim about 300 bytes of the available 2000 bytes, but that still leaves you about 1700 bytes (about 850 int variables) that you can declare and use. It is unlikely that you will ever run out of memory on Wink. The only time you may press these memory limits is if you re using large arrays (that s a Skill Level 3 topic, so don t worry about it now). Memory Re-Use: Keep in mind that every time you load a program onto your Wink, all the memory is erased and re-used. (Except for some special memory called EEPROM that keeps values forever - we ll discuss that later in Skill Level 3). For now, just know that you can keep re-writing the memory over and over. If you use lots of variables in a given sketch, you won t eventually run out of space later on.

Other variable Types... We mentioned before that there are several different types of variables. We ll briefly discuss them here. There are even more types than we ll cover, but these are the common ones that will get you through almost anything you ll ever need to do. Variable Type Values Stored Bits Notes byte 0 to 255 8 Number from 0 to 255, no negative numbers allowed. char -128 to 127 8 Some compilers will try to interpret this variable type as a Character (like a letter typed on your keyboard) word 0 to 65535 16 This can count higher than int except you can t use it to store negative numbers. int -32768 to 32767 16 This is the most common general purpose variable type. It allows storage of fairly large numbers as well as negative numbers. unsigned long 0 to 4,294,967,295 32 This variable type is required to store the result of the millis() function which returns the number of milliseconds the current code has been running. long float -2,147,483,648 to 2,147,483,647-3.4028235 e38 to 3.4028235 e38 32 Useful for storing very large numbers that could be positive or negative. 32 The Floating Point data type can store very large numbers as well as decimal numbers. It is very flexible, though the processor does need more time to process it. Use float data types only when you really need the decimal function. Note about variable Bit-Length: You ll notice the Bits column in this chart. We ll go deeper into bits in Skill Level 3, but here s a quick intro. Computers store values as sequences of 1 s and 0 s. The byte variable type can be stored using a series of eight 1 s and 0 s, so we say it is 8 bits long. In order to store bigger numbers like the word variable type, eight bits isn t enough. We need a sequence of sixteen 1 s and 0 s to store a word. A float variable needs a sequence of 32 ones and zeros. This doesn t really matter now in our simple examples, but know that Wink s brain (and all other 8-bit processors) can only think about 8 bits of information at once. Usually Wink can add a pair of 8-bit numbers together in a single cycle. He can add 16 bit numbers together, but he has to break them into several 8-bit cycles, and to do math on 32 bit numbers, he has to perform quite a few 8-bit cycles. He performs 8 million cycles each second, so even handling 32 bit numbers is extremely fast. As a general rule it is a good idea to stick to 8 bit numbers if possible, with 16 bit as a second choice, and leave 32 bit variable types only for when you really need them.