Arduino Uno Introduction: Difference between revisions

From Sensors in Schools
Jump to navigation Jump to search
 
(39 intermediate revisions by the same user not shown)
Line 93: Line 93:


[[File:Screenshot 2023-04-30 at 5.42.46 pm.png | 900px]]
[[File:Screenshot 2023-04-30 at 5.42.46 pm.png | 900px]]
= Arduino Uno - Traffic Lights =
== TinkerCAD Circuit Diagram ==
* Open a web browser and got to www.tinkercad.com
* You need to register as a new user.
* Create a new '''Circuit'''
[[File:TrafficLights16June2023.PNG | 900px]]
== Arduino Code ==
<syntaxhighlight lang="c++">
#define red 13
#define amber 12
#define green 11
void setup() {
  Serial.begin(9600);
  pinMode(red, OUTPUT);
  pinMode(amber, OUTPUT);
  pinMode(green, OUTPUT);
}
void loop() {
  // red light on for 5 seconds
  digitalWrite(red, HIGH);
  digitalWrite(amber, LOW);
  digitalWrite(green, LOW);
  delay(5000);
  // amber light on for 1 second
  digitalWrite(red, LOW);
  digitalWrite(amber, HIGH);
  digitalWrite(green, LOW);
  delay(1000);
  // green light on for 5 seconds
  digitalWrite(red, LOW);
  digitalWrite(amber, LOW);
  digitalWrite(green, HIGH);
  delay(5000);
  // amber light on for 1 second
  digitalWrite(red, LOW);
  digitalWrite(amber, HIGH);
  digitalWrite(green, LOW);
  delay(1000);
  // repeat
}
</syntaxhighlight>


= Arduino Uno - Connect a Distance Sensor to an Arduino Uno =
= Arduino Uno - Connect a Distance Sensor to an Arduino Uno =
Line 108: Line 163:
* Here’s the formula: '''distance to an object = ((speed of sound in the air)*time)/2'''
* Here’s the formula: '''distance to an object = ((speed of sound in the air)*time)/2'''


== Fritxing Circuit Diagram ==
== Fritzing Circuit Diagram ==


[[File:Screenshot 2023-05-02 at 5.20.43 am.png | 900px]]
[[File:Screenshot 2023-05-02 at 5.20.43 am.png | 900px]]
Line 168: Line 223:


