Internet of Things with Repka Pi Microcomputer

What is ADC/DAC

In the simplest case, we can identify the appearance of current on a device contact or a microcircuit pin using 0 and 1. The absence of current or failure to exceed a certain value can be considered zero, and any excess of this value is already a unit. However, this approach is convenient only in the simplest cases, when it is necessary to detect pressing a button or other contact closure.

But if we need to measure the level of the transmitted signal, then we need to use analog-to-digital conversion, that is, a system that converts an analog signal, such as sound captured by a microphone or light falling on a sensor, into a digital signal. The idea here is that the same light sensor reacts to the activity of the light falling on it in analog mode, for example, by changing the resistance. But for use in our firmware, we need some digital value that can be compared with some constant, for example, so that our device turns on the lighting when the light level is below a certain value. Usually, the digital output signal is a number that is proportional to the signal level on the ADC. The higher the bit depth of this number, the higher the accuracy of the value that we get as a result of analog-to-digital conversion.

In practice, there are several ADC architectures. Due to the complexity and need for precision in the operation of components, all ADCs, except for the most specialized ones, are implemented as integrated circuits (ICS). Further in the article, we will consider one of such modules for ADC/DAC conversion on the PCF8591 chip.

Accordingly, the Digital-to-Analog Converter (DAC) performs the opposite function – it converts a digital signal into an analog one.

ADC/DAC module

The module we have chosen provides 8-bit analog-to-digital and 8-bit digital-to-analog conversion, with which we can read analog values ​​from 4 inputs and, if necessary, generate analog values ​​to one output. The module requires a supply voltage of 2.5-6 V to operate. Data exchange with the chip is carried out via the I2C interface. We will talk about this interface and its implementation on Repka Pi a little later.

The module already has additional components installed: a potentiometer, a photoresistor, a thermistor, which are connected to the ADC inputs (0, 1 and 3) using jumpers, and the location of the input contacts allows it to be used on a breadboard without additional modifications.

Learning to correctly understand the ADC result

The ADC gives us some digital value and our task is to correctly understand what we have received. The formulas presented below are taken from the documentation for working with Repka Pi.

When working with ADC/DAC modules on the input lines of Repka Pi 3, we will receive the values ​​of the input signal converted by the chip, i.e. integer values ​​in the range from 0 to 255.

The input signal values ​​are calculated using the formula:

V = (U_in / U_adc) * 255

Where:

V – value from the ADC input;

U_in – voltage received by the ADC at the input;

U_adc – supply voltage.

For a better understanding, let's look at a small example:

As a result, the ADC received a value of 93, it is known that the contact is connected to a network with a voltage of 3.3 V. Let's calculate the voltage received at the ADC signal input.

(93 / 255) * 3.3 = 1.2 V.

I2C interface and its implementation

The I2C (Inter-Integrated Circuit) interface is a bidirectional asynchronous serial data bus. It uses two bidirectional communication lines (SDA and SCL) and is used to connect low-speed peripheral components to processors and microcontrollers. In our case, we will be interacting with a microcomputer.

A device connected to the I2C bus can perform one of two roles: master or slave. I2C allows multiple master and slave devices to coexist on the same bus. Data exchange occurs in sessions that are completely controlled by the master.

As a protocol for exchanging data with the device, we will use SMBus (System Management Bus) – a serial protocol for exchanging data for devices. Support for this protocol is implemented at the Linux kernel driver level.

To allow users in RepkaOS to access I2C controllers, you need to run the command to create a group

sudo groupadd i2c

Then assign the i2c group as the owner of the I2C controller. In the example below, we assign the owner to the first controller:

sudo chown :i2c /dev/i2c-1

Let's allow members of the i2c group to read and write data to the first controller:

sudo chmod g+rw /dev/i2c-1

And finally, we need to add the user to the i2c group with the command

sudo usermod -aG i2c user_name

Log out and log back in to apply the settings.

Next, we will install the necessary packages:

sudo apt update

sudo apt install python3-smbus

Next, let's see what we got.

Testing the ADC

The circuit recommended by the vendor for Repka Pi operation with ADC is as follows:

To programmatically process the received signal, we will use a small Python program.

import os # модуль для работы с ОС

import time # модуль работы со временем

from smbus import SMBus # модуль для работы с I2C контроллером

 

# адрес устройства (PCF8591) на шине I2C

DEV_ADDR = 0x48

 

# словарь адресов данных для входных каналов АЦП

adc_channels = {

    'AIN0':0b_0100_0000, # 0x40 (фоторезистор)

    'AIN1':0b_0100_0001, # 0x41 (терморезистор)

    'AIN2':0b_0100_0010, # 0x42 (свободный)

    'AIN3':0b_0100_0011, # 0x43 (потенциометр)

}

# адрес данных для ЦАП

dac_channel = 0b_0100_0000 # 0x40

 

# получаем доступ к контроллеру I2C 

# (1 контроллер I2C для 2-5 вариантов распиновки - контакты 3-SDA и 5-SCL)

# (2 контроллер I2C для 4 варианта распиновки - контакты 27-SDA и 28-SCL)

bus = SMBus(1)

# устанавливаем значение для ЦАП

dac_value = 0

 

while(True):

    os.system('clear') # очищаем терминал

    print("Нажмите Ctrl + C для завершения работы...\n")

    # запускаем "бесконечный" цикл для обмена информацией с АЦП/ЦАП

    for channel in adc_channels:

        # получаем значения из АЦП для всех аналоговых входов

        bus.write_byte(DEV_ADDR, adc_channels[channel])

 

        # выбрасываем старое значение АЦП дважды (особенность устройства)

        # т.к. нам не нужно сравнивать новое значение с предыдущим

        bus.read_byte(DEV_ADDR) 

        bus.read_byte(DEV_ADDR) 

 

        value = bus.read_byte(DEV_ADDR) # получаем новое значение

        # если текущая лини 3, то получаем значение с потенциометра

        if channel == 'AIN3': 

            dac_value = value

        # выводим в консоль значение АЦП для каждого входа

        print('Канал ' + channel + ' ---> ' + str(value))

    # устанавливаем значение для ЦАП (изменяем яркость светодиода)

    bus.write_byte_data(DEV_ADDR, dac_channel, dac_value)

    # ждем 100 миллисекунд

    time.sleep(0.1)

 

You can test the ADC operation on a microcomputer in fairly simple ways, for example by shining a flashlight on a photoresistor or breathing on a thermistor. As a result, we will see changes in the values ​​coming from the ADC module.

Conclusion

Analog-to-digital conversion is actively used in solving various Internet of Things problems. Thus, in a “smart” home, we can automatically collect information about the temperature, humidity and illumination of rooms for subsequent visualization on a map of the apartment. And the Repka Pi microcomputer can be used as a silent home server.


In conclusion, I would like to remind you about the open lessons that will soon be held as part of the “IoT Developer” course:

  • July 3: Transport monitoring in the ThingsBoard platform. Let's go step by step: connecting devices, creating entities, developing rule chains, developing a dashboard. Registration via link

  • July 17: Energy accounting in the ThingsBoard platform. In this lesson, we will look at the solution for accounting of energy resources (water, gas, electricity, heat). Registration via link

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *