Input-Output Components

by fenilchandarana in Circuits > Arduino

982 Views, 5 Favorites, 0 Comments

Input-Output Components

Screenshot_1.png

In this Instructable, I'll give brief description of various Input-Output components, mainly the wiring and the code for reading it's data. Here is the list of all the components,


  1. RGB LED - Common anode & Common cathode
  2. Photoresistor/Light dependent resistor
  3. Thermistor
  4. A3144 Hall effect sensor
  5. Infrared LED
  6. 4x4 Keypad
  7. Stepper motor with driver
  8. Sound sensor
  9. PIR sensor
  10. Accelerometer
  11. OLED
  12. Hall effect sensor module
  13. LM393 Voltage comparator module
  14. Compass/Magnetometer
  15. 7 segment display
  16. Servo motor
  17. Radio frequency 430mhz transmitter and receiver
  18. 8x8 LED dot matrix
  19. Real-time clock module
  20. Temperature sensor
  21. DC motor and driver
  22. Touch sensor
  23. Joystick
  24. LCD with I2C module
  25. Ultrasonic sensor
  26. Color sensor
  27. RFID Sensor
  28. BO Motor and driver
  29. Single channel relay module
  30. Current sensor

Supplies

You will find most of the components in electronicscomp or robu website. Just copy paste the following name of the components in the website or Search engine. The sequence of the list of components and the name of components to search are parallel.


  1. RGB LED - 5mm - Common Anode & RGB LED - 5mm - Common Cathode
  2. LDR-8mm
  3. 10K Ohm NTC Thermistor
  4. A3144 Hall Effect Sensor
  5. IR Transmitter LED 5mm & IR Receiver LED 5mm
  6. 4x4 Matrix Membrane Type Keypad -16 Keys
  7. 28BYJ-48 Stepper Motor - 5V Unipolar & ULN2003 Stepper Motor Driver Board
  8. Sound Detection Sensor Module
  9. PIR Motion Detector Sensor Module HC-SR501
  10. MPU6050 - Triple Axis Gyro Accelerometer Module
  11. 2.44 cm (0.96 Inch) I2C/IIC 128x64 OLED Display Module 4 Pin - White Color
  12. Hall Effect Sensor Module
  13. LM393 – Comparator Module
  14. GY-271 QMC5883 Electronic Compass Module Three-Axis Magnetometer Field Sensor
  15. TM1637 4 Digits 7 Segment Led Display Module
  16. Tower Pro SG90 Servo - 9 gms Mini/Micro Servo Motor
  17. FS1000A 433mHz Transmitter Receiver RF Radio Module
  18. MAX7219 8x8 LED Dot Matrix Display Module
  19. DS3231 Real Time Clock (RTC) Module
  20. DHT22 - Temperature and Humidity Sensor Module
  21. L293D Motor Driver Board & DC Toy Motor
  22. TTP223 - 1 Channel Capacitive Touch Sensor Module Blue Color
  23. Dual Axis XY Joystick Module
  24. 16x2 (1602) Character Blue Backlight LCD Display & I2C Module for 16x2 (1602) Character LCD
  25. Ultrasonic Distance Sensor Module - HC-SR04
  26. TCS3200 TCS230 Color Sensor Module
  27. RC522 RFID 13.56MHZ Reader Writer Module
  28. L298N Motor Driver & BO Motor
  29. 5V 1 Channel Relay Module
  30. ACS712 - 30A Range Current Sensor Module

RGB LED Common Anode and Common Cathode

Screenshot_2.png
Screenshot_1.png

This the the code for blinking common anode LED,

/*
  Blink


  Turns an LED on for one second, then off for one second, repeatedly.


  Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
  it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
  the correct LED pin independent of which board is used.
  If you want to know what pin the on-board LED is connected to on your Arduino
  model, check the Technical Specs of your board at:
  https://www.arduino.cc/en/Main/Products


  modified 8 May 2014
  by Scott Fitzgerald
  modified 2 Sep 2016
  by Arturo Guadalupi
  modified 8 Sep 2016
  by Colby Newman


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/Blink
*/


// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
}


// the loop function runs over and over again forever
void loop() {
  digitalWrite(5, LOW);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(5, HIGH);    // turn the LED off by making the voltage LOW
  delay(100);                       // wait for a second


  digitalWrite(6, LOW);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(6, HIGH);    // turn the LED off by making the voltage LOW
  delay(100);                       // wait for a second


  digitalWrite(7, LOW);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(7, HIGH);    // turn the LED off by making the voltage LOW
  delay(100);                       // wait for a second


}


This is the code for blinking common cathode LED,

/*
  Blink


  Turns an LED on for one second, then off for one second, repeatedly.


  Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
  it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
  the correct LED pin independent of which board is used.
  If you want to know what pin the on-board LED is connected to on your Arduino
  model, check the Technical Specs of your board at:
  https://www.arduino.cc/en/Main/Products


  modified 8 May 2014
  by Scott Fitzgerald
  modified 2 Sep 2016
  by Arturo Guadalupi
  modified 8 Sep 2016
  by Colby Newman


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/Blink
*/


// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
}


// the loop function runs over and over again forever
void loop() {
  digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(5, LOW);    // turn the LED off by making the voltage LOW
  delay(100);                       // wait for a second


  digitalWrite(6, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(6, LOW);    // turn the LED off by making the voltage LOW
  delay(100);                       // wait for a second


  digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
  delay(100);                       // wait for a second


}

Photoresistor/Light Dependent Resistor

0400+-+Photoresistor.png

This is the code for reading Analog signal from the photoresistor,

/*
  AnalogReadSerial


  Reads an analog input on pin 0, prints the result to the Serial Monitor.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/AnalogReadSerial
*/


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}


// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

Downloads

Thermistor

0440+-+Thermistor+5V.png
0440+-+Thermistor+3V3.png

This is the code for reading the temperature for Thermistor,

/*  Thermistor temperature sensor demonstration sketch
 * 
 * This sketch calculates the the temperature by reading the voltage of a 
 * thermistor connected in a voltage divider circuit.
 * 
 * It then does a caclulation to convert this raw reading into a temperature.
 * 
 * This sketch was adapted for Arduino Step by Step by Peter Dalmaris from the 
 * demo sketch that ships with the library, written by Daniel Berenguer.
 * 
 * Components
 * ----------
 *  - Arduino Uno
 *  - thermistor temperature sensor
 *  - 10 kOhm resistor
 *  
 *  Libraries
 *  ---------
 *  Thermistor.h
 *
 * Connections
 * -----------
 * 
 * Connect the Arduino 5V pin to one end of the
 * thermistor. Connect the resistor to the Arduino GND
 * pin. Connect the free pins on the thermistor and 
 * resistor together. Connect the thermistor and resistor
 * junction to the Arduino analog pin 0. This
 * structure is called a "voltage divider".
 *                    10 kΩ
 *  5V -----OOO------\/\/\/-----GND
 *                |
 *                |
 *                |
 *                A0
 *      
 * 
 * Other information
 * -----------------
 * 
 * About the termistor: https://en.wikipedia.org/wiki/Thermistor
 * The Github repository for the library: https://github.com/panStamp/thermistor
 * 
 * 
 * 
 *  Created on October 8 2016 by Peter Dalmaris
 * 
 */


/**
 * Copyright (c) 2015 panStamp S.L.U. <contact@panstamp.com>
 * 
 * This file is part of the panStamp project.
 * 
 * panStamp  is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * panStamp is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with panStamp; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 
 * USA
 * 
 * Author: Daniel Berenguer
 * Creation date: 06/24/2015
 */


#include "thermistor.h"


// Analog pin used to read the NTC
#define NTC_PIN               A0


// Thermistor object
THERMISTOR thermistor(NTC_PIN,        // Analog pin
                      7500,          // Nominal resistance at 25 ºC
                      3950,           // thermistor's beta coefficient
                      9950);         // Value of the series resistor


// Global temperature reading
uint16_t temp;


/**
 * setup
 *
 * Arduino setup function
 */
void setup()
{
  Serial.begin(9600);
}


