text:
How do I interface my ESP32 board with my 3.5" TFT Screen
I've bought an ESP32 board from here and a 3.5" TFT Screen from here. The ESP32 board has an UNO type layout so I thought it would work with the screen which is designed to  plug in and play with Arduino UNOs.
However upon plugging the board and shield together (they fit perfectly, each pin goes in a corresponding slot), loading one of the example scripts (provided on the 3.5" Screen .rar download on the page), set Arduino to use ESP32 Development Board on COM3 (my usual settings for the ESP32) and uploading the code I just get a white screen on the TFT.
Is there some accommodation that I have to make because my board is not an UNO but instead a ESP32, i.e. is the pin layout different so maybe I'll need to wire this manually?
I've included the pin out diagrams below:

Arduino Sketch Code:

#include <MCUFRIEND_kbv.h>
#include <Adafruit_GFX.h>    // Core graphics library

// wiring with UNO or Mega2560:
//--------------POWER Pins--------------------------------
//   5V  connects to DC 5V
//   GND connects to Ground
//   3V3 do not need to connect(NC)
//--------------LCD Display Pins--------------------------
//   LCD_RD   connects to Analog pin A0
//   LCD_WR   connects to Analog pin A1
//   LCD_RS   connects to Analog pin A2
//   LCD_CS   connects to Analog pin A3
//   LCD_RST  connects to Analog pin A4
//   LCD_D0   connects to digital pin 8
//   LCD_D1   connects to digital pin 9
//   LCD_D2   connects to digital pin 2
//   LCD_D3   connects to digital pin 3
//   LCD_D4   connects to digital pin 4
//   LCD_D5   connects to digital pin 5
//   LCD_D6   connects to digital pin 6
//   LCD_D7   connects to digital pin 7
//--------------SD-card fuction Pins ----------------------
//This Connection Only for UNO, Do not support Mega2560
//because they use different Hardware-SPI Pins
//SD_SS    connects to digital pin 10
//SD_DI    connects to digital pin 11
//SD_DO    connects to digital pin 12
//SD_SCK   connects to digital pin 13

#define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin
#define LCD_CS A3   // Chip Select goes to Analog 3
#define LCD_CD A2  // Command/Data goes to Analog 2
#define LCD_WR A1  // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0

// Assign human-readable names to some common 16-bit color values:
#define  BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

MCUFRIEND_kbv tft;

unsigned long testFillScreen() {
  unsigned long start = micros();
  tft.fillScreen(BLACK);
  tft.fillScreen(RED);
  tft.fillScreen(GREEN);
  tft.fillScreen(BLUE);
  tft.fillScreen(BLACK);
  return micros() - start;
}

unsigned long testText() {
  tft.fillScreen(BLACK);
  unsigned long start = micros();
  tft.setCursor(0, 0);
  tft.setTextColor(WHITE);  tft.setTextSize(1);
  tft.println("Hello World!");
  tft.setTextColor(YELLOW); tft.setTextSize(2);
  tft.println(1234.56);
  tft.setTextColor(RED);    tft.setTextSize(3);
  tft.println(0xDEADBEEF, HEX);
  tft.println();
  tft.setTextColor(GREEN);
  tft.setTextSize(5);
  tft.println("Groop");
  tft.setTextSize(2);
  tft.println("I implore thee,");
  tft.setTextSize(1);
  tft.println("my foonting turlingdromes.");
  tft.println("And hooptiously drangle me");
  tft.println("with crinkly bindlewurdles,");
  tft.println("Or I will rend thee");
  tft.println("in the gobberwarts");
  tft.println("with my blurglecruncheon,");
  tft.println("see if I don't!");
  return micros() - start;
}

unsigned long testLines(uint16_t color) {
  unsigned long start, t;
  int           x1, y1, x2, y2,
                w = tft.width(),
                h = tft.height();

  tft.fillScreen(BLACK);

  x1 = y1 = 0;
  y2    = h - 1;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = w - 1;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t     = micros() - start; // fillScreen doesn't count against timing

  tft.fillScreen(BLACK);

  x1    = w - 1;
  y1    = 0;
  y2    = h - 1;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = 0;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t    += micros() - start;

  tft.fillScreen(BLACK);

  x1    = 0;
  y1    = h - 1;
  y2    = 0;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = w - 1;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t    += micros() - start;

  tft.fillScreen(BLACK);

  x1    = w - 1;
  y1    = h - 1;
  y2    = 0;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = 0;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);

  return micros() - start;
}

unsigned long testFastLines(uint16_t color1, uint16_t color2) {
  unsigned long start;
  int           x, y, w = tft.width(), h = tft.height();

  tft.fillScreen(BLACK);
  start = micros();
  for(y=0; y<h; y+=5) tft.drawFastHLine(0, y, w, color1);
  for(x=0; x<w; x+=5) tft.drawFastVLine(x, 0, h, color2);

  return micros() - start;
}

unsigned long testRects(uint16_t color) {
  unsigned long start;
  int           n, i, i2,
                cx = tft.width()  / 2,
                cy = tft.height() / 2;

  tft.fillScreen(BLACK);
  n     = min(tft.width(), tft.height());
  start = micros();
  for(i=2; i<n; i+=6) {
    i2 = i / 2;
    tft.drawRect(cx-i2, cy-i2, i, i, color);
  }

  return micros() - start;
}

unsigned long testFilledRects(uint16_t color1, uint16_t color2) {
  unsigned long start, t = 0;
  int           n, i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(BLACK);
  n = min(tft.width(), tft.height());
  for(i=n; i>0; i-=6) {
    i2    = i / 2;
    start = micros();
    tft.fillRect(cx-i2, cy-i2, i, i, color1);
    t    += micros() - start;
    // Outlines are not included in timing results
    tft.drawRect(cx-i2, cy-i2, i, i, color2);
  }

  return t;
}

unsigned long testFilledCircles(uint8_t radius, uint16_t color) {
  unsigned long start;
  int x, y, w = tft.width(), h = tft.height(), r2 = radius * 2;

  tft.fillScreen(BLACK);
  start = micros();
  for(x=radius; x<w; x+=r2) {
    for(y=radius; y<h; y+=r2) {
      tft.fillCircle(x, y, radius, color);
    }
  }

  return micros() - start;
}

unsigned long testCircles(uint8_t radius, uint16_t color) {
  unsigned long start;
  int           x, y, r2 = radius * 2,
                w = tft.width()  + radius,
                h = tft.height() + radius;

  // Screen is not cleared for this one -- this is
  // intentional and does not affect the reported time.
  start = micros();
  for(x=0; x<w; x+=r2) {
    for(y=0; y<h; y+=r2) {
      tft.drawCircle(x, y, radius, color);
    }
  }

  return micros() - start;
}

unsigned long testTriangles() {
  unsigned long start;
  int           n, i, cx = tft.width()  / 2 - 1,
                      cy = tft.height() / 2 - 1;

  tft.fillScreen(BLACK);
  n     = min(cx, cy);
  start = micros();
  for(i=0; i<n; i+=5) {
    tft.drawTriangle(
      cx    , cy - i, // peak
      cx - i, cy + i, // bottom left
      cx + i, cy + i, // bottom right
      tft.color565(0, 0, i));
  }

  return micros() - start;
}

unsigned long testFilledTriangles() {
  unsigned long start, t = 0;
  int           i, cx = tft.width()  / 2 - 1,
                   cy = tft.height() / 2 - 1;

  tft.fillScreen(BLACK);
  start = micros();
  for(i=min(cx,cy); i>10; i-=5) {
    start = micros();
    tft.fillTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
      tft.color565(0, i, i));
    t += micros() - start;
    tft.drawTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
      tft.color565(i, i, 0));
  }

  return t;
}

unsigned long testRoundRects() {
  unsigned long start;
  int           w, i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(BLACK);
  w     = min(tft.width(), tft.height());
  start = micros();
  for(i=0; i<w; i+=6) {
    i2 = i / 2;
    tft.drawRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(i, 0, 0));
  }

  return micros() - start;
}

unsigned long testFilledRoundRects() {
  unsigned long start;
  int           i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(BLACK);
  start = micros();
  for(i=min(tft.width(), tft.height()); i>20; i-=6) {
    i2 = i / 2;
    tft.fillRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(0, i, 0));
  }

  return micros() - start;
}
void setup(void) {
   Serial.begin(9600);
  Serial.println(F("TFT LCD test"));

  tft.reset();

  uint16_t identifier = tft.readID();
  if(identifier == 0x9325) {
    Serial.println(F("Found ILI9325 LCD driver"));
  } else if(identifier == 0x9328) {
    Serial.println(F("Found ILI9328 LCD driver"));
  } else if(identifier == 0x4535) {
    Serial.println(F("Found LGDP4535 LCD driver"));
  }else if(identifier == 0x7575) {
    Serial.println(F("Found HX8347G LCD driver"));
  } else if(identifier == 0x9595) {
    Serial.println(F("Found HX8347-I LCD driver"));
  } else if(identifier == 0x4747) {
    Serial.println(F("Found HX8347-D LCD driver"));
  } else if(identifier == 0x8347) {
    Serial.println(F("Found HX8347-A LCD driver"));
  }else if(identifier == 0x9341) {
    Serial.println(F("Found ILI9341 LCD driver"));
  }else if(identifier == 0x7783) {
    Serial.println(F("Found ST7781 LCD driver"));
  }else if(identifier == 0x8230) {
    Serial.println(F("Found UC8230 LCD driver"));
  }else if(identifier == 0x8357) {
    Serial.println(F("Found HX8357D LCD driver"));
  } else if(identifier==0x0101){
      identifier=0x9341;
      Serial.println(F("Found 0x9341 LCD driver"));
  }else if(identifier==0x7793){
       Serial.println(F("Found ST7793 LCD driver"));
  }else if(identifier==0xB509){
       Serial.println(F("Found R61509 LCD driver"));
  }else if(identifier==0x9486){
       Serial.println(F("Found ILI9486 LCD driver"));
  }else if(identifier==0x9488){
       Serial.println(F("Found ILI9488 LCD driver"));
  }else {
    Serial.print(F("Unknown LCD driver chip: "));
    Serial.println(identifier, HEX);
    Serial.println(F("If using the Adafruit 2.8\" TFT Arduino shield, the line:"));
    Serial.println(F("  #define USE_ADAFRUIT_SHIELD_PINOUT"));
    Serial.println(F("should appear in the library header (Adafruit_TFT.h)."));
    Serial.println(F("If using the breakout board, it should NOT be #defined!"));
    Serial.println(F("Also if using the breakout, double-check that all wiring"));
    Serial.println(F("matches the tutorial."));
    identifier=0x9486;
  }
  tft.begin(identifier);

  Serial.println(F("Benchmark                Time (microseconds)"));

  Serial.print(F("Screen fill              "));
  Serial.println(testFillScreen());
  delay(500);

  Serial.print(F("Text                     "));
  Serial.println(testText());
  delay(3000);

  Serial.print(F("Lines                    "));
  Serial.println(testLines(CYAN));
  delay(500);

  Serial.print(F("Horiz/Vert Lines         "));
  Serial.println(testFastLines(RED, BLUE));
  delay(500);

  Serial.print(F("Rectangles (outline)     "));
  Serial.println(testRects(GREEN));
  delay(500);

  Serial.print(F("Rectangles (filled)      "));
  Serial.println(testFilledRects(YELLOW, MAGENTA));
  delay(500);

  Serial.print(F("Circles (filled)         "));
  Serial.println(testFilledCircles(10, MAGENTA));

  Serial.print(F("Circles (outline)        "));
  Serial.println(testCircles(10, WHITE));
  delay(500);

  Serial.print(F("Triangles (outline)      "));
  Serial.println(testTriangles());
  delay(500);

  Serial.print(F("Triangles (filled)       "));
  Serial.println(testFilledTriangles());
  delay(500);

  Serial.print(F("Rounded rects (outline)  "));
  Serial.println(testRoundRects());
  delay(500);

  Serial.print(F("Rounded rects (filled)   "));
  Serial.println(testFilledRoundRects());
  delay(500);

  Serial.println(F("Done!"));
}

