How to write an Arduino sketch Content The

  • Slides: 42
Download presentation
How to write an Arduino sketch Content: ֍ The basic structure of a sketch

How to write an Arduino sketch Content: ֍ The basic structure of a sketch ֍ Language main elements ֍ Examples 1 ֍ How to go on

How to write an Arduino sketch The Arduino language is a sort of simplified

How to write an Arduino sketch The Arduino language is a sort of simplified C Basic hints: Each statement must end with semicolon ; The code is case sensitive Variables cannot use same words as existing commands Comments start with // or are enclosed between /* and */ 2

The minimum amount of elements in a sketch Variable definition void setup() { //

The minimum amount of elements in a sketch Variable definition void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } setup : It is called only when the Arduino is powered on or reset. It is used to initialize variables and pin modes. 3 loop : The loop functions runs continuously till the device is powered off. The main logic of the code goes here.

Variable definition Variables need to be declared before being used. Their names should be

Variable definition Variables need to be declared before being used. Their names should be different from Arduino keywords. Datatype Property byte 8 bit without decimal point 16 bit integer with sign long 32 bit integer with sign float 32 bit with decimal digits …. . Others…. string boolean …. . 4 Range (0, 255) (-32768 , 32767)

Arithmetic and logical operators Variables may be combined through mathematical or logic operators. Basic

Arithmetic and logical operators Variables may be combined through mathematical or logic operators. Basic Arithmetic: +, -, *, / Other functions: Trigonometric: Comparison: Boolean: sqrt(x), abs(x), pow(base, exponent) sin(x), cos(x), tan(x) >, <, >=, <=, ==, !=, . . && (AND), || (OR), ! (NOT) Example: 5 int a, b, c; a= 2; b= 3; if(a*b>5) c=100; x in rad

Control structures allow to execute different parts of a code depending on the result

Control structures allow to execute different parts of a code depending on the result or to repeat parts of a code under specified conditions if if else do while for { } Example: for(int i=0; i<100; i++) { …. . Statements inside the for loop 6 }

Define pin mode A pin on arduino can be set as input or output

Define pin mode A pin on arduino can be set as input or output by using pin. Mode function. pin. Mode(13, OUTPUT); // sets pin 13 as output pin. Mode(13, INPUT); // sets pin 13 as input pin 7

Reading/writing digital values A digital input or output may have the following values: 0

Reading/writing digital values A digital input or output may have the following values: 0 (0 V) = LOW 1 (5 V) = HIGH and we can read or write through the commands digital. Read, digital. Write(13, LOW); // Sets the output voltage on pin 13 to 0 V digital. Write(13, HIGH); // Sets the output voltage on pin 13 to 5 V a = digital. Read(2); // reads the value of pin 2 into the variable a 8

Basic time instructions Commands are executed one after the other, but we can insert

Basic time instructions Commands are executed one after the other, but we can insert a delay in between. . delay(10); // Waits 10 milliseconds delay. Microseconds(400); // Waits 400 microseconds We may have access to the time from the Arduino clock through the commands: a = millis(); // returns the number of milliseconds since the beginning of the program 9 Since the counter is based on a 32 bit register, the max number of milliseconds will be 232 -1 = 4. 294. 967. 295 (about 49. 7 days)

The first Arduino sketch: blinking the internal LED The Arduino board has a LED

The first Arduino sketch: blinking the internal LED The Arduino board has a LED already mounted on pin#13. This can be employed for the first basic tests, without any external component. Remember: any external LED must be powered through a resistor, to limit the current and prevent it burns: 5 V 10 R Ground Usually LED require about 2 V and 10 -20 m. A, so for 5 V, we need a resistor of (5 -2)/0. 01 = 300 Ohm

The first Arduino sketch: blinking the internal LED // Blink //Turns on the LED

The first Arduino sketch: blinking the internal LED // Blink //Turns on the LED for 1 second, then off for 0. 5 second, repeatedly int led = 13; void setup() { pin. Mode(led, OUTPUT); // initialize the digital pin as an output. } 11 void loop() { digital. Write(led, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digital. Write(led, LOW); // turn the LED off by making the voltage LOW delay(500); // wait for 500 mseconds }

What next: Modify the sketch (Exercise 1) Modify the previous sketch (blink. ino) to

What next: Modify the sketch (Exercise 1) Modify the previous sketch (blink. ino) to introduce different light sequences for the LED. Examples: -- Produce short or long light pulses with different delays -- Produce light sequences which transmit a word in the Morse alphabet (for instance an SOS) 12 Letter Sequence A. ------B, C, D, . . S. . . O --- ---- Check what is the shortest light pulse you can perceive