/**
 * loop
 *
 * Arduino main loop
 */
void loop()
{
  temp = thermistor.read();   // Read temperature


  Serial.print("Temp in 1/10 ºC : ");
  Serial.println(temp);


  delay(5000);
}

Downloads

A3144 Hall Effect Sensor

Screenshot_3.png
Screenshot_1.png

This is the code for reading Digital signal from the A3144 Hall effect sensor,

/*
  DigitalReadSerial


  Reads a digital input on pin 2, prints the result to the Serial Monitor


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/DigitalReadSerial
*/


// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}


// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(1);        // delay in between reads for stability
}

Infrared LED

Screenshot_1.png

This is the code for reading the Digital signal from Infrared LED Receiver,

/*
  DigitalReadSerial


  Reads a digital input on pin 2, prints the result to the Serial Monitor


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/DigitalReadSerial
*/


// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}


// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(1);        // delay in between reads for stability
}

4x4 Keypad

Screenshot (1042).png

This is the code for reading the digits in the serial monitor when the key is pressed,

#include "Keypad.h"
 
const byte ROWS = 4; // number of rows
const byte COLS = 4; // number of columns
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','D'},
{'#','0','*','D'}
};


byte rowPins[ROWS] = {9,8,7,6}; // row pinouts of the keypad R1 = D8, R2 = D7, R3 = D6, R4 = D5
byte colPins[COLS] = {5,4,3,2};    // column pinouts of the keypad C1 = D4, C2 = D3, C3 = D2
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
 
void setup()
{
  Serial.begin(9600);
}
 
void loop()
{
  char key = keypad.getKey(); 
  if (key != NO_KEY)
    Serial.println(key);
}

Downloads

Stepper Motor With Driver

Wiring-Two-28BYJ48-Stepper-Motors-with-Arduino.png

This is the code for driving 2 stepper motor,

// credits for this sketch goes to Stein. 
// Stein's email address: harelabb@lyse.net


#include <SerialStepper.h>
#include <arduinostepper.h>


// Define 2 steppers
Stepper steppers[2];


// each using an ArduinoStepper control
ArduinoStepperControl stepper_ctl[] = {
  ArduinoStepperControl {4, 5, 6, 7},
  ArduinoStepperControl {8, 9, 10, 11}// the pins
 };


// Helper function to check if all the steppers has reached target
bool anyRunning() {
  for (const auto& stepper : steppers) {
    if (stepper.running()) {
      return true;
    }
  }
  return false;
}


void setup() {
  /// Initialize the stepper motor controllers
  for (auto& ctl : stepper_ctl) {
    ctl.begin();
  }


  /// Assign steppers to the controllers
  for (int i = 0; i <2 ; ++i) {
    stepper_ctl[i].addStepper(steppers[i]);
  }


  // Set stepper speed to 16 RPM
  for (auto& stepper : steppers) {
    stepper.speed(7);
  }


}


// Forward is CCW
constexpr auto CCW   = Stepper::BACKWARD;
constexpr auto CW  = Stepper::FORWARD;


void loop() {
  float pos = 0; // keep track of position


  delay(4000);


  // need to loop until time for next delay
  // the clock must be updated before the step terget is set
  
  loopClock::tick();


  for (auto& stepper: steppers) {
    stepper.direction(CW);
    


    steppers[0].turn(1.0);
    steppers[1].turn(0.625);


  }
  
  while (anyRunning()) {
    loopClock::tick();
    for (auto& ctl : stepper_ctl) {
      ctl.run();
    }
    yield();
  }


delay(2000);


}

Sound Sensor

0560+-+Digital+sound+sensor.png

This is the code for reading Analog signal of the sound sensor,

/*
  AnalogReadSerial


  Reads an analog input on pin 0, prints the result to the Serial Monitor.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/AnalogReadSerial
*/


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}


// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

1023 is the total range of analog. 

To set the sensitivity, turn the knob of potentiometer and look at the readings. If the readings will be below 512, on board led will be on. If the value is above 512. on board led will be off.

So set the value/sensitivity accordingly. You set the sensitivity at 520, DO pin will give HIGH signal/on board led will turn on with slightest amount of noise. Similarly, if you set the value to 800, it will take a loud noise for the DO pin to give HIGH signal/on board led will turn on. 

PIR Sensor

Screenshot_9.png
Screenshot_1.png

This is the code for reading Digital signal of the PIR sensor,

/*
  DigitalReadSerial


  Reads a digital input on pin 2, prints the result to the Serial Monitor


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/DigitalReadSerial
*/


// digital pin 2 has a pushbutton attached to it. Give it a name:
int pirpin = 7;


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pirpin, INPUT);
}


// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int pirpinState = digitalRead(pirpin);
  // print out the state of the button:
  Serial.println(pirpinState);
  delay(1);        // delay in between reads for stability
}

description of PIR sensor module


sensitivity adjust: rotate the knob clockwise and its sensitivity will increase. Sensitivity means distance, from how much distance will the PIR sensor detect the motion. 

time delay adjust: rotate the knob and the time delay will increase. Time delay means for how long will the signal remain high after the sensor is triggered from the motion. SO when there is motion, the signal from the output pin will be HIGH for 5 seconds. If you increase the time delay the output pin will be high for 60 seconds, example

after the sensor is triggered, the output pin will be high for the time you set in time adjust delay and then it will be turned off. it will be off for a fixed amount of time around 4 seconds for both mode- single and repeat trigger. It is kind of reset time it takes. If however there is motion after 2 seconds output pin being low, the output pin will turn on high after completing the 4 second cycle. 

in single trigger the output pin will be high just once and it will turn off no matter if there is movement. in repeat trigger it will remain on until there is motion.

Accelerometer

Screenshot_1.png

This is the Arduino code for reading the values in the serial monitor,

// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//      2019-07-08 - Added Auto Calibration and offset generator
//    - and altered FIFO retrieval sequence to avoid using blocking code
//      2016-04-18 - Eliminated a potential infinite loop
//      2013-05-08 - added seamless Fastwire support
//                 - added note about gyro calibration
//      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
//      2012-06-20 - improved FIFO overflow handling and simplified read process
//      2012-06-19 - completely rearranged DMP initialization code and simplification
//      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
//      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
//      2012-06-05 - add gravity-compensated initial reference frame acceleration output
//                 - add 3D math helper file to DMP6 example sketch
//                 - add Euler output and Yaw/Pitch/Roll output formats
//      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
//      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
//      2012-05-30 - basic DMP initialization working


/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg


Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:


The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/


// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"


#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file


// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif


// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high


/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */


/* =========================================================================
   NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
   when using Serial.write(buf, len). The Teapot output uses this method.
   The solution requires a modification to the Arduino USBAPI.h file, which
   is fortunately simple, but annoying. This will be fixed in the next IDE
   release. For more info, see these links:


   http://arduino.cc/forum/index.php/topic,109987.0.html
   http://code.google.com/p/arduino/issues/detail?id=958
 * ========================================================================= */


// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION


// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER


// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL


// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL


// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL


// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT


#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;


// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer


// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector


// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };


// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================


volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}


// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================


void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif


    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(9600);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately


    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3V or Arduino
    // Pro Mini running at 3.3V, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.


    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);


    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));


    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again


    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();


    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip


    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // Calibration Time: generate offsets and calibrate our MPU6050
        mpu.CalibrateAccel(6);
        mpu.CalibrateGyro(6);
        mpu.PrintActiveOffsets();
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);


        // enable Arduino interrupt detection
        Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
        Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
        Serial.println(F(")..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();


        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;


        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }


    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
}


// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================


void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;
    // read a packet from FIFO
    if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) { // Get the Latest packet 
        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif


        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif


        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif


        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif


        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif
    
        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif


        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}

This is the Processing code for for getting the feedback in the form of Airplane visual,

// I2C device class (I2Cdev) demonstration Processing sketch for MPU6050 DMP output
// 6/20/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//     2012-06-20 - initial release


/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg


Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:


The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/


import processing.serial.*;
import processing.opengl.*;
import toxi.geom.*;
import toxi.processing.*;


// NOTE: requires ToxicLibs to be installed in order to run properly.
// 1. Download from http://toxiclibs.org/downloads
// 2. Extract into [userdir]/Processing/libraries
//    (location may be different on Mac/Linux)
// 3. Run and bask in awesomeness


ToxiclibsSupport gfx;


Serial port;                         // The serial port
char[] teapotPacket = new char[14];  // InvenSense Teapot packet
int serialCount = 0;                 // current packet byte position
int synced = 0;
int interval = 0;


float[] q = new float[4];
Quaternion quat = new Quaternion(1, 0, 0, 0);


float[] gravity = new float[3];
float[] euler = new float[3];
float[] ypr = new float[3];


void setup() {
    // 300px square viewport using OpenGL rendering
    size(300, 300, OPENGL);
    gfx = new ToxiclibsSupport(this);


    // setup lights and antialiasing
    lights();
    smooth();
  
    // display serial port list for debugging/clarity
    println(Serial.list());


    // get the first available port (use EITHER this OR the specific port code below)
    //String portName = Serial.list()[0];
    
    // get a specific serial port (use EITHER this OR the first-available code above)
    String portName = "COM22";
    
    // open the serial port
    port = new Serial(this, portName, 9600);
    
    // send single character to trigger DMP init/start
    // (expected by MPU6050_DMP6 example Arduino sketch)
    port.write('r');
}


void draw() {
    if (millis() - interval > 1000) {
        // resend single character to trigger DMP init/start
        // in case the MPU is halted/reset while applet is running
        port.write('r');
        interval = millis();
    }
    
    // black background
    background(0);
    
    // translate everything to the middle of the viewport
    pushMatrix();
    translate(width / 2, height / 2);


    // 3-step rotation from yaw/pitch/roll angles (gimbal lock!)
    // ...and other weirdness I haven't figured out yet
    //rotateY(-ypr[0]);
    //rotateZ(-ypr[1]);
    //rotateX(-ypr[2]);


    // toxiclibs direct angle/axis rotation from quaternion (NO gimbal lock!)
    // (axis order [1, 3, 2] and inversion [-1, +1, +1] is a consequence of
    // different coordinate system orientation assumptions between Processing
    // and InvenSense DMP)
    float[] axis = quat.toAxisAngle();
    rotate(axis[0], -axis[1], axis[3], axis[2]);


    // draw main body in red
    fill(255, 0, 0, 200);
    box(10, 10, 200);
    
    // draw front-facing tip in blue
    fill(0, 0, 255, 200);
    pushMatrix();
    translate(0, 0, -120);
    rotateX(PI/2);
    drawCylinder(0, 20, 20, 8);
    popMatrix();
    
    // draw wings and tail fin in green
    fill(0, 255, 0, 200);
    beginShape(TRIANGLES);
    vertex(-100,  2, 30); vertex(0,  2, -80); vertex(100,  2, 30);  // wing top layer
    vertex(-100, -2, 30); vertex(0, -2, -80); vertex(100, -2, 30);  // wing bottom layer
    vertex(-2, 0, 98); vertex(-2, -30, 98); vertex(-2, 0, 70);  // tail left layer
    vertex( 2, 0, 98); vertex( 2, -30, 98); vertex( 2, 0, 70);  // tail right layer
    endShape();
    beginShape(QUADS);
    vertex(-100, 2, 30); vertex(-100, -2, 30); vertex(  0, -2, -80); vertex(  0, 2, -80);
    vertex( 100, 2, 30); vertex( 100, -2, 30); vertex(  0, -2, -80); vertex(  0, 2, -80);
    vertex(-100, 2, 30); vertex(-100, -2, 30); vertex(100, -2,  30); vertex(100, 2,  30);
    vertex(-2,   0, 98); vertex(2,   0, 98); vertex(2, -30, 98); vertex(-2, -30, 98);
    vertex(-2,   0, 98); vertex(2,   0, 98); vertex(2,   0, 70); vertex(-2,   0, 70);
    vertex(-2, -30, 98); vertex(2, -30, 98); vertex(2,   0, 70); vertex(-2,   0, 70);
    endShape();
    
    popMatrix();
}


void serialEvent(Serial port) {
    interval = millis();
    while (port.available() > 0) {
        int ch = port.read();


        if (synced == 0 && ch != '$') return;   // initial synchronization - also used to resync/realign if needed
        synced = 1;
        print ((char)ch);


        if ((serialCount == 1 && ch != 2)
            || (serialCount == 12 && ch != '\r')
            || (serialCount == 13 && ch != '\n'))  {
            serialCount = 0;
            synced = 0;
            return;
        }


        if (serialCount > 0 || ch == '$') {
            teapotPacket[serialCount++] = (char)ch;
            if (serialCount == 14) {
                serialCount = 0; // restart packet byte position
                
                // get quaternion from data packet
                q[0] = ((teapotPacket[2] << 8) | teapotPacket[3]) / 16384.0f;
                q[1] = ((teapotPacket[4] << 8) | teapotPacket[5]) / 16384.0f;
                q[2] = ((teapotPacket[6] << 8) | teapotPacket[7]) / 16384.0f;
                q[3] = ((teapotPacket[8] << 8) | teapotPacket[9]) / 16384.0f;
                for (int i = 0; i < 4; i++) if (q[i] >= 2) q[i] = -4 + q[i];
                
                // set our toxilibs quaternion to new data
                quat.set(q[0], q[1], q[2], q[3]);


                /*
                // below calculations unnecessary for orientation only using toxilibs
                
                // calculate gravity vector
                gravity[0] = 2 * (q[1]*q[3] - q[0]*q[2]);
                gravity[1] = 2 * (q[0]*q[1] + q[2]*q[3]);
                gravity[2] = q[0]*q[0] - q[1]*q[1] - q[2]*q[2] + q[3]*q[3];
    
                // calculate Euler angles
                euler[0] = atan2(2*q[1]*q[2] - 2*q[0]*q[3], 2*q[0]*q[0] + 2*q[1]*q[1] - 1);
                euler[1] = -asin(2*q[1]*q[3] + 2*q[0]*q[2]);
                euler[2] = atan2(2*q[2]*q[3] - 2*q[0]*q[1], 2*q[0]*q[0] + 2*q[3]*q[3] - 1);
    
                // calculate yaw/pitch/roll angles
                ypr[0] = atan2(2*q[1]*q[2] - 2*q[0]*q[3], 2*q[0]*q[0] + 2*q[1]*q[1] - 1);
                ypr[1] = atan(gravity[0] / sqrt(gravity[1]*gravity[1] + gravity[2]*gravity[2]));
                ypr[2] = atan(gravity[1] / sqrt(gravity[0]*gravity[0] + gravity[2]*gravity[2]));
    
                // output various components for debugging
                //println("q:\t" + round(q[0]*100.0f)/100.0f + "\t" + round(q[1]*100.0f)/100.0f + "\t" + round(q[2]*100.0f)/100.0f + "\t" + round(q[3]*100.0f)/100.0f);
                //println("euler:\t" + euler[0]*180.0f/PI + "\t" + euler[1]*180.0f/PI + "\t" + euler[2]*180.0f/PI);
                //println("ypr:\t" + ypr[0]*180.0f/PI + "\t" + ypr[1]*180.0f/PI + "\t" + ypr[2]*180.0f/PI);
                */
            }
        }
    }
}


void drawCylinder(float topRadius, float bottomRadius, float tall, int sides) {
    float angle = 0;
    float angleIncrement = TWO_PI / sides;
    beginShape(QUAD_STRIP);
    for (int i = 0; i < sides + 1; ++i) {
        vertex(topRadius*cos(angle), 0, topRadius*sin(angle));
        vertex(bottomRadius*cos(angle), tall, bottomRadius*sin(angle));
        angle += angleIncrement;
    }
    endShape();
    
    // If it is not a cone, draw the circular top cap
    if (topRadius != 0) {
        angle = 0;
        beginShape(TRIANGLE_FAN);
        
        // Center point
        vertex(0, 0, 0);
        for (int i = 0; i < sides + 1; i++) {
            vertex(topRadius * cos(angle), 0, topRadius * sin(angle));
            angle += angleIncrement;
        }
        endShape();
    }
  
    // If it is not a cone, draw the circular bottom cap
    if (bottomRadius != 0) {
        angle = 0;
        beginShape(TRIANGLE_FAN);
    
        // Center point
        vertex(0, tall, 0);
        for (int i = 0; i < sides + 1; i++) {
            vertex(bottomRadius * cos(angle), tall, bottomRadius * sin(angle));
            angle += angleIncrement;
        }
        endShape();
    }
}

these are examples from the mpu6050 library. 


with teapot line commented, you can get the reading of the mpu6050 from the serial monitor


 just uncomment the teapot line from the arduino.ino file and then upload the processing file with correct port name and same baud rate to get the 3d visual of the sensor


for nano you can use 115200 baud rate. For esp32 and UNO, you have to use 9600 baud rate


earlier uno was freezing serial monitor with 115200 baud rate. Now it is working fine with 9600 baud rate. If it still freezes later, you can follow the link below.

https://forum.arduino.cc/t/mpu6050-freezing-crashing/393676/6

OLED

Screenshot_1.png

Use this code to find the I2C address of your module,

#include <Wire.h>


void setup()


{
  Serial.begin (9600);
   while (!Serial)
    {
    }


  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;
  pinMode(13,OUTPUT); 
  digitalWrite(13,HIGH);
  Wire.begin();
  for (byte i = 1; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1); 
      } 
  } 
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");



void loop() {}


Use the same I2C address in the line

  display.begin(SSD1306_SWITCHCAPVCC, 0X3C);


Then use this code to display text in OLED,

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>


#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);


#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels


void setup() {
  // put your setup code here, to run once:
  display.begin(SSD1306_SWITCHCAPVCC, 0X3C);
  display.clearDisplay();
}


void loop() {
  // put your main code here, to run repeatedly:
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println("row number 1");
  display.setCursor(0,12);
  display.println("row number 2");
  display.setCursor(0,24);
  display.println("row number 3");
  display.display();
}

Hall Effect Sensor Module

Screenshot_2.png

This is the code for reading the digital signal from the hall effect sensor module,

/*
  DigitalReadSerial


  Reads a digital input on pin 2, prints the result to the Serial Monitor


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/DigitalReadSerial
*/


// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}


// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(1);        // delay in between reads for stability
}

LM393 Voltage Comparator Module

LM393-Module-pin.jpg
LM393-Module-wire.jpg

You can attach any input component on the two input pins of the LM393 Voltage comparator like photoresistor, thermistor, electret microphone.

If you want to read the Analog signals from the component use this code,

/*
  AnalogReadSerial


  Reads an analog input on pin 0, prints the result to the Serial Monitor.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/AnalogReadSerial
*/


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}


// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

If you want to read the digital signal from the component use this code,

/*
  DigitalReadSerial


  Reads a digital input on pin 2, prints the result to the Serial Monitor


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/DigitalReadSerial
*/


// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 3;


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}


// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(1);        // delay in between reads for stability
}

Compass/Magnetometer

Screenshot_1.png

Use this code to find the I2C address of your module,

#include <Wire.h>


void setup()


{
  Serial.begin (9600);
   while (!Serial)
    {
    }


  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;
  pinMode(13,OUTPUT); 
  digitalWrite(13,HIGH);
  Wire.begin();
  for (byte i = 1; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1); 
      } 
  } 
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");



void loop() {}

If your I2C address is 0x0D then you can proceed and use this code to get the readings from the QMC5883 module,

#include <Wire.h>
#include <MechaQMC5883.h>


MechaQMC5883 qmc;


void setup() {
  Wire.begin();
  Serial.begin(9600);
  qmc.init();
  //qmc.setMode(Mode_Continuous,ODR_200Hz,RNG_2G,OSR_256);
}


void loop() {
  int x, y, z;
  int azimuth;
  //float azimuth; //is supporting float too
  qmc.read(&x, &y, &z,&azimuth);
  //azimuth = qmc.azimuth(&y,&x);//you can get custom azimuth
  Serial.print("x: ");
  Serial.print(x);
  Serial.print(" y: ");
  Serial.print(y);
  Serial.print(" z: ");
  Serial.print(z);
  Serial.print(" a: ");
  Serial.print(azimuth);
  Serial.println();
  delay(100);
}

7 Segment Display

Screenshot_1.png

This is the code to display text in 7 segment display module,

// Include the library
#include <TM1637Display.h>


// Define the connections pins
#define CLK 11
#define DIO 12


// Create a display object of type TM1637Display
TM1637Display display = TM1637Display(CLK, DIO);


// Create an array that turns all segments ON
const uint8_t allON[] = {0xff, 0xff, 0xff, 0xff};


// Create an array that turns all segments OFF
const uint8_t allOFF[] = {0x00, 0x00, 0x00, 0x00};


// Create an array that sets individual segments per digit to display the word "dOnE"
const uint8_t done[] = {
  SEG_B | SEG_C | SEG_D | SEG_E | SEG_G,           // d
  SEG_A | SEG_B | SEG_C | SEG_D | SEG_E | SEG_F,   // O
  SEG_C | SEG_E | SEG_G,                           // n
  SEG_A | SEG_D | SEG_E | SEG_F | SEG_G            // E
};


// Create degree celsius symbol
const uint8_t celsius[] = {
  SEG_A | SEG_B | SEG_F | SEG_G,  // Degree symbol
  SEG_A | SEG_D | SEG_E | SEG_F   // C
};


// Create an array that sets individual segments per digit to display the word "ALL"
const uint8_t all[] = {
  SEG_A | SEG_B | SEG_C | SEG_E | SEG_F | SEG_G,   // A
  SEG_D | SEG_E | SEG_F,   // L
  SEG_D | SEG_E | SEG_F   // L
};


// Create an array that sets individual segments per digit to display the symbol "dash"
const uint8_t dash[] = {
SEG_G, SEG_G, SEG_G, SEG_G
};


void setup() {
  // Set the brightness to 5 (0=dimmest 7=brightest)
  display.setBrightness(3);
  display.setSegments(dash);
    delay(500);
  display.clear();
  
  display.setSegments(allOFF);
  delay(2000);
}


void loop() {


  
  display.showNumberDec(-12);     // Prints _-12
  delay(2000);
  display.clear();


  display.showNumberDec(31, false); // Prints __31
  delay(2000);
  display.clear();


    display.showNumberDec(31, true); // Prints __31
  delay(2000);
  display.clear();


  display.showNumberDec(31, true);  // Prints 0031
  delay(2000);
  display.clear();


  display.showNumberDec(14, false, 2, 1); // Prints _14_
  delay(2000);
  display.clear();


    display.showNumberDec(14, false, 2, 0); // Prints _14_
  delay(2000);
  display.clear();


    display.showNumberDec(14, false, 2, 2); // Prints _14_
  delay(2000);
  display.clear();


    


//   Prints 15°C
  int temperature = 15;
  display.showNumberDec(temperature, false, 2, 0);
  display.setSegments(celsius, 2, 2);
  delay(2000);
  display.clear();


  // Prints ALL
    display.setSegments(all, 3, 0);
      delay(2000);
  display.clear();


  // Prints dOnE
  display.setSegments(done);


  delay(2000);
  display.clear();


}

Servo Motor

Screenshot_1.png

This is the code for controlling servo motor,

/*  0932 - Simple servo motor demo
 * 
 * This sketch shows you how to control two small 5V servo motors connected directly to the Arduino.
 * 
 * The sketch makes the arm of the servo motor to move in a 180 degree angle.
 * 
 * 
 * Components
 * ----------
 *  - Arduino Uno
 *  - One or two hobby servo motors
 *  - A small electrolitic capacitor
 *  
 *  Libraries
 *  ---------
 *  - Servo (comes with the Arduino IDE)
 *
 * Connections
 * -----------
 *  
 * For the motors:
 * Brown wire: Breadboard's "-" power rail.
 * Red wire: Breadboard's "+" power rail.
 * Yellow wire: One motor's to Arduino pin 9, and the other motor's to Arduino pin 10.
 * 
 * For the breadboard:
 * Connect the external power supply. The GND wire goes to the breadboard's "-" power rail. The 5V 
 * wire goes to breadboard's "+" power rail.
 * Connect a small electrolitic capacitor directly onto the power rail if you notice your servos
 * not working properly. Observe the polarity of the capacitor!
 * 
 *     
 *  More information
 *  ----------------
 *  For more information on the servo library, see https://www.arduino.cc/en/reference/servo
 *  
 *  Created on May 29 2017 by Peter Dalmaris
 * 
 */


