Categories

Follow Us

Arduino and PCF8575 I/O expander examples

This 16-bit I/O expander for the two-line bidirectional bus (I2C) is designed for 2.5-V to 5.5-V VCC operation.

The PCF8575 device provides general-purpose remote I/O expansion for most microcontroller families by way of the I2C interface [serial clock (SCL), serial data (SDA)].

The device features a 16-bit quasi-bidirectional input/output (I/O) port (P07–P00, P17–P10), including latched outputs with high-current drive capability for directly driving LEDs. Each quasi-bidirectional I/O can be used as an input or output without the use of a data-direction control signal. At power on, the I/Os are high. In this mode, only a current source to VCC is active.

Features

  • I2C to Parallel-Port Expander
  • Open-Drain Interrupt Output
  • Low Standby-Current Consumption of 10 µA Max
  • Compatible With Most Microcontrollers
  • 400-kHz Fast I2C Bus
  • Address by Three Hardware Address Pins for Use of up to Eight Devices
  • Latched Outputs With High-Current Drive Capability for Directly Driving LEDs

 

Connection

This example shows only one LED

Arduino and PCF8575

Arduino and PCF8575

 

Parts List

Part Link
Arduino Uno UNO R3 CH340G/ATmega328P, compatible for Arduino UNO
Dupont cable Free shipping Dupont line 120pcs 20cm male to male + male to female and female to female jumper wire
PCF8575 PCF8575 IIC I2C I/O Extension Shield Module 16 bit SMBus I/O

 

Code examples

Output – switch LED on and off

#include <Wire.h>
 
// Set I2C address
int address = 0x20;
 
void setup()
{ 
  Wire.begin();
  // Set all ports as output
  pf575_write(word(B11111111,B11111111));
} 
 
void loop()
{
  // Set port P0 on
  pf575_write(word(B00000000,B00000001));
  delay(1000);
  // Set port P0 off
  pf575_write(word(B00000000,B00000000));
  delay(1000);
} 
 
// Function for writing two Bytes to the I2C expander device
void pf575_write(uint16_t data) 
{
  Wire.beginTransmission(address);
  Wire.write(lowByte(data));
  Wire.write(highByte(data));
  Wire.endTransmission();
}

 

Output – switch LEDs on and off

#include <Wire.h>
 
byte address = 0x20;   // address of PCF8575
 
void setup()
{
   Wire.begin();       // join i2c bus as master
}
 
 
void loop()
{
  unsigned char x;
  unsigned char y;
 
  for (x=0, y=255; (x+y)==255; x++, y--)
  {
      Wire.beginTransmission(address);   // send the address and the write cmnd
      Wire.write(x);                      // pack the first byte
      Wire.write(y);                      // pack the second byte
      Wire.endTransmission();            // send the data
      delay(150);     
   }
}
Share

Arduino and APDS-9960 sensor example

In this example we will connect a APDS-9960 sensor to an Arduino Uno

Lets look at some information about the APDS-9960

The Broadcom APDS-9960 is a digital RGB, ambient light, proximity and gesture sensor device in a single 8-pin package. The device has an I2C compatible interface providing red, green, blue, clear (RGBC), proximity and gesture sensing with IR LED. The RGB and ambient light sensing feature detects light intensity under various lighting conditions and through various attentuation materials including darkened glass. In addition, the integrated UV-IR blocking filter enables accurate ambient light and correlated color temperature sensing.

The proximity and gesture feature is factory-trimmed and calibrated to 100mm proximity detection distance without requiring customer calibrations. Gesture detection utilizes four directional photodiodes, integrated with visible blocking filter, to accurately sense simple UP-DOWN-RIGHT-LEFT gestures or more complex gestures. The addition of micro-optics lenses within the module provides high efficient transmission and reception of infrared energy. An internal state machine allows the device to be put into a low power state between RGBC, proximity and gesture measurements providing very low power consumption.

Connection

 

Arduino and APDS-9960

Arduino and APDS-9960

Parts List

Part Link
Arduino Uno UNO R3 CH340G/ATmega328P, compatible for Arduino UNO
Dupont cable Free shipping Dupont line 120pcs 20cm male to male + male to female and female to female jumper wire
APDS-9960 sensor (cjmcu-88) APDS-9960 proximity detection and non-contact gesture detection RGB and Gesture

Code

This is the gesture example from the sparkfun library – https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor

#include <Wire.h>
#include <SparkFun_APDS9960.h>
 
// Pins
#define APDS9960_INT    2 // Needs to be an interrupt pin
 
// Constants
 
// Global Variables
SparkFun_APDS9960 apds = SparkFun_APDS9960();
int isr_flag = 0;
 