= Arduino Uno - Read Voltage of Solar PV Panel using Voltage Divider Circuit =  
= Arduino Uno - Read Voltage of Solar PV Panel using Voltage Divider Circuit =  
[[File:IMG 5304.JPG | 900px]]
* In this circuit the voltage of a small 5V 0.5 Watt solar panel is read using Analog Pin A2 on the Arduino Uno.
* In this circuit the voltage of a small 5V 0.5 Watt solar panel is read using Analog Pin A2 on the Arduino Uno.
* The Arduino analog pins can read voltages from 0 to 5.0 volts.
* The Arduino analog pins can read voltages from 0 to 5.0 volts.
Line 269: Line 327:
void loop() {
void loop() {
   digitalWrite(13, HIGH); // relay ON
   digitalWrite(13, HIGH); // relay ON
   Serial.println("Relay is ON";
   Serial.println("Relay is ON");


   delay(1000);
   delay(1000);
Line 312: Line 370:


//Variables
//Variables
int chk;
float hum;  //Stores humidity value
float hum;  //Stores humidity value
float temp; //Stores temperature value
float temp; //Stores temperature value
Line 338: Line 395:


</syntaxhighlight>
</syntaxhighlight>


== Installation of DHT.h Library ==
== Installation of DHT.h Library ==
Line 387: Line 443:
** Pin 10 - Servo 1
** Pin 10 - Servo 1


== Materials ==
* [https://www.jaycar.com.au/arduino-compatible-motor-servo-controller-module/p/XC4472 Arduino Motor Servo Controller - Jaycar]
* Servo motor - metal gears 5V.


== Fritzing - Hobby Servo Motor ==
== Fritzing - Hobby Servo Motor ==


[[File:Screenshot 2023-05-05 at 5.22.05 am.png | 900px]]
[[File:Screenshot 2023-05-05 at 5.22.05 am.png | 900px]]
== Servo connected to Motor Driver Board ==
* The servo motor has been plugged into the Motor Driver board - servo 1 connector
* Other wires from the board are in preparation for other inputs.
[[File:Screenshot 2023-05-29 at 7.13.37 am.png | 900px]]


== Arduino Code Example - Sweep ==
== Arduino Code Example - Sweep ==


<syntaxhighlight lang="c++">
<syntaxhighlight lang="c++">
Line 414: Line 478:


void loop() {
void loop() {
   for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
   for (pos = 20; pos <= 160; pos += 1) { // goes from 0 degrees to 180 degrees
     // in steps of 1 degree
     // in steps of 1 degree
     myservo.write(pos);              // tell servo to go to position in variable 'pos'
     myservo.write(pos);              // tell servo to go to position in variable 'pos'
Line 420: Line 484:
     delay(15);                      // waits 15 ms for the servo to reach the position
     delay(15);                      // waits 15 ms for the servo to reach the position
   }
   }
   for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
   for (pos = 160; pos >= 20; pos -= 1) { // goes from 180 degrees to 0 degrees
     myservo.write(pos);              // tell servo to go to position in variable 'pos'
     myservo.write(pos);              // tell servo to go to position in variable 'pos'
     Serial.println(pos);
     Serial.println(pos);
Line 436: Line 500:
  Enter a value from 0 to 9 to control the servo
  Enter a value from 0 to 9 to control the servo
  This value is translated to a value between 0 and 180
  This value is translated to a value between 0 and 180
However this range has been reduced to between 20 and 160 to stop servo jitters
*/
*/


Line 546: Line 611:
* As total suspended solids increases, turbidity values also increase.
* As total suspended solids increases, turbidity values also increase.


== Analog Turbidity Sensor - How it works ==
== Materials ==
* Turbidity sensor - [https://core-electronics.com.au/gravity-analog-turbidity-sensor.html Analog Turbidity Sensor]
* Make up different turbidity samples using instant coffee mixed into tap water.
 
== Fritzing - Analog Turbidity Sensor ==


[[File:Screenshot 2023-05-29 at 6.53.53 am.png | 900px]]


== Materials ==
== Photo of turbidity sensor circuit connect to Arduino Uno ==
* Turbidity sensor - [https://core-electronics.com.au/gravity-analog-turbidity-sensor.html Analog Turbidity Sensor]
* Analog output of turbidity sensor connected to Arduino Uno analog input pin A1
* Turbidity sensor connected to 5V supply (5V and GND pins)


== Fritzing - How the Circuit Works ==
[[File:Screenshot 2023-05-29 at 7.30.33 am.png | 900px]]


== Arduino Code Example - Analog Turbidity Sensor ==
== Arduino Code Example - Analog Turbidity Sensor ==
Line 558: Line 629:
<syntaxhighlight lang="c++">
<syntaxhighlight lang="c++">


int sensorPin = A1;    // select the input pin for the turbidity sensor
int sensorPin = A1;    // Analog pin A1 used as input for the turbidity sensor
int sensorValue = 0;  // variable to store the value coming from the sensor
int sensorValue = 0;  // variable to store the value coming from the sensor


Line 566: Line 637:


void loop() {
void loop() {
   // read the value from the sensor:
   sensorValue = analogRead(sensorPin);  // read the value from the sensor:
   sensorValue = analogRead(sensorPin);
   Serial.println(sensorValue);          // print the value to the Arduino Serial Monitor
   Serial.println(sensorValue);
  delay(1000);
}
 
</syntaxhighlight>
 
= Arduino Uno - Fan Module =
* Arduino compatible Fan Module SKU: DFR0332 Brand: DFRobot
* Make a cooling system for a tiny house or a greenhouse with this small fan module.
* It comes with a propeller, a 15,000 rpm motor and cable.
* Fan speed is controlled using the '''analogWrite(pin, speed)''' statement.
* Arduino Uno pins need to support '''Pulse width Modulation'''. Example pins include pins 3, 5, 6, 9, 10, 11.
* Pulse width modulation compatible pins can be identified because they have a '''~''' tilde symbol next to their number.
* Speed setting values can range from 0 - 255.
 
== Parts list and supporting information ==
* [https://core-electronics.com.au/fan-module.html Arduino Fan Module Core Electronics]
* [https://wiki.dfrobot.com/Fan_Module_DFR0332 Wiki documentation for Fan Module]
 
== Fritzing - Arduino compatible Fan module DFRobot DR0332 ==
 
[[File:Screenshot 2023-05-30 at 3.32.35 am.png | 900px]]
 
== Photo showing Fan Module connected to Arduino Uno ==
 
== Arduino Code Example - Gradual speed increase ==
* Speed of fan will increase by 5 unit increments every second.
* Speed values range from 0 to 255.
* Current speed can be viewed using the Serial Monitor.
 
<syntaxhighlight lang="c++">
 
//Arduino Sample Code for Fan Module
//www.DFRobot.com
//Version 1.0
 
#define Fan 3    //define driver pins
 
void setup()
{
  pinMode(Fan,OUTPUT);
  Serial.begin(9600);    //Baudrate: 9600
}
void loop()
{
  int value;
  for(value = 0 ; value <= 255; value+=5)
  {
    analogWrite(Fan, value);  //PWM
    Serial.println(value);
    delay(1000);
  }
}
 
</syntaxhighlight>
 
 
== Arduino Code Example - Single speed setting ==
* Fan speed set to 200 units.
 
<syntaxhighlight lang="c++">
 
//Arduino Sample Code for Fan Module
//www.DFRobot.com
//Version 1.0
 
#define Fan 3    //define driver pins
 
void setup()
{
  pinMode(Fan,OUTPUT);
  Serial.begin(9600);    //Baudrate: 9600
}
 
void loop()
{
  int value = 200;          // Fan set at fixed value
  analogWrite(Fan, value);  //PWM
  Serial.println(value);
  delay(1000);
}
 
</syntaxhighlight>
 
= Arduino Uno - One Wire Temperature sensor =
 
== Frizing - Circuit diagram ==
* In this circuit diagram the data line is connected to pin 2.
* In the Arduino code below the data line is connected to pin 4.
 
[[File:Screenshot 2023-06-24 at 9.20.39 pm.png | 900px]]
 
== One Wire Library installation ==
 
* Select '''Sketch > Include Library > Manage Libraries'''
* Wait for libraries to update. This may take 1-2 minutes.
* In the search bar enter '''onewire''' and press Enter.
 
[[File:Screenshot 2023-06-24 at 8.24.52 pm.png | 900px]]
 
* Install the '''One Wire''' library.
* Use the One wire library with the author '''Paul Stoffregen'''
 
[[File:Screenshot 2023-06-24 at 8.32.20 pm.png | 900px]]
 
* In this example the onewire library version 2.3.7 was installed.
 
[[File:Screenshot 2023-06-24 at 8.48.39 pm.png | 900px]]
 
== Dallas Temperature Library installation ==
* After installing the onewire library now enter '''Dallas''' as the search term.
 
[[File:Screenshot 2023-06-24 at 8.53.33 pm.png | 900px]]
 
* In this instance version 3.9.0 of the DallasTemperature library was installed.
 
[[File:Screenshot 2023-06-24 at 9.04.40 pm.png | 900px]]
 
== Arduino Uno Code ==
 
<syntaxhighlight lang="c++">
 
#include <OneWire.h>
#include <DallasTemperature.h>
 
// Data wire is conntec to the Arduino digital pin 4
#define ONE_WIRE_BUS 4
 
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);
 
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
 
void setup(void)
{
  // Start serial communication for debugging purposes
  Serial.begin(9600);
  // Start up the library
  sensors.begin();
}
 
void loop(void){
  // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
  sensors.requestTemperatures();
 
  Serial.print("Celsius temperature: ");
  // Why "byIndex"? You can have more than one IC on the same bus. 0 refers to the first IC on the wire
   Serial.println(sensors.getTempCByIndex(0));  
   delay(1000);
   delay(1000);
}
}


</syntaxhighlight>
</syntaxhighlight>
== Serial Monitor output ==
* Temperature readings output to the Serial Monitor.
[[File:Screenshot 2023-06-24 at 9.23.58 pm.png | 900px]]
= Arduino Uno - Real Time Clock and Data Logger Shield =
== References ==
* [https://learn.adafruit.com/adafruit-data-logger-shield Adafruit Data Logger Shield]
* [https://www.instructables.com/Logger-Shield-Datalogging-for-Arduino/ Logger Shield for Arduino]
== Example Code to read Time and Date ==
<syntaxhighlight lang="c++">
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include "RTClib.h"
RTC_DS1307 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
void setup () {
  Serial.begin(57600);
//#ifndef ESP8266
  //while (!Serial); // wait for serial port to connect. Needed for native USB
//#endif
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    while (1) delay(10);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}
void loop () {
    DateTime now = rtc.now();
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    delay(3000);
}
</syntaxhighlight>
== Example output of code - Time and Date ==
[[File:Screenshot 2023-10-12 at 7.11.35 am.png | 900px]]
== Example Code - Timestamp ==
<syntaxhighlight lang="c++">
/* Timestamp functions using a DS1307 RTC connected via I2C and Wire lib
**
** Useful for file name
** ` SD.open(time.timestamp()+".log", FILE_WRITE) `
*/
#include "RTClib.h"
RTC_DS1307 rtc;
void setup () {
  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    while (1) delay(10);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}
void loop() {
DateTime time = rtc.now();
//Full Timestamp
Serial.println(String("DateTime::TIMESTAMP_FULL:\t")+time.timestamp(DateTime::TIMESTAMP_FULL));
//Date Only
Serial.println(String("DateTime::TIMESTAMP_DATE:\t")+time.timestamp(DateTime::TIMESTAMP_DATE));
//Full Timestamp
Serial.println(String("DateTime::TIMESTAMP_TIME:\t")+time.timestamp(DateTime::TIMESTAMP_TIME));
Serial.println("\n");
//Delay 5s
delay(5000);
}
</syntaxhighlight>
== Timestamp - Example output ==
[[File:Screenshot 2023-10-12 at 7.27.24 am.png | 900px]]
== SD Card Test - Example Code ==
<syntaxhighlight lang="c++">
/*
  SD card test
  This example shows how use the utility libraries on which the'
  SD library is based in order to get info about your SD card.
  Very useful for testing a card when you're not sure whether its working or not.
  The circuit:
    SD card attached to SPI bus as follows:
** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
** CS - depends on your SD card shield or module.
Pin 4 used here for consistency with other Arduino examples
  created  28 Mar 2011
  by Limor Fried
  modified 9 Apr 2012
  by Tom Igoe
*/
// include the SD library:
#include <SPI.h>
#include <SD.h>
// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;
// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
// MKRZero SD: SDCARD_SS_PIN
const int chipSelect = 10;
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("\nInitializing SD card...");
  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    while (1);
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }
  // print the type of card
  Serial.println();
  Serial.print("Card type:        ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }
  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    while (1);
  }
  Serial.print("Clusters:          ");
  Serial.println(volume.clusterCount());
  Serial.print("Blocks x Cluster:  ");
  Serial.println(volume.blocksPerCluster());
  Serial.print("Total Blocks:      ");
  Serial.println(volume.blocksPerCluster() * volume.clusterCount());
  Serial.println();
  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("Volume type is:    FAT");
  Serial.println(volume.fatType(), DEC);
  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();      // we'll have a lot of clusters
  volumesize /= 2;                          // SD card blocks are always 512 bytes (2 blocks are 1KB)
  Serial.print("Volume size (Kb):  ");
  Serial.println(volumesize);
  Serial.print("Volume size (Mb):  ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Gb):  ");
  Serial.println((float)volumesize / 1024.0);
  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);
  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
}
void loop(void) {
}
</syntaxhighlight>
== SD Card Test - Example Output ==
[[File:Screenshot 2023-10-12 at 7.19.10 am.png | 900px]]

Latest revision as of 18:36, 4 November 2023

Light up LED 13 on an Arduino Uno

  • Open the Arduino IDE and create a new sketch.
  • In the sketch, write the following code:
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}
  • This code sets pin 13 as an output using the `pinMode()` function in the `setup()` function.
  • In the `loop()` function, it turns the LED on by setting pin 13 to `HIGH` using the `digitalWrite()` function, waits for a second using the `delay()` function, turns the LED off by setting pin 13 to `LOW`, and waits for another second.
  • Verify that your Arduino Uno board is connected to your computer and select the correct board and port under the "Tools" menu.
  • Upload the sketch to the Arduino Uno board by clicking on the "Upload" button.
  • Once the sketch is uploaded, the LED connected to pin 13 should start blinking on and off every second.
  • Video - Program lights up Arduino UNO on-board LED connected to pin 13 for 1 second.

Arduino UNO - Safety

  • Wear eye protection.
  • Always get a teacher to inspect your circuit before powering up.
  • Wear cotton shirts and pants and closed shoes.
  • Even low voltages can cause burns because wires can heat up if shorted.


Wire up an LED connected to Pin 13 on the Arduino Uno

  • To light up an LED connected to pin 13 on an Arduino Uno board, you can follow these steps:
  • Connect the positive (anode) leg of the LED to pin 13 on the Arduino Uno board.
  • Add a 300 Ohm resistor in series
  • Connect the negative (cathode) leg of the LED to the GND pin on the Arduino Uno board.

Arduino code

  • Open the Arduino IDE and create a new sketch.
  • In the sketch, write the following code:
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}
  • This code sets pin 13 as an output using the `pinMode()` function in the `setup()` function.
  • In the `loop()` function, it turns the LED on by setting pin 13 to `HIGH` using the `digitalWrite()` function, waits for a second using the `delay()` function, turns the LED off by setting pin 13 to `LOW`, and waits for another second.
  • Verify that your Arduino Uno board is connected to your computer and select the correct board and port under the "Tools" menu.
  • Upload the sketch to the Arduino Uno board by clicking on the "Upload" button.
  • Once the sketch is uploaded, the LED connected to pin 13 should start blinking on and off every second.

Arduino UNO - Building a LED Blink Circuit on a Breadboard

  • Video - Build an external LED Blink Circuit for the Arduino UNO.

Fritzing Circuit Diagram for external LED

Arduino Uno - Traffic Lights

TinkerCAD Circuit Diagram

  • Open a web browser and got to www.tinkercad.com
  • You need to register as a new user.
  • Create a new Circuit

Arduino Code

#define red 13
#define amber 12
#define green 11

void setup() {
   Serial.begin(9600);
   pinMode(red, OUTPUT);
   pinMode(amber, OUTPUT);
   pinMode(green, OUTPUT);
}

void loop() {
   // red light on for 5 seconds
   digitalWrite(red, HIGH);
   digitalWrite(amber, LOW);
   digitalWrite(green, LOW);
   delay(5000);

   // amber light on for 1 second
   digitalWrite(red, LOW);
   digitalWrite(amber, HIGH);
   digitalWrite(green, LOW);
   delay(1000);

   // green light on for 5 seconds
   digitalWrite(red, LOW);
   digitalWrite(amber, LOW);
   digitalWrite(green, HIGH);
   delay(5000);

   // amber light on for 1 second
   digitalWrite(red, LOW);
   digitalWrite(amber, HIGH);
   digitalWrite(green, LOW);
   delay(1000);

   // repeat
}

Arduino Uno - Connect a Distance Sensor to an Arduino Uno

  • The popular HC-SR04 ultrasonic distance module provides an easy way for an Arduino to measure distances up to 2.0m.
  • It is typically used in robot projects to detect and avoid obstacles.
  • If attached to a servo it can even create a LiDAR map.
  • In this project we will be using it in a Smart Tank to measure tank volume.
  • The surface of water reflects ultrasonic sound waves similar to solid objects.

How it Works

  • The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz). Humans can only detect sounds in a frequency range from about 20 Hz to 20 kHz.
  • The sound travels through the air. If it finds an object (or water), it bounces back to the module.
  • The ultrasound receiver (echo pin) receives the reflected sound (echo).
  • The time between the transmission and reception of the signal allows the distance to an object to be calculated because we know the velocity of sound in air.
  • Here’s the formula: distance to an object = ((speed of sound in the air)*time)/2

Fritzing Circuit Diagram

Wiring Diagram

  • Photo showing the arrangement of pins on the distance sensor.
  • From left to right
    • Ground - Negative terminal
    • Echo - connected to pin 13
    • Trigger - connect to pin 10
    • VCC - Positive terminal

Arduino code

#define trigPin 10
#define echoPin 13

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  float duration, distance;
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);
 
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;
  
  if (distance >= 400 || distance <= 2){
    Serial.print("Distance = ");
    Serial.println("Out of range");
  }
  else {
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.println(" cm");
    delay(500);
  }
  delay(500);
}

Arduino Uno - Read Voltage of Solar PV Panel using Voltage Divider Circuit

  • In this circuit the voltage of a small 5V 0.5 Watt solar panel is read using Analog Pin A2 on the Arduino Uno.
  • The Arduino analog pins can read voltages from 0 to 5.0 volts.
  • The Arduino then translates the voltage reading to a number (bin) between 0 and 1023.
    • zero volts - 0 value
    • 5.0 volts - 1023 value
  • The Arduino analog pins can be damaged if the voltage exceeds 5.0 volts.
  • As a safety measure we can reduce the voltage from the solar PV panel by connecting it to a Voltage Divider Circuit.

Voltage Divider Circuit

  • A voltage divider circuit is simply two 10,000 Ohm (10K Ohms) resistors connected in series and connected to the output of the solar PV panel.
  • The connection point (mid-point) between the two resistors will be exactly half the voltage of the solar PV panel.
  • This mid-point is connected to Analog pin A2.
  • Note that high precision resistors need to be used to make the Voltage Divider.
  • These resistors have less than a 0.5% error in their stated value.

Fritzing Circuit

Arduino Uno - Photo of Solar PV Panel and Voltage Divider circuit

Arduino Uno - Code to read Analog Pin A2

  • This code (Arduino Sketch) reads the voltage of the solar PV Panel.
  • The code will output raw analog readings from Pin A2.
  • Analog values will range from 0 to 1023.
  • Note that it does not correct for the Voltage Divider Circuit.
/*
  Reading an analog Input from solar PV panel

  Read the analog input on analog pin A2
  Pin A2 in connected to a Voltage Divider circuit (2 x 10,000 ohm resistors)
  The Voltage divider circuit is connected to a 5V PV panel (0.5W)

  Edmond Lascaris
  10 April 2023
*/

int solarPin = A2;    // select the input pin for the potentiometer
int solarValue = 0;  // variable to store the value coming from the sensor

void setup() {
  // Initiate serial communication
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  // analog pin returns reads 0-5V by returning a value between 0 and 1023
  solarValue = analogRead(solarPin);
  Serial.println(solarValue);
  delay(1000);
}

Arduino Uno - Relay Circuit

  • A relay is similar to an electrical switch, however this switch can be turned on and off by a computer or micro-controller.
  • A relay is normally used to control larger electrical devices such as pumps and motors that need to be powered on a separate circuit.
  • A separate circuit may be powered using a battery, power supply or even a solar PV panel.
  • In this example we are using a 5V relay Pololu Basic SPDT Relay Carrier with 5VDC Relay
  • Later we will also learn that special Power Transistors can also be to turn high power devices on and off Controlling Circuits with a Power Transitior

Fritzing Circuit Diagram

Relay Circuit with Photos

  • input pins (left of photo) on the relay are:
    • Ground - negative terminal
    • VDD - positive terminal
    • EN - ENergiser. Setting to HIGH (5V) turns relay on. Setting to LOW (0 volts) turns relay off. The input pin is controlled using Pin 13 on the Arduino Uno.
  • Output Pins are used to control an external circuit.
    • COM - Common.
    • NC - Normally Closed. When the relay is not powered or the EN pin is set to LOW, the NC pin is connected to the COM pin.
    • NO - Normally Open. When the relay is powered or the EN pin is set to HIGH, the NO pin is connected to the COM pin. This is normally when an external circuit is connected.

  • Input pin EN on the relay is controlled by Pin 13 on the Arduino Uno.

Arduino Uno - Code to control Relay

  • The relay is controlled by pin 13.
  • Open the Serial Monitor in the Arduino IDE to see the Serial outputs.
void setup() {
  // Initiate serial communication
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH); // relay ON
  Serial.println("Relay is ON");

  delay(1000);
  digitalWrite(13, LOW); // relay OFF
  Serial.println("Relay is OFF");
  delay(1000);
}

Arduino Uno - DHT22 Temperature and Humidity Sensor

  • DHT22 is a digital temperature and humidity sensor which outputs calibrated digital signals.
  • DHT22 comes with very high reliability and excellent long-term stability.
  • To read the signals from the DHT22 module a library DHT.h

Fritzing Circuit Diagram

  • Circuit diagram for the DHT22 temperature and humidity sensor.
  • Only 3 of the 4 pins are used.
  • The data pin from DHT22 sensor is connected to Pin 7 on the Arduino.

Arduino Code - DHT22

  • Copy this code to the Arduino IDE and save the file.
  • Running this code will generate an error because a DHT22.h library needs to be installed.
  • The DHT22.h library is defined near the start of the code using the command #include <DHT.h>
  • The following section describes how to install the library using the Arduino IDE Library Manager.
/* How to use the DHT-22 sensor with Arduino Uno
   Temperature and humidity sensor
*/

//Libraries
#include <DHT.h>;

//Constants
#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino


//Variables
float hum;  //Stores humidity value
float temp; //Stores temperature value

void setup()
{
  Serial.begin(9600);
  dht.begin();
}

void loop()
{
    delay(2000);  //Delay 2 seconds
    //Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.print(" %, Temp: ");
    Serial.print(temp);
    Serial.println(" Celsius");
    delay(2000); //Delay 2 sec.
}

Installation of DHT.h Library

  • The DHT22 sensor requires the installation of a DHT22.h library.

  • From the Dropdown menus select - Sketch > Include Library > Manage Libraries

  • A Library Manager Window will open.
  • The first time it opens it will require 1-2 minutes to update libraries.
  • Be patient and wait for the libraries to load.

  • Enter the search term DHT22 and press Enter.
  • Select the DHT sensor library by Adafruit
  • Ensure the most up to date version of the library is installed.
  • In this case the library version is 1.4.4
  • Then click Install
  • The installation will take approximately 1 minute.

  • A window will appear with different installation options for the DHT sensor library.
  • Select Install All.
  • This will install the DHT22 library and all other library dependencies. The installation of these other libraries will ensure that the sensor works correctly.

  • The Library Manager will then return to the home screen.
  • It should show that the DHT22 sensor library is installed.

Arduino Uno - Servo and Motor Controller Module

  • Servo motors can be controlled using an Arduino Uno.
  • To get best results they need to be connected to a special Shield that plugs into the top of the Arduino Uno.
  • The Shield provides extra power and more accurate timekeeping to the Servo which keeps the servo running smoothly (not jittery).
  • An Arduino Compatible Motor Servo Controller Module is the Shield used in this lesson Jaycar.
  • The Shield provides 2 x 5V servo ports.
  • They are controlled using Pins 9 and 10 on the Arduino.
  • The traditional Servo library in Arduino IDE is used to operate the servo. This is installed by default.
  • Note:
    • Pin 9 - Servo 2
    • Pin 10 - Servo 1

Materials

Fritzing - Hobby Servo Motor

Servo connected to Motor Driver Board

  • The servo motor has been plugged into the Motor Driver board - servo 1 connector
  • Other wires from the board are in preparation for other inputs.

Arduino Code Example - Sweep

/* Sweep
   Servo motor will sweep back and forwards repeatedly
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin(9600);
  myservo.attach(10);  // attaches the servo on pin 10 to the servo object (Servo 1 on the Shield)
}

void loop() {
  for (pos = 20; pos <= 160; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    Serial.println(pos);
    delay(15);                       // waits 15 ms for the servo to reach the position
  }
  for (pos = 160; pos >= 20; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    Serial.println(pos);
    delay(15);                       // waits 15 ms for the servo to reach the position
  }
}

Arduino Code Example - Control Servo Position using Serial Monitor Inputs

/*
 Controlling a servo position using serial input
 Enter a value from 0 to 9 to control the servo
 This value is translated to a value between 0 and 180
 However this range has been reduced to between 20 and 160 to stop servo jitters
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
String command;  // variable to hold command from Serial Monitor
int servoPosition = 0; 

void setup() {
  myservo.attach(10);  // attaches the servo on pin 10 to the servo object (Servo 1 on Shield)
  Serial.begin(9600);
  Serial.println("Enter a value from 0 to 9 to control the servo");
}

void loop() {
if(Serial.available()){
    char ch = Serial.read();
    if(ch >= '0' && ch <= '9') // is this an ascii digit between 0 and 9?
    {
      servoPosition = (ch - '0');           // ASCII value converted to numeric value
      servoPosition = servoPosition * 20;   // servoPosition can range from 0 to 180
      Serial.print("The servo position is ");
      Serial.println(servoPosition);
      myservo.write(servoPosition);        // sets the servo position according to the scaled value
      delay(150);                          // waits for the servo to get there
    }
  }
}

Arduino Uno - Atlas Electrical Conductivity probe

  • An electrical conductivity (EC) probe is used to measure the amount of salt and minerals dissolved in water.
  • If water if purified or distilled the electrical conductivity will be low.
  • An EC probe can be used to test the purity of water.
  • Atlas Scientific Conductivity sensor

Installation of SoftwareSerial library

  • The SoftwareSerial library is pre-installed on the Arduino IDE.
  • No installation is required, but the library needs to included at the beginning of the code.

Fritzing - Electrical Conductivity Probe Circuit

Photo of electrical conductivity sensor connected to Arduino Uno

  • There are 4 pins that are connected from the Atlas Scientific Conductivity sensor to the Arduino Uno.
    • RX (receive) - connected to Arduino Uno pin 3
    • TX (transmit) - connected to Arduino Uno pin 2
    • GND (ground) - connected to GND or the negative (-ve) terminal
    • VCC (Voltage Common Collector) is the higher voltage (+5V supply)

Arduino Code Example - Atlas Scientific Electricity Conductivity probe

#include <SoftwareSerial.h>                           //we have to include the SoftwareSerial library
#define rx 2                                          //define what pin rx (receive) is going to be
#define tx 3                                          //define what pin tx (transit) is going to be

SoftwareSerial myserial(rx, tx);                      //defines the object myserial port for the conductivity probe

String sensorstring = "";                             //a string to hold the data from the Atlas Scientific product
boolean sensor_string_complete = false;               //have we received all the data from the Atlas Scientific product


void setup() {                                        //set up the hardware
  Serial.begin(9600);                                 //Serial prints results to the Arduino Monitor
  myserial.begin(9600);                               //myserial is used to read data from the conductivity probe
  sensorstring.reserve(30);                           //set aside some bytes for receiving data from Atlas Scientific product
}


void loop() {                                
  // loop until data set complete
  if (myserial.available() > 0) {                     //if we see that the Electricity Conductivity probe has sent a character
    char inchar = (char)myserial.read();              //get the char we just received
    sensorstring += inchar;                           //add the char to the var called sensorstring
    if (inchar == '\r') {                             //if the incoming character is a <CR>
      sensor_string_complete = true;                  //set the flag
    }
  }


  if (sensor_string_complete == true) {               //if a string from the EC probe has been received in full
      char sensorstring_array[30];                        //we make a char array
      char *EC;                                           //char pointer used in string parsing
      sensorstring.toCharArray(sensorstring_array, 30);   //convert the string to a char array 
      EC = strtok(sensorstring_array, ",");               //let's pars the first value into an array
      Serial.print("The Electrical Conductivity = ");
      Serial.println(EC);                                 //this is the EC value - send this value to the Raspberry Pi 
      sensorstring = "";                                //clear the string
      sensor_string_complete = false;                   //reset the flag used to tell if we have received a completed string
  }
}

Arduino IDE Serial Monitor - Example of output

  • Example of output from conductivity sensor when placed in tap water.

Arduino Uno - Turbidity Sensor

  • A turbidity sensor measures the cloudiness of water.
  • Turbidity sensors are used to monitor water ways and also the cleanliness of water.
  • Turbidity sensors detect suspended particles in water by measuring the light transmittance and scattering rate which changes with the amount of total suspended solids (TSS) in water.
  • As total suspended solids increases, turbidity values also increase.

Materials

  • Turbidity sensor - Analog Turbidity Sensor
  • Make up different turbidity samples using instant coffee mixed into tap water.

Fritzing - Analog Turbidity Sensor

Photo of turbidity sensor circuit connect to Arduino Uno

  • Analog output of turbidity sensor connected to Arduino Uno analog input pin A1
  • Turbidity sensor connected to 5V supply (5V and GND pins)

Arduino Code Example - Analog Turbidity Sensor

int sensorPin = A1;    // Analog pin A1 used as input for the turbidity sensor
int sensorValue = 0;  // variable to store the value coming from the sensor

void setup() {
  Serial.begin(9600);
}

void loop() {
  sensorValue = analogRead(sensorPin);  // read the value from the sensor:
  Serial.println(sensorValue);          // print the value to the Arduino Serial Monitor
  delay(1000);
}

Arduino Uno - Fan Module

  • Arduino compatible Fan Module SKU: DFR0332 Brand: DFRobot
  • Make a cooling system for a tiny house or a greenhouse with this small fan module.
  • It comes with a propeller, a 15,000 rpm motor and cable.
  • Fan speed is controlled using the analogWrite(pin, speed) statement.
  • Arduino Uno pins need to support Pulse width Modulation. Example pins include pins 3, 5, 6, 9, 10, 11.
  • Pulse width modulation compatible pins can be identified because they have a ~ tilde symbol next to their number.
  • Speed setting values can range from 0 - 255.

Parts list and supporting information

Fritzing - Arduino compatible Fan module DFRobot DR0332

Photo showing Fan Module connected to Arduino Uno

Arduino Code Example - Gradual speed increase

  • Speed of fan will increase by 5 unit increments every second.
  • Speed values range from 0 to 255.
  • Current speed can be viewed using the Serial Monitor.
//Arduino Sample Code for Fan Module
//www.DFRobot.com
//Version 1.0

#define Fan 3    //define driver pins

void setup()
{
  pinMode(Fan,OUTPUT);
  Serial.begin(9600);    //Baudrate: 9600
}
void loop()
{
  int value;
  for(value = 0 ; value <= 255; value+=5)
  {
    analogWrite(Fan, value);   //PWM
    Serial.println(value);
    delay(1000);
  }
}


Arduino Code Example - Single speed setting

  • Fan speed set to 200 units.
//Arduino Sample Code for Fan Module
//www.DFRobot.com
//Version 1.0

#define Fan 3    //define driver pins

void setup()
{
  pinMode(Fan,OUTPUT);
  Serial.begin(9600);    //Baudrate: 9600
}

void loop()
{
   int value = 200;           // Fan set at fixed value
   analogWrite(Fan, value);   //PWM
   Serial.println(value);
   delay(1000);
}

Arduino Uno - One Wire Temperature sensor

Frizing - Circuit diagram

  • In this circuit diagram the data line is connected to pin 2.
  • In the Arduino code below the data line is connected to pin 4.

One Wire Library installation

  • Select Sketch > Include Library > Manage Libraries
  • Wait for libraries to update. This may take 1-2 minutes.
  • In the search bar enter onewire and press Enter.

  • Install the One Wire library.
  • Use the One wire library with the author Paul Stoffregen

  • In this example the onewire library version 2.3.7 was installed.

Dallas Temperature Library installation

  • After installing the onewire library now enter Dallas as the search term.

  • In this instance version 3.9.0 of the DallasTemperature library was installed.

Arduino Uno Code

#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is conntec to the Arduino digital pin 4
#define ONE_WIRE_BUS 4

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature sensors(&oneWire);

void setup(void)
{
  // Start serial communication for debugging purposes
  Serial.begin(9600);
  // Start up the library
  sensors.begin();
}

void loop(void){ 
  // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
  sensors.requestTemperatures(); 
  
  Serial.print("Celsius temperature: ");
  // Why "byIndex"? You can have more than one IC on the same bus. 0 refers to the first IC on the wire
  Serial.println(sensors.getTempCByIndex(0)); 
  delay(1000);
}

Serial Monitor output

  • Temperature readings output to the Serial Monitor.

Arduino Uno - Real Time Clock and Data Logger Shield

References


Example Code to read Time and Date

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include "RTClib.h"

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
  Serial.begin(57600);

//#ifndef ESP8266
  //while (!Serial); // wait for serial port to connect. Needed for native USB
//#endif

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    while (1) delay(10);
  }


  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    delay(3000);
}

Example output of code - Time and Date

Example Code - Timestamp

/* Timestamp functions using a DS1307 RTC connected via I2C and Wire lib
**
** Useful for file name
**		` SD.open(time.timestamp()+".log", FILE_WRITE) `
*/

#include "RTClib.h"

RTC_DS1307 rtc;

void setup () {
  Serial.begin(57600);

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    while (1) delay(10);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}

void loop() {
 DateTime time = rtc.now();

 //Full Timestamp
 Serial.println(String("DateTime::TIMESTAMP_FULL:\t")+time.timestamp(DateTime::TIMESTAMP_FULL));

 //Date Only
 Serial.println(String("DateTime::TIMESTAMP_DATE:\t")+time.timestamp(DateTime::TIMESTAMP_DATE));

 //Full Timestamp
 Serial.println(String("DateTime::TIMESTAMP_TIME:\t")+time.timestamp(DateTime::TIMESTAMP_TIME));

 Serial.println("\n");

 //Delay 5s
 delay(5000);
}

Timestamp - Example output

SD Card Test - Example Code

/*
  SD card test

  This example shows how use the utility libraries on which the'
  SD library is based in order to get info about your SD card.
  Very useful for testing a card when you're not sure whether its working or not.

  The circuit:
    SD card attached to SPI bus as follows:
 ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
 ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
 ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
 ** CS - depends on your SD card shield or module.
 		Pin 4 used here for consistency with other Arduino examples


  created  28 Mar 2011
  by Limor Fried
  modified 9 Apr 2012
  by Tom Igoe
*/
// include the SD library:
#include <SPI.h>
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
// MKRZero SD: SDCARD_SS_PIN
const int chipSelect = 10;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }


  Serial.print("\nInitializing SD card...");

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    while (1);
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.println();
  Serial.print("Card type:         ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    while (1);
  }

  Serial.print("Clusters:          ");
  Serial.println(volume.clusterCount());
  Serial.print("Blocks x Cluster:  ");
  Serial.println(volume.blocksPerCluster());

  Serial.print("Total Blocks:      ");
  Serial.println(volume.blocksPerCluster() * volume.clusterCount());
  Serial.println();

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("Volume type is:    FAT");
  Serial.println(volume.fatType(), DEC);

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize /= 2;                           // SD card blocks are always 512 bytes (2 blocks are 1KB)
  Serial.print("Volume size (Kb):  ");
  Serial.println(volumesize);
  Serial.print("Volume size (Mb):  ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Gb):  ");
  Serial.println((float)volumesize / 1024.0);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);

  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
}

void loop(void) {
}

SD Card Test - Example Output