EasyManua.ls Logo

Freenove Ultimate Starter Kit - Page 106

Freenove Ultimate Starter Kit
286 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
Chapter 7 AD/DA Converter
106
www.freenove.com
support@freenove.com
The following is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <wiringPi.h>
#include <pcf8591.h>
#include <stdio.h>
#define address 0x48 //pcf8591 default address
#define pinbase 64 //any number above 64
#define A0 pinbase + 0
#define A1 pinbase + 1
#define A2 pinbase + 2
#define A3 pinbase + 3
int main(void){
int value;
float voltage;
wiringPiSetup();
pcf8591Setup(pinbase,address);
while(1){
value = analogRead(A0); //read A0 pin
analogWrite(pinbase+0,value);
voltage = (float)value / 255.0 * 3.3; // calculate voltage
printf("ADC value : %d ,\tVoltage : %.2fV\n",value,voltage);
delay(100);
}
}
The default I2C address of PCF8591 is 0x48. The pinbase is an any value greater than or equal to 64. And we
have defined the ADC input channel A1, A2, A0, A3 of PCF8591.
#define address 0x48 //pcf8591 default address
#define pinbase 64 //any number above 64
#define A0 pinbase + 0
#define A1 pinbase + 1
#define A2 pinbase + 2
#define A3 pinbase + 3
In the main function, after PCF8591 is initialized by pcf8591Setup(pinbase, address), you can use the function
analogRead() and analogWrite() to operate the ADC and DAC.
pcf8591Setup(pinbase,address);
In the “while” cycle, analogRead (A0) is used to read the ADC value of the A0 port (connected potentiometer),
then the read ADC value is output through analogWrite(). And then the corresponding actual voltage value
will be calculated and displayed.
while(1){
value = analogRead(A0); //read A0 pin
analogWrite(pinbase+0,value);
voltage = (float)value / 255.0 * 3.3; // calculate voltage
printf("ADC value : %d ,\tVoltage : %.2fV\n",value,voltage);

Table of Contents