#include <Servo.h> 
 
Servo myservo;  // create servo object to control a servo 
                           // a maximum of eight servo objects can be created 
 
int pos = 0 ;    // variable to store the servo position 
 
void setup() 

  myservo.attach(9);  // attaches the servo on pin 9 to the servo object 


 



 
void loop() 



  


// If you are using a normal 180-degree servo, try the following. 
// The code below sweeps the servo from 0 degrees to 180 degrees
// If you notice that your servo is "trashing" when it reaches the ends of its travel
// path, increase the low end by a little (say, make it 10 degrees) and decrease the 
// top end by a little (say, make it 170 degrees).


//myservo.write(120);
//delay(2000);


for (pos = 0; pos <= 150; pos += 1) { // goes from 0 degrees to 180 degrees
   
    myservo.write(pos);              // tell servo 1 to go to position in variable 'pos'
    delay(50);                       // waits 5ms for the servo to reach the position
}


delay(2000);


for (pos = 90; pos >= 0; pos -= 1) { // goes from 0 degrees to 180 degrees
   
    myservo.write(pos);              // tell servo 1 to go to position in variable 'pos'
    delay(50);                       // waits 5ms for the servo to reach the position
}


delay(2000);


myservo.write(0);
delay(2000);


}


//myservo.write(180);
//delay(1000);
//
//myservo.write(30);
//delay(1000);
//
//for (pos = 150; pos >= 60; pos -= 1) { // goes from 0 degrees to 180 degrees
//   
//    myservo.write(pos);              // tell servo 1 to go to position in variable 'pos'
//    delay(50);                       // waits 5ms for the servo to reach the position
//}
//delay(1000);
//
//myservo.write(180);
//delay(1000);
//
//for (pos = 180; pos >= 30; pos -= 1) { // goes from 0 degrees to 180 degrees
//   
//    myservo.write(pos);              // tell servo 1 to go to position in variable 'pos'
//    delay(50);                       // waits 5ms for the servo to reach the position
//}
//delay(1000);
//
//for (pos = 30; pos <=90; pos+=1) {
//
//  myservo.write(pos);
//  delay(20);
//}

Downloads

Radio Frequency 430mhz Transmitter and Receiver

Screenshot_1.png
Screenshot_2.png

You will require two microcontroller board. Transmitter will be connected to one microcontroller board and receiver will be connected to another microcontroller board. Make sure to attach some sort of wire as antenna specially onto the transmitter.

This is the code for transmitter. It will send the message to the receiver,

#include <RH_ASK.h>
#include <SPI.h>


RH_ASK driver(2000, 4, 2, 5); //attach data on pin2


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


  if (!driver.init())
    Serial.println("init failed");


}


void loop()
{
  const char *msg = "this is ";


  driver.send((uint8_t *)msg, strlen(msg));
  driver.waitPacketSent();
  delay(200);
}


This is the code for receiver. It will receive the message from transmitter,

#include <RH_ASK.h>


#include <SPI.h>


RH_ASK driver(2000, 2, 4, 5); //attach data on pin2


void setup()
{


  Serial.begin(9600);
  if (!driver.init())


    Serial.println("init failed");


}


void loop()
{
  uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
  uint8_t buflen = sizeof(buf);


  if (driver.recv(buf, &buflen)) // Non-blocking
  {
    // int i;


    // Message with a good checksum received, dump it.
    driver.printBuffer("Got:", buf, buflen);


    String rcv;


    for (int i = 0; i < buflen; i++) {
      rcv += (char) buf[i];
    }


    Serial.println(rcv);
    delay(100);
  }
}

8x8 LED Dot Matrix

0760+-+8x8+LED+matrix+display.png

This is the code to display dots/text/character on the 8x8 LED dot matrix,

/*  0760 - Single 8x8 LED matrix display
 * 
 * This sketch shows you how to display simple shapes and animation
 * on a 8x8 LED matrix display
 * 
 * The sketch contains instructions that demonstrate various primitives, like pixels
 * lines and circles. Uncomment the instructions that you are interested in to 
 * see them in action.
 * 
 * This sketch was written by Peter Dalmaris for Arduino Step by Step.
 * 
 * Components
 * ----------
 *  - Arduino Uno
 *  - 1 x 8x8 LED matrix display with the Max72xx driver IC
 *  - Jumper wires
 *  
 *  Libraries
 *  ---------
 *  - SPI (Comes with the Arduino IDE)
 *  - Adafruit_GFX
 *  - Max72xxPanel
 *
 * Connections
 * -----------
 *  
 *  Arduino Uno   |     8x8 LED Matrix
 *  ------------------------------
 *        5V      |      VCC
 *        GND     |      GND
 *        11      |      DIN (SPI data)
 *        13      |      CLK (SPI Clock)
 *        10      |      CS
 *        
 *  Other information
 *  ------------------
 *  For more info on the graphics primitives that you can use, see https://github.com/adafruit/Adafruit-GFX-Library/blob/master/Adafruit_GFX.h
 *  
 *  Created on May 22 2017 by Peter Dalmaris
 * 
 */


#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Max72xxPanel.h>


int pinCS = 10; // Attach CS to this pin, DIN to MOSI and CLK to SCK (cf http://arduino.cc/en/Reference/SPI )


Max72xxPanel matrix = Max72xxPanel(pinCS, 1, 1);  // This constructor needs the CS pin and the display dimensions


const int total_pixels_in_smiley=25;
const int total_coordinates_per_pixel=2;
int smiley[total_pixels_in_smiley][total_coordinates_per_pixel] =
{
  {1, 0},
  {2, 0},
  {1, 1},
  {1, 2},
  {2, 1},
  {2, 2},
  {5, 0},
  {6, 0},
  {5, 1},
  {5, 2},
  {6, 1},
  {6, 2},
  {3, 1},
  {3, 2},
  {3, 3},
  {3, 4},
  {4, 4},
  {0, 5},
  {1, 6},
  {2, 7},
  {3, 7},
  {4, 7},
  {5, 7},
  {6, 6},
  {7, 5}
};


void setup() {
  matrix.setIntensity(1); // Set brightness between 0 and 15
  matrix.fillScreen(LOW); // Clear the screen
//                 x, y, color (individual pixels)
//  matrix.drawPixel(4, 4, HIGH); //copy paste these lines to activate different pixels


//  // LEFT EYE
//  matrix.drawPixel(1, 0, HIGH);
//  matrix.drawPixel(2, 0, HIGH);
//  matrix.drawPixel(1, 1, HIGH);
//  matrix.drawPixel(1, 2, HIGH);
//  matrix.drawPixel(2, 1, HIGH);
//  matrix.drawPixel(2, 2, HIGH);
//  //--------
//  // RIGHT EYE
//  matrix.drawPixel(5, 0, HIGH);
//  matrix.drawPixel(6, 0, HIGH);
//  matrix.drawPixel(5, 1, HIGH);
//  matrix.drawPixel(5, 2, HIGH);
//  matrix.drawPixel(6, 1, HIGH);
//  matrix.drawPixel(6, 2, HIGH);
//  //--------
//  // NOSE
////  matrix.drawPixel(3, 1, HIGH);
////  matrix.drawPixel(3, 2, HIGH);
////  matrix.drawPixel(3, 3, HIGH);
//  matrix.drawPixel(3, 4, HIGH);
//  matrix.drawPixel(4, 4, HIGH);
//  //--------
//  // MOUTH
//  matrix.drawPixel(0, 5, HIGH);
//  matrix.drawPixel(1, 6, HIGH);
//  matrix.drawPixel(2, 7, HIGH);
//  matrix.drawPixel(3, 7, HIGH);
//  matrix.drawPixel(4, 7, HIGH);
//  matrix.drawPixel(5, 7, HIGH);
//  matrix.drawPixel(6, 6, HIGH);
//  matrix.drawPixel(7, 5, HIGH);


//Instead of setting the pixels manually, using the individual drawPixel instructions above, just use this loop:
//  for (int pixel=0; pixel< total_pixels_in_smiley;pixel++)
//    matrix.drawPixel(smiley[pixel][0], smiley[pixel][1], HIGH);


//There are also a few other things you can do:
//Draw a line
//               x0, y0, x1, y1, color
//matrix.drawLine(0, 0, 7, 7, HIGH);


//Draw a box
//              x, y, w, h, color
//matrix.drawRect(0, 0, 8, 8, HIGH);
//matrix.fillRect(0, 0, 6, 5, HIGH);


//Draw a circle
//                x, y, r, color
//matrix.drawCircle(3, 3, 3, HIGH);
//matrix.fillCircle(3, 3, 3, HIGH);


//Draw a letter
//              x, y, char, clr, bg, size
//matrix.drawChar(2, 0, 'F', HIGH, LOW, 1);  


matrix.write(); // Send bitmap to display
}


