AVR library for working with the I2C bus and with the PCF8583 real time clock.

This article will show you how to use an I2C interface module to control an LCD display (2x16 / 20x4) with an Arduino. This module allows you to reduce the number of controller pins used, instead of an 8 or 4-bit connection, only 2 pins (SDA and SCL) are required.

Technical specifications

Display Support: LCD 16 × 02/20 × 04
Optional: contrast adjustment
Supply voltage. 5B
Interface: I2C
Dimensions: 54mm x 19mm x 15mm

General information of the I2C interface module

Since the number of pins on Arduino controllers is limited and often when used various sensors and they run out of modules, there is a need to save them, for these cases this module has been developed, with its help it is possible to implement transmission over two contacts (SDA and SCL).

Now a little about the module itself, it is built on the PCF8574T microcircuit. Resistors R8 (4.7kOhm) and R9 (4.7kOhm) are needed to pull up the SDA and SCL lines, ideally, when connecting two or more devices via the I2C bus, you need to use pull-up on only one device, later I will write why. There are three jumpers on the board (the diagram shows that the lines A0, A1, A2 are pulled up to power through the resistors R4, R5, R6), they are needed to change the addressing of the device, there are 8 options in total. Changing the addressing gives us the ability to connect up to eight devices via the IC2 bus with the PCF8574T microcircuit, the address options are shown in the figure (by default, the device address is 0x27). The module is also equipped with a potentiometer R11 with its help you can change the contrast of the LCD display.

For connection, the module has three groups of contacts:

First group:
SCL: Serial CLock
SDA: data line (Serial Dft)
VCC: "+" power
GND: "-" power

Second group:
VSS: "-" power supply
VDD: "+" power supply
VO: Contrast control pin
RS: Register selection
RW: Read / Write (write mode when connected to ground)
E: Enable (fall-off strobe)
DB0-DB3: Low-order bits of the interface
DB4-DB7: Most significant bits of the interface
A: "+" backlight power
K: "-" backlight power

Third group: (jumper installed by default)
VCC:
A from LCD:

Connecting to Arduino

Required details:
Arduino UNO R3 x 1pc
LCD display 1602A (2 × 16, 5V, Blue) x 1 pc.
Interface module I2C, IIC, TWI for LCD x 1 pc.
DuPont Wire, 2.54mm, 20cm, F-M (Female to Male) x 1
USB cable 2.0 A-B x 1pc

Connection:
First of all, we solder the I2C module to the LCD display, then we need to connect the display to the Arduino UNO. To do this, we will use DuPont wiring, we connect according to the table below.

For clarity, I will give one more diagram.

For this experiment, you need to download and install the "LiquidCrystal_I2C" library. Then copy and paste this sample code into the Arduino IDE window and upload to the controller.

/ * Tested on Arduino IDE 1.6.11 Test date 09/15/2016 * / #include #include LiquidCrystal_I2C lcd (0x27,16,2); // Set the address and size of the display void setup () (lcd.init (); // Initialize lcd lcd.backlight (); // Turn on the backlight lcd.setCursor (0,0); // Set the cursor to the beginning of line 1 lcd .print ("Hello, world"); // Display the text lcd.setCursor (0,1); // Set the cursor to the beginning of line 2 lcd.print ("www.robotchip.ru"); // Display the text) void loop () ()

Download program

If you did everything correctly, but there are no symbols on the display, try increasing the contrast with the potentiometer.


Links
Download LiquidCrystal_I2C Library
Documentation for the PCF8574T chip
LCD1602A Documentation

Buy on Aliexpress

I needed to make a clock based on a microcircuit with an I 2 C interface. RTC microcircuit, so-called. "real time clock" PCF8583.

Inside the microcircuit are located: a clock, an alarm clock, a timer, a calendar (curve), and 240 bytes of RAM, where you can write any information you want. RAM is a very useful thing, unlike flash memory, RAM has no restrictions on the number of rewriting cycles, and you can save some data, settings, as often as you like.

But there was one problem - I really didn't want to write the code, and I decided to find the ready-made code on the Internet. As it turned out later, to find "on your own head." I downloaded an example of working with I 2 C, corrected it, flashed the microcontroller. It didn't work. I started picking the code, looking for the reason for the inoperability ... and was horrified !! In some cases, recording was made to the entire port at once, and not to specific bits. Thus, if you hang something else on the port, for example, a display, then most likely it will not work. Also, reading data via the bus was incorrectly implemented (without generating the end-of-receipt condition, or simply without NACK). But this is half the trouble. The main problem is different. Often the author of the code put a logical "1" in the port, and as we know, the I 2 C bus is controlled by "pulling" the SDA and SCL pins to the common wire. And the logical "1" on the bus, in turn, is formed by pulling up to the positive power supply with 4.7 kilo-ohm resistors. Thus, if you set the logic "1" at the microcontroller output, and the slave device "pulls" this output to the common wire, you get "bang bang" short circuit... I really did not like this, and I decided to reinvent my bicycle to write my own library, or rather even 2 libraries: one for working with the I 2 C bus, and the other directly for working with the PCF8583 real-time clock. By the way, the code is written in.

In order to connect the I 2 C library to the project, you need to register it via include, as in the picture, and also copy the library to the project folder.

After that, you need to open the "i2c.h" file and specify the legs of the microcontroller that will act as the I 2 C bus. By default, the bus is configured for the PC0 (SCL) and PC1 (SDA) legs. And the setting is done here:

That's it, we connected the I2C library, set up the legs, the library is ready to work. Usage example:

I2c_init (); // Initialize the I2C bus i2c_start_cond (); // start of the bus i2c_send_byte (0xA0); // address of the device that hangs on the bus i2c_send_byte (0x10); // data byte, which is written to the device i2c_send_byte (0x10); // one more byte of data, which we write to the device i2c_stop_cond (); // stop tires

After the stop condition, we can check if everything is in order with the I 2 C bus. To do this, we need to read the "i2c_frame_error" variable. If everything is fine, then it will contain 0. If one of the bus pins is not "pulled up" to the power supply, and the logical "1" is not installed on the bus, then the library generates an error and writes the number 1 to the "i2c_frame_error" variable. Read the variable " i2c_frame_error "is needed after the stop condition. The figure below will demonstrate how error control works:

Now let's start connecting the PCF8583 real-time clock library. To do this, you need to do the same. Copy the file "PCF8583.h" to the folder with the project, and add it to include, as in the photo:

Ready. Real time clock library PCF8583 is connected. It does not require any settings, so you can immediately start reading the time and date from the microcircuit. I draw your attention to the fact that the PCF8583 library works using the I2C library, so if we want to work with PCF8583, then you need to connect both libraries!

An example of using the library (writing and reading time and date):

// Initialize the I2C bus i2c_init (); // Prepare the time and date for writing to the PCF8583 chip PCF_hour = 23; // 23 hours PCF_min = 59; // 59 minutes PCF_day = 31; // 31st number PCF_month = 12; // 12 month - December PCF_year = 0; // year (0 - not a leap year) PCF_weekday = 6; // 6th day of the week (Sunday) // Write the time and date to the PCF8583 chip PCF_write_hh_mm_ss (); // Read the time and date from the PCF8583 chip PCF_read_hh_mm_ss (); An example of working with RAM (writing and reading): // Prepare 5 bytes for writing to the PCF8583 microcircuit PCF_data_ram_1 = 255; // byte 1 PCF_data_ram_2 = 255; // byte 2 PCF_data_ram_3 = 255; // byte 3 PCF_data_ram_4 = 255; // byte 4 PCF_data_ram_5 = 255; // byte 5 // Write 5 bytes to the PCF8583 PCF_write_ram (); // Read 5 bytes from PCF8583 PCF_read_ram ();

Reading from a microcircuit is even easier - just call the functionPCF_ read_ hh_ mm_ ss() after that, the time and date will appear in the variables, from where you just take them. To read the RAM, respectively, we use the functionPCF_ read_ ram() after which we take the data in variablesPCF_ data_ ram_ N

