Skip to content

Instantly share code, notes, and snippets.

@a-h
Created March 17, 2019 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-h/9d0d618b935449220afc0829a413e3ea to your computer and use it in GitHub Desktop.
Save a-h/9d0d618b935449220afc0829a413e3ea to your computer and use it in GitHub Desktop.
ESP32 DAC square wave
#include <U8x8lib.h>
U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/15, /* data=*/4, /* reset=*/16);
// Timer setup.
volatile int interruptCounter;
volatile int totalInterruptCounter;
hw_timer_t *timer = NULL;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
void IRAM_ATTR onTimer()
{
portENTER_CRITICAL_ISR(&timerMux);
interruptCounter++;
portEXIT_CRITICAL_ISR(&timerMux);
}
void setup()
{
u8x8.begin();
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, 0, "square");
u8x8.setCursor(0, 0);
// if (totalInterruptCounter % 1000 == 0)
// {
// u8x8.drawString(0, 0, " ");
// u8x8.setCursor(0, 0);
// u8x8.print(totalInterruptCounter, DEC);
// }
// Setup a timer.
int prescaler = 80;
timer = timerBegin(0, prescaler, true); // 80Hz (base frequency) / prescaler (80) = 1,000,000Hz timer.
timerAttachInterrupt(timer, &onTimer, true);
timerAlarmWrite(timer, 200, true); // 1,000,000Hz / 50 = 20Khz max frequency
timerAlarmEnable(timer);
}
void loop()
{
if (interruptCounter > 0)
{
portENTER_CRITICAL(&timerMux);
interruptCounter = 0;
totalInterruptCounter++;
portEXIT_CRITICAL(&timerMux);
}
if (totalInterruptCounter % 2 == 0)
{
dacWrite(25, 250);
}
else
{
dacWrite(25, 5);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment