text:
Run esp32 without freeRTOS in order to execute something faster
I am currently running Arduino with this configuration (using atmega328p chip):

Basically, my program wakes up every 2 seconds for 10ms each time. If during those 10ms it finds and event of interest it will perform some actions. Because it only takes 10ms to check for those events the battery lasts for over a year even though it wakes up every 2 seconds.
Anyways now I want to migrate that same project to an esp32. I am not able to do so because the esp32 takes about 40ms to run the startup function plus the 10ms it takes to check for events it will be 50ms. Waking up for 50ms every 2 seconds will drain my battery to fast! Is there a way I can run some code before the setup function? I believe the reason it takes 40ms is because it uses freeRTOS. Is there a way I can run the esp32 without freeRTOS just like the atmega328P? I don't mind losing WiFi/bluetooth functionality. Moreover, the esp32 chip is able to run at lower voltages than the atmega328p and this makes it very convenient when using batteries. For example now I would be able to use 2 AA batteries instead of 3 that I need now.

With your current Arduino setup, you're externally waking it up (applying power) every two seconds? Or are you having a sketch that delays for two seconds?

The above picture doesn't seem to be related to your question at all. It's just the basic schema how to wire up an AtMega chip.

You could run the 328p at 8 MHz and with 2 AA batteries as well. The Arduino-Core for an ESP32 is based on freeRTOS.  Your question is OT in Arduino.SE

I have a watchdog timer to wake up every 2 seconds @PMF.

If you have a 32, why not use the ULP to make those decisions without even waking up? Then your battery will likely last a lot longer than a year.

What I am looking for is "Deep Sleep Wake Stubs"
Here is an example that works that I found from the internet:
#include <Arduino.h>

#include "driver/rtc_io.h"
#include "rom/ets_sys.h"
#include "rom/rtc.h"
#include "esp_attr.h"
#include "esp_sleep.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "soc/rtc.h"
#include "soc/rtc_cntl_reg.h"
#include "soc/rtc_io_reg.h"
#include "soc/timer_group_reg.h"
#include "soc/uart_reg.h"
#include <stdio.h>
#include <string.h>

RTC_IRAM_ATTR void deepsleep_for_us(uint64_t duration_us);

#define S_TO_NS 1000000ULL
// Boot counter value, stored in RTC_SLOW_MEM
static size_t RTC_DATA_ATTR boots;
static size_t RTC_DATA_ATTR max_boots;

// Function which runs after exit from deep sleep
static void RTC_IRAM_ATTR wake_stub();
void setup(){

}
void loop(void) {
  if (rtc_get_reset_reason(0) == DEEPSLEEP_RESET) {
    printf("I'm back! Wake up from (extended) deep sleep. Should be 60s elapsed.\n");
    printf("Boot count=%d\n", boots);
    while (1) {
      ;
    }
  } else {
    printf("Not a deep sleep wake up\n");
  }

  printf("Going to deep sleep for 5x12=60s second\n");
  boots = 0;
  max_boots = 12;
  // hold high during deep sleep
  esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);

  // Set the wake stub function
  esp_set_deep_sleep_wake_stub(&wake_stub);

  esp_sleep_enable_timer_wakeup(5 * S_TO_NS);
  esp_deep_sleep_start();
}

static const char RTC_RODATA_ATTR wake_fmt_str[] = "count=%d\n";
static const char RTC_RODATA_ATTR sleep_fmt_str[] = "sleeping\n";

static void RTC_IRAM_ATTR wake_stub() {
  // Increment the Boot counter
  boots++;
  // and print the Boot counter value:
  ets_printf(wake_fmt_str, boots);

  if (boots >= max_boots) {
    // On revision 0 of ESP32, this function must be called:
    esp_default_wake_deep_sleep();
    // Return from the wake stub function to continue
    // booting the firmware.
    return;
  }

  // Print status
  ets_printf(sleep_fmt_str);
  // Wait for UART to end transmitting.
  // feed the watchdog
  REG_WRITE(TIMG_WDTFEED_REG(0), 1);
  while (REG_GET_FIELD(UART_STATUS_REG(0), UART_ST_UTX_OUT)) {

  }
  deepsleep_for_us(5 * S_TO_NS);

  // Set the pointer of the wake stub function.
  REG_WRITE(RTC_ENTRY_ADDR_REG, (uint32_t)&wake_stub);
  // Go to sleep.
  CLEAR_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_SLEEP_EN);
  SET_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_SLEEP_EN);
  // A few CPU cycles may be necessary for the sleep to start...
  while (true) {
    ;
  }
  // never reaches here.
}

// Comment out this line if you're using the internal RTC RC (150KHz) oscillator.
//#define USE_EXTERNAL_RTC_CRYSTAL
#ifdef USE_EXTERNAL_RTC_CRYSTAL
#define DEEP_SLEEP_TIME_OVERHEAD_US (650 + 100 * 240 / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ)
#else
#define DEEP_SLEEP_TIME_OVERHEAD_US (250 + 100 * 240 / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ)
#endif // USE_EXTERNAL_RTC_CRYSTAL

RTC_IRAM_ATTR void deepsleep_for_us(uint64_t duration_us) {
  // Feed watchdog
  REG_WRITE(TIMG_WDTFEED_REG(0), 1);
  // Get RTC calibration
  uint32_t period = REG_READ(RTC_SLOW_CLK_CAL_REG);
  // Calculate sleep duration in microseconds
  int64_t sleep_duration = (int64_t)duration_us - (int64_t)DEEP_SLEEP_TIME_OVERHEAD_US;
  if (sleep_duration < 0) {
    sleep_duration = 0;
  }
  // Convert microseconds to RTC clock cycles
  int64_t rtc_count_delta = (sleep_duration << RTC_CLK_CAL_FRACT) / period;
  // Feed watchdog
  REG_WRITE(TIMG_WDTFEED_REG(0), 1);
  // Get current RTC time
  SET_PERI_REG_MASK(RTC_CNTL_TIME_UPDATE_REG, RTC_CNTL_TIME_UPDATE);
  while (GET_PERI_REG_MASK(RTC_CNTL_TIME_UPDATE_REG, RTC_CNTL_TIME_VALID) == 0) {
    ets_delay_us(1);
  }
  SET_PERI_REG_MASK(RTC_CNTL_INT_CLR_REG, RTC_CNTL_TIME_VALID_INT_CLR);
  uint64_t now = READ_PERI_REG(RTC_CNTL_TIME0_REG);
  now |= ((uint64_t)READ_PERI_REG(RTC_CNTL_TIME1_REG)) << 32;
  // Set wakeup time
  uint64_t future = now + rtc_count_delta;
  WRITE_PERI_REG(RTC_CNTL_SLP_TIMER0_REG, future & UINT32_MAX);
  WRITE_PERI_REG(RTC_CNTL_SLP_TIMER1_REG, future >> 32);
  // Start RTC deepsleep timer
  REG_SET_FIELD(RTC_CNTL_WAKEUP_STATE_REG, RTC_CNTL_WAKEUP_ENA, RTC_TIMER_TRIG_EN); // Wake up on timer
  WRITE_PERI_REG(RTC_CNTL_SLP_REJECT_CONF_REG, 0);                                  // Clear sleep rejection cause
  // Go to sleep
  CLEAR_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_SLEEP_EN);
  SET_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_SLEEP_EN);
}

I will try to see how hard is to run my code that checks for events on the wake_stub that runs before anything else.


text:
Is WiFi traffic encrypted on ESP32?
I am using the ESP32 in soft access point mode. In other words I specify my wifi username and password on the ESP32 and I am able to connect to it from my phone.
So I am not using any router or internet connection. Only my phone and the esp32.
If my phone is the only device on the network created by the esp32 do I have to worry about HTTPS? People say HTTP is not secure and I also know how easy it is to see http traffic with Wireshark. But if no one else has access to the network I guess http is secure correct? If no one knows the wifi password will my http requests be encrypted? Moreover, if I connect from my computer instead than my phone via wifi to the ESP32 and send UDP packets will those be encrypted?

the quality of the encryption depends solely on the quality of the wifi password.

WiFi with WPA2 (which is what you get when you specify a password) is encrypted.
As long as your HTTP requests only go over that connection and nowhere else then yes, they are encrypted and as secure as WPA2 (which isn't unbreakable, but not easy to break).
HTTPS adds encryption for use over the internet which in general is not encrypted.

If you provide a password for you network, it will be encrypted. Thats the point of the password. When you look at the function description in the WifiAP.cpp file of the Wifi class for the ESP32, the description suggests, that it will be encrypted with WPA2, which is currently the standard in Wifi encryption. (Though that can depend on the actual library, that you are using)

do I have to worry about HTTPS?

That depends on your needs. In IT security is a scale, not a binary. Using HTTP on a WPA2 protected network can be considered safe on the one side and unsafe on the other. You need to thing about, if your project needs that additional layer of encryption through HTTPS.
For example: If you control your Smart Home with that ESP32, which may be able to open your windows or even the door, I would consider that critical. Then I would take every bit of security, that I can get, as there are ways to break into a WPA2 protected wifi network.
An example in the other direction: I'm currently building a game, which gets configured on a smartphone via the Wifi network of an ESP32. The network is encrypted to prevent casual attackers from messing with my current game run, but the project has so low security needs, that I will not bother with HTTPS. It's just a game, that will not that often being used, and the possibility of an attack on it is very low.
So it's about risk assessment (as with all security in IT).

if I connect from my computer instead than my phone via wifi to the ESP32 and send UDP packets will those be encrypted

The mentioned types of encryption (WPA2 and HTTPS) happen on two different layers of the network communication. With WPA2 your complete wifi data of that network is encrypted. So the UDP packet is also encrypted, but only in that wifi network, and it can be read by any authenticated user of the network. HTTPS works in a layer above that, so that your packet would be encrypted, even if it would move out of that Wifi network. For learning more about network layers, refer to the OSI model.

Apart from the security perspective: When you use HTTPS you also need to think about the certificate, that you are using. If you use a self-signed one, your browser will present you a warning about that, everytime you open that site. To prevent that, you either need to trust that certificate on all your devices, or you need to use an officially signed certificate (which might be a problem for a pure local project).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Using esp-wroom-32 without a development board
There are lots of examples on the internet on how to build Arduino from scratch such as IN THIS LINK. I will like to do the same but with the esp32.
I have this development board:

And I am able to program it with the Arduino framework/IDE thanks to THIS VIDEO.

Now the question
How can I flash my code and run it on a standalone ESP-WROOM-32 chip like this one:

I do not want to use voltage regulator etc as I am planning to run it from a 3.3V battery.
Before asking this question this was my research:

In this video (https://www.youtube.com/watch?v=n43rHugPbTg) Hugatry does exactly what I am looking for but he does not explain what pins he is using. Moreover what happens if I connect my 5v serial to the chip? will it burn?

I went directly to espressif website and looked for the schematics (https://www.espressif.com/sites/default/files/documentation/esp32-wroom-32d_esp32-wroom-32u_datasheet_en.pdf). It is hard to understand I just want to do something simple.

This blog (http://blogs.oregonstate.edu/copaps/resources/programming-esp32-on-custom-pcb/) explains how but the pins are different than my esp-wroom-32 chip.

Looking more on the internet/youtube everyone explains how to solder it. But I haven't found a diagram that will enable me to flash it and run my code. Also will I have to burn a bootloader like with arduino?
What I am about to try is to buy a 5V to 3.3V serial converter connecting TX with RX and RX with TX. Providing 3.3V power to the 3.3V pin and connect the last cable to ground. If I try that will it work?

It looks like you need to increase your general level of understanding of electronics. There is no "really simple" way except for buying a ready-made board. Look at the schematics of a standard ESP32 board to see what you need for support circuitry. As for your questions: 1) Yes, it will burn at 5V. 2) See my first comment. 3) See my first comment.

The development board is basically the minimum circuit plus a USB to UART interface and a 3.3V regulator. Once you remove the regulator and its capacitors, and the USB interface and the few components for that, what you are left with is the bare minimum. You can't get much simpler than those development boards.

The third link from the Oregon State University is unfortunately no longer available. It would be interesting to know what they wrote there.

This is what I was looking for. The development board is not the minimum as @Majenko and @StarCat stated on their comments. This is exactly what I need as I plan to run my project from a battery. Moreover, the development board consumes a lot more energy when in sleep mode. I will even remove the LED that shows on this diagram:

So basically use a programming board like @KenVanHoelandt stated to program the board and then wire the esp32 like in the diagram above.
I got that diagram from this link:
https://www.14core.com/wiring-and-flashing-programming-esp-32-esp32s-with-usb-ttl-uart/

you don't really need the buttons either

Is this recognized as a programmer board by Arduino software (like the IDE or some plugin)?

I am not sure what the exact minimum voltage esp32 requires, but make sure it is at least 3.6v that will be able to support it when wifi is being used . Also if you dont have a cut off circuitry for low voltage it might mess up your memory when the voltage is too low as the battery discharges.

There are programming boards available to which you can plug one of these SOCs into them. There are different boards for different types of ESP SOCs.
You can find them at popular Chinese vendors, and probably elsewhere too.
They look like this:

You could use wireless.  First, use OTA programming (eg Elegant OTA) to burn a basic OTA uploader.  Then, in principle,  you can then upload any sketch you want so long as it ALWAYS has the basic OTA sketch included within your program.

I don't think this answers the question. You still need support circuitry to auto-update, even if only updating over Wifi.

OK, so the answer to the original question, how to upload code to a bare ESP32 that's not on a Development board, is as follows:

Using an FTDI board, connect FTDI ground to ESP32 Ground, connect the FTDI TX pin to the ESP RX pin, then connect the FTDI RX pin to the ESP TX pin.
Make sure you have a decent 3.3v power supply connected to the 3.3v and ground pins of the ESP32, do not use the FTDI power pins, the FTDI board doesn't supply enough power for the WiFi of the ESP32 and it will just keep rebooting.
On the ESP32 connect the D0 pin to Ground to enable Flash mode.
Upload your code.
Disconnect D0 from ground and reboot the ESP32.

Job done.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Runtime compilation
I want to compile a sketch on Arduino Uno, while Arduino is running and not connected to anything else, and then run the compiled sketch automatically.
Is this feasible?
How?

maybe yes, google arduino forth .... here is one of the search hits https://arduino-forth.com/

While the answer is no, jsotola's suggestion might be a work-around. Forth is an interpreted language. Python would be another option.

No, not feasable, not possible.
The Arduino runs machine code and it does not have enough space or computation power for a compiler (also there is simply no version of the avr C++ compiler for the AVR platform, for obvious reasons). Also it is internally hardwired to run code from the flash memory. You cannot execute code from RAM. The Arduino is a microcontroller, not a computer. (Here I mean computer as something like: Has a microprocessor to execute code from RAM; has an OS; has huge amount of resources in relation to the average microcontroller)
Also: "not connected to anything else" --> Then how would you interact with the Arduino, writing the code, triggering compilation?
If this is about the cable connection, you can implement programming over bluetooth through the HC-05 module (google for it, there should be plenty of tutorials out there). Or go away from the Arduino and change to an ESP, so that you can do Over The Air (OTA) updates over wifi.
Or you could change to a minicomputer like the Raspberry Pi Zero, which is just a little bigger than the Arduino Nano and smaller than the Uno. (Though that hardly depends on the goal, what you are trying to achieve. Microcontrollers are sometimes better used for specific tasks in contrast to minicomputers)

No. It's not feasible.
The Uno cannot compile.  The Uno cannot run code from RAM.  The Uno is not a computer.
You might be able to find some small scripting language that could run on an Uno, but TBH the Uno is so underpowered you'd be able to do little more than blink an LED...

Of course it's a computer. It's just a computer with limited function. As a single function microcontroller it's ideal for a vast number of purposes not just blinking LEDs.

It may be a computing device, but it's not a "computer" - as in that big box on your desk with a screen and keyboard.

@Dougie and the "little more than blinking a LED" is in the context of trying to use a scripting language. You know, you really should learn to read the whole of an answer, not just pick out individual short phrases and pick at them like a complete pedantic ****.


text:
i2c scanner stuck on scanning for my 0.96in OLED screen with my Arduino Nano

My pins are connected as follows; vcc-3v3, gnd-gnd, sda-A4, scl-A5.

Measure the voltage at SCL after the scan has been stuck. If it's LOW, the problem is probably the slave. Do you have external pullups?

no I don't have any pullup resistors on hand but do you think that could be the problem

I2C requires pullups, but sometimes, slaves already have them onboard. Can you measure the resistance between Vcc-SDA and Vcc-SCL? If it's larger than 10kOhm this can be the problem.

Is it a 3.3 V only OLED? I suppose its vcc(OLED)-3v3(Nano).
Most OLEDs use 3.3V -5V where sometimes the 3.3V from the Arduino is not sufficient.If its a 3.3V only OLED could you give the make of the OLED (does it have jumpers to change I2C address). Normaly the I2C scanner should return at least with nothing found.


text:
NodeMCU V2 ESP8266 - Use 5VIN as power for heater of a MQ-9 Sensor
Right now I'm trying to understand how I could (easily) power the heater of my MQ-9 carbon monoxid and gas sensor.
Here is the datasheet: http://www.haoyuelectronics.com/Attachment/MQ-9/MQ9.pdf
It needs 5V for some gases, so I thought I could maybe power the heater via the 5VIN pin (while plugged via usb), since the other output pins have a max. voltage of only 3.3 V?
And to control the power, I could then add a relay switch, which would cut the circuit between heater and VIN (if I only want to measure the gases)?
Or am I completely wrong?
P.S: And no - I don't want to add a 5V power supply additional to the normal USB plugging on VIN :)

The VIN pin is NOT directly connected to the USB's 5V supply as it is an VIN PIN for powering the MCU from an external source other than the USB - this means the pin cannot be used as a 5V supply output.

Never ever connect VIN to a power source AND connect the USB plug. That can destroy the USB port in your computer. There is zero back-powering protection on the MCU board.

According to the datasheet the sensor (heater) needs upto 350mW which IMHO makes powering via an extra power board (which can also power the MCU) a necessity.

I see, thanks!!

actually VIN (on non lo-lin nodeMCUs) is connected through a diode, so there's a voltage drop on the usb voltage, and heavy loads will heat the diode. 350mw is only 70ma, and that should be fine for the diode, as long as the heater doesn't mind 4.3v it will work.


text:
ESP8266 to ESP8266 via home rooter
I would like to ask how to build a star topology network with several ESP8266s, pc and a home wifi router?
I would like to connect my computer (as a client) and ESP8266s (as clients) together via a wifi router and exchange data between them.
Thanks in advance,
Best,

Sure, you can do that by making all of the devices log on to the same Wifi network (provided by your router presumably) as a client. You can then exchange data between them. But what is your actual question?

@StarCat That I have done already - that was simple. Now, I cannot find any sample code how to send my data from one client to another one - that is my problem. How to send it over?

I can find many example sketches that feature two ESP8266's talking to each other. You might need to be clearer about what kind of data you want to exchange and what you're having difficulty with.

@StarCat Thank you for your help. You are right, apparently I have been missing some concepts. Now i am good to go. Thank :)

The sending / receiving of data has nothing to do with the topology. In fact, when you have one ESP8266 as an access point and another as a station that is no different to having two ESP8266's as stations communicating through an access point.  The topology is transparent to the communication of user data as that is a completely different (lower) layer of the OSI model and as such is hidden from the layers above.
You communicate in exactly the same way regardless of your topology.  That is - one end opens a socket of some form and the other end connects to (for TCP) and sends data to (for both TCP and UDP) that socket. For TCP the "server" socket can then also send data back through the same connection. For UDP there is no "server" as such, but just two peers that send data to each other and for two-way communication both ends need to be a "server" to receive data.
What you need to do is define what data you want to send and what method of sending that data will be most suitable for your system - be that simple UDP packets, or something more complex like one of the many HTTP-based API systems.

Thank you for the answer! It clarifies everything! Now I know what to do! :)


text:
WebClient Not Working On Shared Network
I'm working on a school project, and I use Arduino Uno to collect some data with sensors, and then send it to an online database. The Arduino is connected to the Internet via an Ethernet Shield and an Ethernet cable. I connected the Ethernet cable to my home router, and to the Arduino and everything works fine, the data is colledted, and sent to the database. But when I will present the project I won't have an access directly to a router, so I have to connect my laptop to WiFi and connect the Arduino to my laptop and share network. When I tested this it just did't work, I changed the Wifi network properties on my Windows 10 Laptop, to a shared network. The Arduino boots up and optains an IP adress, but when it tries to send data to the database it it doesn't work. I connected it to the home router again and everything worked so the problem is with the shared network. What is the problem? And how to solve it?

If the problem is with the shared network then you should head over to SuperUser.com - they know all about Windows and networking.  If you're getting an IP address and a gateway address and DNS address then the Arduino is fine. The problem is with Windows and we can't help you there.

can you reach the database server from the laptop?

@jsotola yes I can.


text:
Relay module not working
I used 2 relay modules. One single channel 5 volt and  another 2 channel 5 volt. On connecting 5v of arduino uno the relay modules arent getting on(led on modules not on). 2 channel once worked with 9volt dc adapter supplying to arduino board.By work i mean the led on relay blinked as per code but no clicking sound.The next time i made the exact same connection and code it didn't work..Single channel arent working with 9v adapter also.Sometimes the led on single channel module is on but no switching and most of the times its not even getting on.i used 9 volt battery to supply vcc and ground to single channel module.This turned on the led on it but no switching.i don't understand how 9 volt powered 5 volt single channel relay without burning it.
Connection :: vcc to 5 v (arduino)   gnd to gnd on arduino
Digital pin 8 to in of module.
I used the blinking led type code and tried with and without serial.begin. Arduino is working as serial monitor was giving on /off output at every 2 second.
Load::200 watt bulb from 220 volts AC...under the limit of my modules i.e. 10A 230 volts
I tried 4 different single channel modules and 1 double channel.

And the Arduino is powered how? USB power is usually way too weak to switch the relay (poly fuse is fast and inrush peaks are higher than 500mA).

Provide a link for the actual modules used. Then maybe we can have an idea of how much current each relay requires to turn on.


text:
Using a toggle switch to run part of a sketch
First, I am a beginner for this.  I just ordered my first book on coding Arduino and I'm working through some simple applications using a DS3231 (that has a temperature reading), LCD, MicroSD card module, etc.  My board is a Uno R3.  Currently, I need a sketch to run part of a program which contains a loop to collect data and have this run when a toggle switch is turned on.  So, toggle goes on and part of program runs, toggle goes off and this part exits.
The reason I need a toggle with constant on/off is the problem with G forces and vibration.  I momentary push button input will not be reliable.  Ultimately, all the components will be in a amateur high-power rocket to run a roll control program.
If you can help, I greatly appreciate your assistance.

push button switch and a toggle button switch are the same electrically ..... a toggle switch has a mechanical device that keeps the switch closed when it is activated  .......... pressing a pushbutton, or flipping a toggle switch, or twisting two wires together are all the same thing as far as the Arduino is concerned

I did find an example where a push button was held during a calibration.  As you probably know, there are many examples where a momentary switch is used, but few where a toggle is used.  I appreciate the suggestion to use the if-else statements to get this accomplished.  I'm waiting to receive some resistors and the screw-type switches I use for rocketry to test the circuit out.  I'm interested in how to prevent the potential bounce when I'm closing the screw switch.  This could happen because these switches do have some play until the switch is tightened.

i am uncertain that you understand my comment ...... electrically, there is no difference between a pushbutton and a toggle switch ...... there is no reason why you should be distinguishing between the examples on the web ....... just use a debounce library in your sketch

There are different ways to accomplish the same thing.
The condition is a flag, or a read port.
if(digitalRead(inPin))
     {
     // Your first code here.
     }
else
     {
     // second code
     }

Switch contacts will bounce when opening or closing. You may want to consider that. Usually it is stable within 10 milliseconds. Depending on what you are doing it may or may not be relevant.

You need a few things.
At the top of your sketch, before setup()
byte togglePin = x; // from 2 to 19 with an Uno. Wire to connect pin to Gnd when closed.

In setup()
 pinMode (togglePin, INPUT_PULLUP);

In loop()
if (digitalRead(togglePin) == LOW){
// switch closed, do something - or stop doing something
// maybe set a flag too, like
toggleState = 0;
}
else {
// switch, stop doing something - or start doing something
toggleState = 1;
}

The flag can be used elsewhere in your code
if (someOtherCondition && toggleState == 0){
// run a timer or motor or something
}
if (someOtherCondition && toggleState == 1){
// turn off timer or motor or something
}

Thank you!  I'm going to try this.  RE previous comments, sorry if there was any misunderstanding.  Just wanted to assure that people understood that I wasn't using a momentary switch like turning an LED on and off.  I need to turn on the system, start the program and  then wait for me to turn on the screw switch to start the sensor and control program.  This will only be done once per flight.

You could use a while (digitalRead()==Low) in setup() instead. It will sit there reading the pin until the condition becomes false.

The if-else statement works great; thanks again for the help.  To gain some experience, I also used the toggleState variable too.  I just had to add to define as an int in the beginning of the program.  Do you think the (digitalRead()==Low) would be faster or behave any differently?  Also, I'm curious, do comments (i.e. //) slow program execution, or does compiling disregard these comments?

Comments do nothing, the compiler strips them out.  "Do you think the (digitalRead()==Low) would be faster or behave any differently?" Than what?

I was thinking that although there might be several ways to accomplish the same behavior, some routines may be faster.  And, I mean perceived faster, not just machine time.  Although I'm sure that slower routines would add time if they are repeated many times.  Anyway, I just received my first book on Arduino sketching and started reading it.  Hopefully, I'll know more in about a week.  But, I'll still have questions no doubt.  This is an excellent resource!

Sure, that's true. You can do port manipulation to read & write the bits faster, but you lose whatever checking that the Arduino software does for you in the background.  For example, I might do (if (PIND && 0b00000100) == 0b00000100){  }  vs if (digitalRead(D2) == HIGH){  } to see if a pin is High,  or PORTB = PINB | 0b00000100; vs digitalWrite (D10, HIGH); to set a pin (make it high), but for a lot of things the possible1-2uS saved are not perceivable. I once had to update 45 shift registers at 20KHz rates, and needed all the speed available. I used an oscilloscope to confirm the timing.


text:
Can it time between blips, store the time between blips, subtract one time from the other and divide one time by another and display it?
I am counting rotations of a shaft and timing events that occur during that rotation.  I wish to display
the event timing as a percentage of ~1/4 of the rotation timing.  This would involve recording the rotation time, dividing that number by 3.6 and dividing that number by the value of the event timer, then displaying that percentage on an LCD array.

I don't really understand, what you are trying to do. I also don't understand, what exactly your problem is with writing the code. For normal timing the millis() and micros() function can be used, which give you the time since startup in milliseconds or microseconds respectively

your last sentence is a rough outline of the program function ... This would involve recording the rotation time, dividing that number by 3.6 and dividing that number by the value of the event timer, then displaying that percentage on an LCD array. .... add much, much more detail ... basically, turn it into a flow chart that you can convert into code

Welcome to SE/Arduino! Please take the [tour] and read "[ask]". Please also note, that these sites are neither services to get a program written nor teaching in depth. Show us some code, describe the specific problem and post a detailled question. As your question is now, the answer is simply "yes."

What you are looking for is the millis() function.
It returns the time that passed in milliseconds since the board power up.
With this function you can find the time delta, and achieve all the described calculations.
For more information


text:
Heart Pulse sensor analog value doesn't change even if sensor pressed by finger
I have recently bought a Heart Pulse Sensor. Then, to check whether the sensor is working correctly or not, I uploaded this below code:
void setup() {

 Serial.begin(9600);
}

void loop() {
 int sensorValue = analogRead(A0);

 Serial.println(sensorValue);
 delay(1);        // delay in between reads for stability
}

I know, that this code doesn't calculate the actual BPM. It sends 380-400 sensor value through
the Serial monitor, while the sensor is not being pressed by my finger. But when I press it with
my finger, the sensor value doesn't even come out of the range 380-400. But the sensor value was supposed to jump over 500 when a beat happened.
I think, that probably means my sensor is unable to detect beats. And now, my question is, why
my sensor is unable to detect beats?
After looking at some forums, I learned that this sensor can be a clone. After looking at my sensor
carefully, I found some little differences in my sensor than the sensors other people used in their
tutorials. And, the most spottable differences were:
*the colors of my sensor's pre-soldered jumper wires were different than other sensors.
*"pulsesensor.com" was written in the other sensors, but it wasn't written on my sensor
There were also some other differences. I have given three pictures of my pulse sensor below.

My final questions:-

Why my pulse sensor is unable to detect beats?
Is my pulse sensor a clone or not?
If it is a clone, can it be fixed somehow?
Do I need to buy another one?

That's all I know. Can anyone help me! Any help appreciated.
Thanks a lot!

how is it wired to the Uno?

Pulse sensor + to Arduino 3.3v (Also tried with 5v), Pulse sensor - to Arduino GND, and finally, pulse sensor Signal pin to Arduino A0 pin

Serial.print takes time to execute ... print only if sensorValue > 500

Use 5v, if you use 3.3v, your ADC Vref will be wrong.

Have you looked at the pulsesensor.com/ site for more information about your sensor? Especially note this page: https://pulsesensor.com/pages/getting-advanced  which recommends using 115200 baud "or you won't see anything". I don't know this sensor - have you tried touching either side? Tried the sample code from the site (though your code looks fine to me...).

Why my pulse sensor is unable to detect beats?
Chances are something wrong.  The only way to tell what specifically is to keep debugging.  If you don't have access to an Oscilloscope or Multimeter, this will involve checking your wiring and altering code.  To check wiring, make sure:

Minus (-) is to ground
Plus (+) s to your + voltage
S is to the A0.

Is my pulse sensor a clone or not?
It is likely.  Open-Source Hardware tends to have many clones.
If it is a clone, can it be fixed somehow?
Clones sell repeatedly if they work.  There is little point making a clone sensor that does not- if scamming was the point, one could ship empty envelopes.  If two different people make the exact same electronics, we hope that they behave very similarly regardless of who made them.
Do I need to buy another one?
Possible but unlikely.  If you can prove your sensor is defective, a seller might be willing to ship a replacement.
Try the following code to test the sensor.  My guess is that you are missing something due to Serial spamming.  Beyond that, taking a pulse may be tricky - the unskilled can easily pronounce some of the living as dead from just the wrist.  I suggest putting it to your throat to be on the safe side.

int minSV;
int maxSV;
unsigned int Frame;

void setup() {
 minSV=500;
 maxSV=0;
 Serial.begin(9600);
}

void loop() {
 int sensorValue = analogRead(A0);
 if(sensorValue > maxSV) maxSV = sensorValue;
 if(sensorValue < minSV) minSV= sensorValue;
 Frame = Frame +1;
 if(Frame > 10000) //would be 1s if frame takes 0.1 ms
 {
  //might want to reset min and max here after debug is complete and sensor is verified to work.  Until then, reset the arduino to reset min and max.
  Frame =0;
  Serial.print("Min: ");
  Serial.print(minSV);
  Serial.print("; Max: ");
  Serial.println(maxSV);
 }
 // removed: delay(1);        // delay in between reads for stability
}


text:
Trigger cheap wireless doorbell
I would like to trigger a simple wireless doorbell.
The doorbell uses 433Mhz. To read and send signals I am using the FS1000A Set (sender and receiver).
I've started by connecting the receiver to the Arduino and afterwards I uploaded the ReceiveDemo_Advanced (RCSwitch library). If I press the Doorbell Button it ouputs:
 Decimal: 1987151315 (32Bit) Binary: 01110110011100011000010111010011 Tri-State: not applicable PulseLength: 708 microseconds Protocol: 2
Raw data: 7272,444,1612,1464,588,1464,588,1464,588,440,1612,1472,568,1476,580,456,1596,452,1600,1476,580,1472,580,1468,584,444,1608,444,1608,448,1608,1464,584,1468,584,448,1608,444,1608,440,1608,448,1604,1472,584,444,1608,1468,584,1464,588,1464,592,440,1612,1464,588,444,1608,440,1612,1464,588,1464,600,

Decimal: 1987151104 (32Bit) Binary: 01110110011100011000010100000000 Tri-State: not applicable PulseLength: 727 microseconds Protocol: 2
Raw data: 7268,448,1604,1472,584,1468,580,1472,584,444,1608,1472,584,1468,588,444,1604,444,1608,1468,584,1472,588,1460,592,436,1616,440,1608,444,1608,1464,592,1464,588,440,1612,440,1612,440,1608,444,1608,1472,584,444,1608,1468,584,1468,588,1464,588,440,1612,1464,592,436,1612,440,1612,1464,592,1460,600,

Decimal: 1987151315 (32Bit) Binary: 01110110011100011000010111010011 Tri-State: not applicable PulseLength: 726 microseconds Protocol: 2
Raw data: 7272,444,1604,1472,584,1468,580,1468,588,444,1608,1468,588,1460,592,440,1612,440,1612,1464,588,1464,592,1460,592,436,1612,440,1616,436,1612,1468,584,1468,584,444,1608,444,1608,444,1608,444,1612,1464,584,444,1608,1468,584,1468,588,1460,588,444,1612,1464,592,436,1608,444,1612,1464,592,1460,600,

Now I am trying to send the signal via the FS1000A Set to the "Doorbell Receiver" but nothing happens. I tried it via the Binary send and via the Decimal send method. But the "Doorbell Receiver" remains silent.
Please help me!

go here https://test.sui.li/oszi/ and paste the raw data .... paste each raw data group separately .... you will see that the second binary: does not match

if you have two arduinos, then transmit the RF code from one arduino and receive on the other arduino .... see if the RF code matches what the doorbell button transmits


text:
LCD (I2C) issues with pull up resistor
I'm close to finish my first DYI project. But a never seen issue on the breadboard has apprear as soon as assembled.
The LCD is always / totally blank/black.
When I remove the 4.7 K ohm pull-up resistor from my 2 temperature sensors 18b20 the LCD works like a charm but temperature sensor doens't work. If a reconnect the pull-up resistor when the LCD is OK the temperature is displayed.
So it could be a wrong initialisation in my code (maybe during last cleaning)
Or a bad way to do this with my sensors and resistors.
I have theory but I'm quite a noob on electronic. What do you think I can do to resolve that ?
Thanks,
.
.
.
It's a LoLin card an not a Wemos.

#include <Arduino.h>
#include <math.h>
#include <TimeLib.h>
#include <ArduinoJson.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

#define PIN_DZero D4    // LCD PIN D0
#define PIN_DOne D3     // LCD PIN D1
#define PIN_RESET D2    // LCD PIN RST
#define PIN_DC D1       // LCD PIN DC

#define PIN_TEMP D8     // TEMP PIN
#define PIN_BtnMoins D6 // Button -
#define PIN_BtnPlus D7  // Button +
#define PIN_RELAY D0    // RELAY PIN
#define PIN_UV A0       // UV ANALOG PIN

// Temperature sensor
#include <Wire.h>
#include <DallasTemperature.h>
OneWire oneWire(PIN_TEMP); // Setup a oneWire instance to communicate with any OneWire devices
DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature.

// LCD
#include <U8g2lib.h>
#include <U8x8lib.h>
U8G2_SSD1306_128X64_NONAME_F_4W_SW_SPI u8g2(U8G2_R0, PIN_DZero, PIN_DOne, U8X8_PIN_NONE, PIN_DC, PIN_RESET);

ESP8266WiFiMulti WiFiMulti;

/*-----SENSOR VALUES-----*/
float sensorUVvolt ;
float sensorUV ;
float sensorTemp0 ;
float sensorTemp1 ;
String macAddress = "";
String txtWebService = "";
String txtTime ;
String txtSunRise;
String txtSunSet ;
int utcTime ;
int utcSunRise;
int utcSunSet ;
long timeLast = -55000;
bool isInternetConnected = 0;
bool isLampOn = 0;

time_t timeNow = now();
int minuteSunRise = 0;
int minuteSunSet = 0;

bool previousBlink = 0;
int menu = 0;
bool freezeMenu = 0;
unsigned int paramMinuteTimeNow;
unsigned int paramMinuteSunRise;
unsigned int paramMinuteSunSet;
int paramLampMode = 0; // AUTO

void setup() {
  Serial.begin(9600);

  digitalWrite(PIN_RELAY, LOW);
  pinMode(PIN_RELAY, OUTPUT);
  digitalWrite(PIN_RELAY, LOW);

  pinMode(PIN_BtnMoins, INPUT_PULLUP);
  pinMode(PIN_BtnPlus, INPUT_PULLUP);
  //pinMode(PIN_TEMP, INPUT_PULLUP);

  txtTime = "1990-01-01 00:00:00";
  setTime(txtTime.substring(11, 13).toInt(), txtTime.substring(14, 16).toInt(), txtTime.substring(17, 19).toInt(), txtTime.substring(8, 10).toInt(), txtTime.substring(5, 7).toInt(), txtTime.substring(0, 4).toInt()); // Another way to set

  Serial.setDebugOutput(true);

  Serial.println(".");
  Serial.println(".");
  Serial.println(".");

  sensors.begin();

  u8g2.begin();

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("WIFINAME", "PASS");
  macAddress = WiFi.macAddress();

}

void GetAllSensorValues() {

  sensorUVvolt = 3.3 * analogRead(PIN_UV) / 1024; ;  //*100/1024;
    sensorUV = mapfloat(sensorUVvolt, 1.06, 2.9, 0.0, 15.0);
    if (sensorUV <= 0 ) sensorUV =0;

  sensors.requestTemperatures(); // Send the command to get temperature readings
    sensorTemp0 = sensors.getTempCByIndex(0);
    sensorTemp1 = sensors.getTempCByIndex(1);

    if (sensorTemp0 <= 0 ) sensorTemp0 =0;
    if (sensorTemp1 <= 0 ) sensorTemp1 =0;

}

void ActuorAll() {
  if (paramLampMode == 3) {
    digitalWrite(PIN_RELAY, HIGH);
  } else if (paramLampMode == 2) {
    digitalWrite(PIN_RELAY, LOW);
  } else {
    if ( minuteSunSet != minuteSunRise && minuteSunSet != 0 && minuteSunSet > minuteSunRise && year(timeNow) != 1982 && hour(timeNow) + minute(timeNow) !=0 ) {
      if (  minuteSunRise + paramMinuteSunRise <= 60 * hour(timeNow) + minute(timeNow) + paramMinuteTimeNow && 60 * hour(timeNow) + minute(timeNow) + paramMinuteTimeNow <= minuteSunSet + paramMinuteSunSet  ) {
        isLampOn = 1;
        digitalWrite(PIN_RELAY, HIGH);
      } else {
        isLampOn = 0;
        digitalWrite(PIN_RELAY, LOW);
      }
    }
  }
}

//The Arduino Map function but for floats
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

void loop() {

  boolean btnPlus = !digitalRead(PIN_BtnPlus);
  boolean btnMoins = !digitalRead(PIN_BtnMoins);

  if ( !freezeMenu && btnMoins==HIGH && btnPlus==HIGH ) {
      if (menu >= 6) {
        menu = 0;
        freezeMenu = 1;
      } else {
        menu++;
        freezeMenu = 1;
      }
  }

  if ( btnMoins==LOW || btnPlus==LOW) {
    freezeMenu = 0;
  }

  if (menu != 0) {
    if (previousBlink) {
      previousBlink = 0;
    } else {
      previousBlink = 1;
    }
    if (menu == 2 && btnMoins==HIGH) { paramMinuteTimeNow=paramMinuteTimeNow-10; }
    if (menu == 2 && btnPlus==HIGH) { paramMinuteTimeNow=paramMinuteTimeNow+10; }
    if (menu == 3 && btnMoins==HIGH) { paramLampMode--; }
    if (menu == 3 && btnPlus==HIGH) { paramLampMode++; }
    if (menu == 5 && btnMoins==HIGH) { paramMinuteSunRise=paramMinuteSunRise-10; }
    if (menu == 5 && btnPlus==HIGH) { paramMinuteSunRise=paramMinuteSunRise+10; }
    if (menu == 6 && btnMoins==HIGH) { paramMinuteSunSet=paramMinuteSunSet-10; }
    if (menu == 6 && btnPlus==HIGH) { paramMinuteSunSet=paramMinuteSunSet+10; }
  } else {
    previousBlink = 0;
  }

  if (paramLampMode>3) {paramLampMode=0;}
  if (paramLampMode<0) {paramLampMode=3;}

  GetAllSensorValues();

  if ( millis()-timeLast >= 60000 ) {

    WebServiceCall("UV", String(sensorUV), "Temp0", String(sensorTemp0), "Temp1", String(sensorTemp1) );

    timeLast = millis();
  }

  ActuorAll();

  DisplayLCD();

  delay(500);
}

void DisplayLCD(){
  String line1 = "";
  String line2 = "";
  String line3 = "";

  float txtTemp0 = round(sensorTemp0*10);
  txtTemp0 = txtTemp0/10;
  float txtTemp1 = round(sensorTemp1*10);
  txtTemp1 = txtTemp1 /10;

  /*Serial.print(" | minute timeNow:");
  Serial.print(minute(timeNow));
  Serial.print(" | A0:");
  Serial.print(sensorUVvolt);
  Serial.print("V ");
  Serial.print(sensorUV);
  Serial.print(" mW/cm² | temp0:");
  Serial.print(sensorTemp0);
  Serial.print("°C | temp1 ");
  Serial.print(sensorTemp1);
  Serial.println("°C");
  */
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_helvB12_tf);

  /* ------- LINE 1 ------- */
  if (menu == 1 && previousBlink) line1 = macAddress;
  if (menu != 1) line1 = String(txtTemp0).substring(0, 4) + " | " + String(txtTemp1).substring(0, 4) + " | " + String(sensorUV);

  /* ------- LINE 2 ------- */

  String dsplTime = MinuteToTime(60*hour(timeNow)+minute(timeNow)+paramMinuteTimeNow);
  if (menu == 2 && previousBlink) dsplTime = "__:__";

  String txtLamp = GetLampMode();
  if (menu == 3 && previousBlink) txtLamp = "____";

  String txtInternet = "X";
  if (isInternetConnected) txtInternet = "@";
  if (menu == 4 && previousBlink) txtInternet  = "_";

    line2 = dsplTime+ "  " +txtLamp+ "  " +txtInternet;

  /* ------- LINE 3 ------- */
  String dsplSunRise = MinuteToTime(minuteSunRise+paramMinuteSunRise);
  if (menu == 5 && previousBlink) dsplSunRise  = "__:__";

  String dsplSunSet = MinuteToTime(minuteSunSet+paramMinuteSunSet);
  if (menu == 6 && previousBlink) dsplSunSet  = "__:__";

    line3 = "  " +dsplSunRise+ " > " +dsplSunSet;

  u8g2.drawStr(0,12, line1.c_str() );
  u8g2.drawStr(0,35, line2.c_str() );
  u8g2.drawStr(0,55, line3.c_str() );

  u8g2.sendBuffer();

}
String GetLampMode(){
  if (paramLampMode == 3) {return "ON";}
  else if (paramLampMode == 2) {return "OFF";}
  else {return "AUTO";}

}

String MinuteToTime(int min) {
  int resutHour = min/60;
  int resutMin = min - resutHour*60;
  String resultTime = String(resutHour);

  if (resutHour < 10) {
    resultTime = "0" + String(resutHour);
  }
  if (resutMin < 10 ) {
    resultTime = resultTime + ":0" + String(resutMin);
  } else {
    resultTime = resultTime + ":" + String(resutMin);
  }

  return resultTime;

}

int WebServiceCall(String sensor1Id , String sensor1Value, String sensor2Id , String sensor2Value, String sensor3Id , String sensor3Value) {
  String url = "http://MYWEBSERVICE/save?mac=" + macAddress + "&sensor1id=" + sensor1Id + "&sensor1value=" + sensor1Value + "&sensor1id=" + sensor2Id + "&sensor2value=" + sensor2Value + "&sensor3id=" + sensor3Id + "&sensor3value=" + sensor3Value;
  Serial.println("[HTTP] url is:" + url);
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {
    isInternetConnected = 1;
    WiFiClient client;

    HTTPClient http;

    Serial.print("[HTTP] begin...\n");
    if (http.begin(client, url)) {  // HTTP

      Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      int httpCode = http.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = http.getString();
          Serial.print("JSON:" + payload);
          txtWebService= payload;
          StaticJsonDocument<200> doc;
          DeserializationError error = deserializeJson(doc, payload);

          if (error) {
            Serial.print("[HTTP] JSON error ");
            Serial.println(error.c_str());
            //return;
          }

          JsonObject root = doc.as<JsonObject>();
          txtTime = root["time"].as<String>();
          txtSunRise = root["sunRise"].as<String>();
          txtSunSet = root["sunSet"].as<String>();
          minuteSunRise = 60 * txtSunRise.substring(11, 13).toInt() + txtSunRise.substring(14, 16).toInt();
          minuteSunSet = 60 * txtSunSet.substring(11, 13).toInt() + txtSunSet.substring(14, 16).toInt();

          setTime(txtTime.substring(11, 13).toInt(), txtTime.substring(14, 16).toInt(), txtTime.substring(17, 19).toInt(), txtTime.substring(8, 10).toInt(), txtTime.substring(5, 7).toInt(), txtTime.substring(0, 4).toInt()); // Another way to set
          //Serial.printf("[TIME] TimeNow %s\n", txtTime);
          //Serial.printf("[TIME] hour %d\n", txtTime.substring(11, 13).toInt());
          //Serial.printf("[TIME] minute %d\n", txtTime.substring(14, 16).toInt());

        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end();
    } else {
      Serial.printf("[HTTP} Unable to connect\n");
      //isInternetConnected = 0;
    }
  } else {
    isInternetConnected = 0;
  }

}

tip: previousBlink is boolean, so use true/false for the values ............................. also, you can reduce if (previousBlink) { previousBlink = 0; } else { previousBlink = 1; } to just previousBlink = !previousBlink;

what happens if you remove one of the sensors?

Thanks @jsotola. With only the relay & 1 sensor it do the same. Blank if connected at launching - LCD OK if the pull-up resistor is not connected at launching

Youtube video here: https://www.youtube.com/watch?v=hwbx0FxLWJ4

start at the beginning ..... leave everything connected ..... run LCD demo sketch

Thnaks @jsotola for your support I found the error.

... by doing it again and with observation on a few GPIO maps (lolin 32 pro, Wemos mini, ...). The GPIO pins cannot be used as you want and you have dedicated I2C and SPI pins. My conclusion is (not sure of that): the temperature sensors cannot use the SPI pins when you have an I2C. I switched sensor pin on my test breadboard from D8 to D4 (youtube link) and it's OK. I will not do a deep study on my project already soldered but will try a few other pins and I hope it will work .


text:
Configuring I2S with ESP32 and WM8978
I'm trying to get I2S audio working with an ESP32 and WM8978 codec, using the TTGO TAudio dev board. Currently, I'm trying to implement the I2S example code provided by Espressif (link below) using the Arduino ESP32 framework.
I'm using a library for sending I2C commands to the codec, and that works fine - I'm able to configure the analog signal path in the codec and change gain levels, but getting the DAC/ADC to work has been more of a challenge.
The code below compiles and seems to run - but on boot the ESP32 I2S function i2s_driver_install returns an error "I2S: clkmdiv is too large".  Looking at the driver on github it seems like this is because either the bits_per_sample or samplerate are too small, but they are currently set at the max.
https://github.com/espressif/esp-idf/blob/master/components/driver/i2s.c
Also, I note that i2s_write() returns a 'not declared in this scope' error, which makes me think that the esp32 arduino framework is out of date? But there are examples using i2s_write_bytes() which seem to be working for people.
I don't see what I am doing wrong, based on my reference examples below. Any suggestions of things to try?
Arduino 1.8.7
ESP hardware definitions by espressif, v1.0.0
code below based on the espressif sample i2s code:
https://github.com/espressif/esp-idf/tree/97eecfa1b2b95a6f77e8e9ffcb676ded687ab68f/examples/peripherals/i2s
And the TTGO TAudio demo sketch:
https://github.com/LilyGO/TTGO-TAudio
And the DFRobot NuvotonDuino:
https://github.com/DFRobot/NuvotonDuino
//WM8978 I2S dependencies
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/i2s.h"
#include "esp_system.h"

//WM8978 I2C dependencies
#include <types.h>
#include <WM8978.h> //borrowed from the NuvotonDuino example
#include <Wire.h>

const byte I2S_SERIAL_DEBUG = 1;
const byte SAMPLE_RATE  = 48000;
const byte I2S_NUM = 0;

//16-bit 128-sample sine wavetable
int sineT[128]= {0, 1620, 3237, 4845, 6442, 8023, 9584, 11122,
12633, 14113, 15558, 16965, 18331, 19651, 20924, 22146,
23313, 24423, 25474, 26462, 27385, 28241, 29029, 29745,
30388, 30957, 31451, 31867, 32205, 32465, 32645, 32745,
32765, 32705, 32565, 32345, 32046, 31668, 31213, 30682,
30076, 29396, 28644, 27822, 26931, 25975, 24956, 23875,
22736, 21541, 20294, 18997, 17653, 16266, 14840, 13377,
11881, 10356, 8806, 7234, 5645, 4042, 2429, 810, -810,
-2429, -4042, -5646, -7235, -8807, -10357, -11881, -13377,
-14840, -16267, -17653, -18997, -20294, -21542, -22736,
-23875, -24956, -25976, -26932, -27822, -28644, -29396,
-30076, -30682, -31214, -31668, -32046, -32345, -32565, -32705,
-32765, -32745, -32645, -32465, -32205, -31867, -31450, -30957,
-30388, -29745, -29028, -28241, -27385, -26461, -25473, -24423,
-23313, -22145, -20924, -19651, -18330, -16965, -15557, -14112,
-12632, -11122, -9584, -8022, -6441, -4845, -3236, -1620};

//i2s configuration
int i2s_num = 0; // i2s port number
i2s_config_t i2s_config = {
     .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_RX),
     .sample_rate = SAMPLE_RATE,
     .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
     .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
     .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
     .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // high interrupt priority
     .dma_buf_count = 3,
     .dma_buf_len = 1024,
     .use_apll = false
};

//updated I2S pins for tAudio
i2s_pin_config_t pin_config = {
    .bck_io_num = 33, //this is BCK pin
    .ws_io_num = 25, // this is LRCK pin
    .data_out_num = 26, // this is DATA output pin
    .data_in_num = 27   //
};

uint32_t missedByteCounter = 0; //debug variable

 // I2S FUNCTIONS

//this function just streams samples from the wavetable to the codec
static uint16_t setup_triangle_sine_waves(int bits)
{
  static byte index = 0;
   uint16_t samples_data = sineT[index/2] + 32765;
   //write to codec below
   int bytes_written = i2s_write_bytes((i2s_port_t)I2S_NUM, (const char *)&samples_data, 2, 100);

  //i2s_write((i2s_port_t)I2S_NUM, (const char *)&samples_data, 2, &bytes_written, 100);

  if (bytes_written > 0)  index++;
  else missedByteCounter++;
  index+=11;
 // missedByteCounter+=bytes_written;
   return samples_data;
}

void i2sSetup()
{
    i2s_driver_install((i2s_port_t)I2S_NUM, &i2s_config, 0, NULL);
    i2s_set_pin((i2s_port_t)I2S_NUM, &pin_config);
}

void i2sLoop(){
  static uint32_t timer = 0;
  int interval = 1000;
  uint16_t val = setup_triangle_sine_waves(0);

  if (I2S_SERIAL_DEBUG) {
    if( millis() - timer > interval){
      timer = millis();
      Serial.print(" i2s buffer full cycles: ");
      Serial.println( missedByteCounter );
      Serial.println(val);
      missedByteCounter = 0;
    }
  }
}

//WM8978 I2C SETUP
//Uses the WM8978 I2C library distributed with the NuovoDuino
  void wm8978Setup() {
  Wire.begin(19,18); //(SDA,SCL,Frequency)
  WM8978_Init();

  unsigned char dacen = 1;
  unsigned char adcen = 1;
  unsigned char micen = 1;
  unsigned char lineinen = 0;
  unsigned char auxen = 0;
  unsigned char bpsen = 1;

  unsigned char initVal = WM8978_Init();

  WM8978_ADDA_Cfg(dacen, adcen);
  WM8978_Input_Cfg(micen, lineinen, auxen);
  WM8978_Output_Cfg(dacen, bpsen);
  WM8978_MIC_Gain(50);
  WM8978_SPKvol_Set(30);
  WM8978_HPvol_Set(50,50);
  //WM8978_ALC_Set(1,7,3);
  WM8978_Write_Reg(3,0xFF);
  WM8978_I2S_Cfg(2,0); //format, bit-length
  WM8978_Write_Reg(7,4<<1);//sets sample rate to 12kHz
  WM8978_Write_Reg(11,0xFF);
  WM8978_Write_Reg(12,0xFF|1<<8);
} //wm8978Setup

// SETUP AND LOOP

void setup() {
  Serial.begin(115200);
  //wm8978Setup();
  i2sSetup();
}

void loop(){
  i2sLoop();
}


text:
USB Communication between Arduino Nano and UHF Reader module
I am working on a project that requires a UHF reader development kit that can communicate using either RS232 or by USB.  Via USB and a Serial terminal, I have been able to send commands to the reader as well as analyze its response.
My goal is to send these same commands to the reader, but through an Arduino Nano.  My first instinct was to use the RS232, converting the signal via a MAX232.  However, this is for a school project, and my advisor preferred I try to work with USB.  I am familiar with UART communication, and I've been under the assumption that USB operates using UART.
I had purchased a USB converter that gives me access to the pins, but it had two additional pins than I was not expecting: CTS and DTR.  I attempted to communicate despite these pins (just leaving them open, and connecting Rx, Tx, Vcc and GND as I normally would).  When plugged into the UHF reader, the device did power on (as it draws power from the USB connection), however, it did not receive the output signal from the Arduino Nano.
I know that my baud rate and other settings are correct, because, as I have said, communicating via USB and a Serial terminal gives me no problems.  My initial thought is that I need to properly connect the CTS and DTR pins, but immediately I could not find a good reference on how to do this, and I am not entirely convinced this is the issue.  My other thought was that perhaps I am writing out my HEX values wrong from the Arduino, using a line similar to the following, where "UHF_Reader" is defined by SoftwareSerial:
UHF_Reader.write(0xAA);

However, it appears to me from research that this is indeed the correct way to output HEX values via serial.
My final attempt to resolve this was to connect the micro-USB from the Nano to the USB of the reader, and then use Software Serial in conjunction with the USB converter to analyze the output on a Serial terminal, while powering the Nano via a 5V power supply.  However, since the reader draws power from the USB port, it did not even turn on when I attempted this (I am assuming that the Vcc can only be supplied from the USB end?).  Regardless, this attempt proved useless as well.
If anyone can offer any advice, or point me towards any references for something similar, I would much appreciate it!  I have spent a while on this, and I just can't figure out what the problem is.
For reference, the reader I am using is found here: UHF Reader
And the USB converter I am using is here: USB Converter

I've been under the assumption that USB operates using UART.

No. You have it backwards.  Devices can emulate a UART (known as CDC/ACM) over a USB connection as one of the many possible device profiles, but it is about as far from being a UART as an F1 car is from a Penny Farthing.
USB operates on a strict Master / Slave principle. That is, it has a single master device, called the Host, which coordinates all the devices on the bus and makes requests to them.  Everything you plug into a USB system is a Device and requires a Host to tell it what to do.
Neither the Nano, nor this adaptor you bought, are Hosts. They are just Devices. And Devices cannot talk to Devices. Only Hosts can talk to Devices.
Which means you need a Host in there somewhere. If you want it controlled by Arduino then you need a USB Host Shield (or something similar) which normally communicates over SPI.
If the device you are trying to talk to uses the CDC/ACM profile then you can use the USB Host Shield with it. If it uses a proprietary profile, like the CH340G or FT232, then getting it to work with the USB Host Shield will be much harder (maybe even impossible) unless you are intimate with the underlying protocol used.


text:
OV2640 with 18 Pins - No XLCK System Clock
I'm trying to connect an OV2640 camera module to a microcontroller.
This camera module has only 18 pins as seen in this schema:
https://i.sstatic.net/wVBwV.jpg
Here an image of the module:
https://i.sstatic.net/tUVg0.jpg
These pins are on the module:

3.3V
GND
VSYNC
SCL
SDA
HREFF
D0 - D7
DCLK
PWDN
NC

Maybe I could set XLCK and PLCK via the DCLK pin but I don't know how.
I am pretty new to camera modules and searched the net a lot of times. Most examples are for the OV7670. This module has also 18 Pins but all are used quiet contrary to the OV2640.
Could anybody help me connect and get a signal?

http://www.arducam.com/camera-modules/2mp-ov2640/

Can you be specific about which microcontroller you want to use?

@MichaelT i tried it with an ESP8266, ESP32 and RaspberryPi 3 Model B+. I used this example: https://www.instructables.com/id/OV7670-Without-FIFO-Very-Simple-Framecapture-With-/ and https://www.instructables.com/id/How-to-Connect-OV7670-to-Arduino-Due/ http://embeddedprogrammer.blogspot.com/2012/07/hacking-ov7670-camera-module-sccb-cheat.html These examples are for ov7670 but i tried to adapt them.

In this specific OV2640 module, it's supposed to have a 12MHz oscillator in the board connected to XLCK pin (you can all time adjust the PLL trough SCCB interface as usual). Remove the plastic lens and see near the CMOS.
Regards

Thanks for your answer. Yes there is a oscillator right to the CMOS, i am a nooby when it comes to cameras with microcontroller. In all examples the XCLK is connected to a pin, i read that the XCLK could be "simulated" but i don't know how.

I also bought one of these to use with an esp32, not realizing that there was an on-board oscillator and no system clock pin. I just left the pin on the esp that's supposed to connect to XCLK hanging, and set the frequency to 12000000 in my code. It seems to work alright!


text:
Arduino UNO bricked?
How can I figure out, if an Arduino UNO is defect?
Have on, which I can't upload sketches to.
It's not working on Windows, even on Linux.
Everytime the following warning appears:
avrdude: stk500_cmd(): programmer is out of sync
avrdude: stk500_loadaddr(): (a) protocol error, expect=0x14, resp=0x18

avrdude: stk500_paged_load(): (a) protocol error, expect=0x14, resp=0x98
avrdude: stk500_cmd(): programmer is out of sync
avr_read(): error reading address 0x0000
    read operation not supported for memory "flash"
avrdude: failed to read all of flash memory, rc=-2
avrdude: stk500_disable(): protocol error, expect=0x14, resp=0xe6

I don't have a clue of how to fix it.
The IDE's version is 1.8.8
Is the Arduino Bricked? Restarting both systems, the Arduino IDE and even Arduino (Reset) didn't help.
~ JackyTech

Had it ever worked before now?

Is it genuine or a Chinese clone?

It had worked over three years.
It's the original (dark blue) Arduino UNO.

When the serial port is detected by the computer but uploading is not possible, then you can try to burn the bootloader.

What did u selected in board menu?

I've burnt the bootloader on it and it works now. But now I've the same problem with an unrecognized Micro... Thanks for the advice mentioning the bootloader.


text:
Prevent function inlining
I'm trying to shrink the compiled code size, and I have noticed that the compiler inlines functions a lot, even the ones I have not marked "inline", but I can't manage to turn that off.
It looks like the compiler uses the -Os flag by default (optimize for low program size), because when I add it, the resulting program size is the same.
I tried adding "__attribute__((noinline))" to the functions but it makes no difference. Any idea how to prevent function inlining?
I'm using Visualmicro on Visual Studio Community 2017. Arduino 1.8.8. Arduino Uno board.

Did you try  __declspec(noinline)? https://docs.microsoft.com/pl-pl/cpp/cpp/noinline?view=vs-2017

@FilipFranik That is only for Microsoft's compiler. Arduino uses GCC, which doesn't use Microsoft's custom cr@p.

@BjörnMorén How have you determined that it's inlining the functions?

See over on SO https://stackoverflow.com/questions/7244363/how-to-prevent-gcc-to-inline

Do you assume that not inlining a function shrinks the compiled code size? That might not be correct. The gcc compiler follows the -Os flag. Forcing to make a function call might increase the code size. You could show us your code, and we can shrink it. For an arduino uno, you could also move data from code to eeprom.

Thanks for the replies!
I created a class with a function with no arguments containing dummy code. Then I tried calling this function from the main() section, first one time and noted the size, then two times in a row and watched how it increased the compiled code size by 60 bytes. Then I applied the noinline attribute, and it made no difference. However, now when I do the same thing, the compiler behaves like it should. So my apologies for wasting your time with this.

But there is definitely something fishy going on with this compiler. Another test I did was to make all private variables public. Compiled code size shrunk, which is to be expected, since some optimizations could be made. Then I made them private again. Compiled size stayed at the shrunk size. It is as if the compiler needs a few tries to really optimize the code.

It is also weird how using the -Os flag still inlines functions even though they are not marked "inline". -Os means optimize for size. I can clearly tell it does this, because when I apply the noinline attribute to the functions, it makes my compiled code size smaller. I wish there was a compiler flag that meant "no inlining, except when the inline keyword is used".

What you call weird is in fact the extremely optimized code that the gcc compiler makes. The gcc can (almost) do whatever it wants. The "lto" optimization globally optimizes things, and the result is hard to predict. Sometimes variables are only temporary in registers and never occupy a memory location. There are options to control inlining: http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html You can add them to a sketch with the #pragma. I took one of my larger sketches and tried a few inline options, but the code size never got smaller. Can you give a small sketch that becomes smaller?

As I wrote in the comments, I can't recreate this problem again. So I apologize for wasting everyone's time. But I still find it weird how the -Os flag works. I assumed it meant smallest possible size. But I now think it means "fairly small, but also make it run fast". Look at the code below, and how using the noinline attribute makes the code smaller. I added the -Os compiler flag to be sure, but I think it is already on by default.
class InlineClass
{
public:
    void __attribute__((noinline)) testFunc(int arg1)       // 570 bytes
    //void testFunc(int arg1)               // 602 bytes
    //inline void testFunc(int arg1)        // 602 bytes
    {
        _var1 = arg1 + 1;
        _var2 = arg1 + 2;
        _var3 = arg1 + 3;
        _var4 = arg1 + 4;
        _var5 = arg1 + 5;
    }

private:
    volatile int _var1 = 0;
    volatile int _var2 = 0;
    volatile int _var3 = 0;
    volatile int _var4 = 0;
    volatile int _var5 = 0;
};

void setup()
{
    InlineClass ic;
    ic.testFunc(1);
    ic.testFunc(2);
    ic.testFunc(3);
    ic.testFunc(4);
    ic.testFunc(5);
}

Did you check all the inline options in that link? https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html The -Os turns on some them and the compiler uses heuristic to decide what to do. For example with the -finline-small-functions option. I get the 570 and 602 size for an arduino uno, that means you have found a miscalculation of the heuristic. That is an impressive achievement! I tried to turn the inline options off to be able to control it with a compiler option, but that did not work. When testFunc is made larger, the sizes are the same.

@Jot Thanks for the reply. I played around with the compiler flags relating to inline functions in the document you linked, but could not get it to work well. This is all a mystery to me, because when I selectively apply "attribute((noinline))" to certain functions in my sketch, I can shrink it by 578 bytes, from 32492 to 31914 bytes, which is a lot when you are close to the limit. Could it be that the compiler isn't properly tailored for the AVR processor? I assume that making it work for a certain instruction set requires a lot of tuning, that might have been done poorly?

@Jot I also posted this question to the people at Arduino.cc, lets see what they have to say. Maybe it is a GCC issue, or maybe an Arduino specific issue. https://forum.arduino.cc/index.php?topic=607719.0

In my "local.h" file - macros & other definitions I tend to use a lot, just such as one you're asking about - I keep this one:
// Don't compile this function inline
//   '__NOINLINE void foo(void){ ... }'
#ifdef __GNUC__
#define __NOINLINE  __attribute__ ((noinline))
#else
#define NOINLINE error 'NOINLINE' not defined for this compiler
#endif

which both gives me a fairly simple way to invoke no-inlining, and a warning if I try to use it with a compiler for which I haven't defined its use. You don't really need the macro; you could use the gcc-dependent syntax - I just favor a simpler (and portable) symbol that could be defined for any compiler's no-inline syntax.

Great idea. I was thinking of doing the same to avoid the ugly noinline attribute string.

Would the drive-by down-voter care edify the rest of us with his/her reasons why this answer fails to address "Any idea how to prevent function inlining?"


text:
Reading NFC card (PN532) with Arduino Uno
I am trying to detect a RFID card using the NFC-PN532 module and Adafruit_PN532 library.
Initialization code:-
#include <Adafruit_PN532.h>
#include <Wire.h>

#define SCK  (13)
#define MISO (12)
#define MOSI (11)
#define SS   (10)
Adafruit_PN532 nfc(SCK, MISO, MOSI, SS);

void setup()
{
  Serial.begin(9600);
  Serial.println("Initializing please wait.......");
  delay(3000);
  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata)
  {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }

  Serial.print("Device Found PN5 Chip");
  Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware version > ");
  Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.println((versiondata>>8) & 0xFF, DEC);
  nfc.SAMConfig(); //Set to read RFID tags
  Serial.println("Waiting for RFID Card ...");
}

Main loop:-
void loop()
{
  uint8_t success = 0;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success)
  {
      Serial.println("Card Detected!");
  }
  else
  {
      Serial.println("Card Not Detected or Removed!");
  }
}

Whenever i place a valid card on the PN532, Card Detected! is printed on the serial monitor.
However, when i remove the card, Card Not Detected or Removed! does not get printed.
How can i make the program  to loop in such a way that it can detect when the card is present/removed?

once you fix this (not sure why it is behaving this way)  you wont detect when a card is removed ... you'll detect when a card is not present ... there's a difference :p

@JaromandaX yes, you are right. But then how do i modify the code to detect "card inserted"and "card removed"?

you'd achieve that with code that only prints card removed if this is the first loop after card was present, ... try adding nfc.setPassiveActivationRetries(0x10); to your setup just before nfc.SAMConfig(); - this should stop the code waiting for a card :p

The default behaviour of readPassiveTargetID is to wait "forever" for a card - which is why your code only sees when there is a card present
So, in setup() add nfc.setPassiveActivationRetries(0x10); as follows - comments came from my own code, but I'm sure they were originally in some example or other :p
// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
nfc.setPassiveActivationRetries(0x10);

// configure board to read RFID tags
nfc.SAMConfig();

As for "detecting" removal
void loop()
{
  static bool wasSuccess = false;
  uint8_t success = 0;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success)
  {
      wasSuccess = true;
      Serial.println("Card Detected!");
  }
  else if (wasSuccess)
  {
      wasSuccess = false;
      Serial.println("Card Removed!");
  }
  else
  {
      // you may want to remove this, it will flood the output :p
      Serial.println("Card Not Detected!");
  }
}

@Patrick - including the detection of remove? I ask, because I've been meaning to write some code for my PN532 :p


text:
Serial Port not recognized by Arduino IDE
I’m attempting to connect with a Adafruit Huzzah Feather ESP8266 board. I’m running a 2018 mbp with Mojave. I loaded the Silabs driver (CP210) to connect with the onboard UART on Huzzah board. I got the Arduino IDE 1.8.8 installed and loaded the 2.5.0 ESP8266 library (I also tried library 2.4.2).
The serial port appears  in the IDE (SLAB_USBtoUART). It also appears when I run the /dev/tty.* command and in About this Mac. From the IDE when I try to Get Board Info. Nothing. I get the message “Native serial port, can’t obtain info”. Everything seems good, except nothing from the IDE. I pulled up CoolTerm, set it the port and hit the reset on the Huzzah. I see data after hitting reset.
I run the Huzzah board from a powered USB hub through one of the USB-C ports. Tried different combinations, no luck.
I have a very old WIn7 machine, loaded everything like on my mbp, there I can get board info. I would run the IDE on it, except the machine is sooo slow. I would very much like to get it working on my mac. It seems so close, but no cigar.

did you try to upload to the board? the "Get Board Info" works only with some Arduinos

Yes, on the win7 machine I was able to upload to the board.

and on Mac? do you have same error message? turn on verbose mode in Preferences.

I solved the problem. Thanks to @Juraj for suggesting turning on verbose mode. Thanks. Not getting Board Info from the IDE, I figured the port wasn't working. Ignoring the Board Info problem, I went to compile and upload a simple program. Without verbose mode on, it looked like it wasn't connecting up. In reality it was a problem with the esp8266 libraries. After fixing that issue all is good.

Download usb port driver from the link below
http://www.wch-ic.com/downloads/CH341SER_EXE.html

Adafruit Huzzah Feather ESP826 has CP2104 as USB chip, not CH340


text:
How to avoid calling multiple times Wire.begin() in libraries?
it's all in the title ; I'm developping a library and use *TwoWire pointers in this library ; but I am using an external library that calls Wire.begin(). I've seen something about TWCR register in arduino but I don't know what it is exaclty.
Thanks in advance :)

What you are interested in is this bit of the Wire library:
TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);

The important bit is the TWEN bit - TwoWire ENable.
If that bit is set in the TWCR register than Wire.begin() has been called already and you don't need to call it again:
if (TWCR & _BV(TWEN) == 0) {
    Wire.begin();
}

However, it really doesn't matter if you call it multiple times.

other thing is if you do setFrequency(400000L) and then some other library calls Wire.begin()

Just to precise, it was to avoid such problems https://github.com/esp8266/Arduino/issues/2607 I don't know if it concerns me but I'll see with the prototype

@Storca Note that that's for a completely different architecture, so the "fix" I detail above has no relevance to it. The proper place for it to be fixed would be in the Wire library. We do it properly chipKIT: https://github.com/chipKIT32/chipKIT-core/blob/master/pic32/libraries/Wire/Wire.cpp#L122 - only allow begin to run the first time it's called.


text:
Background "static" on side of TFT screen?
I recently bought an XC4629 128x128 TFT screen and noticed that failing to initialise a background for the screen produced this RBG static.
A red line drawn on the screen without a background:

The problem, however, is that when I did initialise a background, the "static" remained on 3-4 pixels down the side of the screen:

Here is the code I used:
 #include <TFT.h>
 #include <SPI.h>

 #define CS   10
 #define DC   9
 #define RESET  8

 TFT myScreen = TFT(CS, DC, RESET);

 void setup(){
   myScreen.begin();
   myScreen.background(0,0,0);
 }

 void loop(){
   myScreen.stroke(255, 0, 0);
   myScreen.line(0, 128, 128, 10);
 }

Is this a problem with the screen itself? I have searched around the internet and have found no similar issues. Due to the behaviour it seems like an code issue but I have made it as simple as possible and experimented and only found it goes away if I remove the signal and just have the screen on backlight only. I also double checked that the wiring was all in the correct slots (both referencing the code and the datasheet for the screen).
Many thanks in advance.

It will be a problem with the library you are using. Not all screens that use the same CoG are wired in quite the same way. Often a CoG that supports a larger number of columns is used with a screen that doesn't have that many columns (132 in this case), and the actual screen is placed at an offset within the available columns, and it's up to the manufacturer of the screen where that offset is.
So the library has to initialize the CoG with where the screen actually is within its physical column range, and your screen is different to what the library is expecting.  Looking at the TFT library bundled with the IDE most screen configurations appear to impose a couple of pixels offset in the columns, which you don't want.
I would suggest investigating other TFT libraries, such as UTFT, which may give better control over screen parameters.


text:
LCD display not working properly + inconsistent results
I have soldered the pins to my 20x4 LCD display. The soldering is not very good, but this is the best i can do. I have measured the resistance between each of the pins of the LCD with my multimeter to check if the pins are isolated. And they are! So the bad soldering is not the problem...
Last night, the display showed weird results and non-existent characters, all over the 20x4 display.
This morning, it showed only full blocks. But now it is showing only 2 of the 4 rows.
I think this is weird because i did not touch it in my sleep...
I should see the text 'Welcome', but i only see blocks now.
I dont have a potentiometer any more, so i used a for-loop with a PWM signal to check the contrast i need. This did work the last time for me.
I use the arduino MEGA.
Below you see my code, and photo's of my little project.
#include <LiquidCrystal.h>
LiquidCrystal lcd(9, 10, 48, 46, 44, 42);

const int contrastPin = 8;

void setup() {
  // put your setup code here, to run once:
  lcd.begin(20,4);
  pinMode(contrastPin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  lcd.setCursor(0,0);
  lcd.print("Welcome");

  //LOOP TO CHECK TE CONTRAST
  for(int i = 0; i <= 255; i++){
    analogWrite(contrastPin,i);
    delay(30);
  }
}

It may well be the bad soldering. Not short circuits, but dry joints and bad connections.

Okay, i will try it again then...

Add some flux to ease your soldering nightmare.

That PWM signal to control the contrast unsettles me.  At the very least, use a capacitor to smooth out the voltage.  If you google this technique most say not to do it and replace the PWM with a digital pot.  But, then, an analog pot would be much easier to implement.

It that water you are pumping around?  At the very least, get your electronics away from where water might collect in case of a plumbing failure.

I will add some flux then. That's a good idea. And yes, it is demi-water. So don't worry, it does not conduct electricity

I re-soldered the pins. Also, I used a small resistor between my PWM signal and the VO port. Now it works perfectly.


text:
Could i use a stepper motor?
i want to make a 3-axis gimbal with arduino but brush-less motors seem incredibly hard so would stepper motors work for this purpose?
if their is a way if not, is how can i connect 3 gimbal motors to one arduino board and control them seperately? (links if possible)

If I would have planned to build a arduino controlled gimbal, I would use servos which are DC motors with a feedback control system. There so many videos on youtube for example that show how to build a gimbal with servos. OK you are to lazy to find one, here is one of them. I'm nice; I know ;-) https://www.youtube.com/watch?v=UxABxSADZ6U
OK, and now switch the jokes off: You are new to this forum. The people who answer your question are glad to help you. But do not expect them to provide you with a solution for a problem if it is easy for you to check the internet and get answers.

Why should brushless motors be incredibly hard? You only need an ESC as a driver, which then can easily controlled via PWM

@PeterPaulKiefer thank you but the reason i asked for links is because ive been searching for hours without luck on finding a way to control three brushless DC motors. i looked at servos but they dont meet my needs as they seem to be not very smooth

@chrisl thanks chris so i just need to find the right ESC and ill be able to use three on my arduino board? thatll fix all my problems thanks

Ok, I was was not very nice, I'm sorry about that. You are right, Servos are not very smooth, but you did not specify your needs for smooth operation. Please see my answer.

DC Motors with a feedback line (so called PID Controller; https://en.wikipedia.org/wiki/PID_controller) would be the best way to do it. You need the motor as an actor and some sensors that sense the direction of the axis's of the gimbal. The PID controller should be very fast for smooth operation. (Perhaps an ESP32 is a better MCU for this purpose).
The PID controller uses a motion sensors.
It's good to have strong motors that do not react "nervous" on on voltage changes. You probably will have to use motors with gears. Even fast PID controller won't be able to keep your camera from turning cartwheels if a 10.000 cycles per minute racing motor gets full voltage applied.
I searched the internet for videos of such a setup but the only thing I found, are the commercial (?) gimbal "alexmos" "how to" videos. I'm with you that it is hard to build such a gimbal without much knowledge of how PIDs work. I'm also not sure if there is an arduino that's fast enough to realize a PID that gets its feedback from motion sensors and drives dc motors with this information, then get's feedbach of the motor movements (from the motion sensors) and so on.
And probably a better/stronger servo and and very fast PID setup might eventually smooth the gimbals movements.
Here is a link that might help you as a start point for PID (if you are not discouraged yet):
https://www.youtube.com/watch?v=9TTDmWiMg_Y
And even professional setups can make problems: (It's a matter of the PID parameters)
https://www.youtube.com/watch?v=UeeTXH2Qv2o

A stepper motor might work, but it is certainly not the best choice for what you try.
Instead you should use brushless motors. There are not so hard to use, as you think. Driving them directly is difficult, but no one does that. Instead just buy an ESC (Electronic Speed Control) (one for each brushless motor). That is an extra chip/board, where you need to connect a PWM signal and ground from the Arduino and the power source of the motor. Then connect the motor to the ESC and you will be able to control the brushless motor with a simple PWM signal.
For further information you can read this post in the Arduino forum, or you just google. There is plenty of information the web about ESCs.


text:
Controlling multiple servos as one
I want to attach multiple servos to Arduino but all them must receive same command. If it possible to connect all servos to one command pin (I don't want to use "for" in code to minimize processor time for operation)?

why do you need to have multiple servos perform identical motion?

To perform identical motion in several places (e.g. move forward)

IMHO it is possible to connect more than one server PWM control inputs to a Arduino output pin.
The Servo input is something like a comparator with an very high resistance. So the servos should not influence each other in any way, nor will the output pin be overloaded.
Because of the input capacities of the servos, there might be a limit of the count of the servos.
And if you supply the servos with power from the arduino then, there is of cause a limit.
EDIT:
It is always a good idea to use buffers in a servo control circuit, to keep a sharp square wave signal. Parasitic capacities can reshape the signal even to a sinus signal.
That might confuse the servo control unit which works well only with a square wave (i.e a PWM-Signal).

simulate this circuit – Schematic created using CircuitLab

Thanks for response. In this case should I add some kind of signal amplifier after pin?

I was very busy. Sorry about the delay. I edited the answer.


text:
Measuring Battery level with ADC already in use
I have NodeMCU v3 with ESP8266 and I am running small project where I am measuring the input from IR phototransistor via ADC pin (A0) and everything is working flawlessly.
But now I want to transfer it to battery source (powerbank -> microUSB) and I want to be able to tell the remaining battery capacity, but all tutorials I found were going through switching ADC(A0) to internal, thus disabling it.
Is there any other way I can either measure the battery OR input from phototransistor?
Thanks!

you can just stop exploring now; the power bank will spit out 5.0v until it's dead.

As @dandavis rightly says in the comments, you can't measure the battery voltage from a power bank.  This is because the power bank typically includes a step-up converter to turn the batter voltage (3.2 to 4V) into a stable 5V.  That 5V will alwaye be 5V (or thereabouts) until the battery runs out and the power bank shuts itself off.
To measure the battery state you will have to directly interface with the batteries (disassemble the power bank) and tap into the battery terminals themselves.
Some power banks also have LEDs in them to display the power remaining. It could be possible to interface directly with these as well.
One thing to note, though, is that using a power bank for an ESP8266 board is pretty silly.  You are taking nominal 3.6V, stepping it up to 5V, then linearly dropping it back down to 3.3V again.  Both stages involve power wastage - the 5V to 3.3V most of all (a linear regulator turns the waste voltage into heat).
You would be better removing the batteries from the power bank and wiring them directly to the power input - or better still, feed them through a high efficiency switching regulator to get a stable 3.3V and feed that directly into the 3.3V pin.  be sure to include some way of monitoring the battery voltage and shutting off the power when it gets too low. Since your ADC input is already in use the simplest way is to add an external ADC chip to your design.


text:
How do I create global pointers with low memory overhead?
Problem
I have a few large objects in my code that need global visibility, but creating them seems to eat up memory significantly faster than simple math would dictate, and furthermore, using them differently in code seems to change how much RAM the compiler tells me I have left for local variables.
How do I optimize the use of my RAM while still being able to use an object in both my setup() and my loop() functions?
Note: Skim the Pseudo-Code section and then skip to the Discussion section if want to get to the meat of my question (I just wanted to provide plenty of background, if needed).
Test Code
To demonstrate that reported global RAM usage changes due not only the number of variables I define globally, but how those variables are used in code, I created a test program.  I compiled this code on the Arduino IDE on a Mac, and ran this on multiple Elegoo Nanos.
Please forgive the particularly long "minimal" complete verifiable code, but it has a bit going on.  Here's the pseudo-code for it.
Pseudo-Code
"T" (for tested) before a line means that I commented out a line or left it be depending on what test I was running:
Define a function to check how much memory remains, freeRam() (taken from https://playground.arduino.cc/Code/AvailableMemory, bottom of page)
Create a class that uses a ton of RAM, about 1024B (GinormousClass)
Create a wrapper for GinormousClass (GinormousClassWrapper) that may or may not construct the GinormousClass, based on how it is implemented

Global scope:
Run freeRAM() to see how much initial RAM is available before setup() is run.
T Create a global pointer to the wrapper class

Local scope (setup):
Report initial RAM
T Create a local pointer to the wrapper class
T Assign a newly constructed wrapper object to the pointer, which does NOT instantiate the huge class
    Report how much RAM remains after creation and after deletion
T Assign a newly constructed wrapper object to the pointer, which DOES instantiate the huge class
    Report how much RAM remains after creation and after deletion

Note: Remaining RAM before creation and after deletion were always the same.
Actual Code
#define ARRAY_SIZE 256

// Method to determine how much memory is left (https://playground.arduino.cc/Code/AvailableMemory, bottom of page)
int freeRam() {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
};

// Define a class that uses a ton of RAM
class GinormousClass {
  public:
    GinormousClass() { // Fill array with (kind of) random numbers
      for (int i = 0; i < ARRAY_SIZE; i++) {
        BIG[i] = random(1000);
      }
    };

    long BIG[ARRAY_SIZE]; // Have this class control a huge array
};

// Define a class that has the potential to use a ton of RAM
class GinormousClassWrapper {
  public:
    GinormousClassWrapper(bool createGiantObject) { // Constructor
      if (createGiantObject) {
        // Create a GinormousClass object (use a ton of RAM)
        gPointer = new GinormousClass();
      } else {
        // Do not create GinormousClass object
      }
    };

    ~GinormousClassWrapper() { // Delete the Ginormous Class, if it exists
      if (gPointer) {
        delete gPointer;
      }
    }

    GinormousClass *gPointer = NULL; // Initialize pointer to NULL
};

int initialFreeRam = freeRam(); // Figure out how much RAM is available before the fun begins
GinormousClassWrapper *ginny; // Declare a GLOBAL pointer to the potentially enormous class

void setup() {
  // Start the Serial connection, and get the initial amount of RAM
  Serial.begin(9600);
  Serial.print("Initial free RAM: ");
  Serial.println(initialFreeRam);

  //  GinormousClassWrapper *ginny; // Declare a LOCAL pointer to the potentially enormous class

  // Try making the class, without defining the array
  Serial.println("Making Ginormous Class (do nothing constructor)...");
  ginny = new GinormousClassWrapper(false);

  Serial.print("Current free RAM: ");
  Serial.println(freeRam());
  Serial.println();

  // Delete the class
  Serial.println("Deleting first class...");
  delete ginny;

  Serial.print("Current free RAM: ");
  Serial.println(freeRam());
  Serial.println();

  // Try making the class, WITH defining the array
  Serial.println("Making Ginormous Class (use a ton of RAM constructor)...");
  ginny = new GinormousClassWrapper(true);

  Serial.print("Current free RAM: ");
  Serial.println(freeRam());
  Serial.println();

  //  Delete the class
  Serial.println("Deleting second class...");
  delete ginny;

  Serial.print("Current free RAM: ");
  Serial.println(freeRam());
  Serial.println();
};

void loop() {

};

Results
I've collected the RAM reported at 4 different times:

after compilation
before setup()
after the "do-nothing" construction of the wrapper
after the "use-space" construction of the wrapper

5 different scenarios were tested:

no pointer declared/wrapper not constructed
pointer declared but object not constructed
do-nothing constructor used
use-space constructor used
do-nothing constructor used, object deleted, and use-space constructor used

Raw Results:
Numbers are amount of RAM left, in bytes
0 Not declared:
    Compiler: 1836
    Initial: 1830
    Do-nothing constructed: N/A
    Use-space constructed: N/A

1 Declared global, not constructed:
    Compiler: 1836
    Initial: 1830
    Do-nothing constructed: N/A
    Use-space constructed: N/A

2 Declared global, constructed do-nothing:
    Compiler: 1734
    Initial: 1728
    Do-nothing constructed: 1724
    Use-space constructed: N/A

3 Declared global, constructed use-space:
    Compiler: 1722
    Initial: 1716
    Do-nothing constructed: N/A
    Use-space constructed: 686

4 Declared global, constructed both:
    Compiler: 1648
    Initial: 1640
    Do-nothing constructed: 1636
    Use-space constructed: 610

Note: Local pointer instead of global pointer had no change except increase all reported RAM by 2 bytes.
Discussion
In the raw results, the GinormousClassWrapper takes 4B when constructed (the pointer it owns) and GinormousClass takes about 1024B when constructed (exactly 1030B, we can assume there's some overhead).  However, one strange thing is of note:
The amount of room stated by the compiler to be available for local variables decreases significantly when the wrapper is constructed  versus when it is not (1836B down to 1640B when both constructors are used).  I would expect that the amount of RAM used by globals would not change, because technically only the pointer is in global scope.  If it is SUPPOSED to change according to how the pointer is used, then why does it change by 196B, of all numbers?
I am assuming that the RAM given by the compiler is fact, and it's one that I would like to know because my project is running on tight memory restrictions.  So where is all of this valuable extra RAM going, and what can I do to reduce it?  Thank you for any help!

I compiled a slightly modified version of your code, with some
#defines for selecting which objects get constructed or not. I also
printed the available RAM right after entering setup(). I found that,
at this point in the program, the version constructing both objects
is using 178 bytes more RAM than the version that constructs none.
I then used the commands avr-nm and avr-objdump to try to figure out
how the program is using its memory. I found the 178 bytes
difference is as follows:
157 bytes of string data
  6 bytes of malloc data
  4 bytes of random state
  2 bytes for the ginny variable
  8 bytes of stack
  1 mystery byte

The difference in string data comes from messages such as “Making
Ginormous Class (do nothing constructor)...”, “Deleting first class...”,
etc., which are #defined out in the version that does not construct
the objects. The malloc() data (heap_start, heap_end and margin) is
not used in the version that does not use new, so it is not included
in that version. For the same reason, the random() state is not
included in the version that does not use random(). The ginny
variable, although declared in both versions, is optimized-out by the
compiler in the version where it remains unused. The 8 bytes of stack
come from the fact that the largest version of setup() needs more
CPU register to do its work, and hence pushes more registers to the
stack. There is only one byte I could not account for, with value 0,
sitting at the end of the .data section, with no associated symbol.
As you can see from this, the difference has little to do with the
objects being constructed. It is mostly due to the string data. A
smaller part of that difference comes from variables (ginny, random
state and malloc() data) which are used only in one version of the
program. The practical conclusions are:

If you want to save RAM, use the F() macro when printing constant
strings.
If you want to benchmark memory consumption, beware your benchmarking
method can have non-obvious effects on the consumption yo are trying
to measure.

I am assuming that the RAM given by the compiler is fact ...

That's about the only thing I wouldn't assume. The compiler can't really know how much RAM your code is going to use, especially when you do dynamic memory allocation. The compiler can certainly report on how much space your global variables take, as it has to allocate addresses for them.
I have a post about what RAM is used in a minimal sketch, for example this:
#include "memdebug.h"

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.print (F("Free memory = "));
  Serial.println (getFreeMemory ());
  }  // end of setup

void loop () { }

Perhaps surprisingly, that sketch already uses 346 bytes of RAM, and it hasn't got any (visible) variables in it.

what can I do to reduce it?

  Serial.println("Making Ginormous Class (do nothing constructor)...");

You could start by using the F macro:
  Serial.println(F("Making Ginormous Class (do nothing constructor)..."));

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Feather MO: How would I change my code to have my txt file data be in columns rather than be staggered?
First of all, I am using the Feather MO Adalogger from Adafruit with the Ultimate GPS Feather hat to collect some GPS data: time stamp (millisec), GPS Coordinates (latitude & longitude), speed (knots), and altitude (meters). The GPS data is stored on a micro SD card and I have the GPS portion of the code working. The data I want is being stored on the micro SD card. My only problem is that I can't get the data to be appropriately put in columns under their respective "headers". I used .print("\t") after each data type in attempt to tab the data into columns. This worked for the "headers" but not for the data itself. Screenshots and code are below. Thanks in advance!
My txt file: Headers

My text file: working GPS data

Code for Headers

Code for data

The tab '\t' has no fixed number of positions. It can be every 2 or every 8 or anything else. You can try to fill up with spaces. For example the sprintf function can do that. Are you sure you want to show the text file nicely formatted under the headers? It is more common to use the text file as data for visualization tools.

@Jot  I just want my data to be easily copy/pasted into a data manipulation/graphing program like excel or matlab. Any suggestions on how to do that? I copied the data the way it is but it pastes awkwardly into excel. Thanks btw

@user52619 And we want easily copy/pasteable code for testing.

Since I don't like the tab character, I would use only ", " between the numbers with a println() at the end as @jose-can-u-c wrote.

Change the println()s to print()s. Put one println() at the end of the list of data prints.  You want each row of data to not take up more than one line in the text file. A println() starts a new row after printing.
Also, you’ll want to open the text file in a tabular program like Excel or similar. A plain text editor likely won’t utilize tab characters in the way you like.

Thank you so much!! That worked perfectly just how I wanted! (:

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/