Controlling sounds with Arduino A basic way of producing a sound with Arduino is

Controlling sounds with Arduino A basic way of producing a sound with Arduino is to employ a passive buzzer, which can be programmed to play a note (frequency) with its duration. The quality is not very good, (based on piezoelectric effect) but it is very simple. Sophisticated audio control requires additional boards. 13

Controlling sounds with Arduino The buzzer is connected to a digital pin Basic commands:

Controlling sounds with Arduino The buzzer is connected to a digital pin Basic commands: tone(Buzzer. Pin, f); // Start playing a sound with frequency f no. Tone(Buzzer. Pin); // Stop playing delay(delta); // introduces a delay of delta milliseconds 14 Note Frequency Do 131 Re 147 Mi 165 Fa 175 Sol 196 La 220 Si 247 Next octave: a factor 2 Do 131*2 = 262 ………………. . Additional semitones Do# 139 Mib 156 Fa# 185 Lab 208 Sib 233

A simple sketch to play a music sequence 15 const int Buzzer. Pin =

A simple sketch to play a music sequence 15 const int Buzzer. Pin = 8; // the number of pin where the Buzzer is connected // Notes: Do, Re, Mi, Fa, Sol, La, Si, . . next octave Int notes[28]={131, 147, 165, 175, 196, 220, 247, 262, 294, 330, 349, 392, 440, 494, 523, 587, 659, 698, 784, 880, 988, 1047, 1175, 1319, 1397, 1568, 1760, 1976}; void setup() { // initialize the Buzzer pin as an output: pin. Mode(Buzzer. Pin, OUTPUT); } void loop(){ for(int i=0; i<28; i++){ tone(Buzzer. Pin, notes[i]); delay(500); The frequency of the various } stored in an array no. Tone(Buzzer. Pin); //delay(2000); for(int i=0; i<28; i++){ tone(Buzzer. Pin, notes[28 -i]); delay(100); } no. Tone(Buzzer. Pin); delay(1000); } notes is

What next: Producing music by yourself (Exercise 2) Suggestions: consider the duration of different

What next: Producing music by yourself (Exercise 2) Suggestions: consider the duration of different notes, as submultiples of a time interval Italian name 4/4 Semibreve 2/4 Minima 1/4 Semiminima 16 1/8 Croma 1/16 Semicroma

What next: Producing music by yourself (Exercise 2) Music sheets report the sequence of

What next: Producing music by yourself (Exercise 2) Music sheets report the sequence of the various notes, with their duration and pause 17