void loop() {
//  animate_pixel();
}


void animate_pixel(){
//Simple animation demo
//Make a pixel move left-right


matrix.fillScreen(LOW); // Clear the screen before we start
for (int x_pixel_loc=0; x_pixel_loc<8; x_pixel_loc++)
{
  matrix.drawPixel(x_pixel_loc, 3, HIGH);
  matrix.write();
  delay(20);
  matrix.drawPixel(x_pixel_loc, 3, LOW);
  matrix.write();
}
for (int x_pixel_loc=7; x_pixel_loc>-1; x_pixel_loc--)
{
  matrix.drawPixel(x_pixel_loc, 3, HIGH);
  matrix.write();
  delay(60);
  matrix.drawPixel(x_pixel_loc, 3, LOW);
  matrix.write();
}
  


}

Real-time Clock Module

Screenshot_1.png

This is the code to set the time in the RTC module,

/*
DS3231_test.pde
Eric Ayars
4/11


Test/demo of read routines for a DS3231 RTC.


Turn on the serial monitor after loading this to check if things are
working as they should.


*/


#include <DS3231.h>
#include <Wire.h>


DS3231 Clock;
bool Century=false;
bool h12;
bool PM;
byte ADay, AHour, AMinute, ASecond, ABits;
bool ADy, A12h, Apm;


void setup() {
// Start the I2C interface
Wire.begin();
// Start the serial interface
Serial.begin(9600);
}


void loop() {
// send what's going on to the serial monitor.
// Start with the year
Serial.print("2");
if (Century) { // Won't need this for 89 years.
Serial.print("1");
} else {
Serial.print("0");
}
Serial.print(Clock.getYear(), DEC);
Serial.print(' ');
// then the month
Serial.print(Clock.getMonth(Century), DEC);
Serial.print(' ');
// then the date
Serial.print(Clock.getDate(), DEC);
Serial.print(' ');
// and the day of the week
Serial.print(Clock.getDoW(), DEC);
Serial.print(' ');
// Finally the hour, minute, and second
Serial.print(Clock.getHour(h12, PM), DEC);
Serial.print(' ');
Serial.print(Clock.getMinute(), DEC);
Serial.print(' ');
Serial.print(Clock.getSecond(), DEC);
// Add AM/PM indicator
if (h12) {
if (PM) {
Serial.print(" PM ");
} else {
Serial.print(" AM ");
}
} else {
Serial.print(" 24h ");
}
// Display the temperature
Serial.print("T=");
Serial.print(Clock.getTemperature(), 2);
// Tell whether the time is (likely to be) valid
if (Clock.oscillatorCheck()) {
Serial.print(" O+");
} else {
Serial.print(" O-");
}
// Indicate whether an alarm went off
if (Clock.checkIfAlarm(1)) {
Serial.print(" A1!");
}
if (Clock.checkIfAlarm(2)) {
Serial.print(" A2!");
}
// New line on display
Serial.print('\n');
// Display Alarm 1 information
Serial.print("Alarm 1: ");
Clock.getA1Time(ADay, AHour, AMinute, ASecond, ABits, ADy, A12h, Apm);
Serial.print(ADay, DEC);
if (ADy) {
Serial.print(" DoW");
} else {
Serial.print(" Date");
}
Serial.print(' ');
Serial.print(AHour, DEC);
Serial.print(' ');
Serial.print(AMinute, DEC);
Serial.print(' ');
Serial.print(ASecond, DEC);
Serial.print(' ');
if (A12h) {
if (Apm) {
Serial.print('pm ');
} else {
Serial.print('am ');
}
}
if (Clock.checkAlarmEnabled(1)) {
Serial.print("enabled");
}
Serial.print('\n');
// Display Alarm 2 information
Serial.print("Alarm 2: ");
Clock.getA2Time(ADay, AHour, AMinute, ABits, ADy, A12h, Apm);
Serial.print(ADay, DEC);
if (ADy) {
Serial.print(" DoW");
} else {
Serial.print(" Date");
}
Serial.print(' ');
Serial.print(AHour, DEC);
Serial.print(' ');
Serial.print(AMinute, DEC);
Serial.print(' ');
if (A12h) {
if (Apm) {
Serial.print('pm');
} else {
Serial.print('am');
}
}
if (Clock.checkAlarmEnabled(2)) {
Serial.print("enabled");
}
// display alarm bits
Serial.print('\nAlarm bits: ');
Serial.print(ABits, BIN);


Serial.print('\n');
Serial.print('\n');
delay(1000);
}

Temperature Sensor

0430+-+DHT22.png

This is the code to display the temperature from the DHT22 module,

// DHT Temperature & Humidity Sensor
// Unified Sensor Library Example
// Written by Tony DiCola for Adafruit Industries
// Released under an MIT license.


// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor


#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>


#define DHTPIN 2     // Digital pin connected to the DHT sensor 
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.


// Uncomment the type of sensor in use:
//#define DHTTYPE    DHT11     // DHT 11
#define DHTTYPE    DHT22     // DHT 22 (AM2302)
//#define DHTTYPE    DHT21     // DHT 21 (AM2301)


// See guide for details on sensor wiring and usage:
//   https://learn.adafruit.com/dht/overview


DHT_Unified dht(DHTPIN, DHTTYPE);


uint32_t delayMS;


void setup() {
  Serial.begin(9600);
  // Initialize device.
  dht.begin();
  Serial.println(F("DHTxx Unified Sensor Example"));
  // Print temperature sensor details.
  sensor_t sensor;
  dht.temperature().getSensor(&sensor);
  Serial.println(F("------------------------------------"));
  Serial.println(F("Temperature Sensor"));
  Serial.print  (F("Sensor Type: ")); Serial.println(sensor.name);
  Serial.print  (F("Driver Ver:  ")); Serial.println(sensor.version);
  Serial.print  (F("Unique ID:   ")); Serial.println(sensor.sensor_id);
  Serial.print  (F("Max Value:   ")); Serial.print(sensor.max_value); Serial.println(F("°C"));
  Serial.print  (F("Min Value:   ")); Serial.print(sensor.min_value); Serial.println(F("°C"));
  Serial.print  (F("Resolution:  ")); Serial.print(sensor.resolution); Serial.println(F("°C"));
  Serial.println(F("------------------------------------"));
  // Print humidity sensor details.
  dht.humidity().getSensor(&sensor);
  Serial.println(F("Humidity Sensor"));
  Serial.print  (F("Sensor Type: ")); Serial.println(sensor.name);
  Serial.print  (F("Driver Ver:  ")); Serial.println(sensor.version);
  Serial.print  (F("Unique ID:   ")); Serial.println(sensor.sensor_id);
  Serial.print  (F("Max Value:   ")); Serial.print(sensor.max_value); Serial.println(F("%"));
  Serial.print  (F("Min Value:   ")); Serial.print(sensor.min_value); Serial.println(F("%"));
  Serial.print  (F("Resolution:  ")); Serial.print(sensor.resolution); Serial.println(F("%"));
  Serial.println(F("------------------------------------"));
  // Set delay between sensor readings based on sensor details.
  delayMS = sensor.min_delay / 1000;
}


