Arduino Programming Language

Similar documents
Arduino project. Arduino board. Serial transmission

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Arduino Lesson 5. The Serial Monitor

Example of a Java program

Microcontroller Programming Beginning with Arduino. Charlie Mooney

Lab 6 Introduction to Serial and Wireless Communication

Sources: On the Web: Slides will be available on:

Lecture 7: Programming for the Arduino

The Answer to the 14 Most Frequently Asked Modbus Questions

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

The C Programming Language course syllabus associate level

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Introduction to Java

VB.NET Programming Fundamentals

Java Basics: Data Types, Variables, and Loops

Pemrograman Dasar. Basic Elements Of Java

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

CS 106 Introduction to Computer Science I

Chapter 2: Elements of Java

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Arduino-Based Dataloggers: Hardware and Software David R. Brooks Institute for Earth Science Research and Education V 1.2, June, , 2015

Lecture 2 Notes: Flow of Control

J a v a Quiz (Unit 3, Test 0 Practice)

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Computer Programming I

Object Oriented Software Design

Arduino provides a standard form factor that breaks the functions of the micro-controller into a more accessible package.

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Programming the Arduino

Informatica e Sistemi in Tempo Reale

GM862 Arduino Shield

Introduction to Java. CS 3: Computer Programming in Java

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Connecting Arduino to Processing a

An Incomplete C++ Primer. University of Wyoming MA 5310

Object Oriented Software Design

Introduction to Python

JavaScript: Control Statements I

Variables, Constants, and Data Types

#820 Computer Programming 1A

Moving from CS 61A Scheme to CS 61B Java

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Keil C51 Cross Compiler

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Chapter 5 Functions. Introducing Functions

HOMEWORK # 2 SOLUTIO

TUTORIAL FOR INITIALIZING BLUETOOTH COMMUNICATION BETWEEN ANDROID AND ARDUINO

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Computer Programming Tutorial

Java Interview Questions and Answers

Computers. Hardware. The Central Processing Unit (CPU) CMPT 125: Lecture 1: Understanding the Computer

arrays C Programming Language - Arrays

The programming language C. sws1 1

Using Arduino Microcontrollers to Sense DC Motor Speed and Position

Arduino Microcontroller Guide W. Durfee, University of Minnesota ver. oct-2011 Available on-line at

EnerVista TM Viewpoint Monitoring v7.10

Chapter One Introduction to Programming

Chapter 2 Introduction to Java programming

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Custom Javascript In Planning

Objective-C Tutorial

Computer Programming I & II*

ESPResSo Summer School 2012

Arduino Internet Connectivity: Maintenance Manual Julian Ryan Draft No. 7 April 24, 2015

Number Representation

Basic Pulse Width Modulation

Introduction to Java Lecture Notes. Ryan Dougherty

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

C++ Language Tutorial

Chapter 2 Elementary Programming

Introduction to Data Structures

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

Java (12 Weeks) Introduction to Java Programming Language

Java Programming Fundamentals

Work with Arduino Hardware

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

ENGI E1112 Departmental Project Report: Computer Science/Computer Engineering

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Introduction to Python

C Coding Style Guide. Technotes, HowTo Series. 1 About the C# Coding Style Guide. 2 File Organization. Version 0.3. Contents

Programing the Microprocessor in C Microprocessor System Design and Interfacing ECE 362

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

1.3 Conditionals and Loops

Statements and Control Flow

Moving from C++ to VBA

Servo Motor API nxt_motor_get_count nxt_motor_set_count nxt_motor_set_speed

AirCasting Particle Monitor Bill of Materials

Transcription:

Introduction to Haptics Arduino Programming Language (optional material for beginning programmers) Allison M. Okamura Stanford University

Programming Guidance Potential resources: Online courses (e.g., EdX, Udacity) Web tutorials (Java or C programming languages are most appropriate) Arduino-specific tutorials In this class: You will start from existing programs (sketches) and modify them The complexity of the programming you will do is low Debugging can be difficult because of the real-time nature of haptic interaction You should learn by doing. There is little you can do to damage your Hapkit through programming mistakes!

We will start by going through some examples at http://www.learn-c.org/

Arduino Programming Language Components Structure Variables Functions Basic syntax Arithmetic operators Control structures Comparison Operators Boolean Operators Constants Data types Scope Digital I/O Analog I/O Math Serial communication Defining your own

Arduino Programming Language Components Structure Variables Functions Basic syntax Arithmetic operators Control structures Comparison Operators Boolean Operators Constants Data types Scope Digital I/O Analog I/O Math Serial communication Defining your own

Structure: Basic Syntax ; { // /* */ #define Each statement ends in a semicolon. For example: int a = 13; Curly braces always come in pairs; they are used to define the start and end of functions, loops, and conditional statements. For example: while (boolean expression) { statement(s) Single line comment Multi-line comment Used to give a name to a constant value. For example: #define ledpin 3

Structure: Arithmetic operators = Assignment operator stores the value to the right of the equal sign in the variable to the left of the equal sign: sensorval = analogread(fsrpin); + - * / Addition, subtraction, multiplication, and division. For example: result = value1 + value2; result = value1 - value2; result = value1 * value2; result = value1 / value2; where value1 and value2 are any variables or constants Tips: Choose variable sizes that are large enough to hold the largest calculated result For math that requires fractions, use float variables (but there are drawbacks) Check for order of operations; use parentheses to enforce order

Structure: Control structures if Tests whether a certain condition has been reached. Used in conjunction with a comparison operator. For example: if (somevariable > 50) { // do something here if...else Allows you to do multiple tests. For example: if (force > 1) { // action A else { // action B

Structure: Control structures for Creates a loop for repetitive operations. for (initialization; condition; increment) { //statement(s);

Structure: Control structures switch case Allows you to specify different code that should be executed in various conditions. For example: switch (var) { case 1: //do something when var equals 1 break; case 2: //do something when var equals 2 break; default: // if nothing else matches, do the default // default is optional

Structure: Comparison Operators The result of a statement with a comparison operator is either TRUE (1) or FALSE (2) x == y (x is equal to y) x!= y (x is not equal to y) x < y (x is less than y) x > y (x is greater than y) x <= y (x is less than or equal to y) x >= y (x is greater than or equal to y) Tips: Be careful not to accidentally use the assignment operator = instead of ==. Cannot use statements such as 0 < x < 1; need to do each comparison separately

Structure: Boolean Operators && Logical AND. True only if both operands are true, e.g. if (digitalread(2) == HIGH && digitalread(3) == HIGH) { // do this only if both inputs are high Logical OR. True if either operand is true, e.g. if (x > 0 y > 0) { // do this if either x or y is greater than 0! NOT. True if the operand is false, e.g. if (!x) { // do this if x is false (0)

Arduino Programming Language Components Structure Variables Functions Basic syntax Arithmetic operators Control structures Comparison Operators Boolean Operators Constants Data types Scope Digital I/O Analog I/O Math Serial communication Defining your own

Variables: Constants HIGH LOW true false When reading or writing to a digital pin, there are only two possible values a pin can take (or be set to): HIGH and LOW Logical levels (result of a comparison): false is defined as 0 true is defined as 1 (but more broadly, anything but 0) In addition, integer and floating-point constants can be used: Decimal integers Floating point 2 101 3200 10.0 2.34E5 67e-12

Variables: Data types void boolean Used in function delcarations to indicate that the function returns no information. For example: void setup() { { //... //... void loop() A boolean holds one of two values, true or false. For example: boolean running = false; if (running) { // do something

Variables: Data types char float double A data type that stores a character value. For example: char mychar = 'A'; char mychar = 65; // both are equivalent Coding is in this ASCII chart: http://arduino.cc/en/reference/asciichart Datatype for floating-point numbers, a number that has a decimal point. Floating-point numbers are often used to approximate analog and continuous values because they have greater resolution than integers. Floats have 6-7 decimal digits of precision. On the Hapkit board, double is the same as float.

Variables: Scope Global vs. Local: A global variable is one that can be seen by every function in a program. Define it outside a function. A local variable is only visible to the function in which it is declared. Define it inside a function. For complex programs, local variables can help prevent programming errors. However, global variables are an easy way to share information across functions. The static keyword is used to create variables that are visible to only one function. However unlike local variables that get created and destroyed every time a function is called, static variables persist beyond the function call, preserving their data between function calls. For example: static int a;

Arduino Programming Language Components Structure Variables Functions Basic syntax Arithmetic operators Control structures Comparison Operators Boolean Operators Constants Data types Scope Digital I/O Analog I/O Math Serial communication Defining your own

Functions: Digital I/O For a description of the roles of different pins on the Arduino/Hapkit, see http://arduino.cc/en/tutorial/digitalpins pinmode(pin, mode) digitalwrite(pin, value) digitalread(pin) Configures the specified pin to behave either as an input or an output. pin is the pin number. Write a HIGH or a LOW value to a digital pin. Reads the value from a specified digital pin. The result will be either HIGH or LOW.

Functions: Analog I/O analogreference(type) analogread(pin) analogwrite(pin,value) The default reference voltage is 5V. This can be changed to a different type and different resolution using this function. Reads the value from the specified analog pin and returns a value between 0 and 1023 to represent a voltage between 0 and 5 volts (for default). It takes about 0.0001 seconds to read an analog pin. Writes an analog value (PWM wave) to a pin. value is the duty cycle: between 0 (always off) and 255 (always on). Works on pins 3, 5, 6, 9, 10, and 11.

Functions: Math min(x, y) max(x, y) abs(x) Calculates the minimum of two numbers Calculates the maximum of two numbers Computes the absolute value of a number pow(base, exponent) sqrt(x) map(value, fromlow, fromhigh, tolow, tohigh) Calculates the value of a number raised to a power Calculates the square root of a number Re-maps a number from one range to another. That is, a value of fromlow would get mapped to tolow, a value of fromhigh to tohigh, values in between to values in between. Trigonometric functions such as sin, cos, and tan are also available.

Functions: Serial communication Typically used for communication between an Arduino board and a computer via the USB port. Use the serial monitor to communicate with the board. Serial.begin(9600); Serial.print(val,format); Serial.println(val); Used to begin serial communications, typically at a 9600 baud rate (bits per second) Prints data to the serial port as human-readable ASCII text. Examples: Serial.print(78) gives "78" Serial.print(1.23456) gives "1.23" Serial.println(1.23456, 4) gives "1.2346" Serial.print("Hello world.") gives "Hello world." Prints val followed by carriage return

Functions: Defining your own Many other functions have been created by Arduino users; some are posted at http://playground.arduino.cc/main/generalcodelibrary You can also define your own function. This could be used to make your code more organized and efficient. int find_text(string needle, String haystack) { int foundpos = -1; for (int i = 0; (i < haystack.length() - needle.length()); i++) { if (haystack.substring(i,needle.length()+i) == needle) { foundpos = i; return foundpos; This is a function that searches for a given string within another string. If the search string is found its position is returned, otherwise -1 is returned.