Reading analog inputs Analog sensors provide values from 0 to the max value (5

Reading analog inputs Analog sensors provide values from 0 to the max value (5 V), ideally proportional to the value of the physical quantity, or related by a linear equation to it. An analog sensor must be connected as a voltage divider between +5 V and Ground: +5 V Analog Sensor RS Arduino A 0 18 R GND

Reading analog inputs At the analog input A 0 there will be a voltage

Reading analog inputs At the analog input A 0 there will be a voltage between 0 and +5 V depending on the values of R and Rs. Some sensors have 3 pins, to be directly connected to GROUND, +5 V and an analog input. +5 V Analog Sensor RS Arduino A 0 19 R GND

Reading analog inputs At the analog input A 0 there will be a voltage

Reading analog inputs At the analog input A 0 there will be a voltage between 0 and +5 V depending on the values of R and Rs. Some sensors have 3 pins, to be directly connected to GROUND, +5 V and an analog input. +5 V Arduino 20 Analog Sensor A 0 GND

Reading from analog sensors The voltage at one of the analog input is transformed

Reading from analog sensors The voltage at one of the analog input is transformed into a number between 0 and 1023 (1024 possible values), proportional to the voltage reading. This operation is carried out by the ADC (Analog to Digital Converter) within Arduino. Even though there are 6 analog inputs, there is a unique ADC, which is being used in turn. Why 1024 values? 21 This depends on the resolution of the ADC, given by the number of bits (10 in Arduino, so 210 = 1024)

ADC and resolution How many values can we distinguish with 3 bits? 000 001

ADC and resolution How many values can we distinguish with 3 bits? 000 001 010 011 100 101 110 111 22 = = = = 0 1 2 3 4 5 6 7 8 different values, 23 = 8 With N bits, we can distinguish 2 N values

ADC and resolution If the voltage range is 0 -5 V, the minimum voltage

ADC and resolution If the voltage range is 0 -5 V, the minimum voltage variation which we can measure is given by 5 V/2 N For instance, with N=3 bits, 5 V/8= 0. 625 V (very poor resolution!) With N=10 bits (1024 values), we can appreciate 5 V/1024 = 4. 88 m. V 23 Note: The ADC we employed for alpha and gamma spectrometry follows the same principles. In that case we have N=11 bits, so 2048 different values (or channels in the histogram)

Reading from analog sensors How much time Arduino needs to perform an analog reading?

Reading from analog sensors How much time Arduino needs to perform an analog reading? About 100 microseconds Then we can read (in principle) 10000 values per second The sampling rate (How many measurements per second) depends on the application, similarly to what discussed with PASCO sensors. 24 Slow phenomena, such as the atmospheric pressure variations, may be sampled even once per minute or less. . Fast phenomena require higher sampling rate.

Reading the light intensity with a photoresistor (Exercise 3) We may employ a photoresistor

Reading the light intensity with a photoresistor (Exercise 3) We may employ a photoresistor to measure the intensity of light through an Arduino analog input. The photoresistor decreases its resistance with increasing light intensity. 25

A basic sketch to read analog sensors int sensor. Pin = A 0; //

A basic sketch to read analog sensors int sensor. Pin = A 0; // select the input pin for the photocell int sensor. Value; void setup() { Serial. begin(9600); } 26 void loop() { sensor. Value=analog. Read(sensor. Pin); // read value from photocell // send the 10 -bit sensor value out the serial port Serial. print("sensor Value: "); Serial. println(sensor. Value); delay(2000); // Wait some time before reading new value }

A basic sketch to read analog sensors int sensor. Pin = A 0; //

A basic sketch to read analog sensors int sensor. Pin = A 0; // select the input pin for the photocell int sensor. Value; void setup() { Serial. begin(9600); } 27 Serial. begin(9600): Transfer data to the serial monitor at a speed of 9600 bps void loop() { sensor. Value=analog. Read(sensor. Pin); // read value from photocell // send the 10 -bit sensor value out the serial port Serial. print("sensor Value: "); Serial. println(sensor. Value); delay(2000); // Wait some time before reading new value }

A basic sketch to read analog sensors int sensor. Pin = A 0; //

A basic sketch to read analog sensors int sensor. Pin = A 0; // select the input pin for the photocell int sensor. Value; void setup() { Serial. begin(9600); } 28 Serial. print(…. . ): Prints a comment void loop() { sensor. Value=analog. Read(sensor. Pin); // read value from photocell // send the 10 -bit sensor value out the serial port Serial. print("sensor Value: "); Serial. println(sensor. Value); delay(2000); // Wait some time before reading new value }

A basic sketch to read analog sensors int sensor. Pin = A 0; //

A basic sketch to read analog sensors int sensor. Pin = A 0; // select the input pin for the photocell int sensor. Value; void setup() { Serial. begin(9600); } 29 Serial. println(…): Prints a variable and go to next line void loop() { sensor. Value=analog. Read(sensor. Pin); // read value from photocell // send the 10 -bit sensor value out the serial port Serial. print("sensor Value: "); Serial. println(sensor. Value); delay(2000); // Wait some time before reading new value }

A basic sketch to read analog sensors int sensor. Pin = A 0; //

A basic sketch to read analog sensors int sensor. Pin = A 0; // select the input pin for the photocell int sensor. Value; void setup() { Serial. begin(9600); } 30 Modify the sampling rate void loop() { sensor. Value=analog. Read(sensor. Pin); // read value from photocell // send the 10 -bit sensor value out the serial port Serial. print("sensor Value: "); Serial. println(sensor. Value); delay(2000); // Wait some time before reading new value }

What next: Modify the sketch int sensor. Pin = A 0; // select the

What next: Modify the sketch int sensor. Pin = A 0; // select the input pin for the photocell int sensor. Value; void setup() { Serial. begin(9600); } 31 Insert here a ckeck with an if statement to switch ON led#13 if the light intensity exceed some predefined value void loop() { sensor. Value=analog. Read(sensor. Pin); // read value from photocell // send the 10 -bit sensor value out the serial port Serial. print("sensor Value: "); Serial. println(sensor. Value); delay(2000); // Wait some time before reading new value }

Reading inputs from digital sensors Digital inputs may have the value LOW (0 V)

Reading inputs from digital sensors Digital inputs may have the value LOW (0 V) or HIGH (5 V). Reading the state of a digital input gives information on the current value. To avoid undefined state on the input, a pulldown resistor (for instance 10 kΩ) is often employed, to have 0 V by default. +5 V Digital Sensor Arduino Digital Input 32 Pulldown resistor R GND

Reading digital inputs from a Geiger (Exercise 4) Digital inputs may be generated by

Reading digital inputs from a Geiger (Exercise 4) Digital inputs may be generated by a switch (which closes a circuit), or by any sensor which produces a +5 V voltage when something happens. An example is the Geiger counter we already employed in the lab. +5 V 33 0 V 120 μs Time

Reading digital inputs from a Geiger For this Geiger, we usually do not need

Reading digital inputs from a Geiger For this Geiger, we usually do not need the pulldown resistor, so we can connect directly the Geiger to a digital input (2, 3, . . ) Arduino Digital Input 34 Geiger GND

Reading digital inputs How much time Arduino needs to perform a digital reading? About

Reading digital inputs How much time Arduino needs to perform a digital reading? About 10 microseconds Then we can read (in principle) 100000 values per second Of course if other instructions must be executed after reading the digital input, the time spent before reading again the same input will be longer… 35

A sketch to manage a Geiger counter with Arduino We may connect the output

A sketch to manage a Geiger counter with Arduino We may connect the output from a Geiger counter wich produces +5 V pulses to a digital input in Arduino and count how many pulses arrive. . Actually we can do much more… For instance: Measure the arrival time of the event Evaluate the time difference between consecutive events Perform some action when a particle hits the Geiger …. . 36

Part 1 // set pin numbers: const int Geiger. Pin = 2; // the

Part 1 // set pin numbers: const int Geiger. Pin = 2; // the number of digital pin where the Geiger is connected const int led. Pin = 13; // the number of the LED pin // variables will change: int Geiger. State = 0; // variable for reading the signal from the Geiger counter int counts = 0; float event_time; float previous_time=0. 0; float diff; 37 void setup() { // initialize the LED pin as an output: pin. Mode(led. Pin, OUTPUT); // initialize the Geiger pin as an input: pin. Mode(Geiger. Pin, INPUT); // Prepare for output on terminal Serial. begin(9600); }

Part 2 void loop(){ // read the state of the Geiger. Pin: Geiger. State

Part 2 void loop(){ // read the state of the Geiger. Pin: Geiger. State = digital. Read(Geiger. Pin); 38 // check if a signal has arrived. if (Geiger. State==1) { event_time=millis()/1000. 0; // Arrival time in seconds diff=event_time-previous_time; // Difference between two consecutive events previous_time=event_time; counts++; // Number of detected events Serial. print("Counts = "); Serial. print(counts); Serial. print(" Time = "); Serial. print(event_time); Serial. print(" Dt = "); Serial. println(diff); delay(1); // Introduces some delay to avoid reading twice same event } }

What next: use the sketch to measure counts First of all you may use

What next: use the sketch to measure counts First of all you may use the sketch as is, to count events from the Geiger. They will be printed on the serial monitor You may save events on a text file for further analysis You can modify the sketch inserting new statements to switch ON the internal LED (Pin#13) when a pulse arrives. 39

Summary of basic Arduino activities discussed so far -- Learn the basic commands of

Summary of basic Arduino activities discussed so far -- Learn the basic commands of the Arduino language -- Train with 4 different exercises to execute sketch already made, and learn how to introduce some modification WHAT NEXT? Write 2 new sketch for Arduino, for the following tasks: 40

Experiment A Write an Arduino sketch to manage 2 Geiger counters, connected to 2

Experiment A Write an Arduino sketch to manage 2 Geiger counters, connected to 2 digital inputs, and count single pulses from each of them, and also coincident events (events which arrive in coincidence, within the duration of the pulses, about 100 microseconds) to both counters. Carry out measurements for some time to collect both single and coincident events, with the 2 Geiger placed one above the other, thus detecting particles which pass through both. 41 Analyze the collected events, to extract The average single rates of the two Geiger The average coincidence rate The rate as a function of the time The time difference between next events

Experiment B Write an Arduino sketch to collect data from two analog sensors (a

Experiment B Write an Arduino sketch to collect data from two analog sensors (a temperature sensor and a light intensity sensor) for various values of the sampling frequency, producing a data file to be analyzed. Collect data for some time interval, to measure various phenomena which may involve light and temperature. 42