Esp8266 какие пины можно использовать

от admin

Esp8266 какие пины можно использовать

While the ESP8266 is often used as a ‘dumb’ Serial-to-WiFi bridge, it’s a very powerful microcontroller on its own. In this chapter, we’ll look at the non-Wi-Fi specific functions of the ESP8266.

Digital I/O

Just like a normal Arduino, the ESP8266 has digital input/output pins (I/O or GPIO, General Purpose Input/Output pins). As the name implies, they can be used as digital inputs to read a digital voltage, or as digital outputs to output either 0V (sink current) or 3.3V (source current).

Voltage and current restrictions

The ESP8266 is a 3.3V microcontroller, so its I/O operates at 3.3V as well. The pins are not 5V tolerant, applying more than 3.6V on any pin will kill the chip.

The maximum current that can be drawn from a single GPIO pin is 12mA.

Usable pins

The ESP8266 has 17 GPIO pins (0-16), however, you can only use 11 of them, because 6 pins (GPIO 6 — 11) are used to connect the flash memory chip. This is the small 8-legged chip right next to the ESP8266. If you try to use one of these pins, you might crash your program.

GPIO 1 and 3 are used as TX and RX of the hardware Serial port (UART), so in most cases, you can’t use them as normal I/O while sending/receiving serial data.

Boot modes

As mentioned in the previous chapter, some I/O pins have a special function during boot: They select 1 of 3 boot modes:

GPIO15 GPIO0 GPIO2 Mode
0V 0V 3.3V Uart Bootloader
0V 3.3V 3.3V Boot sketch (SPI flash)
3.3V x x SDIO mode (not used for Arduino)

Note: you don’t have to add an external pull-up resistor to GPIO2, the internal one is enabled at boot.

We made sure that these conditions are met by adding external resistors in the previous chapter, or the board manufacturer of your board added them for you. This has some implications, however:

  • GPIO15 is always pulled low, so you can’t use the internal pull-up resistor. You have to keep this in mind when using GPIO15 as an input to read a switch or connect it to a device with an open-collector (or open-drain) output, like I²C.
  • GPIO0 is pulled high during normal operation, so you can’t use it as a Hi-Z input.
  • GPIO2 can’t be low at boot, so you can’t connect a switch to it.
Internal pull-up/-down resistors

GPIO 0-15 all have a built-in pull-up resistor, just like in an Arduino. GPIO16 has a built-in pull-down resistor.

Unlike most Atmel chips (Arduino), the ESP8266 doesn’t support hardware PWM, however, software PWM is supported on all digital pins. The default PWM range is 10-bits @ 1kHz, but this can be changed (up to >14-bit@1kHz).

Analog input

The ESP8266 has a single analog input, with an input range of 0 — 1.0V. If you supply 3.3V, for example, you will damage the chip. Some boards like the NodeMCU have an on-board resistive voltage divider, to get an easier 0 — 3.3V range. You could also just use a trimpot as a voltage divider.

The ADC (analog to digital converter) has a resolution of 10 bits.

Communication

Serial

The ESP8266 has two hardware UARTS (Serial ports):
UART0 on pins 1 and 3 (TX0 and RX0 resp.), and UART1 on pins 2 and 8 (TX1 and RX1 resp.), however, GPIO8 is used to connect the flash chip. This means that UART1 can only transmit data.

UART0 also has hardware flow control on pins 15 and 13 (RTS0 and CTS0 resp.). These two pins can also be used as alternative TX0 and RX0 pins.

The ESP doesn’t have a hardware TWI (Two Wire Interface), but it is implemented in software. This means that you can use pretty much any two digital pins. By default, the I²C library uses pin 4 as SDA and pin 5 as SCL. (The data sheet specifies GPIO2 as SDA and GPIO14 as SCL.) The maximum speed is approximately 450kHz.

The ESP8266 has one SPI connection available to the user, referred to as HSPI. It uses GPIO14 as CLK, 12 as MISO, 13 as MOSI and 15 as Slave Select (SS). It can be used in both Slave and Master mode (in software).

GPIO overview

GPIO Function State Restrictions
0 Boot mode select 3.3V No Hi-Z
1 TX0 Not usable during Serial transmission
2 Boot mode select
TX1
3.3V (boot only) Don’t connect to ground at boot time
Sends debug data at boot time
3 RX0 Not usable during Serial transmission
4 SDA (I²C)
5 SCL (I²C)
6 — 11 Flash connection x Not usable, and not broken out
12 MISO (SPI)
13 MOSI (SPI)
14 SCK (SPI)
15 SS (SPI) 0V Pull-up resistor not usable
16 Wake up from sleep No pull-up resistor, but pull-down instead
Should be connected to RST to wake up

The ESP8266 as a microcontroller — Software

Most of the microcontroller functionality of the ESP uses exactly the same syntax as a normal Arduino, making it really easy to get started.

Digital I/O

Just like with a regular Arduino, you can set the function of a pin using pinMode(pin, mode); where pin is the GPIO number*, and mode can be either INPUT , which is the default, OUTPUT , or INPUT_PULLUP to enable the built-in pull-up resistors for GPIO 0-15. To enable the pull-down resistor for GPIO16, you have to use INPUT_PULLDOWN_16 .

(*) NodeMCU uses a different pin mapping, read more here. To address a NodeMCU pin, e.g. pin 5, use D5: for instance: pinMode(D5, OUTPUT);

To set an output pin high (3.3V) or low (0V), use digitalWrite(pin, value); where pin is the digital pin, and value either 1 or 0 (or HIGH and LOW ).

To read an input, use digitalRead(pin);

To enable PWM on a certain pin, use analogWrite(pin, value); where pin is the digital pin, and value a number between 0 and 1023.

You can change the range (bit depth) of the PWM output by using analogWriteRange(new_range);

The frequency can be changed by using analogWriteFreq(new_frequency); . new_frequency should be between 100 and 1000Hz.

Analog input

Just like on an Arduino, you can use analogRead(A0) to get the analog voltage on the analog input. (0 = 0V, 1023 = 1.0V).

The ESP can also use the ADC to measure the supply voltage (VCC). To do this, include ADC_MODE(ADC_VCC); at the top of your sketch, and use ESP.getVcc(); to actually get the voltage.
If you use it to read the supply voltage, you can’t connect anything else to the analog pin.

Communication

Serial communication

To use UART0 (TX = GPIO1, RX = GPIO3), you can use the Serial object, just like on an Arduino: Serial.begin(baud) .

To use the alternative pins (TX = GPIO15, RX = GPIO13), use Serial.swap() after Serial.begin .

To use UART1 (TX = GPIO2), use the Serial1 object.

All Arduino Stream functions, like read, write, print, println, . are supported as well.

I²C and SPI

You can just use the default Arduino library syntax, like you normally would.

Sharing CPU time with the RF part

One thing to keep in mind while writing programs for the ESP8266 is that your sketch has to share resources (CPU time and memory) with the Wi-Fi- and TCP-stacks (the software that runs in the background and handles all Wi-Fi and IP connections).
If your code takes too long to execute, and don’t let the TCP stacks do their thing, it might crash, or you could lose data. It’s best to keep the execution time of you loop under a couple of hundreds of milliseconds.

Every time the main loop is repeated, your sketch yields to the Wi-Fi and TCP to handle all Wi-Fi and TCP requests.

If your loop takes longer than this, you will have to explicitly give CPU time to the Wi-Fi/TCP stacks, by using including delay(0); or yield(); . If you don’t, network communication won’t work as expected, and if it’s longer than 3 seconds, the soft WDT (Watch Dog Timer) will reset the ESP. If the soft WDT is disabled, after a little over 8 seconds, the hardware WDT will reset the chip.

From a microcontroller’s perspective however, 3 seconds is a very long time (240 million clockcycles), so unless you do some extremely heavy number crunching, or sending extremely long strings over Serial, you won’t be affected by this. Just keep in mind that you add the yield(); inside your for or while loops that could take longer than, say 100ms.

Sources

This is where I got most of my information to writ this article, there’s some more details on the GitHub pages, if you’re into some more advanced stuff, like EEPROM or deep sleep etc.

Равнозначны ли все GPIO ESP8266?

Собстн-но, вопрос в названии топика. Возник в связи с необходимостью создания платки универсального переходника для есп, который можно будет использовать на любом из 15 девайсов разрабатываемой системы. Большинство девайсов функционально уникальны, т.е. довольно сильно отличаются друг от друга по назначению, и решаемым задачам. Число потребных пинов GPIO у конкретного девайса для подключения внешних приблуд может быть от 1-2 до 8-10. Это и кнопики (от 1 до 8 на разных девайсах), и исполнительные устройства (до 4-6 штук на девайс), и семи-сегментные индикаторы, и акселерометры, и наконец, вход ADC для мониторинга батарей питания каждого девайса.
Конечно, можно тупо сделать переходник с 22-мя контактными штырями, а выбор конкретных GPIO делать на основной плате каждого девайса, но этот путь мне не кажется оптимальным и обоснованным.

Есть ли статистика по "беспроблеммности" использования GPIO, в том числе и GPIO6 — GPIO11?
Если ли рекомендации, какие пины использовать однозначно не следует? (Например — GPIO16, который может использоваться для вывода есп из спячки), и т.д. Не хочется наступать на грабли, если кто-то уже знает, как их обойти.

P.S. Если этот вопрос уже обсуждался, ткните носом в тему. Форум просмотрел, но ничего похожего не нашел.

Сергей_Ф
Moderator
Valentinych
Member

Согласен, даташит читать надо. Но судя по тому, что здесь часто говорят, верить китайской доке нужно с большими опасениями. Чем я, собственно, и занимался всю прошедшую неделю — читал, делил на два, а из остатка пытался еще и корень извлечь.
В итоге этой читки, и некоторых практических экспериментов, пришел в следующим выводам:
1) GPIO6. 11 следует совсем забыть, и не использовать их в прикладных задачах (когда не нужна внешняя флешка).
2) GPIO15 — постоянно должен быть подтянут внешним резистором к "земле", поэтому если на него и рассчитывать, то только в качестве выходного пина — какой-нить датчик к нему подцепить вряд ли удастся.
3) GPIO16 тоже лучше оставить в покое. На случай, когда потребуется выводить модуль из спячки. Хотя и этот вариант (по крайней мере для меня) довольно не однозначный — пробуждение целесообразно выполнять дистанционно (по воздуху), а если для этого нужно коротить 16 на Res на самом девайсе, то лучше просто отключать и включать питание.
4) GPIO1, 3, в принципе, функциональны, если речь не идет о необходимости реализации сериал-порта для внутрисистемной перепрошивке модуля. Но если делать это "по воздуху", то эти пины вполне можно юзать для своих целей. Однако создалось впечатление, что GPIO1 сам "подтягивается" к Vcc. Хотя возможно, это как раз связано с режимом сериал-порта. Нужно будет дополнительно проверить этот момент.
5) GPIO0 и 2. Субъективно: эти пины толи с норовом, толи тормознутые — их готовность к работе происходит с некоторой задержкой, но после того, как они "успокаиваются", вроде работают нормально.
6) В итоге, самыми адекватными для прикладных целей оказались всего пять пинов: GPIO4, 5, 12, 13 и 14. Как юные пионЭры — всегда готовы! Если этого мало, то с некоторыми ограничениями можно добавить еще и GPIO0, 1, 2 и 3. В самом крайнем случае — еще GPIO15.
В итоге получается девять-десять пинов для "общеюзерских" задач.

Arduino.ru

Если я не буду использовать режим deep sleep то и резистор на GPIO_16 не нужен и я могу использовать этот пин?

Для чего нужна подтяжка GPIO_2 к питанию? (у кого-то на схемах есть, у кого-то нет).

  • Войдите на сайт для отправки комментариев

Irinka аватар

Второй аппаратный UART (Serial1) работает только на передачу?

SoftSerial поддерживается на всех пинах?

  • Войдите на сайт для отправки комментариев

Там табличка — какие пины стоит юзать.

  • Войдите на сайт для отправки комментариев

Irinka аватар

Хорошая статья, Спасибо.

GPIO2: pin is high on BOOT, boot failure if pulled LOW

Про GPIO2 поняла, подтяжка чтобы не было ошибки.

А про эти пины что? Как вход/выход?

  • Войдите на сайт для отправки комментариев

ua6em аватар

на nodemcu я всю правую строну использую, кроме RX-TX: TFT, датчик температуры-влажности, кнопка, проблем нет работает месяцами

  • Войдите на сайт для отправки комментариев

Irinka аватар

А второй uart ? gpio_15 подтянут к gnd

  • Войдите на сайт для отправки комментариев

ua6em аватар

только завтра могу все пины расписать, здесь ни скетча ни девайса нет, если не изменяет память на пинах ниже земли висит дисплей, да, тактовая 160 мегагерц используется

  • Войдите на сайт для отправки комментариев
  • Войдите на сайт для отправки комментариев

Irinka аватар

только завтра могу все пины расписать, здесь ни скетча ни девайса нет, если не изменяет память на пинах ниже земли висит дисплей, да, тактовая 160 мегагерц используется

  • Войдите на сайт для отправки комментариев

Irinka аватар

Это да, там так же указано
GPIO4 and GPIO5 are the most safe to use GPIOs if you want to operate relays.

  • Войдите на сайт для отправки комментариев

Irinka аватар

Мне нужно узнать про uart (буду подключать sim800), а платки ещё в пути, нет возможности попробовать.

  • Войдите на сайт для отправки комментариев

ua6em аватар

Мне нужно узнать про uart (буду подключать sim800), а платки ещё в пути, нет возможности попробовать.

UART не использую,
NODEMCU
D8 — TFT-LED
D7 — TFT-SDA
D6 — BUTTON
D5 — TFT-SCK
D4 — TFT-A0
D3 — TFT-RESET
D2 — LED_BUILTIN
D1 — DHT-11
D0 — TFT-CS

  • Войдите на сайт для отправки комментариев

Irinka аватар

Спасибо. Жду платку для грандиозных экспериментов XDDD

  • Войдите на сайт для отправки комментариев

ua6em аватар

Спасибо. Жду платку для грандиозных экспериментов XDDD

мне с оказией досталась SIM800A а у неё не UART а RS-232 на выход )))

  • Войдите на сайт для отправки комментариев

Irinka аватар

Я покупала SIM800L, дешёвые.

Хочется попробовать SIM800C, но пока всё никак что-то.

  • Войдите на сайт для отправки комментариев

andycat аватар

Зачем? В жизни вы разницы между L C модулями не заметите, по стабильности, командам они одинаковы, разница (ну какую я только в практике заметил) только в логике включения и сброса.

  • Войдите на сайт для отправки комментариев

Irinka аватар

Можно использовать uart0 и для прошивки и для работы с sim800 по такой схеме?

  • Войдите на сайт для отправки комментариев

Komandir аватар

ИМХО не ту линию разделили. Tx от SIM800 «коротит» на Tx USB-UART. Если SIM800 выставит «0», а USB-UART «1» .

  • Войдите на сайт для отправки комментариев

andycat аватар

ИМХО не ту линию разделили. Tx от SIM800 «коротит» на Tx USB-UART. Если SIM800 выставит «0», а USB-UART «1» .

а мне кажеться нормально все соеденено, и конечно одновременно только одно устройство может передавать данные, и вообще USB-UART цеплять параллельно модему так себе затея. если уж нужно контролировать что шлется в модем, то стОит TX USB-UART совсем отключить.

ESP8266 Pinout Reference: Which GPIO pins should you use?

This article is a guide for the ESP8266 GPIOs: pinout diagrams, their functions and how to use them.

ESP8266 Pinout Reference GPIOs Pins Guide

The ESP8266 12-E chip comes with 17 GPIO pins. Not all GPIOs are exposed in all ESP8266 development boards, some GPIOs are not recommended to use, and others have very specific functions.

With this guide, you’ll learn how to properly use the ESP8266 GPIOs and avoid hours of frustration by using the most suitable pins for your projects.

Note: not all GPIOs are accessible in all development boards, but each specific GPIO works in the same way regardless of the development board you’re using. If you’re just getting started with the ESP8266, we recommend checking out our ESP8266 Guides.

ESP8266 12-E Chip Pinout

The following figure illustrates the ESP8266 12-E chip pinout. Use this diagram if you’re using an ESP8266 bare chip in your projects.

ESP8266 12-E chip pinout diagram gpios pins

Note: not all GPIOs are accessible in all development boards, but each specific GPIO works in the same way regardless of the development board you’re using. If you’re just getting started with the ESP8266, we recommend reading our guide: Getting Started with the ESP8266.

At the moment, there are a wide variety of development boards with the ESP8266 chip that differ in the number of accessible GPIOs, size, form factor, etc…

The most widely used ESP8266 boards are the ESP-01, ESP8266-12E NodeMCU Kit, and the Wemos D1 Mini. For a comparison of these board, you can read this guide: ESP8266 Wi-Fi Development Boards comparison.

ESP8266-01 Pinout

If you’re using an ESP8266-01 board, you can use the following GPIO diagram as a reference.

ESP-01 ESP8266 pinout diagram gpios pins

ESP8266 12-E NodeMCU Kit

The ESP8266 12-E NodeMCU kit pinout diagram is shown below.

ESP8266 12-E NodeMCU Kit pinout diagram gpios pins

Wemos D1 Mini Pinout

The following figure shows the WeMos D1 Mini pinout.

WeMos D1 Mini Pinout diagram gpios pins

Download PDF with ESP8266 Pinout Diagrams

We’ve put together a handy PDF that you can download and print, so you always have the ESP8266 diagrams next to you:

ESP8266 Peripherals

The ESP8266 peripherals include:

  • 17 GPIOs
  • SPI
  • I2C (implemented on software)
  • I2S interfaces with DMA
  • UART
  • 10-bit ADC

Best Pins to Use – ESP8266

One important thing to notice about ESP8266 is that the GPIO number doesn’t match the label on the board silkscreen. For example, D0 corresponds to GPIO16 and D1 corresponds to GPIO5.

The following table shows the correspondence between the labels on the silkscreen and the GPIO number as well as what pins are the best to use in your projects, and which ones you need to be cautious.

The pins highlighted in green are OK to use. The ones highlighted in yellow are OK to use, but you need to pay attention because they may have unexpected behavior mainly at boot. The pins highlighted in red are not recommended to use as inputs or outputs.

Label GPIO Input Output Notes
D0 GPIO16 no interrupt no PWM or I2C support HIGH at boot
used to wake up from deep sleep
D1 GPIO5 OK OK often used as SCL (I2C)
D2 GPIO4 OK OK often used as SDA (I2C)
D3 GPIO0 pulled up OK connected to FLASH button, boot fails if pulled LOW
D4 GPIO2 pulled up OK HIGH at boot
connected to on-board LED, boot fails if pulled LOW
D5 GPIO14 OK OK SPI (SCLK)
D6 GPIO12 OK OK SPI (MISO)
D7 GPIO13 OK OK SPI (MOSI)
D8 GPIO15 pulled to GND OK SPI (CS)
Boot fails if pulled HIGH
RX GPIO3 OK RX pin HIGH at boot
TX GPIO1 TX pin OK HIGH at boot
debug output at boot, boot fails if pulled LOW
A0 ADC0 Analog Input X

Continue reading for a more detailled and in-depth analysis of the ESP8266 GPIOs and its functions.

GPIOs connected to the Flash Chip

GPIO6 to GPIO11 are usually connected to the flash chip in ESP8266 boards. So, these pins are not recommended to use.

Pins used during Boot

The ESP8266 can be prevented from booting if some pins are pulled LOW or HIGH. The following list shows the state of the following pins on BOOT:

  • GPIO16: pin is high at BOOT
  • GPIO0: boot failure if pulled LOW
  • GPIO2: pin is high on BOOT, boot failure if pulled LOW
  • GPIO15: boot failure if pulled HIGH
  • GPIO3: pin is high at BOOT
  • GPIO1: pin is high at BOOT, boot failure if pulled LOW
  • GPIO10: pin is high at BOOT
  • GPIO9: pin is high at BOOT

Pins HIGH at Boot

There are certain pins that output a 3.3V signal when the ESP8266 boots. This may be problematic if you have relays or other peripherals connected to those GPIOs. The following GPIOs output a HIGH signal on boot:

  • GPIO16
  • GPIO3
  • GPIO1
  • GPIO10
  • GPIO9

Additionally, the other GPIOs, except GPIO5 and GPIO4, can output a low-voltage signal at boot, which can be problematic if these are connected to transistors or relays. You can read this article that investigates the state and behavior of each GPIO on boot.

GPIO4 and GPIO5 are the most safe to use GPIOs if you want to operate relays.

Analog Input

The ESP8266 only supports analog reading in one GPIO. That GPIO is called ADC0 and it is usually marked on the silkscreen as A0.

The maximum input voltage of the ADC0 pin is 0 to 1V if you’re using the ESP8266 bare chip. If you’re using a development board like the ESP8266 12-E NodeMCU kit, the voltage input range is 0 to 3.3V because these boards contain an internal voltage divider.

You can learn how to use analog reading with the ESP8266 with the following guide:

On-board LED

Most of the ESP8266 development boards have a built-in LED. This LED is usually connected to GPIO2.

ESP8266 NodeMCU On-board LED

The LED works with inverted logic. Send a HIGH signal to turn it off, and a LOW signal to turn it on.

RST Pin

When the RST pin is pulled LOW, the ESP8266 resets. This is the same as pressing the on-board RESET button.

ESP8266 NodeMCU On-board Reset button

GPIO0

When GPIO0 is pulled LOW, it sets the ESP8266 into bootloader mode. This is the same as pressing the on-board FLASH/BOOT button.

ESP8266 NodeMCU GPIO 0 Flash boot button

GPIO16

GPIO16 can be used to wake up the ESP8266 from deep sleep. To wake up the ESP8266 from deep sleep, GPIO16 should be connected to the RST pin. Learn how to put the ESP8266 into deep sleep mode:

The ESP8266 doens’t have hardware I2C pins, but it can be implemented in software. So you can use any GPIOs as I2C. Usually, the following GPIOs are used as I2C pins:

  • GPIO5: SCL
  • GPIO4: SDA

The pins used as SPI in the ESP8266 are:

  • GPIO12: MISO
  • GPIO13: MOSI
  • GPIO14: SCLK
  • GPIO15: CS

PWM Pins

ESP8266 allows software PWM in all I/O pins: GPIO0 to GPIO15. PWM signals on ESP8266 have 10-bit resolution. Learn how to use ESP8266 PWM pins:

Interrupt Pins

The ESP8266 supports interrupts in any GPIO, except GPIO16.

Wrapping Up

We hope you’ve found this guide for the ESP8266 GPIOs useful. If you have some tips on how to use the ESP8266 GPIOs properly, you can write a comment below.

If you’re getting started with the ESP8266, we have some great content you might be interested in:

Читать:
Переменный резистор как делитель напряжения

Похожие публикации