void loop() {
  // Delay between measurements.
  delay(delayMS);
  // Get temperature event and print its value.
  sensors_event_t event;
  dht.temperature().getEvent(&event);
  if (isnan(event.temperature)) {
    Serial.println(F("Error reading temperature!"));
  }
  else {
    Serial.print(F("Temperature: "));
    Serial.print(event.temperature);
    Serial.println(F("°C"));
  }
  // Get humidity event and print its value.
  dht.humidity().getEvent(&event);
  if (isnan(event.relative_humidity)) {
    Serial.println(F("Error reading humidity!"));
  }
  else {
    Serial.print(F("Humidity: "));
    Serial.print(event.relative_humidity);
    Serial.println(F("%"));
  }
}

DC Motor and Driver

Screenshot_1.png

Connect the input pin of the motor M1IN1-M1IN2/M2IN1-M2IN2 to any digital pin of the Arduino UNO

Connect two pins of motor to M1OUT1-M1OUT2/M2OUT1-M2OUT2

Connect Enable pin to any PWM pin on the Arduino UNO.

This is the code for driving DC motor with L293D driver,

int en = 6;
int in1 = 7;
int in2 = 8;


void setup() {
  // put your setup code here, to run once:


  pinMode(en, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);


}


void loop() {
  // put your main code here, to run repeatedly:


digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
analogWrite(en, 250);
//delay(2000);


//digitalWrite(in1, LOW);
//digitalWrite(in2, LOW);
//delay(2000);
//
//digitalWrite(in2, HIGH);
//digitalWrite(in1, LOW);
//analogWrite(en, 255);
//delay(2000);
//
//digitalWrite(in1, LOW);
//digitalWrite(in2, LOW);
//delay(2000);


}

Downloads

Touch Sensor

Screenshot_1.png

This is the code for reading the digital signal of the touch sensor,

/*
  DigitalReadSerial


  Reads a digital input on pin 2, prints the result to the Serial Monitor


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/DigitalReadSerial
*/


// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}


// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(1);        // delay in between reads for stability
}

Downloads

Analog Joystick

thumb_joystick_cppYU8XC7l.png

This is the Arduino code for reading analog signal for the position of the joystick,

int xValue = 0 ;
int yValue = 0 ; 
int bValue = 0 ;


void setup()  

  Serial.begin(9600) ;
  pinMode(8,INPUT); 
  digitalWrite(8,HIGH); 



void loop() 

  xValue = analogRead(A0);  
  yValue = analogRead(A1);  
  bValue = digitalRead(8);  
  Serial.print(xValue,DEC);
  Serial.print(",");
  Serial.print(yValue,DEC);
  Serial.print(",");
  Serial.print(!bValue);
  Serial.print("\n");
  delay(10);  
}


This is the processing code for getting the output in the form of visual,

import processing.serial.*;
Serial myPort;


int x; 
int y;
int b;
PFont f;
String portName;
String val;


void setup()
{
  size ( 512 , 512 ) ; 
  myPort = new Serial(this, Serial.list()[0], 9600);
  myPort.bufferUntil('\n'); 
  f = createFont("Arial", 16, true);
  textFont ( f, 16 ) ; 
}


void draw()
{
  fill(0) ;
  clear() ; 
  fill(255) ; 
  if (b == 1)
  {
    ellipse(x/2,y/2, 50, 50);
  } 
  else
  {
    ellipse(x/2,y/2, 25, 25);
  }
  text("AnalogX="+(1023-x)+" AnalogY="+(1023-y),10,20);
}


void serialEvent( Serial myPort) 
{
  val = myPort.readStringUntil('\n');
  if (val != null)
  {
        val = trim(val);
    int[] vals = int(splitTokens(val, ","));
    x = vals[0];
    y = vals[1] ;
    b = vals[2];


  }
}

LCD With I2C Module

I2C-LCD-Display-Pinout.png
Wiring-I2C-LCD-Display-with-Arduino.png

Use this code to find the I2C address of your device,

#include <Wire.h>


void setup()


{
  Serial.begin (9600);
   while (!Serial)
    {
    }


  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;
  pinMode(13,OUTPUT); 
  digitalWrite(13,HIGH);
  Wire.begin();
  for (byte i = 1; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1); 
      } 
  } 
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");



void loop() {}


Use the same I2C address in this line,

LiquidCrystal_I2C lcd(0x27,16,2);


Use this code to display text in the LCD,



/*  LCD screen with the I2C backpack demo sketch
 * 
 * This sketch shows you how to use the 16x2 LCD display 
 * using the I2C backpack adaptor. This way, we can save a
 * lot of digital pins on the Arduino.
 * 
 * This I2C LCD backpack contains the PCF8574 port-expander
 * IC. Beware that this sketch can work with backpacks that
 * contains this IC, but may not work with variations.
 * 
 * 
 * Components
 * ----------
 *  - Arduino Uno
 *  - An I2C to LCD backpack adaptor
 *  - jumper wires
 *  - Breadboard
 *  
 *  Libraries
 *  ---------
 *  - LCD
 *  - LiquidCrystal_I2C
 *
 * Connections
 * -----------
 *  I2C backpack  |    Arduino Uno
 *  -----------------------------
 *      GND       |      GND
 *      Vcc       |      5V
 *      SDA       |      SDA or A4
 *      SCL       |      SCL or A5
 *      
 * 
 * Other information
 * -----------------
 *  For information on the LiquidCrystal library: https://github.com/marcoschwartz/LiquidCrystal_I2C
 *  
 *  Created on November 18 2016 by Peter Dalmaris
 * 
 */
 
#include <LiquidCrystal_I2C.h>


LiquidCrystal_I2C lcd(0x27,16,2);


void setup()
{
    lcd.init();
    lcd.backlight();
    lcd.setCursor(4, 0);
    lcd.print("Hello World!");
    lcd.setCursor(3, 1);
    lcd.print("Row number: ");
    lcd.setCursor(15, 1);
    lcd.print("2");
}
void loop()
{
 
}

Ultrasonic Sensor

0510+-+Ultrasonic+Sensor+HC-SR04.png

Use this code to get the reading of the ultrasonic sensor in form of distance(cm),

/*  Ultrasonic distance sensor HC-SR04 demo sketch 
 * 
 * This sketch calculates the distance between the HC-SR04 sensor and
 * an object directly infront of it.
 * 
 * 
 * This sketch was written for Arduino Step by Step by Peter Dalmaris.
 * 
 * Components
 * ----------
 *  - Arduino Uno
 *  - HC-SR04 sensor
 *  
 *  Libraries
 *  ---------
 *  - NONE
 *
 * Connections
 * -----------
 *  Break out    |    Arduino Uno
 *  -----------------------------
 *      VCC      |      5V
 *      GND      |      GND
 *      Echo     |      12
 *      Trig     |      13
 *   
 * 
 * Other information
 * -----------------
 *  For information on the ultrasonic transducer: https://en.wikipedia.org/wiki/Ultrasonic_transducer
 *  For information on ultrasounds: https://en.wikipedia.org/wiki/Ultrasound
 *  HC-SR04 datasheet: https://docs.google.com/document/d/1Y-yZnNhMYy7rwhAgyL_pfa39RsB-x2qR4vP8saG73rE
 *  Information about the pulseIn function: https://www.arduino.cc/en/Reference/PulseIn
 *  
 *  Created on October 21 2016 by Peter Dalmaris
 * 
 */


#define trigPin 13
#define echoPin 12


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


void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2); 
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;


  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

Downloads

Color Sensor

TCS230-TCS3200-Color-Sensor-Module-Pinout.png
Wiring-TCS230-TCS3200-Color-Sensor-Module-with-Arduino.png

In order to tell you which color the sensor is detecting, you need a range of value for the Red, Green and Blue color. To find out that range, run the below code and place Red, Green and Blue color object on top of the sensor and note down the minimum value and maximum value for the three color,

// Define color sensor pins
#define S0 7
#define S1 8
#define S2 15
#define S3 2
#define sensorOut 0


// Variables for Color Pulse Width Measurements
int redPW = 0;
int greenPW = 0;
int bluePW = 0;


void setup() {
  // Set S0 - S3 as outputs
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);


  // Set Pulse Width scaling to 20%
  digitalWrite(S0,HIGH);
  digitalWrite(S1,LOW);


  // Set Sensor output as input
  pinMode(sensorOut, INPUT);


  // Setup Serial Monitor
  Serial.begin(9600);
}


void loop() {
  // Read Red Pulse Width
  redPW = getRedPW();
  // Delay to stabilize sensor
  delay(200);


  // Read Green Pulse Width
  greenPW = getGreenPW();
  // Delay to stabilize sensor
  delay(200);


  // Read Blue Pulse Width
  bluePW = getBluePW();
  // Delay to stabilize sensor
  delay(200);


  // Print output to Serial Monitor
  Serial.print("Red PW = ");
  Serial.print(redPW);
  Serial.print(" - Green PW = ");
  Serial.print(greenPW);
  Serial.print(" - Blue PW = ");
  Serial.println(bluePW);
}


// Function to read Red Pulse Widths
int getRedPW() {
  // Set sensor to read Red only
  digitalWrite(S2,LOW);
  digitalWrite(S3,LOW);
  // Define integer to represent Pulse Width
  int PW;
  // Read the output Pulse Width
  PW = pulseIn(sensorOut, LOW);
  // Return the value
  return PW;
}


// Function to read Green Pulse Widths
int getGreenPW() {
  // Set sensor to read Green only
  digitalWrite(S2,HIGH);
  digitalWrite(S3,HIGH);
  // Define integer to represent Pulse Width
  int PW;
  // Read the output Pulse Width
  PW = pulseIn(sensorOut, LOW);
  // Return the value
  return PW;
}


// Function to read Blue Pulse Widths
int getBluePW() {
  // Set sensor to read Blue only
  digitalWrite(S2,LOW);
  digitalWrite(S3,HIGH);
  // Define integer to represent Pulse Width
  int PW;
  // Read the output Pulse Width
  PW = pulseIn(sensorOut, LOW);
  // Return the value
  return PW;
}

Define that range in this line for the three colors,

 if (redfrequency>35 && redfrequency< 45) {Serial.println("RED COLOUR");}

And run the code given below,

#define S0 7
#define S1 8
#define S2 15
#define S3 2
#define sensorOut 0


int redfrequency = 0;
int greenfrequency = 0;
int bluefrequency = 0;


void setup() {
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  pinMode(sensorOut, INPUT);
  
  // Setting frequency-scaling to 20%
  digitalWrite(S0,HIGH);
  digitalWrite(S1,LOW);
  
  Serial.begin(9600);
}
void loop() {
  // Setting red filtered photodiodes to be read
  digitalWrite(S2,LOW);
  digitalWrite(S3,LOW);
  // Reading the output frequency
   redfrequency = pulseIn(sensorOut, LOW);
 
  delay(100);
  // Setting Green filtered photodiodes to be read
  digitalWrite(S2,HIGH);
  digitalWrite(S3,HIGH);
  // Reading the output frequency
  greenfrequency = pulseIn(sensorOut, LOW);
  // Printing the value on the serial monitor
 
  delay(100);
  // Setting Blue filtered photodiodes to be read
  digitalWrite(S2,LOW);
  digitalWrite(S3,HIGH);
  // Reading the output frequency
  bluefrequency = pulseIn(sensorOut, LOW);
  // Printing the value on the serial monitor


 if (redfrequency>35 && redfrequency< 45) {Serial.println("RED COLOUR");} else if (bluefrequency>62 && bluefrequency< 72) {Serial.println("BLUE COLOUR");} else if (greenfrequency>50 && greenfrequency< 60){Serial.println("GREEN COLOUR");}


 else
 {Serial.println("NO COLOUR DETECTION");}
}

RFID Sensor

RC522-RFID-Reader-Writer-Module-Pinout.png
Arduino-Wiring-Fritzing-Connections-with-RC522-RFID-Reader-Writer-Module.png

Every RFID Card and RFID Tag had a Unique Identification Number(UID). To find out the UID of your card and tag run the below code,

/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from a PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 * 
 * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 * 
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 * 
 * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 * 
 * @license Released into the public domain.
 * 
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 * More pin layouts   for other boards can be found here: https://github.com/miguelbalboa/rfid#pin-layout
 */


#include <SPI.h>
#include <MFRC522.h>


#define RST_PIN         2          // Configurable, see typical pin layout above
#define SS_PIN          3         // Configurable, see typical pin layout above


MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance


void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
delay(4); // Optional delay. Some board do need more time after init to be ready, see Readme
mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}


void loop() {
// Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}


// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}


// Dump debug info about the card; PICC_HaltA() is automatically called
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

You can find the code from the library "MFRC522" by GithubCommunity.

Now you can use that UID in the line,

  if (content.substring(1) == "82 A7 B9 4E" , "53 FC C6 1B")

in the below code which will blink the Built in LED if the registered RFID Card or Tag is placed on the RFID sensor,

#include <SPI.h>
#include <MFRC522.h>


#define RST_PIN 2
#define SS_PIN 3
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
 
void setup() 
{
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.println("Put your card to the reader...");
  Serial.println();


}
void loop() 
{
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) 
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) 
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++) 
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "82 A7 B9 4E" , "53 FC C6 1B") //change here the UID of the card/cards that you want to give access
  {
    Serial.println("Authorized access");
    Serial.println();
    delay(500);
    digitalWrite(LED_BUILTIN, HIGH);
    delay(500);
    digitalWrite(LED_BUILTIN, LOW);
  }
 
 else   {
    Serial.println(" Access denied");


  }


BO Motor and Driver

schematic_driver.png

Use the below code to run two BO Motors with L298N Driver. I used an external power supply of 12V and maximum current of 0.3A

#define in1 4
#define in2 5
#define enA 6


#define in3 8
#define in4 9
#define enB 10


void setup() {
  // put your setup code here, to run once:


  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);


  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);


  // Turn off motors - Initial state
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);


}


void loop() {
  // put your main code here, to run repeatedly:


  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);


  analogWrite(enA, 90);
  analogWrite(enB, 90);
}


Downloads

Single Channel Relay Module

Single-Channel-Relay-Module-Pinout.jpg

Connect VCC to 5V of the Arduino

Connect GND to GND of the Arduino

Connect Input to any Digital Input pin of the Arduino.


There are three slots on the screw terminal: Normally Open(NO), Common Contact(CC) & Normally Close(NC).

When HIGH signal or no signal is given to the input pin, there will be continuity between NO and CC and there will be no continuity between NC and CC.

When LOW signal is given to the input pin, there will be no continuity between NO and CC and there will be continuity between NC and CC.

You can operate the relay module with just the Ground signal of 5V. However if you want to interface the relay with Arduino, here is the simple code,

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(2, OUTPUT);
}


// the loop function runs over and over again forever
void loop() {
  digitalWrite(2, LOW);   // turn the LED on (HIGH is the voltage level)
  delay(4000);                       // wait for a second
  digitalWrite(2, HIGH);    // turn the LED off by making the voltage LOW
  delay(4000);                       // wait for a second
}


Downloads

Current Sensor

current sensor_schematic.png

To get the current reading in the form of Analog readings, you need to connect the current sensor in series with the circuit. Refer to the schematic given above.

Use the simple AnalogReadSerial code to get the analog readings of the sensor,

/*
  AnalogReadSerial


  Reads an analog input on pin 0, prints the result to the Serial Monitor.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.


  This example code is in the public domain.


  https://www.arduino.cc/en/Tutorial/BuiltInExamples/AnalogReadSerial
*/


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}


// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}