Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
Diana BernabeiLuigi Francesco Cerfeda
Published © GPL3+

How to Use DAC and ADC on Microcontrollers Using Python

How to convert from analog to digital signals and vice versa using simple Python on microcontrollers.

BeginnerFull instructions provided1 hour5,719

Things used in this project

Hardware components

ESP32S
Espressif ESP32S
×1

Software apps and online services

Zerynth Studio
Zerynth Studio

Story

Read more

Schematics

ESP32

Code

main.py

Python
import streams
import dac # for digital to analog -> write
import adc # for analog to digital -> read
import math # mathematical function

# create a serial port stream with default parameters
streams.serial()

# create list of angles and calculate the cosine
angles = range(0,360,10)
val = []
for ang in angles: 
    val.append(int(math.cos(math.radians(ang))*100)+100)

def read_and_print():
   #  add physical link pin D25 with pin A4 and read value
    while True:
        value = adc.read(A4)
        conv = (value-1500)*80//4095

        if conv>=0:
            print(" "*40,"#"*conv)
        else:
            print(" "*(40+conv),"#"*(-conv))
        sleep(10)

# read input in a separate thread
thread(read_and_print)

# write cos on pin D25
my_dac = dac.DAC(D25.DAC)
my_dac.start()
# circular mode: continuously repeat the input buffer
my_dac.write(val,50,MILLIS,circular=True) 

Credits

Diana Bernabei

Diana Bernabei

2 projects • 1 follower
Luigi Francesco Cerfeda

Luigi Francesco Cerfeda

6 projects • 95 followers
Yet another Tony Stark wannabe

Comments