void loop(void) {
  for(uint8_t rotation=0; rotation<4; rotation++) {
    tft.setRotation(rotation);
    testText();
    delay(2000);
  }
}

You didn't show us the code in question. Please include your code in the question by editing it.

Ok, that's it added

please copy the content of the serial monitor and paste it into your post ... format it as code

If using the Adafruit 2.8" TFT Arduino shield, the line:
  #define USE_ADAFRUIT_SHIELD_PINOUT
should appear in the library header (Adafruit_TFT.h).
If using the breakout board, it should NOT be #defined!
Also if using the breakout, double-check that all wiring
matches the tutorial.
Benchmark                Time (microseconds)
Screen fill              1386975
Text                     52997

The MCUFRIEND_kbv library has the pins hardcoded. To use the Uno pin numbering the Wemos ESP32 D1 board requires to use Dx pin names instead of x. So the library will not work with this board without changing the pins in the source code of the library.

The exact same sketch with included libraries works perfectly on my standard UNO, displays all the graphics. I need to use the ESP32 tho because it has wifi capabilities.

upvote for the use of Vogon poetry ... couldn't help myself


text:
How to burn fuses in Digistump ATTiny85 with the Arduino IDE
I have a Digispark / digistump Attiny85.  Working with Windows 11 and the Arduino IDE 2.0.4
I would like this guy to have Brown Out Detection set to 101 (2.7V)
For this, I'd need to set the BOD fuses.
How can I do this with the USB interface of the Arduino IDE?
To use the USB programming, I have to set the Board to "Digispark (Default 16.5Mhz)".
I have seen that in normal ATTiny85 operation, under the Tools-Menu I could choose the fuses I like.
In the Digispark Default setting this is not available.

Which version of the IDE are you using, on what operating system?

Windows 11, IDE 2.0.4

To answer this well someone would need to to know which exact thing called "digispark" you have. The official one and various clones do different things with the reset pin and its configuration. It may also matter whether or not it is a "Pro" variant.

You can't change the fuses without using an ISP programmer (an Arduino or even another digispark can be configured as such). However, if the reset pin of the ATtiny85 has been disabled, you will first need a high voltage programmer to reset the ATtiny85 to its factory condition. See: http://digistump.com/wiki/digispark/tutorials/programming . With the ISP programmer connected, you can use AVRDUDE also to set the fuses. The last post here http://digistump.com/board/index.php/topic,2257.msg10556.html#msg10556 implies that 2.7v brown out is anyway already enabled.

Thank you very much!

The first thing to say (already mentionened by @timemage) is that there is a large variety of "Digispark / Digistump" devices, both original, clones using the Micronucleus bootloader, even when considering only the ATTiny85 variants. Those variants, where the reset pin has not been re-configured as a GPIO pin, are easier to use. Otherwise, you firstly need a high voltage programmer to reset the ATTiny85 to its factory state, to restore the reset pin for configuring fuses etc.
The second thing is that the last post here:  digistump.com/board/index.php/topic,2257.msg10556.html#msg10556 implies that 2.7v brown out, which you appear to need, is anyway already enabled (at least with the variant described by the author) That  is, the fuse settings are: lfuse 0xE1 hfuse 0x5D efuse 0xFE.
Anyway, to change the fuses (or load the "Digispark / Digistump" (Micronucleus) bootloader) you need an ISP programmer (an Arduino or even another digispark can be configured as such). See: digistump.com/wiki/digispark/tutorials/programming. With the ISP programmer connected, you can then use AVRDUDE also to set the fuses.
In the worst case, you have to start with a factory condition ATtiny85 and go through the entire process of loading the "Digispark / Digistump" firmware onto it and configuring the appropriate fuse settings. See https://circuitdigest.com/microcontroller-projects/attiny85-ic-programming-through-usb-using-digispark-bootloader

Basically you're saying I should use ISP instead of using the advantage of the Digistump USB driver. Thanks, that's an answer!

Yes, but only for the one-time operation of configuring the fuses. Once that is done, you can revert to the USB method for uploading code.

source: Stack Exchange

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

sort: votes


text:
Control Fan Speed Using ESP8266
Hello i am using ESP8266 to control my 220v AC ceiling fan.
I am able to do that easily with a 5v 10A relay module.
But i want to know is there any module to control the fan speed as well? i have checked many videos on YouTube but couldnt understand how can i do that. I just got one thing that it will require Pulse Width Modulation to control it.
Thank you!

I just got one thing that it will require Pulse Width Modulation to control it huh? what?

to control Celling fan speed

no, pwm will not help you. the trick is to turn the relay on and off fast. the mechanical relay cant do it, so you need a SSR (solid state relay)

@Juraj Thank you for amazing suggestion. But can you share any example code? Or any library which can help with this?

Blink example ?

code example..that can be any of the possible one. Just want to test it.

yes Blink. turn on, turn off, turn on, turn off, turn on, turn off,...

you can use "pwm", but not what us makers call pwm, which is a high-frequency DC thing, and you need a low frequency AC thing. It's called phase modulation, and uses a triac. it's a lot more complicated than DC PWM. Look into zero crossing SSRs to make your task half as difficult.

@dandavis do you think this will work? https://robu.in/product/5v-4-channel-ssr-solid-state-relay-module-240v-2a-output-resistive-fuse/

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


text:
How can you check how long a timer interrupt really is?
I'm trying to set a 33 ms interrupt on my Arduino Mega and I'm not sure if I a in fact getting that kind of delay time. Is there a way to check?
I've calculated that that I need 515.6 ticks to achive this kind of delay with a prescaler of 1024 and I've coded it up like so:
void setupInterupt()
{
  noInterrupts();
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = 0;
  OCR2A = PERIOD - 1;
  TIMSK2 = _BV(OCIE2A);
  TCCR2B |= _BV(CS12) | _BV(CS10); // prescale by 1024
  interrupts();
}

I followed the information on the Arduino Playground page and if my math is correct this interrupt should be going off every 33 milliseconds. I tried to test that using the millis(); method but it only returns the time that program was on.

Try counting how many times it fires in a second

Can you expand on that? This is my first Arduino project so I'm not totally sure how to do what you just said.

In your timer ISR add one to a counter. Every second print the counter.

It doesn't fire every 33 milliseconds. First, you missed setting the CSn1 bit necessary for a 1024 prescaler; second, It looks like you want CTC mode (where the timer resets at OCRnA) but you didn't set the WGM21 bit necessary for that mode. After that your problem is that timer2 is an 8 bit timer and so OCR2A cannot store 515, but you math is correct.
You can get the period you want on a 16-bit timer; on the arduino mega thats timers 1,3,4, and 5.
Anyway here is a simple sketch for finding the average interval between interrupts. It just keeps track of the total time elapsed and the number of times the interrupt fired; the ratio of these two is the average time per interrupt.
In this case, with a prescaler of 1024, OCRA = 0xFF, and CTC mode, it runs at an interrupt every 16.384 ms.
volatile uint16_t interruptCount;
volatile uint32_t start;

ISR(TIMER2_COMPA_vect){
    interruptCount++;
}

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

    noInterrupts();
    TCCR2A = _BV(WGM21);
    TCCR2B = _BV(CS22) | _BV(CS21) | _BV(CS20); // prescale by 1024
    OCR2A = 0xFF;
    TIMSK2 = _BV(OCIE2A);
    // start the timer
    interruptCount = 0;
    start = micros();
    interrupts();
}

void loop(){
    // read interrupt count into a local variable atomically
    noInterrupts();
    uint16_t localCount = interruptCount;
    interrupts();
    uint32_t time = micros() - start;

    // time elapsed
    Serial.print(time);
    Serial.print(" ");

    // number of times the interrupt handler fired
    Serial.print(localCount);
    Serial.print(" ");

    // average number of microseconds per interrupt
    Serial.print(time / localCount);
    Serial.println();

    delay(30);
}

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


text:
Large(ish) strings failing to send over WiFi101 using WiFiServer
I've based a sketch off the vanilla WiFi101 server examples.
If I define a const char array like this:
const char HTML_index[] = "test";

The server works well.  However if I increase the char[] size to about 1,300 bytes the server fails to send a response.  The device (Feather M0 WiFi) doesn't lock up, I can continue to make HTTP requests and the serial console functions correctly, just no HTTP response.  The device and laptop (client) are both on the same WiFi AP so nothing weird there.
First I thought this was a memory issues, but as I'm using newer architecture and IDE using const should ensure the string is in FLASH.
So I then read some threads about buffer limits per response using other libraries: https://github.com/esp8266/Arduino/issues/3205
But again not sure how applicable this is to an ARM based system/ WiFi101 library.
Is there a limiting buffer size etc when sending HTTP data in my setup? Do I need to split the string up into smaller pieces and send multiple responses?  How could I go about debugging this situation?
Edit:
This is the example sketch my code is based off:
https://www.arduino.cc/en/Tutorial/Wifi101SimpleWebServerWiFi
Edit2: ok I think I know what's going on but can't test right now, will post an answer when I do.  I found this thread https://github.com/arduino-libraries/WiFi101/issues/163 which talks about SOCKET_BUFFER_UDP_SIZE.  So I looked through the WiFi101 src and found this:
#ifdef LIMITED_RAM_DEVICE
#define SOCKET_BUFFER_SIZE 64
#else
#define SOCKET_BUFFER_SIZE 1472
#endif

https://github.com/arduino-libraries/WiFi101/blob/master/src/utility/WiFiSocket.cpp
It's likely that my string was actually over 1472 bytes so this makes sense.
Edit3:
Found more references:
https://github.com/arduino-libraries/ArduinoHttpClient/issues/14
https://github.com/arduino-libraries/WiFi101/pull/116
So I take it the 1500 in WINC1500 could mean the buffer size.  Either way looks like there's a hardware buffer limit and responses larger than ~1400 bytes need to be chunked.