Here is a list of variables where and what is stored:

// time and date PCF_hour = 0; // time, hours (from 0 to 23, write and read overflow protection) PCF_min = 0; // time, minutes (from 0 to 59, write and read overflow protection) PCF_sec = 0; // time, seconds (read-only, reset to 00 when writing) PCF_day = 0; // day (from 1 to 31, write and read overflow protection) PCF_weekday = 0 // day of the week (0-Monday; 6-Sunday, write and read overflow protection) PCF_month = 0; // month (from 1 to 12, write and read overflow protection) PCF_year = 0; // year (0-leap year; 1,2,3-non-leap years, overflow protection when writing and reading) // RAM PCF_data_ram_1; // Data (PCF8583 RAM), byte 1 PCF_data_ram_2; // Data (PCF8583 RAM), byte 2 PCF_data_ram_3; // Data (PCF8583 RAM), byte 3 PCF_data_ram_4; // Data (PCF8583 RAM), byte 4 PCF_data_ram_5; // Data (PCF8583 RAM), byte 5

Now I'll tell you about overflow protection. Let's say we forgot to connect the microcircuit. Let's read the data from the microcircuit, and ... byte 11111111, or the number 255, is read. The thing is that the I 2 C bus is based on 2 pull-up resistors, so they give us logical "ones" if the microcircuit is not connected. To protect against such cases, in the PCF8583 library I made overflow protection, which makes sure that the clock does not show you 62 hours 81 minutes ... The presence of an overflow can be traced by reading the "PCF_overflow" variable. If it contains 0, then there were no overflow errors. If it contains 1 or more, then there are overflow errors. You need to read the "PCF_overflow" variable after the date and time reading functionPCF_ read_ hh_ mm_ ss()

For clarity, the AVR Studio 6 project for ATmega32 is attached. You can recompile for any AVR. In the project, I also connected a display for visual control. When power is applied, the microcontroller sets 23 hours 59 minutes, December 31, Sunday. And in a minute it becomes 00 hours 00 minutes, January 1, Monday.

Now I'll tell you why I spoke about the "curve" calendar of this microcircuit. The thing is that the microcircuit does not know how to store the current calendar year, but only stores the leap year flag. Shortly speaking:
0 - leap year
1 - not a leap year
2 - not a leap year
3 - not a leap year

And so on the cycle 0-1-2-3-0-1-2-3-0 ...

In general, to make a normal calendar, you need to implement software calculation and save the year, for example, in the same RAM PCF8583, but it is not convenient. And most importantly, with a de-energized circuit, alas, no one will overwrite the memory ...

I also attach a small video report at the end of the article. In programming, I can say a beginner, although I have been programming for 3 years (a little), do not judge strictly for the code, if there are any additions and comments, write, we will correct it. Happy homemade products to everyone!

List of radioelements

Designation Type of Denomination Quantity NoteShopMy notebook
MK AVR 8-bit

ATmega32

1 Into notepad
Real Time Clock (RTC)

PCF8583

1 Into notepad
LCD displayWH16021

In this article, we made an attempt to collect in one place links to all the most popular Arduino libraries, and also prepared a selection of the most popular libraries. Sooner or later, any arduino player is faced with the need to use a particular library. After all, the use of ready-made code greatly reduces programming time. We hope that collected in one place and provided with download links and short examples of use, information about popular libraries will help you in your projects.

The arduino library is a kind program code stored not in the sketch, but in external files that can be connected to your project. The library contains different methods and data structures that are needed to simplify the work with sensors, indicators, modules and other components. The use of ready-made programs greatly simplifies the work on projects, because you can focus on the main logic without wasting time on a lot of little things.

Today, a huge number of libraries have been created that can be easily found and downloaded on the Internet. The vast majority of libraries are distributed by free license so there is no need to search for “pirated” versions. The main thing is to learn.

Arduino standard libraries

It is better to start your acquaintance with libraries from the official site, where you can find an impressive list of standard modules and links to official partner libraries.

List of built-in libraries (they come with the Arduino IDE distribution):

  • EEPROM
  • Ethernet / Ethernet 2
  • Firmata
  • LiquidCrystal
  • Servo
  • SoftwareSerial
  • Stepper

A selection of libraries in one archive

If you do not have time for a detailed analysis of many sites and you want to download everything you need to work with external devices Arduino in one archive, we have prepared a list of the 40 most popular libraries. Simply and unzip its contents (libraries folder) into your Arduino folder.

Libraries for screens, indicators and displays

I2C library

A library designed to operate a peripheral device using the I2C protocol.

Usage example:

#ifndef I2C_MASTER_H

#define I2C_MASTER_H

void I2C_init (void) - creating an object, setting the correct frequency for the bus.

uint8_t I2C_start () - establishing a connection with a new device.

uint8_t I2C_write () - writing data to the current device.

uint8_t I2C_read_ack () - reading a byte from the device, requesting the next byte.

LiquidCrystal Library

Standard library installed in Arduino IDE. Designed to control LCD liquid crystal displays.

Usage example:

#include ... Also, in order not to make mistakes when writing, you can connect it via the Sketch menu - Import Library - LiquidCrystal.

The constructor of the class is LiquidCristal (...). The arguments are rs, rw, en, do… d7. The first 3 correspond to the RS, RW and Enable signal pins. The d pins correspond to the numbers of the data buses to which the display is connected.

void begin (cols, rows) is the method that initializes the display interface. The arguments are the number of characters per line (cols) and the number of rows (rows). This method must be asked first.

void createChar (num, data) - the method needed to create custom characters.

UTFT Library

Standard library required for Arduino to work with TFT screens different types... All supported displays are shown in accompanying document with a library.

Usage example:

#include

UTFT (); - creating an instance of UTFT.

textRus (char * st, int x, int y); - a method that allows you to output a string from a pointer. For example, char * dht = “Temperature, C”;

textRus (string st, int x, int y); - output of a line with an indication in the parameter. For example, g.textRus (“Temperature, C”, 0, 20);

Library LedControl

Allows you to control seven-segment displays, combine an array of LEDs into one matrix.

Usage example:

#include

LedControl lc1 = LedControl ();

- required to initialize the library. It should consist of four arguments - the number of pins to which the display is connected (the first 3 arguments) and the number of connected chips.

writeArduinoOn7Segment () - Displays all numbers from 0 to 15. Uses setChar () functions for characters a and d and setRow () to create a layout for missing characters.

LedControl.shutdown () - shutdown image.

setIntensity () - brightness control.

Libraries for working with Arduino date and time

RTClib library

A library for working with a real-time clock that simplifies interaction with Arduino.

Usage example:

#include

RTC_DS1307 RTC; - sensor selection (in this case DS1307).

rtc.adjust (DateTime (Date, Time)); - setting the time and calendar.

dayOfTheWeek () - displays the day of the week. Argument is from 0 to 6, 0 is Sunday.

Timelib library

Allows Arduino to get information about the date and time at the moment.

Usage example:

#include

Time (); - creating an instance.

setTime (t); - setting the time. The t argument is hour, minute, second, day, month, and year.

timeStatus (); - shows if the time is set.

adjustTime (adjustment); - time setting.

Ds1307 Library

Library for convenient interaction of DS1307 clock with Arduino using the Wire library.

Usage example:

#include

class DS1307RTC - Create a DS1307 object.

SetTime () - setting the time.

get () - reads RTC, returns the resulting date in POSIX format.

Set (time_t t) - writing date to RTC

DS 3231 library

Designed to manage date and time in the ds3231 module.

#include “ds3231.h”

DS3231 Clock (SDA, SCL); - creating a DS3231 object, connecting to a clock line and a data line.

getTime (); - reading the date and time from the clock.

setDate (date, mon, year); - setting the date.

Arduino system libraries

EEPROM library

Standard library. Designed to work with non-volatile memory (data recording, reading).