void setup() {
 
  // Set interrupt pin as input
  pinMode(APDS9960_INT, INPUT);
 
  // Initialize Serial port
  Serial.begin(9600);
  Serial.println();
  Serial.println(F("--------------------------------"));
  Serial.println(F("SparkFun APDS-9960 - GestureTest"));
  Serial.println(F("--------------------------------"));
 
  // Initialize interrupt service routine
  attachInterrupt(0, interruptRoutine, FALLING);
 
  // Initialize APDS-9960 (configure I2C and initial values)
  if ( apds.init() ) {
    Serial.println(F("APDS-9960 initialization complete"));
  } else {
    Serial.println(F("Something went wrong during APDS-9960 init!"));
  }
 
  // Start running the APDS-9960 gesture sensor engine
  if ( apds.enableGestureSensor(true) ) {
    Serial.println(F("Gesture sensor is now running"));
  } else {
    Serial.println(F("Something went wrong during gesture sensor init!"));
  }
}
 
void loop() {
  if( isr_flag == 1 ) {
    detachInterrupt(0);
    handleGesture();
    isr_flag = 0;
    attachInterrupt(0, interruptRoutine, FALLING);
  }
}
 
void interruptRoutine() {
  isr_flag = 1;
}
 
void handleGesture() {
    if ( apds.isGestureAvailable() ) {
    switch ( apds.readGesture() ) {
      case DIR_UP:
        Serial.println("UP");
        break;
      case DIR_DOWN:
        Serial.println("DOWN");
        break;
      case DIR_LEFT:
        Serial.println("LEFT");
        break;
      case DIR_RIGHT:
        Serial.println("RIGHT");
        break;
      case DIR_NEAR:
        Serial.println("NEAR");
        break;
      case DIR_FAR:
        Serial.println("FAR");
        break;
      default:
        Serial.println("NONE");
    }
  }
}

 

Output

Here is the output that I saw in the serial monitor

APDS-9960 initialization complete
Gesture sensor is now running
UP
NEAR
FAR
FAR
UP
NONE
NONE
NEAR
NEAR
LEFT
NONE
RIGHT
LEFT
NONE
LEFT
RIGHT

 

Link

https://docs.broadcom.com/docs/AV02-4191EN

Share

Arduino and MCP3421 A/D converter example

The MCP3421 ADC can be used for various high accuracy analog-to-digital data conversion applications where ease of use, low power consumption and small footprint are major considerations.The MCP3421 is a single channel low-noise, high accuracy delta-sigma A/D converter with differential inputs and up to 18 bits of resolution in a small SOT-23-6 package.

The on-board precision 2.048V reference voltage enables a differential input range of ±2.048V. The device uses a two-wire I2C™ compatible interface and operates from a single power supply ranging from 2.7V to 5.5V. The MCP3421 ADC performs conversions at rates of 3.75, 15, 60 or 240 samples per second with corresponding resolutions of 18, 16, 14 and 12 bits. The onboard programmable gain amplifier (PGA) provides gain up to 8x. The device has two conversion modes: Continuous mode and One-Shot mode. In One-Shot mode, the device enters a low current standby mode automatically after a conversion, greatly reducing power use.

Features
    • 18-bit resolution
    • Small 6-lead SOT-23 packaging
    • Differential input operation
    • On-board voltage reference with 5 ppm/°C drift
    • On-board PGA, gains of 1, 2, 4, 8
    • Programmable data rate options
      • 3.75 SPS (18 bits)
      • 15 SPS (16 bits)
      • 60 SPS (14 bits)
      • 240 SPS (12 bits)
    • INL 10 ppm of FSR max
    • Low current consumption, 145 µA at 3V
    • One-shot or continuous conversion options
    • Supports I2C™ serial interface
    • Extended temperature range: -40°C to +125°C

Parts List

Part Link
MCP3421 MCP3421 I2C SOT23-6 delta-sigma ADC Evaluation Board
Connecting cable Free shipping Dupont line 120pcs 20cm male to male + male to female and female to female jumper wire Dupont cablefor Arduino
Arduino Uno UNO R3 CH340G/ATmega328P, compatible for Arduino UNO R3

 

Connection

Its an I2C device – I connected the VIN- to Gnd and Vin+ to Pin 6

 

Code

You need to download and install the following library – https://github.com/uChip/MCP342X

// Include libraries this sketch will use
#include  <Wire.h>
#include  <MCP342X.h>
 
// Instantiate objects used in this project
MCP342X myADC;
int outputPin = 6;
 
void setup() 
{
  Wire.begin();  // join I2C bus
  TWBR = 12;  // 400 kHz (maximum)
 
  Serial.begin(9600); // Open serial connection to send info to the host
  while (!Serial) {}  // wait for Serial comms to become ready
  Serial.println("Starting up");
  Serial.println("Testing device connection...");
  Serial.println(myADC.testConnection() ? "MCP342X connection successful" : "MCP342X connection failed");
 
  myADC.configure( MCP342X_MODE_CONTINUOUS |
                   MCP342X_CHANNEL_1 |
                   MCP342X_SIZE_16BIT |
                   MCP342X_GAIN_1X
                 );
 
  Serial.println(myADC.getConfigRegShdw(), HEX);
 
}  // End of setup()
 