the examples don't use const char HTML_index[]. show the sketch you use. do you set content-legth header?

I'll add a stripped down example sketch soon.  But it follows this example exactly, except I define a const char HTML_index[] = "..."; in global scope and call client.print(HTML_index); in the client connected loop. https://www.arduino.cc/en/Tutorial/Wifi101SimpleWebServerWiFi

try to add a delay before client.stop()

I'll give that a try, but since my HTTP header doesn't specify Connection: close execution stays in the while (client.connected()) loop and doesn't hit client.stop().  But maybe that's a problem

As per my notes the WINC1500 has a limit of 1500 bytes per transmission.  But some of this is always taken up by TCP overhead so the payload buffer must be smaller, that's why you see numbers like 1460.
From:
http://ww1.microchip.com/downloads/en/appnotes/atmel-42739-tcp-client-and-server-operation-using-atwinc1500_at14596_applicationnote.pdf

2.2.2 TCP Packet Size
A packet is sized as per the lowest MTU (Maximum
  Transmission Unit) on the path, which is typically 1500 bytes (for
  Ethernet) of data including TCP (20 bytes) and IP headers (20 bytes).
  The packet size is defined in main.h as :

#define MAIN_WIFI_M2M_BUFFER_SIZE 1460

The application then defines a socket buffer of this size in main.c as:

static uint8_t gau8SocketTestBuffer[MAIN_WIFI_M2M_BUFFER_SIZE];

This means that HTTP responses over ~1400 bytes need to be chunked which means split up into multiple calls.
FYI chunked Transfer-Encoding is superseded in HTTP/2:
http://undertow.io/blog/2015/04/27/An-in-depth-overview-of-HTTP2.html
Info on HTTP chunked encoding:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding
Transfer-Encoding: chunked

Data is sent in a series of chunks. The Content-Length header is
  omitted in this case and at the beginning of each chunk you need to
  add the length of the current chunk in hexadecimal format, followed by
  '\r\n' and then the chunk itself, followed by another '\r\n'. The
  terminating chunk is a regular chunk, with the exception that its
  length is zero. It is followed by the trailer, which consists of a
  (possibly empty) sequence of entity header fields.

https://www.httpwatch.com/httpgallery/chunked/
https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88

Transfer-Encoding
The use of Transfer-Encoding: chunked is what allows streaming within
  a single request or response. This means that the data is transmitted
  in a chunked manner, and does not impact the representation of the
  content.
Officially an HTTP client is meant to send a request with a TE header
  field that specifies what kinds of transfer encodings the client is
  willing to accept. This is not always sent, however most servers
  assume that clients can process chunked encodings.
The chunked transfer encoding makes better use of persistent TCP
  connections, which HTTP 1.1 assumes to be true by default.
Chunked data is represented in this manner:

4\r\n
Wiki\r\n
5\r\n
pedia\r\n
e\r\n
 in\r\n\r\nchunks.\r\n
0\r\n
\r\n

Each chunk starts with its byte length expressed as a hexadecimal
  number followed by optional parameters (chunk extension) and a
  terminating CRLF sequence, followed by the chunk data. The final chunk
  is terminated by a CRLF sequence.
Chunk extensions can be used to indicate a message digest or an
  estimated progress. They are just custom metadata that your layer 7
  receiver needs to parse. There's no standardised format for it.
  Because of this, it's probably better to just add your metadata (if
  any) into the chunk itself for your layer 7.5 application to parse.
For your application to send out chunked data, you must first send out
  the Transfer-Encoding header, and then you must flush content in
  chunks according to the chunk format. If you don't have an appropriate
  HTTP server that handles this, then you need to implement the syntax
  generator yourself. Sometimes you can use a library to provide an
  abstract interface.

Possible fix on Arduino platforms is to use StreamLib library or roll-your-own chunking system.
Update:  I hacked together a sketch and confirmed this works.  Next issue was the buffer must be null terminated, BUT this is stripped out before transmitted over TCP so the HTTP chunk size is the buffer size -1.


text:
Arduino One Wire Bus DS18B20 self developed driver missing bits or extraneous bits
I recently got to code my own driver for the One-Wire-Bus specifically with the ubiquitous DS18B20 temperature sensor in mind for an application.
I am running that code on an Arduino Mega 2560. Programming is done in Atmel Studio 7 and an AVR ISP mk2.
In the version as-of yesterday see here I get missing binary digits while trying to send the 0x55 One-Wire-Command (i.e. Match-Rom-Code).
It appears like it where the least significant two bits that are missing (Oscilloscope capture).
Today I tried to sort out that bug and "fixed" it by counting to 9 instead of 8 (even though I can't explain why this should work, it should rather break stuff [turns out it does]...) and subtracting 1 from my index variable. (See file "OneWire.c" line 83 and following for the old version).
Todays version is here (compare file "OneWire.c" line 81 and following).
In the new version (as-of today) I am able to get the 0x33 opcode (i.e. Send-Rom-Command) transmitted as wanted and get the ID of my specific sensor on the bus (atleast my oscilloscope shows the correct waveform). In the newer version I do the following chain of operations:

get the ID of the single sensor I have connected at the moment
send the Match-Rom-Command (just because that is something actually meaningful to do)
send the 64-Bit Rom-Code after that (or atleast what ever the statemachine of the getID function did end up writing in the output parameter)
send the 0x44 opcode (i.e. start temperature conversion)

This scenario yields me no correct Rom-code being sent on the bus, one byte more on the bus and another single bit too much on the bus for the temperature-conversion opcode. The Match Rom Code command does get transfered as supposed to and does not yield any extraneous or missing bits (no scope capture for that since that would not be possible to get into one shot that shows it all [at a workable scaling]...).
I would highly apprechiate anyone looking at my code and trying to figure out what is going wrong here since I am completely in the dark right now.
Before anybody asks:
I specifically did not want to use the readily available One-Wire-Libraries as they tend to be bloated and heavily rely on the delay function, which is fine if you are doing little else with your chip but not else. Since I have multiple sensors to read out (not yet but as soon as I got the drivers working) have to do some post processing on the raw data (i.e. put some sort of math to it) and transmit that data on a usually slow interface (I2C, Serial, you name it), which all takes time (and all that [periodically and as fast as possible of-course] on a poor 8-Bit Micro that runs at a underwhelming 16MHz...), I decided to keep polling and delay()-uses to a minimum and rather rely (heavily?) on a timer interrupt and a series of Statemachines...
It is not at  all obvious to me why the code does act in that way.

I can't say much about your specific problem as a don't have too much experience with 1-wire. Actually, I always avoided using it, because those software implementations usually are so slow and blocking. That's why I'm curious about what you are trying to achieve. From what I know, 1-wire needs very accurate timing. I guews, one does not want anything else to happen while communication with a 1-wire device is going on. I think, reading several sensors synchronously will not be trivial

yes they are slow and blocking (due to the use of the delay function and similar bad techniques (we are talking about 500us for the reset and presence pulse together alone so roughly 7500 clock cycles at a 16MHz uC…) this is exactly what i want to circumvent by writing my own code for the job and by relying on timers where-ever possible. reading several sensors syncronously is not neccesary and not possible (if they are on the same bus else it is possible but anywhy) i plan to read them sequentially as soon as i can get at least one sensor working. The problem it self is not 1-wire-specific...

what i am exactly trying to archive is to measure a bunch of temperatures for a engine test rig. My supervisor advocated for the one wire temperature sensors and gave me the Arduino mega to have it all running on. it is planned to make the test rig a distributed System so that there is not much else going on on the uC just reading many sensors one at a time and converting the raw data to natural units and send them over to a "master"-Controller. Maybe some statistical stuff as well (mean temperature, dTemp/dTime and the like). The 7500 cycles mentioned above should be suffice for the math.

thats why i dont want to waste them. the real issue is just that the bit pattern on the bus shows more (or less) bits than what it is supposed to and from the code i can not get why it behaves that why. though i think that who ever takes a look at the code should easily see that i am somewhat proficent in writing code so its not that that is a problem...

DS18B20 is not the sensor for you, it's to slow you had to find another sensor!

@Carlmikael i have to use it. this how the Setup is no matter if you like it or dont. i have a half running Code for reading and writing the bus and an as far as i can test it with not working baselayer a working toplayer Code to read the scratchpad and thus the temperatures. provide helpful feedback or dont give any at all. btw the dynamics of temperature-related systems are low (i mean really really slow) so a slow sensor on a slow bus with a slow processor is absolutely fine

Sorry can´t help you.

I managed to find the bug and fix it.
I was missing that after the reset pulse the master must be in RX mode for atleast 480us no matter what, even if the presence pulse did occur and even if it's rising Edge did appear already. This mistiming did lead to the missing bits that were corrected with sending more bits until now (which in turn lead to the extraneous bits later on in the transmission).


text:
H-Bridge vs Motor shield for the arduino
Assuming we wish to control a small toy car with an arduino - meaning spinning the right and left wheels forward and backward and being able to break and control the speed, where each wheel has it's own engine (but of course two engines on the same side will run on the same speed and direction).
We saw we have two main options - Buying and wiring up a H-Bridge or buying a motor shield (which is based on one).
Are there any advantages for using a motor shield?
Thanks in advance.

The shield is just plug and play. The bare H-bridge requires a bit more work. E.g. you'd have to add some capacitors. You can look at the schematic of the motor shield to see what other components you need (not much).

If I were a beginner, I'd go with the Motor shield.
I'm even personaly using the one from DfRobot, which as @Gerben said, is just plug and play.
It also allows you to select the input power for the motors, which can be either from the 5V Arduino pin or from an external battery. This is pretty convenient if you need more than 5V to power up your motors. It can also support 2A of current draw, which is more than enough for small arduino toy cards.
Here is the shield: https://www.dfrobot.com/index.php?route=product/product&product_id=1180&search=2A&description=true

Thank you (and Gerben), I've decided to go for the motor shield, also because it allows me to see the current the motor is using so I can easilly detect whether it's stuck or blocked by something.

Glad I could help :)

While not unworkable, an L298 based board like that, or any with a bipolar bridge, is a relatively poor choice for a battery powered device as there will be substantial loss across the transistors (essentially one of your cells will go just to that).  MOSFET based bridges such as the TB6612FNG work much better with low voltage supplies, and are sold on modules as well.

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


text:
datalogging sampling frequency bottleneck
My datalogging system which consits of the Flora, RTC, SD card breakout board, LSM9DS0 sensor is shown in the picture below;
https://www.dropbox.com/s/d8pwcn59nq11lzs/2014-11-25%2012.26.56.jpg?dl=0
The sampling rate/s is capped at 30 when writing into the sd card. If I disable the sensor and only save the time it goes up to 65. Writing into the serial interface rather than the sd card makes the rate goes up even higher at 127. for my application I need at least 100 samples/s. I am thinking the sd card is the problem after making the tests mentioned. The flora clock at 16Mhz is surely able to provide a higher sampling frequency. After checking the sensor datasheet and library I haven't found any limitation either. any input on this issue?

We can't help much without any code.

What sd card model do you use? Write performance varies a lot between models.

SD cards have a lot of intermittent delay.  To stream to them well, you need to buffer a full sector worth of samples to write at once, and have spare buffer memory to hold incomming samples across the maximum expected SDcard delay until you can write to it again.  You will need a primitive form of multitasking, even if as simple as collecting your samples in an interrupt.

Add some debugging code that writes "Serial.println( millis() )" before and after the SD card write so you can figure out how long it's really taking (is that really the bottleneck?). Then make a short demo program that demonstrates just the bottleneck, post it here and let us help you make it better.

First, based on my experience with similar hardware, something about the sd card I/O stinks: it should be plenty fast enough. Using a class 4 (cheapo) sd card I've seen a 16mhz AVR do a FAT filesystem open for appending, write a new record of maybe 70 characters and close the file, all a few hundred times per second. This was with the Arduino "SD" library apparently written by Sparkfun in 2010 and improved by Adafruit sometime later.
Maybe the I/O library you're using is dog slow? Another possibility is that your SD card has a lot of files on it and something about directory (folder) traversal during an open is the bottleneck? (my experience is with just a few files on a given sd card)
But you could try buffering N samples so each sd card write records N samples.
If you do this, don't forget to "flush" any remaining samples when you go from "sampling" to "not sampling" modes, if that's possible. That is, if something is telling the thing 'start', then 'stop', part of the response to 'stop' is to get the N-m buffered samples written out to the sd card.

I have used Sparkfun's OpenLog as I have also found the SD library slow when writing many small samples.  It lets you log directly from the Serial connection, so you should be able to get at least the 127 samples per second.  You may also try increasing the baud rate, especially if you are using outputting to Serial.


text:
Controlling water temperature accurately
I have following setup:

Arduino Duemilanove
Small water heater connected with optical relay (PWM is ok)
Waterproof DS18B20 temperature sensor
Unknown amount of water (but temperature sensor and heater are always underwater).

How can I accurately control water temperature, based on temperature sensor readings? By accurately, I mean up to accuracy of temperature sensor (in this case, ±0.5°C). Everything should run on Arduino, so no additional data storage or processing power is available. For debugging, I can obviously use computer.
I have tried running PID, but it seems really hard to

Avoid overshooting - going over target temperature either initially, or when (cold) water is added
Stabilize properly after adding cold water.

Did you tune your PID, or were you just using standard values?

I tried to tune PID parameters with various 'how to tune PID' guides, with no luck. I also tried PIDAutotune, but couldn't get anything better out from it. I'm not saying PID could not fit to this.

With water heating, you are going to have a lot of inconsistencies. Where is the heater in your tank relative to the temperature probe?

You'd probably have to add something that mixes the water to homogenize the temperature throughout.  Then you'd have to take into account the thermal properties of your heating element, how long it takes to cool off after disabled, etc... It is dependent on how much water is in the system as well.  If you can control the temperature of the heating element, that would go a long way.

Not part of your issue ATM, but worth noting: Don't confuse accuracy, precision, and repeatability. Accuracy means how close the reported temperature is to the actual temperature. Precision is the smallest difference the device can distinguish (.0625 degC for DS18b20). Repeatability is how much reported measurements of the same temperature vary from one another. The last two are of more concern than the first. Even with +/-0.5degC accurate sensor, you could still hold temperature to within (or at least distinguish differences, which is a necessary condition) of a few 1/16ths degC....

... as long as you control or filter electrical noise, the sensor is repeatable to a 16th, and your system otherwise has the ability to maintain the temperature. Good averaging may well bring the repeatability well below 0.5 degC.

You need to know the response time of your system and the repeatability of your measurements to characterize your data (establish confidence). I suggest taking samples and average them before turning the heater back on.
Imho, water will not happily stay within 0.5°C. Can you allow for coarse and fine modes? Use a higher PWM for great differences and then lower PWM for when close to target.
Once homed in on your target, there are a few means you can try to improve temperature stability. While pre-built things like PID work for many, I normally implement functionality like this manually.


text:
Unexpected Timer Conflicts (Uno)
I've been working on a project (Arduino Uno: Atmega328) that implements a gyroscope (which is used with the LSM9DS0 spark-fun library) that is communicated with through I2C and uses a Servo library. Due to a timer conflict with the standard Servo library and another library I've been using, I am now using the ServoTimer2 library which obviously uses timer 2. This is when the problem started.
When I call the attach() function of the ServoTimer2 library, it allows the gyroscope to be read a few times and then the gyroscope feed cuts out. I am using the serial monitor (115200 baud) to read the gyroscope data. The Serial monitor is not the problem because it uses a UART interrupt for Serial.
To fix this error, I modified the ServoTimer2 library to run on Timer0 (Yes I know this handles the delay functions, but they are not needed in my case), which is now called ServoTimer0. This modified version of the library works perfect except for when I attempt to use it with the gyroscope. The same problem still arises though. I've traced what causes this failure down to one line of code that sets up the interrupts:
TIMSK0 =  _BV(OCIE0A) //This is in my own modified version of the library.

That is what causes it to fail. I believe the AtMega328 can run I2C natively, and my thought is that this native running somehow uses these timers.
Any solutions?
Thanks

The I2C (Wire) functionality does not user Timer0. TIMSK0 = _BV(OCIE0A) //This is in my own modified version of the library.: That line enables the output-compare interrupt. Why are you enabling that? Do you have a handler to handle that interrupt? That would look like this: ISR(TIMER0_COMPA_vect) { // some code }

Please post your code. The line you mention needs the TIMER0_COMPA_vect interrupt vector to be supplied or it will crash.


text:
Communication between two ESP32, USART vs RS232 with MAX3232
I have two ESP32 that are communicating via USART (TTL) on the Serial2.
The TX2 pin of ESP_Alice is connected with the RX2 pin of ESP_bob.
The RX2 pin of ESP_Alice is connected with the TX2 pin of ESP_bob.
(left on the image)
It works, but it's a noisy channel and I need to increase cable length.
I bought two MAX3232-based boards and I connected them as in the right scheme on the image:
TX2 RX2 between ESP and MAX3232 boards are connected directly (on the TTL SIDE), the TX and RX pin of the two boards (on the RS232 side) are crossed.
Boards are powered with 3.3 V and GND pin connected to ESP_Alice
It does not communicate at all (same program that works correctly when the two boards are connected directly with the TTL USART).

What am I doing wrong here?

On the right side, 3.3v and GND, and GND on the second board, are connected to the wrong pins.

try to esp tx <--> rx max3232 And esp rx <--> tx max3232

@EdanLee Look at the arrows on the PCB: TXD of the MAX3232 boards is an input, so  connecting ESP's TX here is correct.

You seem to have the polarity of the supply to the RS232-TTL boards reversed.
There is a + symbol next to the pads that you have the GND connected to.
It should be like this:

Sorry, I messed up with the second image that I meant to use as an 'enlargement' of the first one. The wiring is already connected as you suggest in your image.
I'll try to update my question with your image


text:
Arduino Nano TX and RX LEDs Not Lighting Up During Upload
I'm encountering a problem with my Arduino Nano board. When I attempt to upload sketches to the board using the Arduino IDE, only the Power LED lights up, and the TX and RX LEDs remain inactive. I've tried several troubleshooting steps, including reinstalling drivers, using different USB cables, and trying different USB ports on my computer. Despite these efforts, I haven't been able to resolve the issue.
Board Details:

Arduino Nano with ATmega microcontroller
Power LED is lit when the board is connected
"L" LED blinks rapidly during upload
TX and RX LEDs are not lighting up during upload

Troubleshooting Steps Taken:

Reinstalled Arduino IDE and drivers
Tried multiple USB cables and ports
Verified COM port selection in Arduino IDE
Checked USB-Serial converter chip for damage

I'm reaching out to the community for help and guidance. Has anyone else encountered this issue? What further steps should I take to diagnose and resolve this problem? Any insights or suggestions would be greatly appreciated.

does the program upload correctly?

Were there any error messages during upload? Have you tried programming another Arduino using the same cables & IDE (even an Uno, in case you don't have another Nano)? Can you tell whether the Nano got programmed? If you have an Arduino that is already programmed, and talks to the serial port, have you tested whether you can read or write to that one from your IDE's serial terminal?

There are many varieties of "Nanos" with different processor types which may require a special configuration of the IDE, selection of a bootloader type etc. Here, for example, is one using a "near" clone of the ATmega328P chip: https://robot-r-us.com.sg/p/lgt8f328p-more-capable-than-arduino-nano-v3-0. Can you provide a link to the one you have purchased?

They many times will not light because of the bit pattern being sent and the short time the bit is active to light the LED. If it is uploading code without errors you are good to go.  Quick test, If not try another Arduino and see if it uploads or not. If not it is your computer or a bad cable otherwise it is a bad Arduino.


text:
Why does a Piezo Buzzer not require a PWM digital pin (Gallileo Gen2)?
According to my current (poor) understanding, only the PWM pins (with the ~) among the digital pins (ignoring Analog pins) can be passed to analogWrite().  I understand the servo therefore - since interfaced by a variable voltage signal - must be connected to such a PWM pin.

Why is the humble Piezo Buzzer not bound to this condition?
Why can I connect the buzzer to a digital pin that is not PWM (and so should only be able to output binary LOW, HIGH voltage at some consistent frequency) and still achieve a varying sound by calls to the tone() function?
Surely under the limitations of being digital and non-PWM, the pin could only cause some consistent buzzer frequency?

I'm reading online that the Piezeo Buzzer does indeed require a PWM digital pin, but I can connect it to any digital pin on my Galileo gen2 and have it function seemingly correctly (differing tones produced).
Also, since slightly relevant; what exactly is the difference between a PWM digital pin and an analog pin, in terms of output? They both use PWM, right? Why can't even a PWM digital pin read analog input?

The PWM pins do hardware PWM. You can however also have the software do PWM. I guess that is what the library you use does. The analog pins are for reading an analog voltage between 0 and 5 volts. This has noting to do with PWM, besides the misleading name analogWrite arduino uses.

Why does a Piezo Buzzer not require a PWM digital pin?

Tone() uses the microcontroller's hardware timers to control the related code function but do not use the hardware PWM features. The timer can be assigned to any pin that has a digital output capability.
Tone() sends a "rail to rail" square wave (50% duty cycle) to the selected pin
Slightly more lower level information here under Ugly details
They say:

The library uses the hardware timers on the microcontroller to generate square-wave tones in the audible range.
You can output the tones on any pin (arbitrary). The number of tones that can be played simultaneously depends on the number of hardware timers (with CTC capability) available on the microcontroller.
ATmega8: 2 (timers 2, and 1)
ATmega168/328: 3 (timers 2, 1, and 0)
ATmega1280: 6 (timers 2, 3, 4, 5, 1, 0)
The timer order given above is the order in which the timers are allocated. Timer 0 is a sensitive timer on the Arduino since it provides millis() and PWM functionality.

... what exactly is the difference between a PWM digital pin and an analog pin, in terms of output? They both use PWM, right? Why can't even a PWM digital pin read analog input?

There is a misconception there.
Analog pins are capable of Analog INPUT functionality .
"PWM" output is known as "analogWrite" but is actually a purely digital function and is not related to whether a pin has analog read functionality.
PWM out = analogWrite is available on pins which have associated PWM hardware.
The actual signal is a "rail to rail" square wave with a mark:space (on:off)that varies.   Filtering the PWM produces DC at the average DC level. PWM range is 0 to 255 (8 bits)

Is there a difference in the square-wave produced by a digital pin via timers and that of a PWM digital pin? Why is any PWM hardware needed if timers can emulate analog output on all digital pins? Why can the servo not be operated from a non-PWM digital pin by a square wave produced using timers?

@AntiEarth, the PWM can be set up to do their thing, and then left to it (indefinitely, or until the settings are changed). To change any other pin from high to low, or from low to high, requires attention at the exact time of the transition.

@RussellMcMahon, so it's a matter of computational intensity (or at least, scheduling)? Why still is the servo bound to hardware PWM?

@AntiEarth AMADANON's answer would be correct in some systems but not here (probably). I'll check the hardware features of the uC before saying too much more, but whereas AMADANON is suggesting a pure software based answer, the tone() command uses system timers. It appears that the timers can be assigned to any pin. | Re PWM versus square wave. "Square wave" unless specified otherwise is assumed to mean a rail to rail waveform with 50:50 mark space ratio.  A servo's position control requires a variable mark:space ratio. The PWM does that, the timer does not. Note that ALL digital capable ....

.... pins are capable of outputting PWM under software control. For a single channel this is trivially easy. But, with due care and knowledge and skill [tm] you could probably have every output providing PWM by using the millis() or micros() functions. These allow you to run in an uninterrupted loop while checking the timer "on the fly". You can use this like a "round robin" scheduler with each PWM having its own timing register to compare with micros() result OR all channels could be combined with the routine waiting until each way-point arrived and changing relevant output bits. ....

Super rough pseudo code example of former. E&OE! : |// say 32:68 PWM; int mark = 32;  int space = 68; thenM=micros(); MainLOOP { IF thenM = micros()  { setPWMhigh(); thenS = micros() + mark;} IF thenS = micros() {setPWMlow(); thenM = micros() + space;}  Other stuff ... ; } // end of main loop
|| This does not handle micros() rollover and has other issues but shows general principle. Simplistically you could run N of these in a loop independently. Size of N depends on time taken clock speed etc.

The timer isn't "connected" to an arbitrary output pin. The timer is set to trigger an interrupt at a set frequency, and the interrupt handler uses digitalWrite() (or equivalent) to toggle the pin.

@Osvein Your comment does not relate to my answer - maybe you intended to post it against the original question? | The word 'connected' - which you quote and comment on, does not appear in my answer. | You mention an arbitrary output pin -  as does my answer. I explain the relationship between output pins and timers. It's not at all apparent that your comment relates to this. it PERHAPS adds a little as a comment on the OP's question. If you think that you have something useful to add I suggest that you create a new answer, or transfer your comment to the original post.

@Russell I was referring to your comment "it appears that the timers can be assigned to any pin". There also seems to be a misconception here that timers and PWM are separate parts of the hardware - PWM is just one of several different ways to configure the timers to generate a signal on the timer's output compare pins.

@osvein My answer, which is my definitive statement of what I'm stating. including viz " ... The timer can be assigned to any pin that has a digital output capability ...", which is true. The slightly more general comment in the comments re "any pin" is correct enough in context. IF a pin CAN be a digital output a timer can be assigned to it when using the TONE() command (which is what the question was and is about.). ...

@osvein ... Re misconceptions -> I dont see any. You seem to be straining at finding somewhat obscure points in the fine detail which
THE ANSWER as it is now and has been since 1 Feb 2015 seems to address the query without confusion, for most people, anyway.
If, 4 years on, you think that a better answer can be given, you are welcome to supply one. [Please do not attempt to modify my one to say something other than it already says].

@Russell I wasn't trying to refute your answer, I was just adding a piece of detail that I think is necessary to understand the difference between the implementation of analogWrite() and tone(). Re misconception, you seemed to imply that the duty cycle of a PWM signal was not controlled by the timer - "The PWM does that, the timer does not"

The signals that you mention are of different nature.
1) The PWM signal is a digital signal (output voltage is either ground or supply) that is modulated in time. It has a fixed period and its duty cycle varies from 0% (always ground) for value 0, to 100% (always supply) for value 255, the middle value being a signal that switches between ground and supply with 50% of its period at ground and 50% of its period at supply.
2) A servo is controlled by a signal that has a fixed period of 20 ms and a pulse of varying duration (between 0.5 to 2.5 ms).
3) A tone for a buzzer has a variable period (or variable frequency - both being linked by the equation frequency * period = 1). The period is audible if is is between 0.06 ms (15 kHz) and 60 ms (15 Hz) (the exact value change from person to person. If the frequency is higher than 15 kHz, you are entering ultra-sonic.
All three signals are digital in their voltage and modulated in time. But the modulation is very different as indicated above and the Arduino driver is therefore different for each one.

You don't explain how these differences make it possible to generate a tone on an arbitrary output pin. Truth is all of these could have been made to work on any pin with slightly less accuracy using timer interrupts, but the Arduino creators chose not to for reasons unbeknownst to me.

@osvein There can be a good reason: The MCU has specific hardware to support PWM output, it is therefore more efficient to use this hardware instead of interrupts when possible. But the way a PWM hardware is controlled is not ideal for some applications (like tone generation). The second part of your comment is on coding preferences, and that's to be discussed with the Arduino coding team.

The hardware timers can do tone generation directly on the output compare pins without interrupts just as well as they do PWM. See the datasheet.

Yes, sometimes, but you do not use a PWM to do tone generation. It's another way to use the timer hardware (and in some processors, these are separate timers).

but in the case of the Arduino, they're not separate hardware. It can use the exact same hardware (the same output compare pins on the same timers) for PWM and tone generation.


text:
Arduino NANO RF reciever and Digispark Attiny 85 transmitter issues
I am trying to send RF signal from Digispark Attiny 85 (this one) and receive the signal with Arduino NANO V3.0 ATmega328 (this one). Transmitter and receiver are STX882 and SRX882 (these). Library used is RCSwitch.h.
The goal is to light up the external LED connected to NANO when I press the button connected to Attiny.
I am not skilled in Arduino stuff, but I have really tried to figure this one out on my own and find answers online. Sorry if this question does not belong here. Anyways, here is the problem:
// NiceRF 433MHz reciever SRX887

#include <RCSwitch.h>

RCSwitch reciever = RCSwitch();

void setup() {
  Serial.begin(9600);
  reciever.enableReceive(2);
  pinMode(7, OUTPUT);
}
void loop() {
  if (reciever.available()) {
    int size = reciever.getReceivedValue();
    if (size == 0) {
      Serial.print("Unknown message"); //probably kinda useless line
    }
    else {
      digitalWrite(7, HIGH); // Turn on the LED
      delay(1000); // Wait for 1 second
      digitalWrite(7, LOW); // Turn off the LED
      delay(1000); // Wait for 1 second
    }
    // reset of module to be able to recieve next message
    reciever.resetAvailable();
  }
}

I understand the code like this: The Receiver will check if it receives anything and if so, it will light up pin 7 and therefore the LED connected to the pin 7 will be on.
Now for the Digispark Attiny 85 transmitter:
#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  pinMode(1, OUTPUT);
  mySwitch.enableTransmit(2);
}

void loop() {
    mySwitch.send("000110110001010100010001");
    digitalWrite(1, HIGH);
    delay(250);
    digitalWrite(1, LOW);
    delay(250);
}

I found this piece of code online and did not modify it. If I understand this correctly, it is not important, what the message is, but if it is sent at all. The receiver should light an LED up in every time it receives the signal.
I am confident that the wires are connected correctly.
Do you have any idea why this setup does not work?

Edit: As @jsotola suggested, I tried to make a circuit that will simply send HIGH signal to transmitter module, receive this signal at receiver module and if arduino board recognises that there is HIGH signal coming from receiver, it will send HIGH signal to the LED pin and LED would light up.
For this experiment, I switched Digispark for generic Arduino UNO ATmega clone to make things simpler. There is no library used in this example.
TRANSMITTER CODE:
const int TPin = 10;

void setup() {
  // Initialize the LED pin as an output
  pinMode(TPin, OUTPUT);
}

void loop() {
  // Turn on the LED
  digitalWrite(TPin, HIGH);
  delay(500); // Wait for 1 second

  // Turn off the LED
  digitalWrite(TPin, LOW);
  delay(500); // Wait for 1 second
}

RECEIVER CODE:
// Pin connected to the LED
const int ledPin = 7;
// Pin connected to input signal
const int inputPin = 2;

void setup() {
  // Initialize the LED pin as an output
  pinMode(ledPin, OUTPUT);
  // Initialize the input pin as an input
  pinMode(inputPin, INPUT);
}

void loop() {
  // Read the state of the input pin
  int inputState = digitalRead(inputPin);

  // Check if the input pin is HIGH
  if (inputState == HIGH) {
    // Turn on the LED
    digitalWrite(ledPin, HIGH);
  } else {
    // Turn off the LED
    digitalWrite(ledPin, LOW);
  }
}

TRANSMITTER SETUP:

(note that there is an antenna soldered to the transmitter module, but it is out of frame) The LED is simply for me to see when a signal is send to the transmitter. (Blinks in intervals as intended)
RECEIVER MODULE SETUP:
Pins on receiver from left to right (form orange to green wire) are GND, CS, DATA, VCC.
GND and CS are connected to the GND pin on Nano, VCC is connected to the 5V pin on Nano (this receiver works on 5V and does not require the usual ~3.3V). DATA is connected to the D2 pin on Nano.

The LED is simply connected to GND and pin D7 on Nano (out of frame) and does light up even if I touch the pin. LED stays off when D2 is grounded.
This setup does not work correctly and I have tried it for different Receivers/Transmitters (i have multiple of each). Once again thank you for all your suggestions. Does anyone have any idea what do I do wrong in here?
Thanks!

If you open the serial monitor what do you see?  Is it printing "Unknown message"?

you have not said that you verified the LED ... start with that ... write simple code that blinks the LED

the two radio modules act as a wire ... set the output data pin high and the receiver data pin should follow ... write a simple sketch to "blink" the output every second ... write a simple sketch to light an LED when receive pin is high, turn off LED if the pin is low

Thank you all for help. @Delta_G when i open the correct (9600) serial monitor, I do not see anything. If I try to SerialPrint any other message paralel to the RF transmit code it does work and print the test message.

@jsotola I am sorry that I did not mention it before, but the LED is checked and works correctly. About your other comment: I have tried to make a new circuit, that will just "blink" every second as you have described. However, I does not work and reciever does not recognise any sent signal. I will post new code and photos in the original post.


text:
Run Arduino Uno with battery AND use 5V output
Newbie here: I built a working binary clock with my Arduino UNO R3, see Picture 1. From my understanding the power supply for the Arduino itself is via USB, and I use the 5V output to supply power to the switch. Now, I would like the Arduino to run on battery and keep using its 5V power output - instead of only when it is connected to the PC.

From what I gathered on the internet, e.g. this page, I can simply connect the + end of my battery to the Vin port and the - end to GND. However, none of the pages I found deal with what to do with the "surrounding power infrastructure". Can I just keep it as is and use the wiring as in Picture 2 (USB is disconnected), i.e. is it safe to connect my 9V battery now? Or is there a better alternative?

Sorry for the beginner question. I am having so much fun learning with the Arduino (blasted through half the starter kit project handbook in just two days -> this is my variant of the digital hourglass) and don't want it to go up in flames already.
UPDATE: After the answers suggested that my idea should work, I tried it and, indeed, it works OK. I am getting a lot of Arduino resets/restarts though. Thanks for the replies!

"I am getting a lot of Arduino resets/restarts though."  Are you sure?  Do the unexpected events happen with using the switch?  If so, consider the switch bouncing causing the unexpected events.

These events occured without me pressing the switch. What do you mean by "switch bouncing"? I attributed this to loose contacts due to my unprofessional wiring or to the battery not providing sufficient power.

Almost all mechanical switches bounce slow enough that the SW will detect many events.  This makes it difficult for people not familiar with this problem to make use of switches in combination with software.  I think I see where you simply inserted the battery wires into the Arduino header.  It may help if you pushed a pin into the same hole to more securely connect the battery.  Or use the proper connector.

It is almost always better to add a schematic to your question. Backwards engineering from a picture can be confusing at times and lead to incorrect assumptions.
What you want to do appears to be possible. It looks like you are injecting 9 Volts positive at VIN (Pin 8 of the POWER header).  Examining the Arduino Uno R3 schematic here we see the VIN net connected to the input Pin 8 of the POWER header and also to the input side of the 5 Volt regulator (NCP1117ST50T3G).  This distributes the 5 Volts to the Atmel processor (appears to power the LED directly) and to the external switch which is assumed to be normally open but when closed connects to a 10Kohm resistor to ground.
The total current needed by external devices connected to the Arduino Uno R3 5 Volt regulator should be considered in such a design.  The NCP1117ST50T3G data sheet here state the regulator can handle in excess of 1 Amp (or 1000mA).
Assuming the LEDs take at most 20mA each and a worse case of all LED in the on state, that is 6 x 20mA or 120mA.  Also, when the switch is closed there is a current path from 5 Volts to ground through a 10Kohm resistor.  Using V = A x R we see that A = V / R = 5 / 10000 = 0.5mA when the switch is closed.  So the total current the external devices might use is likely no more than 120.5mA.  This is far less than 1000mA (the upper limit of the Arduino's 5 Volt regulator) so appears well withing safety margins.
However, an Alkaline 9 Volt battery only contains about 550mAh.  Ignoring the current it takes to run the Arduino Uno R3, we see that dividing the worst case external current demand of 120.5mAh into 550mAh we get 4.6 hours of use.  An Alkaline AA 1.5 Volt battery contains about 2000mAh.. You would need 6 AA 1.5 Volt batteries in series to generate 9 Volts. But they should last about 4 times longer.

Sorry @EdgarBonet, pushed the button a bit eary.  I'll add more text to clarify that (i.e. Pin 8 of connector such-n-such on the schematic).

Thanks, I would upvote your answer but it seems I haven't got enough reputation. I will try and add a schematic next time. I was also wondering about the different GND pins on the Arduino. Are they connected, i.e. could I alternatively plug the - end of the battery into my "ground bus line" on the breadboard? I can't tell from the schematics you linked.

That's actually a good question. Usually all grounds are connected together. In this case ping 6 and 7 of the POWER header and pin 7 of the IOH header are connected together. In general, all grounds should be connected back to one point which should be substantial enough to handle the total current and then some. However, in this case none of the devices draw enough current to be much of a concern. What you have should work.

The voltage regulator in an Arduino might be rated at 1 amp in theory, but they don't have proper heat sinks, and I would expect the linear power supply to overheat in fairly short order under anywhere near that load. (Linear power supplies work by converting excess voltage to heat. So a 9V source dropped down to 5V needs to burn 4V as heat. At one amp output, that's .8 amps converted to heat, assuming my math is right. )

True, and even the 1 Amp talked about in the part spec also considered that part is kept at a reasonable temperature. But likely this project will require a quarter of that.  Maybe even less. Low current / battery operation is difficult even for experienced engineers.  Using a battery pack which supplies the necessary 5 or 3.3 Volts and avoiding the linear regulator is an option (as suggested by @Edgar Bonet). Or switching to a more efficient switching (buck) power supply is another (as you (@Duncan C) suggested).

You could certainly use a 9V battery into the VIN port on your Arduino, but the built-in power supply uses a "linear voltage regulator", which is quite inefficient. If your goal is long battery life you'd be much better off with a buck style power supply or a switching power supply. Those are a LOT more efficient.
You should be able to find modestly priced power supplies built for Adruino online that are a lot more efficient than the built-in supply.
(And as mentioned, 9V batteries have a very small capacity. 6 AA or even C batteries would last a lot longer.)

Yes, that should work, albeit inefficiently: for every milliwatt of power
consumed by an LED, you will have roughly 0.7 mW dissipated in the
series resistor, and 1.3 mW dissipated in the Arduino's voltage
regulator. Given the low capacity of 9 V batteries, I doubt your
clock will run for very long.

Thanks, I would upvote your answer but it seems I haven't got enough reputation. Are there any quick and easy improvements that would lead to a longer uptime?

@Krawabbel: You may use higher capacity batteries, as explained by st2000. Or you may build a breadboard Arduino, run it at 8 MHz, and power it from unregulated 3 V (a pair of C- or D-sized batteries) for maximum power efficiency.

By "breadboard Arduino" you mean something like this? Do I understand it correctly that the idea of using only 3V would be to basically run it at the lowest possible voltage and/or current where the LED is still working? Sorry for the dumb questions, I only took one electrical engineering course at university.

@Krawabbel: Yes, that “breadboard Arduino” tutorial is what I was referring to. The idea of running from 3 V is to reduce the energy loss in the resistors, and completely remove the loss happening in the voltage regulator by removing the regulator itself.


text:
Push button issues
I have been using https://wokwi.com/ to learn Arduino and I am having a problem that seems to be happening no matter what I do. I am trying to set up a push button and an LED. The end goal here is to set it up so that when I tap the push button down and release it that the LED blinks like a turn signal in a car. When I push it down and release it again, the LED should stop blinking. I have tried tons of different code, even using code copied and pasted directly from Arduino's website. What ends up happening is that the button is unreliable. Sometimes the button will click, other times it won't register. It is very bizarre behavior. I read about the bouncing effect but any code I put in to ignore bouncing doesn't seem to have any effect on the system. Why are push buttons so unreliable? I know in real life they aren't because I am able to type this using presumably push buttons on my keyboard. What am I doing wrong??
Here is an example. The push button is totally unpredictable. Why is it behaving like this?

int state = 0;

void setup()
{
  pinMode(9, OUTPUT);
  pinMode(6, INPUT);
}

void loop()
{
  if (digitalRead(6)) {
    state = !state;
  }
  digitalWrite(9, state);
}

the problem is on line 20

I am counting 15 lines

no other guess was possible without seeing the code

you have a logic error in your code ... the code is similar to if it's dark outside, then flip the light switch ... you'd be turning the lights on and off all night long, and the light stands a chance to be left on all day

    state = !state;
  }``` Is that correct?

think about it ... if the button is pressed, then state changes ... this happens 50,000 times per second, once at each iteration of loop()... state will flip back and forth until you release the button

you need to "remember" the state of the button between iterations of loop() ... only if the button state changes, then update the state of the LED

You've got the button wired wrong.  Your resistor is inline with the signal going to the pin.  It should be going from the pin to 5V.  The button should be wired directly to the pin and ground.  Or you can use INPUT_PULLUP in pinMode instead of INPUT and eliminate the resistor entirely.
Your code should test for the button pin being LOW, not HIGH.  When you press the button it will read LOW.  When unpressed it will read HIGH.  This is the normal way that buttons are wired up.
Also note that your loop() function will repeat thousands of times per second.  As long as you still have your finger on the button it will keep cycling the state.  That means that every time you press the button, the state gets cycled a few tens of thousands of times and there's no real way of knowing which state it will be on when you finally get your finger off the button.
You should look at the "State Change Example" in the Arduino IDE.  It shows how to keep track of the previous state of the button so you can react once to each press.

Do you know what I can Google to find that State Change Example? Having trouble finding it. Thanks for the explanation

I think Delta_G means this one: https://docs.arduino.cc/built-in-examples/digital/StateChangeDetection

@wgm, open the Arduino IDE.  Go to the File menu.  File->Examples->Digital.  State Change Detection will be towards the middle.  If you google "Arduino State Change Example" you will be flooded with information and tutorials.  Surely one of them is your speed.

Do you know what I can Google to find that State Change Example - see my website: http://gammon.com.au/switches  - it also talks about transitions

This is my first answer on this platform so pardon my mistakes :P
I too faced this problem. I don't know if my answer will be still helpful but I did find the solution to this problem. Please refer to how I have plugged in my buttons -

Ignore everything other than the buttons. They are not relevant to this question. All black wires are going to gnd pin.
Code for the buttons -
#define btnPinYellow 6
#define btnPinGreen 7
#define btnPinBlue 8
#define btnPinRed 9
#define btnPinBlack 10

void setup() {
 pinMode(btnPinYellow, INPUT_PULLUP);
 pinMode(btnPinGreen, INPUT_PULLUP);
 pinMode(btnPinBlue, INPUT_PULLUP);
 pinMode(btnPinRed, INPUT_PULLUP);
 pinMode(btnPinBlack, INPUT_PULLUP);
 Serial.begin(9600);
}

By defining the button input pin to INPUT_PULLUP, the pin is now in an active HIGH state. When we press the button, the button will go to LOW state. This should also remove the button's erratic behaviour which you were encountering. You can test this using the serial monitor.
Hope this solves your problem ^_^


text:
Rotary Encoder with interrupts - erratic behaviour
I'm trying to change my working rotary encoder code (stolen from here) to an interrupt-based code on my Mega2560. The trouble is that the result behaves very erratically, even though the physical setup is exactly the same as the working code. The determined encoder incrementation is jumping back and forth, when monotonically turning in one direction.
The interrupt-based code currently looks like this:
const long int baudrate = 115200;

const int debounceTime = 5;  // time in ms, in which the interrupt is not reacting. Starting at the first trigger of the switch.

const int clk1Pin = 19; // clkpin (signal A)
const int dt1Pin = 18; // dt pin (signal B)
const int sw1Pin = 4; // switchbutton pin

volatile int encoder1Val = 1500;  // what i want
volatile int firstSwitchTime = 0; // helper variable for debouncing
volatile int cnt = 0; // counters for debugging
volatile int cnt2 = 0;
volatile int cnt3 = 0;
volatile int cnt4 = 0;

volatile bool switchlock = false; // flags for debouncing and readout flow control
volatile bool readoutflag = false;

int cycletime;

void setup() {

  // Set up pins
  pinMode(clk1Pin, INPUT_PULLUP);
  pinMode(dt1Pin, INPUT_PULLUP);
  pinMode(sw1Pin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(clk1Pin), encoder1Decoding, CHANGE);

  Serial.begin(baudrate);
}

void loop() {

  // only [print the data] and [release encoder1Val incrementing lock] after the debouncing period has passed
  cycletime = millis() - firstSwitchTime;
  if (cycletime > debounceTime) {
    readoutflag = true;
  }

  if (readoutflag == true && switchlock == true) {
    switchlock = false;
    readoutflag = false;
    Serial.print(encoder1Val);
    Serial.print(",");
    Serial.print(cnt4); // Total amount of interrupt calls between readouts
    Serial.print(",");
    Serial.print(cnt); // Amount of effective interrupts
    Serial.print(",");
    Serial.print(cnt2); // Amount of "increment branch" calls
    Serial.print(",");
    Serial.print(cnt3); // Amount of "decrement branch" calls
    Serial.println();
    detachInterrupt(digitalPinToInterrupt(clk1Pin)); //ensure atomic action
    cnt = 0;
    cnt2 = 0;
    cnt3 = 0;
    cnt4 = 0;
    attachInterrupt(digitalPinToInterrupt(clk1Pin), encoder1Decoding, CHANGE);
  }
}

void encoder1Decoding() {
  cnt4++;
  // if outside of debounceTime: change encoder1Val
  if (switchlock == false) {
    switchlock = true;
    firstSwitchTime = millis(); // remember the first time, the interrupt changed in a bouncing group
    cnt++;
    // .. decoding encoder ..
    if (digitalRead(clk1Pin) == digitalRead(dt1Pin)) {
      encoder1Val++;
      cnt2++;
    } else {
      encoder1Val--;
      cnt3++;
    }
  }
}

It is relatively complicated for debugging reasons, as will become clear in a moment. When turning the encoder counter-clockwise, the resulting output is this:

Value, Total Interrupts, Effective Interrupts, Increment Branch, Decrement Branch:
1501,2,1,1,0
1500,33,2,0,2
1499,0,0,0,0
1500,1,1,1,0
1499,19,2,0,2
1498,24,0,0,0
1499,5,2,2,0
1500,0,0,0,0
1501,15,1,1,0
1500,16,2,1,1
1501,43,0,0,0
1500,3,1,0,1
1501,1,1,1,0
1502,6,1,1,0
1503,3,1,1,0
1504,2,1,1,0
1505,1,1,1,0

The values should increase monotonically. They don't, so what's happening?

The first readout makes sense: One successful interrupt call, one increment branch run, one value increase.
The second readout is already strange: two decrements, but only one less value?
The third is completely inexplicable: a decrement without the interrupt even being called.

I'm completely puzzled. Anybody got an idea where to start?
What I tried so far:

Searching the web. Seems to be a new problem.
Using the encoder without interrupts ("polling"). Works flawlessly, but is speed limited.
Explicitly analyzed the bouncing period of this rotary encoder using interrupts. Worked flawlessly. Result is: BouncingTime is mostly less than 5ms (very few outliers).
Plotted the data coming from clk and dt (x-ticks are 1ms, they're overlapping):

There is one bounce visible in the beginning, but the rest seems quite alright.
As I'm completely at a loss, any help is much appreciated!
Edit 2023-07-25:
The most important question is, why the ISR keeps on decrementing encoder1Val, even though i only turn in positive direction. This happens in all variants of the code. An absolutely stripped down version with the same behaviour can be found below:
void loop() {
  Serial.println(encoder1Val);
  delay(500);
}

void encoder1Decoding() {

  if (millis() - firstSwitchTime > debounceTime) {
    firstSwitchTime = millis();

    if (digitalRead(clk1Pin) == digitalRead(dt1Pin)) {
      encoder1Val++;

    } else {
      encoder1Val--;

    }
  }
}

Result:

1500
1494
1497
1502
1513
1515
1518
1515
1516

remove debounce code ... each bounce should produce a +1 followed by a -1  ... think about what happens if you ignore the +1

Your code seems to have lost some of  the basic simplicity of the original (non-interrupt version) which you linked but I guess it has grown during your debugging efforts. You haven't said if you are using a raw encoder or one with debouncing/filter circuitry such as here: https://www.aliexpress.com/item/1005002845325794.html. The one in your linked article appears only to have pullup resistors but no capacitors. Your software debouncing is handling only bounces from clk1Pin not dt1Pin.

@jsotola: I'm trying to prevent jitter in the output, as the signal will be transferred to servos.

@6v6gt: It is a simple one without debouncing afaik. I only use the pullup resistors of the Arduino. Do you suggest, I should add some capacitors? Only clk1 is debounced, as it is the only one with the interrupt attached. I will expand the code once using clk1 works.

@Malibu I'm trying to prevent jitter ... maybe something like this might work ... respond to A state change, then ignore any other A state changes until B changes ... basically, accept only the first clock pin transition for every data pin change

@jsotola: Thank you for the suggestion. Sadly it seems not to improve the situation. I have also added an edit to the question, because the most pressing question is: why does the code decrement the values, even though the encoder is only turned in one direction.

volatile int encoder1Val on a Mega is a 2 byte integer which you are updating in an ISR and reading in the loop() here Serial.println(encoder1Val);. This is a non-atomic operation and you could get unlucky in that the read operation is corrupted during a simultaneous interrupt. Temporarily suspend interrupts during which time you make a copy of encoder1Val then later print the copy.

Ok, thanks! I tried detachInterrupt(..); valuesafe = encoder1Val; attachInterrupt(..); Serial.println(valuesafe). The behaviour didn't change, though.


text:
ESP32 Shows Incorrect Input Voltage From Analog Pin
I have an esp32 WROOM-32 connected to a MQ9 gas sensor to GPIO35. Both are powered separately. measuring the output from the sensor directly using a multi-meter shows a constant reading of 0.145 V but the readings on esp32 shows 3.3V and if fluctuates too much.
The circuit:
MQ-9 AO -> voltage divider (using 1k and 2.2k ohm) -> ESP32 (GPIO35)
Sample Code:
void setup() {
  Serial.begin(9600);
  analogReadResolution(11);
  analogSetWidth(11);               // 11Bit resolution
  analogSetAttenuation(ADC_0db);
}
void loop() {
 int ADC = analogRead(35);
 float volt = (ADC * 3.3) / 2045;
 Serial.print("Volt : ");
 Serial.println(volt);
 Serial.print("Analog : ");
 Serial.println(ADC);
 Serial.println("");
 delay(1000);
}

Image of the error:

please do not post a picture of text ... post the text instead, same as the code

the circuit description does not say anything about a ground connection


text:
Is my SIM800L module burned?
I have troubles with powering my SIM800L module. When it was powered from Arduino board using LM2596 DC/DC step-down converter (which is used to lessen voltage to 4.1V), the module restarted every 10 seconds. I have decided to power it up from 9V battery using same converter.
After setting it all up, I have plugged in the wires and the module worked for around 15 seconds and then powered down (signal LED was not blinking). I have measured the voltage and it was around 7.2 VDC. I don't know how that can happen because I have not changed converter settings. I then set up converter to 4.1 VDC again, but module has not started. Also I tried to power it up with 3.3V and 4.5V but nothing changed. Is there any solution for given problem? Have I burned my module?

Since you have  tried to power it up with 3.3V and 4.5V but nothing changed, I think the SIM800L module is gone. If you want to bring another new SIM800L, it will be better to omit the buck module and use a 4V,2A power adapter like this: https://www.amazon.com/Mpkke-Supply-Replacement-Adapter-Center/dp/B07SBW8F1S
In case if you wanna stick to the LM2596, you have to keep in mind that the LM2596 module can overheat if it's not adequately cooled, causing it to shut down intermittently. You can design a board like this and add a heatsink to it.
https://www.pcbway.com/project/shareproject/_Buck_Converter_LM2596_bfb8ec50.html

You have most probably burnt the SIM800L module. When you were powering the buck converter- LM2596, from the Arduino, you didn't account for voltage drop hence the 4.1 volts was not the regulated voltage but rather the maximum the converter could give from a 5V input. Looking at figure 8 from the LM2596 datasheet gives a roughly .9v voltage drop at 25C and 1A load
When you connected the converter to 9V voltage it produced the actual voltage it was set for and this was excessive for the SIM800 hence it blew out.


text:
trying to switch input on my speakers via infrared using web browser but i have issue getting it working
ived tested the IR code with
https://github.com/wemos/D1_mini_Examples/blob/master/examples/04.Shields/IR_Controller_Shield/IRsend/IRsend.ino
and it works that way, but when i try to code it together with the web server, i get nothing, can someone explain to me what's wrong in my code? the webserver works fine, its the IR part i dont fully understand why its not working
#include <i18n.h>
#include "ESP8266WiFi.h"
#include "ESP8266WebServer.h"
#include <IRremoteESP8266.h>
#include <IRsend.h>
ESP8266WebServer server(80);

void setup() {
  Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY);
  WiFi.begin("net", "pass");  //Connect to the WiFi network

  while (WiFi.status() != WL_CONNECTED) {  //Wait for connection

    delay(500);
    Serial.println("Waiting to connect…");

  }

  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //Print the local IP

  server.on("/on", []() {   //Define the handling function for the path

    server.send(200, "text / plain", "Switching to USB input");
    #define IR_LED D3
    IRsend irsend(IR_LED);  // Set the GPIO to be used to sending the message.
    uint16_t rawData[71] = {8992, 4494,  574, 558,  572, 558,  574, 558,  574, 558,  574, 558,  572, 558,  572, 556,  572, 1660,  572, 1658,  574, 1658,  574, 1658,  574, 1660,  574, 1660,  574, 1660,  574, 1658,  602, 528,  574, 558,  574, 1658,  576, 556,  574, 556,  574, 1660,  574, 556,  574, 554,  574, 554,  574, 1658,  574, 556,  574, 1656,  576, 1658,  576, 556,  574, 1658,  576, 1656,  576, 1658,  576, 39978,  8994, 2256,  578};
    irsend.begin();

  });

  server.on("/", handleRootPath);    //Associate the handler function to the path
  server.begin();                    //Start the server
  Serial.println("Server listening");

}

void loop() {

  server.handleClient();         //Handling of incoming requests

}

void handleRootPath() {            //Handler for the rooth path

  server.send(200, "text/plain", "NinjaLights");

}

Look at your code. You set up the sender, define the data and then never use it:
server.on("/on", []() {   //Define the handling function for the path
    server.send(200, "text / plain", "Switching to USB input");
    #define IR_LED D3
    IRsend irsend(IR_LED);  // Set the GPIO to be used to sending the message.
    uint16_t rawData[71] = {8992, 4494,  574, 558,  572, 558,  574, 558,  574, 558,  574, 558,  572, 558,  572, 556,  572, 1660,  572, 1658,  574, 1658,  574, 1658,  574, 1660,  574, 1660,  574, 1660,  574, 1658,  602, 528,  574, 558,  574, 1658,  576, 556,  574, 556,  574, 1660,  574, 556,  574, 554,  574, 554,  574, 1658,  574, 556,  574, 1656,  576, 1658,  576, 556,  574, 1658,  576, 1656,  576, 1658,  576, 39978,  8994, 2256,  578};
    irsend.begin();

  });

You need to add a call to irsend.SendRaw() to actually send the data - otherwise you didn't actually do anything.
So your code would look like:
server.on("/on", []() {   //Define the handling function for the path
    server.send(200, "text / plain", "Switching to USB input");
    #define IR_LED D3
    IRsend irsend(IR_LED);  // Set the GPIO to be used to sending the message.
    uint16_t rawData[71] = {8992, 4494,  574, 558,  572, 558,  574, 558,  574, 558,  574, 558,  572, 558,  572, 556,  572, 1660,  572, 1658,  574, 1658,  574, 1658,  574, 1660,  574, 1660,  574, 1660,  574, 1658,  602, 528,  574, 558,  574, 1658,  576, 556,  574, 556,  574, 1660,  574, 556,  574, 554,  574, 554,  574, 1658,  574, 556,  574, 1656,  576, 1658,  576, 556,  574, 1658,  576, 1656,  576, 1658,  576, 39978,  8994, 2256,  578};
    irsend.begin();

    irsend.sendRaw(rawData, 71, KHZ);
  });

You'll need to replace KHZ with the frequency the remote you're trying to replicate uses, otherwise it still won't work.

thanks you, i knew i was missing something


text:
How to use same sketch on two different computers in two different directories
I have the same sketch one that I use at my desk and in the lab, but they are in different directories on the different computers.  This means that I have to change the paths to the includes which I have to fixup every time I transfer back and fourth.  Is there a way to put in a #ifdef that I can set at the start of the build that would include correct path.

Please edit your question and show the different forms of the includes.  Also say what operating system is on the lab system and on the desk system.   What directories are you allowed to rename on each system?

To do this I usually use a github repository

Having two copies of the code will result in disaster at some point.  Create a shared folder on a server, or your desktop, and place all the code there and then point both machines at the share.

Open preferences.txt in C:\Users\YourUserName\AppData\Roaming\Arduino and change the path of sketchbook.path=C:\Users\YourUserName\Documents\Arduino to sketchbook.path=YourDesiredPath.


text:
Build error on a phantom file that is not in my sketch, but somehow created in AppData/Local/Temp\build
on attempt to build  I get the following error
C:\Users\gmyer\AppData\Local\Temp\build5d24776aeb7b2efec3566cec737c36d8.tmp\sketch\trash\bootloader.c:1:1: error: unknown type name 'This'

 This modules tests receiving vacuum data from the

 ^

The problem is that I have no file of that name, and no text that exactly matches that any where in my sketch.  and my sketch is located in C:\Software
I have tried rebooting, deleting the Temp directory, reverting to known working code.  but it keeps regenerating.

I found the offending file in a sub directory of the C:\Software sketch directory.  I had a subdirectory called trash, and the Arduino build found it from there, and put it in AppData then referenced the error from there.


text:
Environment Variable to change build
Is there a way to get the build to see an environment variable so that all the files can be built differently with one Environment variable change.  Such as
#ifdef UseFirstDir
    #include <C:\MyFirstDir\ImportantIncludes.h>
#else
    #include <C:\MySecondDir\ImportantIncludes.h>
#endif

Not environment, no.
If you have access to the compilation command line you can do the equivalent of #define from there:
avr-gcc ... blah blah ... -DUseFirstDir

That is most effective if you are using a Makefile build system rather than relying on the Arduino IDE which doesn't give you access to those kind of things without modifying the core configuration, which isn't nice, and certainly is neither permanent nor flexible (doesn't survive upgrades to new versions, and isn't easy to turn on and off at will).
A better IDE, though, can do it. Facilities for setting control flags like that exist within UECIDE and it's possible to tie them to menu entries to make switching options on and off easier. It's not documented how to do it though (yet).
Or you can just have a list of #define options at the top of your sketch:
/* Uncomment this to use the first directory. */
// #define UseFirstDir

// .... later ....

#ifdef UseFirstDir
    #include <C:\MyFirstDir\ImportantIncludes.h>
#else
    #include <C:\MySecondDir\ImportantIncludes.h>
#endif

I have Cygwin, but the command line (bash or dos) is not finding avr-gcc.  The second option seems best for now.

@Gregg I have just blogged about adding menu entries for a sketch in UECIDE..


text:
Can't cast char to unsigned char?
byte RSV_Resp_test[3] = {'a', 'b', 0};
Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));

produces the error
error: invalid cast from type 'byte {aka unsigned char}' to type 'char'
Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));
                                                      ^

How can this be an ill-formed cast?  I just need to print the value as a ascii character, not as a number.

Serial.println(static_cast<char>(RSV_Resp_test[1]));

works.  I still don't understand why the reinterpret_cast errors out.

This may help shed light on it: http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used - summary: static_cast is what you normally want in 99% of situations and is what you need here. reinterpret_cast is only used when you want to do really strange things.

In a bit of standardization weirdness, section 5.2.10 [expr.reinterpret.cast] says only certain kinds of reinterpret casts are allowed!? Maybe it is time to move back to 'C'.

Personally I never use them and just use (char)varname instead.


text:
Can I connect a remote control relay to a arduino uno board by disabling the remote control in the relay?
I was making a home automation system by making some of the appliances in the home like fans and lights voice activated. But by mistake I bought a remote controlled relay in place of a normal relay from a shop and return does not seems possible. So I want to know if I will be able to use that remote controlled relay in this project?

You could, let the Arduino control the remote, which activates the relays.

I don't like to work with mains, so I use those outlets and connect a 433MHz transmitter to the arduino to activate the outlets.
You'd have to check the frequency of the unit, and see if anyone have decoded the transmitted data package.
If that doesn't float you're boat, you could open up the unit, and remove/desolder the relay. Add a transistor, and flyback diode and you're done. Just be careful with mains power.

Why use a flyback diode? I assume because it's a mech. relay - I've used these, and had problems one wouldn't expect when switching at ~1 sec intervals for tests. Do you place it between VCC and GND on the relay? (mine were 5V relays which were supposedly isolated from higher currents, but not from the relay 'motor' itself) Did I just answer my own question? Edit: more precisely, the arduino would be reset after the relay went a bit haywire; failing to switch, seitching several other channels.

@user400344 please create a new question instead of hijacking someone else's question.

I would if I could, but it appears I am prevented from posting new questions. I'll just try using a diode from GND to VCC, thanks anyway.


text:
How to map PID output to actuator control?
I'm building a control system for the heating of a house. A sensor reads the temperature inside and is then used as the input in the PID control. The temperature is then controlled by a servo which opens and closes a shunt were water runs to the radiators. I understand all the inner workings of the PID library for Arduino and PID in general, but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive. In what way should the output signal correspond to how open or closed the shunt is?
I understand I can simply map the output signal to the servo signal, but is this the correct way? And with what angle coefficient should I map it with, cause that is basically set with the P parameter, isn't it? Is there some standard way to map the output signal to the actuator "signal", so that that tuning parameters are somewhat "standard".
Hope someone understands anything of what I tried to explain :)

For a radiator TBH is easier to understand, implement, configure and fine tune.

What are the limits of your actuator range?  I don't use 'standard' tuning parameters, with a map(), I use the P term as a conversion of input error units directly into actuator units.  For example P=20 could mean 20 degrees of valve-turning per degreeF of error.  Or P=20000 could mean 20000 milliseconds of on-time during a 3600 second heating cycle.

@jippie --Thanks.  I found https://wiki.purduesigbots.com/software/control-algorithms/take-back-half-tbh-controller  a good reference for the Take-Back-Half algorithm.  From that article, rather than the EDN electronics-based ref, I see TBH as backcalculating the integral sum (for PID-style algorithms) each at each crossing, or as a Newtons-method search for  the proper output value for bang-bang-like control, depending on a history of the last two setpoint crossings.

I don't think you would need to use a PID library (or any control loop for that matter) to control a radiator. You could use a simple threshold code, like this:
Pseudocode:
Check temperature
If radiator is off and temperature > (ideal temp - threshold)
  turn radiator on
If radiator is on and temperature > (ideal temp + threshold)
  turn radiator off

If you can't find some actual info regarding applying PID to a water-based radiator system, then I'd suggest the following principles.
First, I assume that the output of the PID algorithm appears as an An Arduino PWM output at some rate. This could be a fast rate, like in the hundreds of Hz (if the load is DC), or fractions of Hz, or even 10 sec or more cycle time.
Next, I assume that the PID algorithm is likely designed to expect that a linear change in output has a linear effect on the heating output. That is to say, as though it's controlling an electric heater, where, for example, 25% ON-time produces 25% of full heat output.
If these are true, then you need to determine how that relates to what you can control on your shunt valve.
Is it acceptable for the valve to be turned full on/off on a proportion-of-10-seconds basis? Probably not.
Can the valve be set to an intermittent position if fed with a 10 Hz or 100 Hz PWM signal, perhaps so.
If the latter, then a further question is how does the PWM range of values correspond to actual angle of the valve, and more to the point, how does it correspond to flow rate, and ultimately to heat delivery. Perhaps a 33% PWM signal is required to deliver 25% of the full-range heat, for example.
(At a guess, I'd assume that heat delivery is proportional to flow, but as I think you anticipate, flow is not proportional to valve angle.)
You might just mock up your system, program the Arduino to output particular PWM values to the valve, and measure the resulting flow, and if possible, heat delivery. Then, interpose in the PID library the inverse function, perhaps as a lookup table.
So when the PID library wants to command 25%, that number gets looked up in the table, which (continuing my example) translates it to a 33% PWM signal, and your program sends that value to the PWM output.
Hope that provides some ideas.