Usage example:

#include

EEPROM.read (); - creating an object, reading a byte at an address from non-volatile memory.

EEPROM.write (address, value) - writing a byte to non-volatile memory.

EEPROM.put () - writing strings of floating point numbers.

EEPROM.get () - reading strings and floating point numbers.

SoftwareSerial Library

A library that allows you to implement serial interfaces from any digital pins. Also allows the creation of multiple serial ports that operate at speeds up to 115200 baud.

#include

SoftwareSerial mySerial (RX, TX) - object creation, arguments - pins to which RX and TX are connected.

Serial.begin (); - sets the port speed for communication between arduino and computer.

mySerial.overflow () - checking the input buffer for overflow.

Math Library

Includes a large number of mathematical functions for working with floating point numbers.

Usage example:

#include

Math (); - creating an instance of Math.

Serial.print (“cos num =“); - returns the cosine of a number.

Serial.println (fmod (double__x, double__y)); - returns numbers modulo.

Scheduler library

Designed to work with the Arduino Due, allows you to work in multitasking mode. It is still an experimental library.

Usage example:

#include

Scheduler; - creating an instance.

Scheduler.startLoop () - allows you to add a function that will run along with loop ().

yield () - allows you to transfer control to other tasks.

Servo and Stepper Motor Libraries

Servo library

Standard library. Essential for controlling servo motors and is often used in robotic projects with manipulators.

Usage example:

#include

Servo myservo; - creating an object for the servo motor ..

myservo.attach (); - the number of the output to which the servomotor is connected.

myservo.write (180, 30, true); - movement by 180 degrees, speed 30, waiting for the end of the movement.

Stepper library

Required for driving unipolar and bipolar stepper motors.

#include

const int stepsPerRevolution =; - the number of steps for which the engine makes a full turn.

Stepper myStepper = Stepper (steps, pin1, pin2) - creates an instance of the class with the specified number of steps and pins to which the motor is connected.

Arduino sensor libraries

DHT library

#include< DHT.h>

DHT dht (DHTPIN, DHT11); - initializes the sensor (in this case DHT11).

dht.begin (); - starting the sensor.

float t = dht.readTemperature (); - reading the current temperature value in degrees Celsius.

DallasTemperature Library

Designed to work with Dallas sensors. Works in conjunction with the OneWire library.

#include

DallasTemperature dallasSensors (& oneWire); - transfer of the oneWire object to work with the sensor.

put it in the register.

printTemperature (sensorAddress); - request to receive the measured temperature value.

Ultrasonic library

Enables Arduino to work with HC-SR04 ultrasonic distance sensor.

#include

Ultrasonic ultrasonic (tig, echo) - object declaration, arguments - Trig contact and Echo contact.

dist = ultrasonic.distanceRead (); - determination of the distance to the object. Agrument - centimeters (CM) or inches (INC).

Timing () - reading the pulse duration at the Echo output, translating it into the required number system.

ADXL345 Library

Designed to work with the ADXL345 accelerometer.

Usage example:

#include

ADXL345_ADDRESS - creating an object, specifying its address.

ADXL345_REG_DEVID - device identification.

ADXL345_REG_OFSX - X-axis offset.

ADXL345_REG_BW_RATE - baud rate control.

BME280 Library

Designed to work with the BME280 temperature, humidity and pressure sensor.

Usage example:

#include

BME280_ADDRESS - creating a BME280 object, specifying its address.

begin (uint8_t addr = BME280_ADDRESS); - the beginning of the sensor operation.

getTemperature - getting the measured temperature.

getPressure - get the measured pressure.

BMP280 Library

Required to work with the BMP280 atmospheric pressure sensor.

Usage example:

#include

BMP280_CHIPID - creating an instance, specifying its address.

getTemperature (float * temp); - obtaining the measured temperature.

getPressure (float * pressure); - obtaining the measured pressure value.

BMP085 Library

Required to work with BMP085 pressure sensor.

Usage example:

#include

Adafruit_BMP085 bmp; - creating an instance of BMP085.

dps.init (MODE_ULTRA_HIGHRES, 25000, true); - pressure measurement, argument 25000 - altitude above sea level (in this case 250 m above sea level).

dps.getPressure (& Pressure); - determination of pressure.

FingerPrint Library

Required to work with the fingerprint scanner.

Exampleuse of:

#include

Adafruit_Fingerprint finger = Adafruit_Fingerprint (& mySerial); - Finger object declaration. Parameter - a reference to the object for working with the UART, to which the module is connected.

finger.begin (); - initialization of the fingerprint module.

Func_sensor_communication (); - call the fingerprint module.

Communication libraries

Wire library

Required to work with 2-wire I2C interface.

Usage example:

#include

Wire.begin () - initialization of the library, connection to the I2C bus.

Wire.requestFrom () - the master's request for bytes from the slave device.

Wire.beginTransmission () - the beginning of transmission to the slave device.

Irremote library

Required for Arduino to work with an IR receiver.

Usage example:

#include

IRrecv irrecv (RECV_PIN); - pin to which the IR receiver is connected.

SetPinAndButton (int ir1, int ir2, int pin) - allows you to configure a specific output to be triggered at the given values ​​of ir1, ir2.

GSM library

Required to connect via a GSM card to a GSM / GRPS network. With its help, you can implement operations performed by a GSM phone, work with voice calls and connect to the Internet via GRPS.

Usage example:

#include

GSM GSMAccess - initializes an instance of the class.

gprs.powerOn () - power on.

GPRS - setting up an Internet connection.

GSM - radio modem control.

RFID library

Required to connect Arduino and RFID module.

Usage example:

#include

RFID rfid (SS_PIN, RST_PIN); - creating an instance of rfid, arguments - pins to which the module is connected.

rfid.init (); - initialization of the RFID module.

MFRC Library 522

Required to connect Arduino and MFRC522 module.

Usage example:

#include

MFRC522 mfrc522 (SS_PIN, RST_PIN); - creating an instance of MFRC522, the arguments indicate the outputs to which the module is connected.

mfrc522.PCD_Init (); - initialization of the MFRC522.

Ethershield library

New version https://github.com/jcw/ethercard

Required to connect Arduino to local network or the Internet. The library is no longer supported, more a new version Ethercard. There is also standard library Ethernet.

Usage example:

#include "EtherShield.h"

#include

EtherShield es = EtherShield (); - preparing a web page

ether.begin (sizeof Ethernet :: buffer, mymac,); - getting started, arguments - Mac address and the port number to which the CS output is connected.

Library Nrf24l01

Required to work with the RF24 radio module.

Usage example:

#include "RF24.h"

RF24 - Constructor creates a new driver instance. Before using, you need to create an instance and specify the pins to which the chip is connected (_cepin: contact of the Enable module, cspin: contact of the Select module).

Begin - the beginning of the operation of the chip.

setChannel - channels for RF communication.

setPayloadSize - setting a fixed transfer size.

getPayloadSize - getting a fixed size.

TinyGPS library

Required to read GPGGA and GPRMC messages. Helps to read data on position, date, time, altitude and other parameters.

Usage example:

#include

TinyGPS gps; - creating an instance of TinyGPS.

encode () - feeding serial data to an object one character at a time.

gps.stats () - statistics method. Indicates whether valid data has been received or not.

Libraries in Arduino IDE

Among the whole variety of libraries, 3 main groups can be distinguished:

  • Embedded are libraries originally installed in the Arduino IDE. They do not need to be downloaded and installed additionally; they are available for use in the program immediately after starting the development environment.
  • Additional - these are libraries that you need to download and install yourself. Usually, this kind of libraries is developed by the manufacturer of sensors, sensors and other components to facilitate working with arduino.
  • Dependent Libraries - Installed as a helper of an additional library, does not work separately from it.

The most in a simple way working with libraries in arduino is to use the built-in capabilities of the Arduino IDE. We will talk about this in a separate article.

Share this