Skip to content

Commit

Permalink
Support multiple tone(), analogWrite(), and Servo (#4640)
Browse files Browse the repository at this point in the history
Remove and rewrite all the parts of the core/libraries using TIMER1
and consolidate into a single, shared waveform generation interrupt
structure.  Tone, analogWrite(), Servo all now just call into this
shared resource to perform their tasks so are all compatible
and can be used simultaneously.

This setup enables multiple tones, analogWrites, servos, and stepper
motors to be controlled with reasonable accuracy.  It uses both TIMER1
and the internal ESP cycle counter to handle timing of waveform edges.
TIMER1 is used in non-reload mode and only edges cause interrupts.  The
interrupt is started and stopped as required, minimizing overhead when
these features are not being used.

A generic "startWaveform(pin, high-US, low-US, runtime-US)" and
"stopWaveform(pin)" allow for further types of interfaces.  Minimum
high or low period is ~1 us.

Add a tone(float) method, useful when working with lower frequencies.

Fixes #4321.  Fixes 4349.
  • Loading branch information
earlephilhower authored Jun 8, 2018
1 parent ea4720b commit ebda795
Show file tree
Hide file tree
Showing 12 changed files with 600 additions and 841 deletions.
1 change: 1 addition & 0 deletions cores/esp8266/Arduino.h
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 100000
unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);

void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0);
void tone(uint8_t _pin, double frequency, unsigned long duration = 0);
void noTone(uint8_t _pin);

// WMath prototypes
Expand Down
132 changes: 38 additions & 94 deletions cores/esp8266/Tone.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
A Tone Generator Library for the ESP8266
Copyright (c) 2016 Ben Pirt. All rights reserved.
Original Copyright (c) 2016 Ben Pirt. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
Expand All @@ -22,115 +22,59 @@
*/

#include "Arduino.h"
#include "pins_arduino.h"
#include "core_esp8266_waveform.h"

#define AVAILABLE_TONE_PINS 1
const uint8_t tone_timers[] = { 1 };
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255, };
static long toggle_counts[AVAILABLE_TONE_PINS] = { 0, };
#define T1INDEX 0
// Which pins have a tone running on them?
static uint32_t _toneMap = 0;

void t1IntHandler();

static int8_t toneBegin(uint8_t _pin) {
int8_t _index = -1;

// if we're already using the pin, reuse it.
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
if (tone_pins[i] == _pin) {
return i;
}
static void _startTone(uint8_t _pin, uint32_t high, uint32_t low, unsigned long duration) {
if (_pin > 16) {
return;
}

// search for an unused timer.
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
if (tone_pins[i] == 255) {
tone_pins[i] = _pin;
_index = i;
break;
}
}
pinMode(_pin, OUTPUT);

return _index;
}
high = std::max(high, (uint32_t)100);
low = std::max(low, (uint32_t)100);

// frequency (in hertz) and duration (in milliseconds).
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) {
int8_t _index;

_index = toneBegin(_pin);

if (_index >= 0) {
// Set the pinMode as OUTPUT
pinMode(_pin, OUTPUT);

// Alternate handling of zero freqency to avoid divide by zero errors
if (frequency == 0)
{
noTone(_pin);
return;
}

// Calculate the toggle count
if (duration > 0) {
toggle_counts[_index] = 2 * frequency * duration / 1000;
} else {
toggle_counts[_index] = -1;
}

// set up the interrupt frequency
switch (tone_timers[_index]) {
case 0:
// Not currently supported
break;

case 1:
timer1_disable();
timer1_isr_init();
timer1_attachInterrupt(t1IntHandler);
timer1_enable(TIM_DIV1, TIM_EDGE, TIM_LOOP);
timer1_write((clockCyclesPerMicrosecond() * 500000) / frequency);
break;
}
if (startWaveform(_pin, high, low, (uint32_t) duration * 1000)) {
_toneMap |= 1 << _pin;
}
}

void disableTimer(uint8_t _index) {
tone_pins[_index] = 255;

switch (tone_timers[_index]) {
case 0:
// Not currently supported
break;

case 1:
timer1_disable();
break;
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) {
if (frequency == 0) {
noTone(_pin);
} else {
uint32_t period = 1000000L / frequency;
uint32_t high = period / 2;
uint32_t low = period - high;
_startTone(_pin, high, low, duration);
}
}

void noTone(uint8_t _pin) {
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
if (tone_pins[i] == _pin) {
tone_pins[i] = 255;
disableTimer(i);
break;
}

// Separate tone(float) to hopefully not pull in floating point libs unless
// it's called with a float.
void tone(uint8_t _pin, double frequency, unsigned long duration) {
if (frequency < 1.0) { // FP means no exact comparisons
noTone(_pin);
} else {
double period = 1000000.0 / frequency;
uint32_t high = (uint32_t)((period / 2.0) + 0.5);
uint32_t low = (uint32_t)(period + 0.5) - high;
_startTone(_pin, high, low, duration);
}
digitalWrite(_pin, LOW);
}

ICACHE_RAM_ATTR void t1IntHandler() {
if (toggle_counts[T1INDEX] != 0){
// toggle the pin
digitalWrite(tone_pins[T1INDEX], toggle_counts[T1INDEX] % 2);
toggle_counts[T1INDEX]--;
// handle the case of indefinite duration
if (toggle_counts[T1INDEX] < -2){
toggle_counts[T1INDEX] = -1;
}
}else{
disableTimer(T1INDEX);
digitalWrite(tone_pins[T1INDEX], LOW);

void noTone(uint8_t _pin) {
if (_pin > 16) {
return;
}
stopWaveform(_pin);
_toneMap &= ~(1 << _pin);
digitalWrite(_pin, 0);
}
Empty file modified cores/esp8266/base64.cpp
100755 → 100644
Empty file.
Empty file modified cores/esp8266/base64.h
100755 → 100644
Empty file.
Loading

6 comments on commit ebda795

@reaper7
Copy link
Contributor

@reaper7 reaper7 commented on ebda795 Jun 8, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@Rob58329
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@earlephilhower

re. Support multiple tone(), analogWrite(), and Servo (#4640) [commit 8Jun18]

This commit breaks:

  • the simple "tone(D8,3000);" command, with the compile error "call of overloaded 'tone(const uint8_t&, int)' is ambiguous"
  • the simple "tone(D8,3000,100);" command with the compile error "call of overloaded 'tone(const uint8_t&, int, int)' is ambiguous

Reason: because there are now two alternatives being:

  • "void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0);"
    and
  • "void tone(uint8_t _pin, double frequency, unsigned long duration = 0);

To avoid user-confusion(!?), I would suggest it would benefit from:

EITHER: changing the "unsigned int frequency" to just "int frequency" in the relevant [Arduino.h] and assoicated files?

OR: adding a 3rd alternative of "void tone(uint8_t _pin, int frequency, unsigned long duration = 0);" in the relevant [Arduino.h] and associated files?

FYI: My setup is Arduino-IDE using latest github-ESP8266-arduino-software and a D1-mini-ESP8266.

@JAndrassy
Copy link
Contributor

@JAndrassy JAndrassy commented on ebda795 Jun 16, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PWM doesn't work with this. I tested only this commit merged in 2.4.1 and then the complete git version, but no PWM. I need PWM and tone in one sketch.

tested with Wemos D1 mini with pin D1 connected to A0. with 2.4.1 it prints corresponding analog values. with this commit nothing.

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  for (int i = 0; i < 1024; i += 10) {
    analogWrite(D1, i);
    delay(100);
    long sum = 0;
    int n = 0;
    unsigned long start_time = millis();
    while (millis() - start_time < 100) {
      sum += analogRead(A0);
      n++;
    }
    Serial.println(sum / n);
  }
}

Edit: with pinMode(D1, OUTPUT); it does something but A0 is at 1023 from PWM value 250
Edit2: with analogWriteRange(1023); it almost works. only the analog values in under PWM 100 are not good. default range until 2.4.1 was 1023, now it is 256?

@earlephilhower
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JAndrassy PWM and analog in are completely different. PWM will drive either a full 3.3 or 0 volts, with the duty cycle being the percent of time it's on. If you physically connect the pins, which you should not because the ESP Ain only had a 1.0 v range. Assuming it does not kill the device, you'll just be reading garbage. This is not an AVR and there are no built in DACs, and the built in ADC is very limited and relatives slow.

@JAndrassy
Copy link
Contributor

@JAndrassy JAndrassy commented on ebda795 Jun 17, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@earlephilhower Wemos has a cirquit for 3.3 V A0. Not ADC is the issue. Backward compatibility is the issue. You did a great work for this commit, but until now it was not required to set pin mode before using analogWrite and the default range was 1023. Arduino docs for analogWrite has "You do not need to call pinMode() to set the pin as an output before calling analogWrite()." and esp8266 core has met this. And the esp8266 docs has " value may be in range from 0 to PWMRANGE, which is equal to 1023 by default. ".

@Rob58329
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@earlephilhower

re. Compatibility and IRQ fixed for waveform/tone/pwm (#4872) - committed 2Jul18 (be7a732)

The latest commit (as above 2Jul18) fixes the "tone(D8,3000);" and "tone(D8,3000,100);" compile-issues.
Interestinly, "tone(D8,(uint16_t)3000)" now also works again!

Mnay thanks! :-)

Please sign in to comment.