Imprimer
Catégorie : Embedded Systems
Affichages : 1590

 1°/ program structure

2°/ reading/writing on GPIO pins

 

 

 

// example with esp8266 pins
void setup() {
  pinMode(D3, OUTPUT);
  pinMode(D2, INPUT);
  ...
}

 

int val = analogRead(A0); // read a value from 0 to 1023, which correspond to 0V and 3.3V
byte b = digitalRead(D2);
...
digitalWrite(D3,HIGH); // on an esp8266, D3 now outputs 3.3V
digitalWrite(D3,LOW); // on an esp8266, D3 now outputs 0V

 

3°/ Serial communication with a PC

...
void setup() {
  Serial.begin(115200); // initialize serial connection at 115200 bauds
  Serial.println("hello");
  ...
}

 

 

4°/ Interrupts

Exemple : react to a change on pin D3 of an esp8266 board.

volatile byte state;
...
void ICACHE_RAM_ATTR mycallback() {
  state = digitalRead(D3);
  ...
}
...
void setup() {
  ...
  attachInterrupt(digitalPinToInterrupt(D3), mycallback, CHANGE);
  ...
}
Remarks
 
5°/ Pulse Width Modulation (PWM)

 

Exemple :

analogWriteRange(100);
analogWriteFreq(10000); // 10KHz
analogWrite(D3,10); // duty cycle of 10%

 

6°/ Interlude about power consumption

 

 

7°/ Deep sleep

 

7.1°/ on esp8266

Exemple (for esp8266):

uint32_t bootcount;
void setup() {
  Serial.begin(115200);
  ...
  ESP.rtcUserMemoryRead(0, &bootcount, sizeof(bootcount));
  Serial.println(bootcount);
  ...
  bootcount++;
  ESP.rtcUserMemoryWrite(0, &bootcount, sizeof(bootcount));
  ...
}
void loop() {
  ...
  ESP.deepSleep(5000000); // sleep 5s, (=5000000µs)
}

 

7.2°/ on esp32

Example (for esp32):

RTC_DATA_ATTR int bootCount = 0;

// print the reason by which ESP32 has been awaken from sleep
void print_wakeup_reason(){
  esp_sleep_wakeup_cause_t wakeup_reason;
  wakeup_reason = esp_sleep_get_wakeup_cause();
  switch(wakeup_reason)  {
    case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
    case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
    case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
    case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
    case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
    default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
  }
}

void setup() {
  Serial.begin(115200);
  ++bootCount;
  Serial.println(bootCount);
  print_wakeup_reason();
  // configure pin 33 as external wakeup source
  esp_sleep_enable_ext0_wakeup(GPIO_NUM_33,1); //1 = High, 0 = Low
  // configure deep sleep timer
  esp_sleep_enable_timer_wakeup(5000000); // time in µ-seconds
}

void loop() {
  delay(1000);
  Serial.println("Going to sleep now");
  esp_deep_sleep_start();
  Serial.println("This will never be printed");
}