void loop() {
  static int16_t  result;
  for(int i=0; i<=255; i++)
  {
    myADC.startConversion();
    analogWrite(outputPin, i);
    myADC.getResult(&result);
    Serial.print(i);
    Serial.print("  ");
    Serial.print(result);
    Serial.print("  ");
    Serial.println(result, HEX);
  }
 
}  // End of loop()

 

link

Datasheet – http://ww1.microchip.com/downloads/en/DeviceDoc/22003e.pdf

Share

Arduino and MMA8452 sensor example

In this example we will connect a MMA8452Q accelerometer  to an Arduino Uno

Lets look at some information about the sensor

The MMA8452Q is a smart, low-power, three-axis, capacitive, micromachined accelerometer with 12 bits of resolution. This accelerometer is packed with embedded functions with flexible user programmable options, configurable to two interrupt pins. Embedded interrupt functions allow for overall power savings relieving the host processor from continuously polling data.

The MMA8452Q has user selectable full scales of ±2 g/±4 g/±8 g with high-pass filtered data as well as non-filtered data available real-time. The device can be configured to generate inertial wakeup interrupt signals from any combination of the configurable embedded functions allowing the MMA8452Q to monitor events and remain in a low-power mode during periods of inactivity

 

Connection

Here is a layout, its an easy device to connect

Arduino and MMA8452

Arduino and MMA8452

Parts List

Here are the parts I used

Part name Link
Arduino Uno UNO R3 CH340G/ATmega328P, compatible for Arduino UNO R3
MMA8452 saensor GY-45 MMA8452 Module Digital Triaxial Accelerometer Precision Tilt 3-Axis
Dupont cable Free shipping Dupont line 120pcs 20cm male to male + male to female and female to female jumper wire Dupont cablefor Arduino

 

Code

There is a library from sparkfun but there is this example which does not require any libraries

// Distributed with a free-will license.
// Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
// MMA8452Q
// This code is designed to work with the MMA8452Q_I2CS I2C Mini Module available from ControlEverything.com.
// https://www.controleverything.com/content/Accelorometer?sku=MMA8452Q_I2CS#tabs-0-product_tabset-2
 
#include <Wire.h>
 
// MMA8452Q I2C address is 0x1C(28)
#define Addr 0x1C
 
void setup()
{
  // Initialise I2C communication as MASTER
  Wire.begin();
  // Initialise Serial Communication, set baud rate = 9600
  Serial.begin(9600);
 
  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select control register
  Wire.write(0x2A);
  // StandBy mode
  Wire.write(0x00);
  // Stop I2C Transmission
  Wire.endTransmission();
 
  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select control register
  Wire.write(0x2A);
  // Active mode
  Wire.write(0x01);
  // Stop I2C Transmission
  Wire.endTransmission();
 
  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select control register
  Wire.write(0x0E);
  // Set range to +/- 2g
  Wire.write(0x00);
  // Stop I2C Transmission
  Wire.endTransmission();
  delay(300);
}
 
void loop()
{
  unsigned int data[7];
 
  // Request 7 bytes of data
  Wire.requestFrom(Addr, 7);
 
  // Read 7 bytes of data
  // staus, xAccl lsb, xAccl msb, yAccl lsb, yAccl msb, zAccl lsb, zAccl msb
  if(Wire.available() == 7) 
  {
    data[0] = Wire.read();
    data[1] = Wire.read();
    data[2] = Wire.read();
    data[3] = Wire.read();
    data[4] = Wire.read();
    data[5] = Wire.read();
    data[6] = Wire.read();
  }
 
  // Convert the data to 12-bits
  int xAccl = ((data[1] * 256) + data[2]) / 16;
  if (xAccl > 2047)
  {
    xAccl -= 4096;
  }
 
  int yAccl = ((data[3] * 256) + data[4]) / 16;
  if (yAccl > 2047)
  {
    yAccl -= 4096;
  }
 
  int zAccl = ((data[5] * 256) + data[6]) / 16;
  if (zAccl > 2047)
  {
    zAccl -= 4096;
  }
 
  // Output data to serial monitor
  Serial.print("Acceleration in X-Axis : ");
  Serial.println(xAccl);
  Serial.print("Acceleration in Y-Axis : ");
  Serial.println(yAccl);
  Serial.print("Acceleration in Z-Axis : ");
  Serial.println(zAccl);
  delay(500);
}

 

Output

Open the serial monitor – this is what you should expect to see

Acceleration in X-Axis : -186
Acceleration in Y-Axis : 330
Acceleration in Z-Axis : 125
Acceleration in X-Axis : -784
Acceleration in Y-Axis : 426
Acceleration in Z-Axis : 76
Acceleration in X-Axis : -225
Acceleration in Y-Axis : 890
Acceleration in Z-Axis : -273
Acceleration in X-Axis : -199
Acceleration in Y-Axis : 1053
Acceleration in Z-Axis : -260

 

Links

https://www.nxp.com/docs/en/data-sheet/MMA8452Q.pdf

Share