ESP Basic series - I2C driver example for the PCF8591 I2C 8-bit A/D and D/A converter - PART2
For a deeper description of the PCF8591 and simple DAC driver example please go to PART 1
What we will need:
- ESP8266 nEXT EVO Board ( Bare PCB available directly at DirtyPCB's Shop )
- PCF8591 Module like the one from here or here, advertised as new versions.
- For programming and uploading the driver and the software we will use the ESPBasic
Driver implementation
As been a I2C compatible device you need to have a standard I2C Bus Initialisation function as usual and also to know the I2C address of the device.
For a detailed PCF 8591 Control Byte description go to PART1.
Software:
1. Main program:
let address = 72 'PCF8591 I2C Address
i2c.setup(4,5) 'choose your I2C bus pins
cls
let dac = 0
let dac_v = 0
let adc0_1 = 0
let adc0_v = 0
let v_cal = 0.0128
adc0_1 = "ADC stopped"
wprint " <b>PCF8591 8-bit A/D and D/A converter driver demo</b><br><i>by tech@esp8266-projects.com</i><br><br> "
wprint " Input DAC value"
textbox dac
button " Set Value ",[SetDAC]
wprint " <br>DAC Output (V)"
textbox dac_v
wprint "<br>"
wprint "<br><br>ADC0 Read Value:"
textbox adc0_1
wprint "<br>ADC0 Read (Volt):"
textbox adc0_v
wprint "<br><br>"
button " Start ADC_0 ",[ADC0]
button " Stop ADC", [Exit ADC]
wprint "<br><br>"
button " Stop Program", [Exit]
wait
2. Set DAC subroutine:
[SetDAC]
dac_v = dac * v_cal
i2c.begin(address)
i2c.write(64) 'DAC Enable
delay 5
i2c.write(dac)
i2c.end()
wait
3. Enable ADC subroutine:
[ADC0]
timer 1000, [readADC]
wait
4. Read ADC subroutine:
[readADC]
ch = 64
i2c.begin(address) 'start another transaction
i2c.write(ch) 'point to the ADC_0 - keep DAC ON
delay 5
i2c.end() 'end write transaction
i2c.begin(address) 'start another transaction
i2c.requestfrom(address,2) 'start a transaction to read 2 bytes
delay 5
adc0_0 = i2c.read() 'read the 1st byte
adc0_1 = i2c.read() 'read the 2nd byte
i2c.end() 'end read transaction
adc0_v = v_cal + adc0_1 * v_cal
wait
5. EXIT ADC subroutine:
[Exit ADC]
timer 0
adc0_1 = "ADC stopped"
wait
6. Exit Program button subroutine:
[Exit]
timer 0
end
In the ESP Basic Web editor interface Type & Save your program as "PCF8591.bas" and Run it.
If all OK the result should look as below:
1 comment:
Very thorough and helpful demo again TZ, now I shall do a joystick controller amongst other things, thank you very much.
Post a Comment