text:
Arduino 3.5" TFT Display going blank after sending data through I2C
I'm trying to use I2C to send and receive commands between an Arduino UNO R3 and an Arduino Mega R3, with a 3.5" TFT display connected to the Mega. I have verified that my display is fully functional without using I2C by running the MCUFRIEND_kbv graphics tests where they perform exactly as I expect, but when I try to use I2C in combination with the TFT shield, I run into an issue where the display goes completely white and does not change. Could this be caused by the I2C interrupting the tft functions causing it to fail? Any advice would be greatly appreciated!
Here is the i2c code on the mega:
void sendInputs(){
  for(int i = 0; i < NUM_BUTTONS; i++){
    btnArr[i] = digitalRead(btnPinArr[i]);
    Wire.write(btnArr[i]);
  }
  digitalWrite(13, HIGH);
  p = ts.getPoint();
  digitalWrite(13, LOW);
  tsArr[0] = p.x;
  tsArr[1] = p.y;
  tsArr[2] = (p.z > MINPRESSURE && p.z < MAXPRESSURE);
  for(int i = 0; i < NUM_TS_INPUTS; i++){
    Wire.write(tsArr[i]);
  }
}

void getDrawData(){
 graphicsBufferSize = Wire.read();
 for(int i = 0; i < graphicsBufferSize; i++){
    graphicsBuffer[i] = Wire.read();
 }
 drawGraphicsBuffer();
}

Where drawGraphicsBuffer(); parses the array of ints into draw functions
The I2C code on the Arduino UNO is:
void sendGraphics(){
     Wire.beginTransmission(slaveID);
      Wire.write(graphicsBufferSize);
      for(int i = 0; i < graphicsBufferSize; i++){
        Wire.write(graphicsBuffer[i]);
      }
      Wire.endTransmission();
      graphicsBufferSize = 0;
    }

void getInputs(){
  Wire.requestFrom(8, NUM_BUTTONS + NUM_TS_INPUTS);
  for(int i = 0; i < NUM_BUTTONS; i++){
    btnArr[i] = Wire.read();
  }
  for(int i = 0; i < NUM_TS_INPUTS; i++){
    tsArr[i] = Wire.read();
  }
}

void loop(){
  getInputs();
  delay(1000);
  if(btnArr[0]){
    screen.addFillScreen(0);
  }
  if(btnArr[1]){
    screen.addCircle(50, 50, 50, 50);
  }
  screen.sendGraphics();
}

Where the screen methods just populate the graphicsBuffer array to be sent to the Arduino mega.
Edit:  Here is the exact screen I'm using

I ran into a very similar problem. I used an UNO. I simply replaced a TFT from a different brand, and it worked perfectly. Some brands have conflicting i2C pins I guess.

Can you recommend me a brand to try?

I used this one


text:
Chip sync error while updating ATfirmware in esp8266
I find trouble updating my firmware with esp8266 with following error message.
[espDownloader.py][line:351][ERROR]: Chip sync error: Failed to connect to ESP8266: Timed out waiting for packet header
[2019-06-04 07:53:16,009][ESP8266Loader_spi[1]][espDownloader.py][line:439][ERROR]: ESP8266 Chip sync error esp_sync_blocking.
I am unable to resolve even after a number of attempts.
Please help me resolve my issue. Thank you in advance.

is the module in flashing mode, by pulling io 0 LOW at boot?

Yes m putting it in flash mode

does the original firmware answer over that port, cable and adapter?

my original firmware provides Garbage data and displays ready command, but  it doesn't answers any AT command.

read the 'garbage; at 74880 baud. it is the boot log. (some part will be always garbage or Chinese) send AT command at 115200 baud with both line ends set

thank you for your help, there was some problem with my chip. I bought an another one and it's working fine.

source: Stack Exchange

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

sort: votes


text:
RGB LED Mode toggle - Trying to avoid using main loop()
I'd like to start by saying that I have only been dabbling in electronics (not just Arduino) for about 3 days now.
I am trying to write a sketch which changes an RGB LED when a push switch is pressed.
There are 6 modes -
0 = off
1 = dim
2 = mid brightness
3 = full brightness
4 = cycle through RGB colours
5 = pause the colour cycle at the current colour

I have managed to get this working using the code below this explanation.
What I would like to know is this -
Since the LED only changes state when the button is pressed, is it possible to avoid the use of the main 'loop()' entirely?
Will work fine for modes 0, 1, 2 and 3, but the interrupt cannot fire until mode 4 has finished 1 entire colour cycle.
/*
 * LED MODES
 * 0 = off
 * 1 = dim
 * 2 = mid
 * 3 = bright
 * 4 = colour cycle
 * 5 = colour select
 */
volatile int ledMode = 0; // off
const int maxLEDMode = 5;
volatile bool buttonPressed = false;

int rPin = 9;
int gPin = 10;
int bPin = 11;
int ledPin = 5;
int buttonPin = 2;
int currentVals[] = {0, 0, 0};

void setup() {
  Serial.begin(9600);
  pinMode(rPin, OUTPUT);
  pinMode(gPin, OUTPUT);
  pinMode(bPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);

  attachInterrupt(digitalPinToInterrupt(buttonPin), buttonPress, FALLING);
}

void loop() {
  setBrightness(); // try and move outside of main loop
}

// Ensure that buttonPress does not trigger twice
void buttonPress(){
  if(digitalRead(buttonPin) == 0){
    delay(10);
    if(digitalRead(buttonPin) == 0){

      setMode();
      buttonPressed = true;
      Serial.println(ledMode);
    }
  }
}

//Increment LED Mode until max level is reached
void setMode(){
  if(ledMode == maxLEDMode){
    ledMode = 0;
  } else {
    ledMode++;
  }
}

//Set LED colours depending on ledMode
void setBrightness(){
  buttonPressed = false;

  if(ledMode == 0){
    mode0();
  }

  if(ledMode == 1){
    mode1();
  }

  if(ledMode == 2){
    mode2();
  }

  if(ledMode == 3){
    mode3();
  }

  if(ledMode == 4){
    mode4();
  }

  if(ledMode == 5){
    mode5();
  }
}

//Fade to off
void mode0 (){
  fadeTo(0, 0, 0, 10);
}

// Fade to dim light
void mode1 (){
  int val = 255/5;
  fadeTo(val, val, val, 100);
}

// Fade to medium light
void mode2 (){
  int val = (255/3);
  fadeTo(val, val, val, 100);
}

// Fade to bright light
void mode3 (){
  fadeTo(255, 255, 255, 100);
}

// Endlessly cycle through RGB colours
void mode4(){
    fadeToWithCheck(255, 0, 0, 500);
    fadeToWithCheck(255, 255, 0, 500);
    fadeToWithCheck(0, 255, 0, 500);
    fadeToWithCheck(0, 255, 255, 500);
    fadeToWithCheck(0, 0, 255, 500);
    fadeToWithCheck(255, 0, 255, 500);
}

// Pause LED on colour inherited from Mode4
void mode5(){
  int rExisting = currentVals[0];
  int gExisting = currentVals[1];
  int bExisting = currentVals[2];
  fadeTo(rExisting, gExisting, bExisting, 1);
}

// Fade to given colour, with awareness of mode4 toggles
void fadeToWithCheck(int r, int g, int b, int interval){
  if(ledMode == 4){
    int rExisting = currentVals[0];
    int gExisting = currentVals[1];
    int bExisting = currentVals[2];

    for(int i = 0; i <= interval; i++){
      analogWriteInverted(rPin, map(i, 0, interval, rExisting, r));
      analogWriteInverted(gPin, map(i, 0, interval, gExisting, g));
      analogWriteInverted(bPin, map(i, 0, interval, bExisting, b));

      if(buttonPressed == true){
        Serial.println("stopping loop");
        currentVals[0] = map(i, 0, interval, rExisting, r);
        currentVals[1] = map(i, 0, interval, gExisting, g);
        currentVals[2] = map(i, 0, interval, bExisting, b);
        break;
      }
      delay(10);
    }

    if(buttonPressed == true){
      buttonPressed = false;
    } else {
      currentVals[0] = r;
      currentVals[1] = g;
      currentVals[2] = b;
    }
  }
}

// Fade to given colour
void fadeTo(int r, int g, int b, int interval){
  int rExisting = currentVals[0];
  int gExisting = currentVals[1];
  int bExisting = currentVals[2];

  for(int i = 0; i <= interval; i++){
    analogWriteInverted(rPin, map(i, 0, interval, rExisting, r));
    analogWriteInverted(gPin, map(i, 0, interval, gExisting, g));
    analogWriteInverted(bPin, map(i, 0, interval, bExisting, b));
    delay(10);
  }
  currentVals[0] = r;
  currentVals[1] = g;
  currentVals[2] = b;
}

// Invert given value due to cathode/anode LED
void analogWriteInverted( byte pin, byte value)
{
  analogWrite(pin, 255-value);
}

Any help or advice at all would be appreciated!
Many thanks,
Rob
UPDATE - Working solution
Following on from the advice given by Michel, the following code meets my needs perfectly.
#include "TimerOne.h"

/*
 * LED MODES
 * 0 = off
 * 1 = dim
 * 2 = mid
 * 3 = bright
 * 4 = colour cycle
 * 5 = colour select
 */
volatile int ledMode = 0; // off
const int maxLEDMode = 5;
volatile bool buttonPressed = false;
unsigned long lastDebounceTime = -1;
unsigned long debounceDelay = 200;
int lastButtonState = HIGH;
int buttonState;
long secondTimer = 1000000;

int rPin = 6;
int gPin = 5;
int bPin = 3;
int buttonPin = 2;
int currentVals[] = {0, 0, 0};
int mode4Vals[] = {0, 0, 0};
int mode4Stage = 0;

long fadeInterval = 0;
long lastSeenInterval;

void setup() {
  Serial.begin(9600);
  pinMode(rPin, OUTPUT);
  pinMode(gPin, OUTPUT);
  pinMode(bPin, OUTPUT);
  pinMode(buttonPin, INPUT);

  Timer1.initialize(secondTimer / 1000);
  attachInterrupt(digitalPinToInterrupt(buttonPin), buttonPress, FALLING);

  turnOff();
}

void loop() {
  //setBrightness(); // try and move outside of main loop

}

void turnOff(){
  analogWriteInverted(rPin,0);
  analogWriteInverted(gPin,0);
  analogWriteInverted(bPin,0);

  currentVals[0] = 0;
  currentVals[1] = 0;
  currentVals[2] = 0;
}

// Ensure that buttonPress does not trigger twice
void buttonPress(){
  int reading = digitalRead(buttonPin);

  if (lastDebounceTime < 0 || (millis() - lastDebounceTime) > debounceDelay) {
    lastDebounceTime = millis();
    if(ledMode != 4){
        clearTimer();
    }
        setMode();
        buttonPressed = true;
        Timer1.attachInterrupt(incrementGlobalFadeInterval);
      }
    }

//Increment LED Mode until max level is reached
void setMode(){
  if(ledMode == maxLEDMode){
    ledMode = 0;
  } else {
    ledMode++;
  }
}

//Set LED colours depending on ledMode
void setBrightness(){
  buttonPressed = false;

  switch(ledMode){
    case 0: mode0(); break;
    case 1: mode1(); break;
    case 2: mode2(); break;
    case 3: mode3(); break;
    case 4: mode4(); break;
    case 5: mode5(); break;
    default: abort();
  }

}

//Fade to off
void mode0 (){
  fadeTo(0, 0, 0, 400);
}

// Fade to dim light
void mode1 (){
  int val = 255/5;
  fadeTo(val, val, val, 50);
}

// Fade to medium light
void mode2 (){
  int val = (255/3);
  fadeTo(val, val, val, 50);
}

// Fade to bright light
void mode3 (){
  fadeTo(255, 255, 255, 50);
}

// Endlessly cycle through RGB colours
void mode4(){
  switch(mode4Stage){
    case 0: fadeToWithCheck(255, 0, 0, 2000); break;
    case 1: fadeToWithCheck(255, 255, 0, 2000); break;
    case 2: fadeToWithCheck(0, 255, 0, 2000); break;
    case 3: fadeToWithCheck(0, 255, 255, 2000); break;
    case 4: fadeToWithCheck(0, 0, 255, 2000); break;
    case 5: fadeToWithCheck(255, 0, 255, 2000); break;
    default: abort();
  }
}

// Pause LED on colour inherited from Mode4
void mode5(){
  currentVals[0] = mode4Vals[0];
  currentVals[1] = mode4Vals[1];
  currentVals[2] = mode4Vals[2];

  int rExisting = currentVals[0];
  int gExisting = currentVals[1];
  int bExisting = currentVals[2];
  fadeTo(rExisting, gExisting, bExisting, 1);
}

// Fade to given colour, with awareness of mode4 toggles
void fadeToWithCheck(int r, int g, int b, int interval){
  if(ledMode == 4){
    int rExisting = currentVals[0];
    int gExisting = currentVals[1];
    int bExisting = currentVals[2];

    if(fadeInterval <= interval && lastSeenInterval != fadeInterval){
      lastSeenInterval = fadeInterval;
      analogWriteInverted(rPin, map(fadeInterval, 0, interval, rExisting, r));
      analogWriteInverted(gPin, map(fadeInterval, 0, interval, gExisting, g));
      analogWriteInverted(bPin, map(fadeInterval, 0, interval, bExisting, b));

      mode4Vals[0] = map(fadeInterval, 0, interval, rExisting, r);
      mode4Vals[1] = map(fadeInterval, 0, interval, gExisting, g);
      mode4Vals[2] = map(fadeInterval, 0, interval, bExisting, b);
    } else {
      currentVals[0] = map(fadeInterval, 0, interval, rExisting, r);
      currentVals[1] = map(fadeInterval, 0, interval, gExisting, g);
      currentVals[2] = map(fadeInterval, 0, interval, bExisting, b);
      fadeInterval = 0;

      if(mode4Stage == 5){
        mode4Stage = 0;
      } else {
        mode4Stage++;
      }
    }
  }
}

// Fade to given colour
void fadeTo(int r, int g, int b, int interval){
  int rExisting = currentVals[0];
  int gExisting = currentVals[1];
  int bExisting = currentVals[2];

  if(fadeInterval <= interval && fadeInterval != lastSeenInterval){
    lastSeenInterval = fadeInterval;
    analogWriteInverted(rPin, map(fadeInterval, 0, interval, rExisting, r));
    analogWriteInverted(gPin, map(fadeInterval, 0, interval, gExisting, g));
    analogWriteInverted(bPin, map(fadeInterval, 0, interval, bExisting, b));
  } else {
    clearTimer();
    currentVals[0] = r;
    currentVals[1] = g;
    currentVals[2] = b;
  }
}

void incrementGlobalFadeInterval(){
  fadeInterval++;
  setBrightness();
}

void clearTimer(){
  Timer1.detachInterrupt();
  fadeInterval = 0;
  lastSeenInterval = -1;
}

// Invert given value due to cathode/anode LED
void analogWriteInverted( byte pin, byte value)
{
  analogWrite(pin, 255-value);
}

Try switch function in C++.  You'll find the info via a search engine.

I'm guessing it will perform the same way as the switch in C#. That would tidy up my  setBrightness function a lot. Good thinking! I'm not too clear on how this would avoid the use of the main loop function though?

One other problem I see is you use delay, and a delay should not be used inside an interrupt.

Thanks Michel, is this because it is not best practice or can it cause fundamental issues? I put this in place because, when I pressed the button, the ISR was triggering a random number of times, sometimes once, sometimes up to 3 times. Have you seen an issue like that before? Sorry if this should be another post entirely.

upvote for a well written post

Keep interrupt shorts
Inside an interrupt, do not use long pauses, thus not a delay. As chrisl notes below (see comment) delay does not even work inside an interrupt, since it is based on millis(), which are not updated within an interrupt.
The reason is that interrupts should be as short as possible (so even if you would use a for loop with micros() or another way to hold the execution time), because it can cause new interrupts not to be called (during an interrupt, no new interrupts will be called, at least not with the same/lower priority). So always keep code within interrupts very short, especially delay's are violating this, but also serial.print statements.
I see you use this function which will be called if you put everything in the interrupt handler:
// Fade to given colour
void fadeTo(int r, int g, int b, int interval){
  int rExisting = currentVals[0];
  int gExisting = currentVals[1];
  int bExisting = currentVals[2];

  for(int i = 0; i <= interval; i++){
    analogWriteInverted(rPin, map(i, 0, interval, rExisting, r));
    analogWriteInverted(gPin, map(i, 0, interval, gExisting, g));
    analogWriteInverted(bPin, map(i, 0, interval, bExisting, b));
    delay(10);
  }
  currentVals[0] = r;
  currentVals[1] = g;
  currentVals[2] = b;
}

Removing delays
To remove the delay, is a bit tricky though. What you need to do is (approximately):

Create a global variable instead of the loop variable (i, but give it a better name)
Calling an additional interrupt based on 10 ms (the delay).
In that interrupt, handle the next iteration (so increase the global variable i (but the new name)
Handle post processing (e.g. if i == interval, execute the last three statements of the function (and possibly other statements from called functions in the original code).

Multiple if to one switch statement
Also you can use a switch statement.. Instead of
 if(ledMode == 0){
    mode0();
  }

  if(ledMode == 1){
    mode1();
  }

  if(ledMode == 2){
    mode2();
  }

  if(ledMode == 3){
    mode3();
  }

  if(ledMode == 4){
    mode4();
  }

  if(ledMode == 5){
    mode5();
  }
}

Use
switch (ledMode)
{
case 0:
  mode0();
  break;

case 1:
  mode1();
  break;

..

case 5:
  mode5();
  break;

default:
   abort(); // Error condition
}

Since the cases are so simple I put them normally on one line:
switch (ledMode)
{
case 0: mode0(); break;
case 1: mode1(); break;
..
case 5: mode5(); break;
default: abort();
}

Button debouncing
In your remark you say after a button press, sometimes the function is called multiple times. This is caused by button bouncing. When you press a button, for a short time, the contact is somewhere between on and off. During this time, it can change a few times between on and off, thus you get multiple calls, mostly very short after each other. To prevent this, use button debouncing (check the Arduino site for a Button Debounce example). It means that you check if a certain state has been stable for some time, and than perform the action, instead of immediately.

Great answer Michel, I'm pretty sure that all makes sense to me. I will give it a go and get back to you with my findings.

Good luck, if it helps you, please consider upvoting/accepting the answer.

I thought, that delay() does not work at all inside of an ISR, because it relies on millis(), which in turn relies on interrupt for counting time.

@chrisl you are right, mostly, you can use milis(), but it is not updated, so the use of delay doesn't work indeed. I will adapt the answer. Thanks!

Thanks for the help Michel! Not sure if my solution is exactly what you imagined, but it certainly does the trick. I have updated my question with the working code.

Remove the buttonPressed = false; from fadeToWithCheck. As in mode4 this function is called four times, only the current call is skipped if the button is pressed. The following calls are not skipped, because your reset buttonPressed back to false.
There is no need for this, as it's already reset back to false at the beginning of setBrightness.

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


text:
Arduino Uno Issue: No output power
I am currently a first time Arduino user. I decided to get one and start prototyping basic types of circuits.
I have built various basic circuits with the Arduino Uno prototype board and it worked completely fine. I am using the Arduino board to source power to my circuit (5V). However, after building the following circuit, everything stopped working:

simulate this circuit – Schematic created using CircuitLab
I don't get output from any of the Arduino pins and I cannot upload programs to the board. The yellow LED still blinks, and the green power LED remains green and active.
I cannot figure out how I managed to burn the board. The current is around 22.72mA, which is pretty far of the 40mA absolute rating.

I don't see an Arduino in that circuit diagram.

Hi, the Arduino board is powering the circuit above. The 5V is being sourced from the Arduino board.

Did you measure or calculate the 22.72 mA? If not, measure it (maybe the resistor is working) 22.72 mA is just a bit above recommended (20 mA), but I doubt it should give a problem.

It was calculated. I didn't really get time to measure it since the board got damaged right away. I've ordered a few more boards, so I'll keep that in mind.

It sounds like you might have let the Magic Smoke escape! If you remove your circuit, does the arduino still work? Normally, you would use the digital I/O pins to power a 7 segment led. Also, the fact that you connected a whole bunch of the "segments" to ground and another whole bunch to +5 (with maybe a resistor) might be a contributing factor.

Check out this tutorial for how to connect a 7 segment led to arduino. You will note that it says (about 1/3 of the way down):
"Single digit seven segment displays typically have 10 pins. Two pins connect to ground, and the other 8 connect to each of the segments."

I think the whole schematic would help. You are right that, as shown, even with a direct short through the LEDs, that would only draw 22 mA from the power rail which it should easily cope with. I don't see how the Arduino is being used here, and that undisclosed information might be germane to your problem. Are you using manual switches here? Why is the Arduino even involved in this design?

@GMc Even if I remove the circuit, it still won't work. I hastily assumed that the pins above the 7 segment display was the input pins and the pins below it were ground pins. I've built the same circuit with a new Arduino board and the correct configuration (this time I limited the current with a 1K resistor). It works fine now.

LOL when it comes to electronics, haste often makes smoke. Smoke usually means Arduino broke! Follow the tutorial i linked above and check everything at least twice! :-)

You need to have a current limiting resistor for each of the LED segments. Sharing one resistor between them all is a very bad idea, as multiple lit LEDs (in parallel) will be using the same resistor - see this excellent answer to Why exactly can't a single resistor be used for many parallel LEDs?:

The main reason is because you can't safely connect diodes in
  parallel.
So when we use one resistor, we have a current limit for the whole
  diode section. After that it's up to each diode to control the current
  that goes through it.
The problem is that real world diodes don't have same characteristics
  and therefore there's a danger that one diode will start conducting
  while others won't.

I would hazard a guess that you've drawn too much current, or, in your case, tried to sink too much through the PWM pin.
Also, it would (probably) be better to use individual data pins, not PWM pins, to turn on each segment, rather than connecting all of the segments to just one pin. It just seems a bit odd to do it that way.

The schematic you have drawn is completely safe to connect to an Arduino PWM pin. It may not be an optimal choice (closing multiple switches will change the brightness of segments), but it's not dangerous. As you said yourself, the current is limited to a safe value even if there's a dead short in the 7-segment display.
Typically, you burn your board when you connect/disconnect stuff while your Arduino is powered (because intermediate circuits may be unsafe even if the final result is OK), or when you built a circuit which is different from what you think you have built.


text:
Receiving garbled `char` array returned by a function
I return a char[300] array from a function.  If I intialize a char* variable with it, the return is garbled, but not if I append it to a String.  What gives?
  const char* post2 =  uploadHourCsv(timeNow,pulseChangeHour) ;
  String postS2 = "";
  postS2 =  uploadHourCsv(timeNow,pulseChangeHour) ;
  //const char* post2 = { uploadHourCsv(timeNow,pulseChangeHour) };
  if( debug ) {
    Serial.print("received in loop() as : [");
    Serial.println(post2);
    Serial.print("String : [");
    Serial.println(postS2);
  }

...

char postStr[300] = "";
// populate array
if( debug ) {
  Serial.print("postStrCsv generated: ");
  Serial.println(postStr);
}
return postStr;

postStrCsv generated: 00000003;3|  0.00;8|17.55;9|17.55;10|18.12;11|16.92;20|93817;22|93789;101|6;time|1559646000;
received in loop() as : [000?⸮@⸮⸮?" ⸮⸮?17.55;9|17.58! @0⸮⸮⸮⸮G% @5~`⸮h⸮?⸮⸮
String : [00000003;3|  0.00;8|17.55;9|17.55;10|18.12;11|16.92;20|93817;22|93789;101|6;time|1559646000;

What exactly does the uploadHourCsv return? Since post2 is declared as a pointer, without any size, the function has to return a pointer to an already allocated string to do this.

char postStr[300] with contents displayed in blockquote.

How is this Arduino specific? Despite two excellent (and upvoted) answers below, I say that such questions 1) belong on https://stackoverflow.com/ and 2) will get better answers more quickly tehre (no offence to those here)

tks.  do you think that we should move this to SO?  flag for moderator attention or flag to close saying "belongs in so"

It's because you're returning a pointer to a local variable.
You are only returning the address in memory where your char array is allocated. That allocation is on the stack and only exists for the lifetime of the function.  But you still have the address where that memory was allocated, and you're using it as if it's still allocated.
When you append it to a String room is allocated on the heap and the data is copied in. That heap allocation remains until the String object is destroyed, either by going out of scope or by you manually destroying it.
It's pure chance that the data is still available and intact at the point of copying.
In short:

You must never return a pointer to a locally allocated (non-static) array.

Things you can do that are correct:

Pass an array pointer to the function to be populated by the function
Return a pointer to a statically allocated local array
Return a String object (though I wouldn't recommend using String for anything)

My preferred method is the first, whereby you define an array in the outer scope, then pass that (and possibly the array length) to the function. The function then populates the array it has been passed.  This also has the advantage that the function can use the return value to indicate a status or other quantity.
For example:
void myFunc(char *buf, int len) {
    for (int i = 0; i < len - 1; i++) {
        buf[i] = 'A';
    }
    buf[len - 1] = 0;
}

char myBuf[20];
myFunc(myBuf, 20);
Serial.println(myBuf);

--> AAAAAAAAAAAAAAAAAAAA

U da man! UPVOTED and ACCEPTED.  Re use of String: totally agree, unsafe memory allocation in String class.

Following Majenko's invaluable advice and incorporating another similar approach, final working implementation was to treat the function as a method to operate upon the char[300] array as "out parameter".
char postStr[300] =  "";
uploadHourCsv(timeNow,pulseChangeHour,postStr) ;
...

void uploadHourCsv(int unixtimeEvent, int pulseChange, char* postStr) {
  // prepare data and variables
  strcat(postStr, stationId);
  strcat(postStr,";3|"); // chuva hora
  strcat(postStr, dtostrf(rainHour,6,2,charDummy));
  ...
}

If you make the first strcat a strcpy instead, you can avoid initializing the array first.  (And note that the way you initialize it in the caller fills the entire length with zero bytes, not just the first element, so that takes a lot longer than necessary unless it gets optimized away.)


text:
Why am I only seeing white screen in TFT 1.44 ST7735?
I just bought the 3rd TFT and in all my attempts I get the white screen I don't know what I'm doing wrong!
This time I bought it and followed their instruction's guide
I created this schematic using Fritzing which is the one I'm using but still I am getting the white screen again

Here are some Photos of what is the TFT displaying.
Finally, I did also used the recommended testing code which is listed in:
File > Examples > Adafruit ST7735 and ST7789 library > graphicstest
Also, I have did commented the slightly changed. So this is the code I'm using:
/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>

#ifdef ADAFRUIT_HALLOWING
  #define TFT_CS        39 // Hallowing display control pins: chip select
  #define TFT_RST       37 // Display reset
  #define TFT_DC        38 // Display data/command select
  #define TFT_BACKLIGHT  7 // Display backlight pin
#elif defined(ESP8266)
  #define TFT_CS         4
  #define TFT_RST        16
  #define TFT_DC         5
#else
  // For the breakout board, you can use any 2 or 3 pins.
  // These pins will also work for the 1.8" TFT shield.
  #define TFT_CS        10
  #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         8
#endif

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 (including HalloWing) use:
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.54" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
//#define TFT_MOSI 11  // Data out
//#define TFT_SCLK 13  // Clock out
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

float p = 3.1415926;

void setup(void) {
  Serial.begin(9600);
  Serial.print(F("Hello! ST77xx TFT Test"));

#ifdef ADAFRUIT_HALLOWING
  // HalloWing is a special case. It uses a ST7735R display just like the
  // breakout board, but the orientation and backlight control are different.
  tft.initR(INITR_HALLOWING);        // Initialize HalloWing-oriented screen
  pinMode(TFT_BACKLIGHT, OUTPUT);
  digitalWrite(TFT_BACKLIGHT, HIGH); // Backlight on
#else
  // Use this initializer if using a 1.8" TFT screen:
 // tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab

  // OR use this initializer (uncomment) if using a 1.44" TFT:
  tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

  // OR use this initializer (uncomment) if using a 0.96" 180x60 TFT:
  //tft.initR(INITR_MINI160x80);  // Init ST7735S mini display

  // OR use this initializer (uncomment) if using a 1.54" 240x240 TFT:
  //tft.init(240, 240);           // Init ST7789 240x240
#endif

  Serial.println(F("Initialized"));

  uint16_t time = millis();
  tft.fillScreen(ST77XX_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);
  delay(500);

  // large block of text
  tft.fillScreen(ST77XX_BLACK);
  testdrawtext("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", ST77XX_WHITE);
  delay(1000);

  // tft print function!
  tftPrintTest();
  delay(4000);

  // a single pixel
  tft.drawPixel(tft.width()/2, tft.height()/2, ST77XX_GREEN);
  delay(500);

  // line draw test
  testlines(ST77XX_YELLOW);
  delay(500);

  // optimized lines
  testfastlines(ST77XX_RED, ST77XX_BLUE);
  delay(500);

  testdrawrects(ST77XX_GREEN);
  delay(500);

  testfillrects(ST77XX_YELLOW, ST77XX_MAGENTA);
  delay(500);

  tft.fillScreen(ST77XX_BLACK);
  testfillcircles(10, ST77XX_BLUE);
  testdrawcircles(10, ST77XX_WHITE);
  delay(500);

  testroundrects();
  delay(500);

  testtriangles();
  delay(500);

  mediabuttons();
  delay(500);

  Serial.println("done");
  delay(1000);
}

void loop() {
  tft.invertDisplay(true);
  delay(500);
  tft.invertDisplay(false);
  delay(500);
}

void testlines(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(0, 0, x, tft.height()-1, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(0, 0, tft.width()-1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(tft.width()-1, 0, x, tft.height()-1, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(tft.width()-1, 0, 0, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(0, tft.height()-1, x, 0, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(0, tft.height()-1, tft.width()-1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(tft.width()-1, tft.height()-1, x, 0, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(tft.width()-1, tft.height()-1, 0, y, color);
    delay(0);
  }
}

void testdrawtext(char *text, uint16_t color) {
  tft.setCursor(0, 0);
  tft.setTextColor(color);
  tft.setTextWrap(true);
  tft.print(text);
}

void testfastlines(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t y=0; y < tft.height(); y+=5) {
    tft.drawFastHLine(0, y, tft.width(), color1);
  }
  for (int16_t x=0; x < tft.width(); x+=5) {
    tft.drawFastVLine(x, 0, tft.height(), color2);
  }
}

void testdrawrects(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color);
  }
}

void testfillrects(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=tft.width()-1; x > 6; x-=6) {
    tft.fillRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color1);
    tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color2);
  }
}

void testfillcircles(uint8_t radius, uint16_t color) {
  for (int16_t x=radius; x < tft.width(); x+=radius*2) {
    for (int16_t y=radius; y < tft.height(); y+=radius*2) {
      tft.fillCircle(x, y, radius, color);
    }
  }
}

void testdrawcircles(uint8_t radius, uint16_t color) {
  for (int16_t x=0; x < tft.width()+radius; x+=radius*2) {
    for (int16_t y=0; y < tft.height()+radius; y+=radius*2) {
      tft.drawCircle(x, y, radius, color);
    }
  }
}

void testtriangles() {
  tft.fillScreen(ST77XX_BLACK);
  int color = 0xF800;
  int t;
  int w = tft.width()/2;
  int x = tft.height()-1;
  int y = 0;
  int z = tft.width();
  for(t = 0 ; t <= 15; t++) {
    tft.drawTriangle(w, y, y, x, z, x, color);
    x-=4;
    y+=4;
    z-=4;
    color+=100;
  }
}

void testroundrects() {
  tft.fillScreen(ST77XX_BLACK);
  int color = 100;
  int i;
  int t;
  for(t = 0 ; t <= 4; t+=1) {
    int x = 0;
    int y = 0;
    int w = tft.width()-2;
    int h = tft.height()-2;
    for(i = 0 ; i <= 16; i+=1) {
      tft.drawRoundRect(x, y, w, h, 5, color);
      x+=2;
      y+=3;
      w-=4;
      h-=6;
      color+=1100;
    }
    color+=100;
  }
}

void tftPrintTest() {
  tft.setTextWrap(false);
  tft.fillScreen(ST77XX_BLACK);
  tft.setCursor(0, 30);
  tft.setTextColor(ST77XX_RED);
  tft.setTextSize(1);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_YELLOW);
  tft.setTextSize(2);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_GREEN);
  tft.setTextSize(3);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_BLUE);
  tft.setTextSize(4);
  tft.print(1234.567);
  delay(1500);
  tft.setCursor(0, 0);
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextColor(ST77XX_WHITE);
  tft.setTextSize(0);
  tft.println("Hello World!");
  tft.setTextSize(1);
  tft.setTextColor(ST77XX_GREEN);
  tft.print(p, 6);
  tft.println(" Want pi?");
  tft.println(" ");
  tft.print(8675309, HEX); // print 8,675,309 out in HEX!
  tft.println(" Print HEX!");
  tft.println(" ");
  tft.setTextColor(ST77XX_WHITE);
  tft.println("Sketch has been");
  tft.println("running for: ");
  tft.setTextColor(ST77XX_MAGENTA);
  tft.print(millis() / 1000);
  tft.setTextColor(ST77XX_WHITE);
  tft.print(" seconds.");
}

void mediabuttons() {
  // play
  tft.fillScreen(ST77XX_BLACK);
  tft.fillRoundRect(25, 10, 78, 60, 8, ST77XX_WHITE);
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_RED);
  delay(500);
  // pause
  tft.fillRoundRect(25, 90, 78, 60, 8, ST77XX_WHITE);
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_GREEN);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_GREEN);
  delay(500);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_BLUE);
  delay(50);
  // pause color
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_RED);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_RED);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_GREEN);
}

Please don't mark this question as duplicated because I looked at the other guy he/she was using different guide.. the one I'm using is posted by the company I purchased the TFT from.

White screen = display not being initialized. Triple check your wiring and code.

did you insert SD card? if yes, remove it

Juraj - Yes I did it with and without but the output still same. I don't know very frustrating.

Majenko - Thank you for the comment but I'm not expert and I did same as I should be followed  by the guide multiple times and I did upload some photos of what the wiring... I'm sorry I'm not sure what to do next

is your Arduino here the Arduino Micro too as in the next question?

@Glorfindel Hey if you still looking for questions to edit, then go to my recent question asked, I'm sure you will find a common or period missing to fix. I guess that is your job! Way to go!

@Juraj Yes same one

I would like to suggest some changes in your code i.e.
Your Code:
/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>

#ifdef ADAFRUIT_HALLOWING
  #define TFT_CS        39 // Hallowing display control pins: chip select
  #define TFT_RST       37 // Display reset
  #define TFT_DC        38 // Display data/command select
  #define TFT_BACKLIGHT  7 // Display backlight pin
#elif defined(ESP8266)
  #define TFT_CS         4
  #define TFT_RST        16
  #define TFT_DC         5
#else
  // For the breakout board, you can use any 2 or 3 pins.
  // These pins will also work for the 1.8" TFT shield.
  #define TFT_CS        10
  #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         8
#endif

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 (including HalloWing) use:
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.54" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
//#define TFT_MOSI 11  // Data out
//#define TFT_SCLK 13  // Clock out
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

changes suggested:
/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>

  #define TFT_CS        10
  #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         8

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 (including HalloWing) use:
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.54" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
#define TFT_MOSI 11  // Data out
#define TFT_SCLK 13  // Clock out
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

Replace your that part with one I suggested as You commented tha SCK and MISO pins in your code so no data transfer is happening on those pins. Secondly I made changes according to your hardware configuration as well.

You are a genius ... haha No more stupid white screen ... I see a colorful screen

I hope I will not be a bother. I just had a request and not sure if it could work. I was going to use MicroSD but since this has one, can I use it externally? like can I put .wav sound and play it in a speaker? Since you know the wiring I was hoping you could provide me with code which doses load sound file from that sd card and output to a speaker at maybe pin 3? This will help me a lot and make the project smaller so it can be wearable. Thank you

we don't provide code here, we can help you with you problem and provide solution for the problems but not the code.

alright I understand. Thank you anyway!

Maybe I guess I should ask this,  can I still use the built-in MicroSD externally or only it will be for loading images to the TFT?

I don't understand this still use the built-in MicroSD externally, please be clear about what are you looking for.

That TFT 1.44 has a chip for Micro card and they told me it is for loading images .bmp to the screen.. so I was wondering if I can store sound files .wav there and output it to a speaker in different pin  instead of buying this Micro SD Card Breakout Board   - hopefully I explained right sorry for my English.

Do you have exposed pins for Micro SD? If yes you can try.

I'm really not good with this stuff but anyway that is okay ha ha

Sorry, forgot to mark it as the answer!

@Vaibhav, you solved this by switching to bit-banged SPI. you could not know this but a photo in next question revealed an Arduino Micro, not Nano

@Juraj what you guys talking about... you guys are way smart I don't understand these terms. It blacks me out!

the TFT library can work on any pins if you specify them. It will use software SPI. That is why it worked on 'wrong' pins.

Alright, I have made a lot of improvement and added stuff.. and now I don't understand why this line USE_ARDUINO_INTERRUPTS true case my TFT half-working. don't think you need my code but here is it https://github.com/WorldFamousElectronics/PulseSensorPlayground/issues/101

@Juraj I have another problem with the last question I asked in my profile


text:
ESP8266 webserver does not return latest HTTP response
I tried getting a HTTP response from an ESP8266 which is in HTTP server mode, I am getting a response but not the latest one, response is always one command previous to that of my request to the ESP.
Also first time I don't get any response, from the nd request response start coming but previous.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <EEPROM.h>
#include <ESP8266WebServer.h>   //ESP Web Server Library to host a web page

const char* ssid = "SpruceRND";
const char* password = "sprucernd1234";

ESP8266WebServer server(80);   // server at port 80 (http port)

//Variable to store the HTTP request
String inputString ="";
boolean stringComplete = false;
String Clientquery ="";  //for store all query params
char query_array[30];    //for store all query character
int LEDPin = 4;

void ESPserialEvent()
{
  boolean x=0;
  Serial.println("Working ESPserialevent....");
  while (Serial.available())
  {
    char inChar = (char)Serial.read();    // get the new byte:
    if (inChar == 2)   //check if 1st byte is 2
    {
      x=1;
    }
    if (x == 1);
    {
    inputString += inChar;   // add it to the inputString:
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    }
    if (inChar == 3) //check if 1ast byte is 3
    {
      stringComplete = true;
      x=0;
    }
  }
}

void  handleNew()
{
  server.send(200, "text/plain", "Hello! SPRUCE"); //200=http status code,text/plain=content type,message
}

void handleMstring()
{
  Clientquery = server.arg("tx");    //Gets the value of the query parameter
//  Clientquery.toCharArray(query_array, sizeof(Clientquery)); // convert to chararry (buffer,length)
//  if (query_array[0] == 2 )
//  {
    Serial.println(Clientquery);
//  }
//  else
//  {
//     Serial.println("Incorrect string....");
//  }
  Clientquery="";
  ESPserialEvent();
  if (stringComplete == true)
  {
    server.send(200, "text/plain",inputString);
    //Serial.println("Response from Mcu=" +inputString);
    //Serial.println("");
    inputString ="";
    stringComplete = false;
    //Serial.println("Buffer clear...");
  }
}

void setup(void)
{
  pinMode(LEDPin, OUTPUT);
  digitalWrite(LEDPin, LOW);
  delay(1000);
  Serial.begin(9600);
  WiFi.begin(ssid, password); //begin WiFi connection
  Serial.println("Connecting to....");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  server.on("/test", handleNew);
  server.on("/senddata", handleMstring);
  server.begin();
  Serial.println("Web server started!");
}

void loop(void){
  server.handleClient();
}

AT commands or esp8266 sketch? show the sketch

i don't know.How to post code

the cause of your problem is if (stringComplete == true) in handleMstring

I don't  what is the problem can you please help me. I am beginner.

It is a coding logic problem, not an Arduino problem.

one thing that produces a delay between an input and an output in any program is EOL (end of line) not being sent at the end of the command .... check that complete commands are being sent


text:
How to handle a ESP8266 webserver only to the access point?
I'm developing a application that needs to be somewhat secure, so to configure the parameters it handles a GPIO interrupt (from a button) to open a server, that lets you configure it. The problem is that it is configured to send an email, so it is connected to the wifi.
With this in mind, I need to detect the source of the connection so I can serve the html only to the access point connections.
Is it possible?

I think what you want is that it's only accessible on the local network, and not from the internet, right?

Not only the local, no. I don't really know the exact terms, but I create a WiFi with my ESP and I want only people accessing from this exclusive WiFi to be able to change the configuration. Someone in the internet or accessing the same WiFi my esp is connected to gets rejected.

When the flag from the interrupt is 1, it puts the WebServer in STA_AP mode, I want it only be accessible via the AP side of the WebServer. I don't know if this clarifies.

So it's set to both be a client on the Wifi that's connected to the internet, and be an Accesspoint at the same time. Now it makes sense. (I didn't even know the ESP could do that.) I think you can filter based on IP address.

Maybe this is a good solution that I simply overlooked. I'll take a look.

Yep, thats absolutely simple. My access point is a 192.168.4.XXX and my LAN ip is 192.168.88.XXX, I can filter it very very easily. Thanks for the light.

You could also use the less used 10.x.x.x private range, to make it less likely that the network uses the same IP range.

It is not documented, but you can construct WiFiServer or ESP8266WebServer with IP address. If you use the IP address of the AP, the server will be available only on the SoftAP. If you use the IP address of the station, the server will be available only on STA interface.
#include <ESP8266WiFi.h>

WiFiServer telneServer(23);

void setup() {
  ...
  telneServer = WiFiServer(WiFi.softAPIP(), 23);
//  telneServer = WiFiServer(WiFi.localIP(), 23);
  telneServer.begin();

Thanks! I had already solved with the comment from above, but your answer seemed a lot more elegant, so I tried and it works just fine!
I just used had to declare the server with the IP and configure the softAP to be the same using: ESP8266WebServer server(local_ip,80) and WiFi.softAPConfig(local_ip, local_ip, IPAddress(255, 255, 255, 0)) .


text:
Pin headers too long for the sensor i bought
https://www.amazon.co.uk/Adafruit-TCS34725-Color-Sensor-Filter/dp/B00OKCRU5M/ref=sr_1_3?keywords=adafruit+rgb+sensor&qid=1559653098&s=computers&sr=1-3
Just bought this colour sensor for a project and as you can see it comes with the pins detached. There are 8 pins but only 7 holes so how do i assemble it? I'm assuming its super obvious since i havent seen anyone else ask it so im sorry!
Thanks in advance.

Cut one pin off.
Get some wire cutters and position them in the groove between the last and next to last pins in the row. Squeeze. One pin will pop off.

Ok, will do. Why did they make it like that though? It's not just mine, you can see in the picture that all of them are like that

@ThisUsernameHasBeenTaken Simple: you can't (easily and cheaply) buy 7-pin headers, but you can buy 8-pin. They could cut them down to 7 pins for you, but that would cost more.

Didn't matter i screwed up the soldering so i need to buy a new one...


text:
Is it possible to do an OTA update using a GitHub link
I need to be able to download software updates through the internet without having my MKR1000 plugged in. Either that or have new code being pushed from my server (C++) to my MKR1000, and then rebooting with the new code.
Any help is useful.
Thanks.

you could use the InternalStorage object of the WiFi101OTA library to store and apply the downloaded binary

Well the goal is that i can have some MKRs spread out through the province and not have to touch them ever again, and be able to update them as necessary so the internal storage is a no-go.

it is called InternalStorage  because it stores the uploaded or downloaded binary to upper half of the flash memory. after successful upload you call apply() and it copies the binary to the run location and resets the board. new sketch is running

It may be possible if you can write your own bootloader, but it certainly won't be easy.
The normal way of doing OTA updates is to use a chip that has segmentable and remappable flash memory (such as the ESP32, ESP8266, PIC32MZ, etc) where your sketch is running from one segment, and that loads the new code from whatever source into the other segment. It then changes a single boot flag and resets the MCU, and the MCU then maps the second segment into the place of the first (swaps the two segments over) and runs the new code.
That can't be done with the SAMD21 since it has no remappable flash memory segments.
So the best you could hope for would be to reboot into a custom bootloader which then connects to the internet to download new code to flash into the main portion of the flash memory. And of course that would replace the existing bootloader and take a lot of work to create.

Addendum:
Apparently there is the "WiFi101OTA" library which allows over-the-air updates on SAMD21 boards. By all accounts this receives the new code and stores it away somewhere (a chunk of the internal flash, SD card, etc) and then copies that data to the main portion of the flash using a function running from RAM.
While this sounds good, I would not recommend using it in a live situation. For development it's fine, but not "in the field".
This is simply because there is no protection against "bricking" a unit.  Once the copy from storage to main flash starts you are at the point of never being able to go back. If that write should fail for whatever reason (there is a power outage, or the sketch crashes, or any of a myriad of other unpredictable reasons) the unit is dead.  You would have to manually reprogram the unit with a cable to bring it back to life.
By having the programming done by the bootloader (incidentally, some devices, such as AVR based boards, can only write to flash from the bootloader) the code that does the writing never gets overwritten, so a simple manual reset of the unit can restart the programming and recover the board.
If you were to adopt this library you would of course have to modify it to "pull" the update, not receive a "pushed" update. This should be trivial, but some level of network programming ability would be needed.

but the WiFi101OTA library does it. with a function in RAM, which copies the binary stored in upper part of the flash to the target location in flash. and I enhanced this library to other networking libraries and other MCU (nrf5, AVR) in the ArduinoOTA library

@Juraj I was not aware of such a library. Oh, and how does that work with AVR which can only write to flash from the bootloader segment?

@Juraj Also, that method is unsafe. If you start overwriting the code that is doing the programming and there is a crash or power outage the unit is bricked. With dual flash segments that can never happen since the switching of segments only happens once it's been verified the code is all written. That's why you'd want to do it from the bootloader not the main sketch, so it is possible to recover after a crash when running an ota update.

it doesn't brick the board. bootloader is not changed. if OTA fails, USB upload is possible. AVR ArduinoOTA needs enhanced Optiboot: https://github.com/jandrassy/ArduinoOTA#atmega-support

@Juraj "Bricked" means you have to manually re-upload the code through USB - something you don't want to be doing in the field. I would certainly never want to use such a thing in a live system. Anything that doesn't either use dual segment flash, or a bootloader that does the OTA work for you, is unsafe in a real environment. Development, fine. Live, hell no!

the bin is saved to the upper half of the flash and after sucessfull upload it is copied to the run location. there are not many reasons why a flash to flash copy should fail once it started. but yes it is "arduino" level, not professional level. I use it every day and if I have a problem, it is because I made a change which doesn't allow the sketch and OTA server run. but my M0 is only downstairs


text:
ESP 32 changing frequency instead of duty cycle
Using this code on an esp32 allow to vary duty cycle of the PWM with a fixed 5000Hz frequency and is working fine.
My question is how to vary frequency and keep duty cycle on a fixed value?

// the number of the LED pin
const int ledPin = 16;  // 16 corresponds to GPIO16

// setting PWM properties
const int freq = 5000;
const int ledChannel = 0;
const int resolution = 8;

void setup(){
  // configure LED PWM functionalitites
  ledcSetup(ledChannel, freq, resolution);

  // attach the channel to the GPIO to be controlled
  ledcAttachPin(ledPin, ledChannel);
}

void loop(){
  // increase the LED brightness
  for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++){
    // changing the LED brightness with PWM
    ledcWrite(ledChannel, dutyCycle);
    delay(15);
  }

  // decrease the LED brightness
  for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--){
    // changing the LED brightness with PWM
    ledcWrite(ledChannel, dutyCycle);
    delay(15);
  }
}

Thanks

const int freq = 5000; - this is the frequency

Hm. Right, sorry

Use ledcWriteTone ?

Why remove points on the question? changing the frequency will be helpful if you are working with a stepper motor for example.

If you want to change the pwm frequency during runtime there is a function ledc_set_freq() for this purpose. I'm not sure if your duty cycle will remain valid, but I guess it does as long as the resolution does not change. You will have to try that on your own and eventually implement a compensation.

I tried using ledc_set_freq but the issue is that if do it very quickly then is not set it anymore. If I do this on a normal arduino using pwm library i can change pin frequency each 50ms and is fine.


text:
Maximum Capacity Debugging
1. Example
Check the program below for an Arduino Nano, Old Bootloader, for variable values of N.

For low values (N<=1857), the program outputs "[FFFFFFFF]",
For higher values (1858<=N<=1953), the program outputs unpredictable variations of this string,
For higher values (1954<=N<=1955), the program outputs fails flooding the symbol "[",
Over a certain value (1956<=N), the programs does not output any character.

I didn't check extensively these results, which could be very different actually, and totally platform dependent, but I guess, reproducible.
Note that no dynamic allocation is being used.
Note that everything is initialized, first 4 values to 0xFF, next N-3 values to 0x00 (Ref.).
The compilation do not show any relevant alert, showing a modest 10% capacity usage.
Sketch uses 3206 bytes (10%) of program storage space. Maximum is 30720 bytes.
Global variables use 196 bytes (9%) of dynamic memory, leaving 1852 bytes for local variables. Maximum is 2048 bytes.

It is evident from this example how to figure the proper value of N, indeed a capacity related issue could be expected (Ref.).
Note these values are by far less than the "guess" value of N=32767 for 1 byte variables (?) (Ref.).
2. Problem
Now, with a considerably huge, real program, I am having the same issue regarding those unexpected results, so I am almost sure (few moments ago) than this is the cause.
When exceeding some "~maximum~" level, the program starts failing, and when "~releasing~" this capacity, the program starts working well (without those deleted functionality of course!).
3. Question
How should I debug, measure, dimension, or prevent this situation, and specify when it is the proper time to keep this processor, and when should I move into a bigger one, when clearly the compiler is not a reasonable guess?.

// CAPACITY TEST
#include <SoftwareSerial.h>

// SET THE PROPER N VALUE
// N<=1857: Last Valid Result
// 1858<=N<=1953: Last Observable Output - Single Char
//     PC=0x0444. [AVR MEMORY] Writing to memory location 0x0948 outside of memory size 0x0900. [UP0]
// 1954<=N<=1955: Last Observable Output - Flood
//     Invalid opcode 0xFFFF at PC=0xA402
//     PC=0x0444. [AVR MEMORY] Writing to memory location 0x0948 outside of memory size 0x0900. [UP0]
// 1956<=N: No Output
//     Invalid opcode 0xFFFF at PC=0xA402
#define N 1857

void setup()
{
    Serial.begin(38400);while (!Serial){;}

    byte a[N+1]={0xFF,0xFF,0xFF,0xFF};

    char si[3];
    Serial.print("[");
    for (int i1=0;i1<=N-1&&a[i1]!=0;i1++){
        sprintf(si,"%02X",a[i1]);
        Serial.print(si);
    }
    Serial.print("]");
}

void loop(){}

Your numbers are within the SRAM limit of an Arduino Nano (2K byte). There is a distinction between the AVR GCC language limit and the SRAM limit for a given board/MCU.

From the bottom to the top of the RAM, you have:

the .data section (statically allocated initialized variables)
the .bss section (statically allocated non initialized variables)
the heap (dynamic allocations with malloc() and new)
free space
the stack (return addresses and automatic local-variable allocations)

See the memories of an Arduino for a more lengthy
discussion.
The sizes of the .data and .bss sections are known at build time. This
is the “Global variables” memory usage reported at the end of the
compilation. The rest of the RAM is available for the heap and the
stack. This is the amount reported as “leaving 1852 bytes for local
variables”, where “local variables” is a slight oversimplification.
Your example program doesn't use heap allocation. It does use some
static allocation, mostly for the Serial buffers, and a lot of stack
for:

the return addresses from the calls to main() and setup() (4
bytes)
the local arrays a and si (N+4 bytes)
the memory needed by sprintf() or Serial.print() (unknown)

Even ignoring the last item, you can see that the whole RAM will be
consumed when 4 + N + 4 = 1852, i.e. N = 1844. As you make N larger than
this value, the stack bumps into the .bss section, and you start
corrupting your global variables. The behavior you describe is
consistent with the program corrupting the internal data structures of
the Serial object.

How should I debug, measure, dimension, or prevent this situation

There is no easy way to determine beforehand the amount of heap and
stack your program will consume. The usual solution is to measure and
report it at run time. See for example the MemoryFree library
(there are many similar to this).


text:
Trying to individually control the servos in my robot using keyboard input
#include<Servo.h>
Servo ser1;
Servo ser2;
Servo ser3;
Servo ser4;
Servo ser5;
int poser = 0;
int val;
int mot;

void setup() {
  Serial.begin(9600);
  ser1.attach(4);
  ser2.attach(5);
  ser3.attach(6);
  ser4.attach(7);
  ser5.attach(8);
}

void loop() {
    Serial.print("Choose the motor");
      mot=Serial.read();
      switch(mot)
      {
        case 1:
        {
            val = Serial.read();
            if (val == 'd')
             {
                poser += 1;
                ser1.write(poser);
               delay(15);
             }
           if (val == 'a')
             {
                poser -= 1;
                ser1.write(poser);
                delay(15);
             }
           break;
         }
       case 2:
         {
           val = Serial.read();
           if (val == 'd')
            {
               poser += 1;
               ser2.write(poser);
               delay(15);
            }
           if (val == 'a')
            {
               poser -= 1;
               ser2.write(poser);
               delay(15);
            }
           break;
         }
      case 3:
         {
           val = Serial.read();
           if (val == 'd')
            {
              poser += 1;
              ser3.write(poser);
              delay(15);
            }
          if (val == 'a')
            {
              poser -= 1;
              ser3.write(poser);
              delay(15);
            }
          break;
         }
       case 4:
         {
            val = Serial.read();
            if (val == 'd')
             {
                poser += 1;
                ser4.write(poser);
                delay(15);
             }
           if (val == 'a')
             {
                poser -= 1;
                ser4.write(poser);
                delay(15);
             }
           break;
         }
       case 5:
         {
           val = Serial.read();
           if (val == 'd')
             {
                poser += 1;
                ser4.write(poser);
                delay(15);
             }
           if (val == 'a')
             {
                poser -= 1;
                ser4.write(poser);
                delay(15);
             }
           break;
          }
      default:
          {
              Serial.print("Type valid number");
              break;
          }
    }
  }

The code just shows "Choose the motor type valid number" repeatedly and the arm contorts as soon as I upload it. Can someone please check the code and tell me what could've gone wrong?

I had edited your code, basically add indentation so now your code is much clear.

The values that you get from read are characters not integers. You will receive the character '1' or '2' not the integers you are currently checking for. As a result, none of the cases will match and you will always end up at the default: block of code.
So, you need to modify your case statement to check for characters. I.e.
switch(mot){
        case '1':       // put your digit in quoted
        {

And so on throughout the program

Oh, since you are controlling more than one servo, you might want to consider using more than one variable to track their current positions. Unless of course you want the movement of the most recently selected motor to move to one position offset from the previously selected motor. If you unsure what I mean, think about the value of poser if I select motor 1; 20 times and advance it. Poser will = 20. Then select motor 2 and advance it 1 time what will the value of poser be???

Yes, i think i understand what you mean. The value of poser will be 21. So to clarify, you're suggesting that i use different variables (eg.: poser1, poser2, poser3 etc.) for different motors right?

Actually I would suggest use an array but for now maintaining variables named like that is a good first step. If this has helped you can you please accept it as the answer (click the grey checkmark next to the answer that has helped you the most)

@aditii, did either of these answers help you? If so, please accept the one that helped you the most as the answer by clicking on the little check mark next to that answer. Accepting an answer is a way of saying "Thanks for the help".

I would suggest you to add these line in your code.
while(!Serial.available()){;} before mot = Serial.read();
This will hold you logic till any input received from Serial.
Same you add before val = Serial.read();.


text:
Can I use an AC signal to make an LED light up with arduino?
I want to use a 220VAC load as a signal and act as a switch to my arduino so Labview could interpret it as an LED ON state. I used a 4n33 octocoupler but it seems that the LED Simulation on labview keeps fluctuating. I think it's because of the negative half of the signal being blocked. Is there a way to fix this?
Here is my schematic

What code do you use to check the pin and send the value to Labview?

There's certainly an issue with your optocoupler circuit aside from the fluctuation you observe.
During a negative half-wave of 220V, you expect D1 to block the current through the LED. However, 1N4007 as any power rectifier has significant leakage current, about 5μA at normal temperature and up to 50μA when the diode is hot. This current will go though the LED which may have a much lower admissible reverse current (typical 0.1μA), damaging it. One possible schematic would be:

simulate this circuit – Schematic created using CircuitLab
Note that D1 is here not to block reverse current, but rather conduct it safely, protecting the LED of the optocoupler. Also, consider reducing the value of R2 while realising the bulk of current limitation with a non-polar capacitor: this setup will limit the current just the same but will dissipate 0.5W of heat instead of 2W as your resistor would.
Now, in either case the LED is only active when it's forwad-biased, which is less than half of the time, so it's quite normal that you see this fluctuation. In most cases, it can be reasonably dealt with by software: read your pin 3 times with a 5ms delay after each reading, and make a logical AND of your three readings.
If, for some reason you cannot do that in software, you could implement an envelope detector in hardware. I strongly suggest to do it on the low-voltage side instead of 220V side (as e.g. here)


text:
Why am not being able to initialize the Micro-SD?
The reason I bought this MicroSD board because to follow their guide
and I have used the recommend code in:
 File > Example > SD > CardInfo
also did the slight change in the code for const int chipSelect = 10;
Here is the exact code I am using:

/*
  SD card test

  This example shows how use the utility libraries on which the'
  SD library is based in order to get info about your SD card.
  Very useful for testing a card when you're not sure whether its working or not.

  The circuit:
    SD card attached to SPI bus as follows:
 ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
 ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
 ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
 ** CS - depends on your SD card shield or module.
     Pin 4 used here for consistency with other Arduino examples

  created  28 Mar 2011
  by Limor Fried
  modified 9 Apr 2012
  by Tom Igoe
*/
// include the SD library:
#include <SPI.h>
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
// MKRZero SD: SDCARD_SS_PIN
const int chipSelect = 10;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

    pinMode(10, OUTPUT); // change this to 53 on a mega(don't follow this!!)
    digitalWrite(10, HIGH); // Add this line

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("\nInitializing SD card...");

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    while (1);
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.println();
  Serial.print("Card type:         ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    while (1);
  }

  Serial.print("Clusters:          ");
  Serial.println(volume.clusterCount());
  Serial.print("Blocks x Cluster:  ");
  Serial.println(volume.blocksPerCluster());

  Serial.print("Total Blocks:      ");
  Serial.println(volume.blocksPerCluster() * volume.clusterCount());
  Serial.println();

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("Volume type is:    FAT");
  Serial.println(volume.fatType(), DEC);

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize /= 2;                           // SD card blocks are always 512 bytes (2 blocks are 1KB)
  Serial.print("Volume size (Kb):  ");
  Serial.println(volumesize);
  Serial.print("Volume size (Mb):  ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Gb):  ");
  Serial.println((float)volumesize / 1024.0);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);

  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
}

void loop(void) {
}

and this is the schematic I have used as they recommended

but the serial monitor keeps outputting Initializing SD card...initialization failed  I have tried wiring again and again but I am still getting the same result.
Here are the photo of the wiring and running the test.
There is something I'm not sure if it is helpful but after I upload the file and before the serial monitor output:
Initializing SD card...initialization failed. Things to check:
* is a card inserted?
* is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

a red led located next to R1 of the MicroSD card starts flashing and before that output, it flashes faster then it stops and I will be presenting with that output.
Things I have tried...

Different card
Without the card
Tried the 3v
Tried using  pin 4 for chipSelect

Please don't mark as duplicate because I looked at the other and I'm trying to use this guide by this company and also this guide was presenting as a solution for others and here I am using it.
Edit 1:
After the writing this question, I had to upload the file again so I can take pictures when I did that this time the serial monitor outputs:
23:02:10.089 ->
23:02:10.089 -> Initializing SD card...initialization failed. Things to check:
23:02:12.106 -> * is a card inserted?
23:02:12.106 -> * is your wiring correct?
23:02:12.106 -> * did you change the chipSelect pin to match your shield or module?

Looks like I am stuck with that and the only number keep changing
23:11:02.769 ->
23:11:02.769 -> Initializing SD card...initialization failed. Things to check:
23:11:04.778 -> * is a card inserted?
23:11:04.778 -> * is your wiring correct?
23:11:04.778 -> * did you change the chipSelect pin to match your shield or module?

Edit 2:
Sorry but it looks these numbers coming because I did mark the show timestamps box by mistake.

it looks everything ok. check the soldering of the pins of Nano.

Juraj -Tomorrow I was going to try to test the connective of the pins at school, hopefully, it is the cause.

Also wiggle the wires in the breadboard. Sometimes they don't make an electrical connection, even thought they are fully pushed in.

A quick question after only skimming the post, is this an older standard SDCard or one of the High Capacity SDCard which uses a different way to address internal memory?

@Juraj have checked connectives of all pins and they were good so soldering was alright. I don't know what next I should do

@Gerben  I have just tried that too and I even did it again in a different breadboard. No luck for me.

@st2000  I'm a beginner and not really sure about these terminologies but I can tell you I bought my Micro SD Card Breakout Board from adafruit.com

@Juraj I did upload new two images there https://imgur.com/a/B4La8kx

I think the SDCard addressing change somewhere around the 8GByte size.  Under and an address gets you a byte.  Above and an address gets you a block of bytes.  The drivers has to be able to handle both.  I think SDCards using the block of bytes approach are labeled "HC".  This has nothing to do with the SDCard break out board.

The board on the photo is Arduino Micro, not Arduino Nano. Arduino Micro doesn't have SPI on pins 11, 12, 13. Use pins MOSI, MISO and SCK.

MO to DI
MI to DO
SCK to CLK
you can use any pin as CS, only set it as parameter to SD.begin()

I'm sorry, would you explain again! So where are these DI, DO, and CLK located in my Arduino Micro!

DI, DO and CLK are on the SD module. MISO, MOSI and SCK are on the Arduino

Alright If this is what you meant
** MOSI - DI - pin  11
** MISO - DO - pin 12
** SCK - CLK -  pin 13
** CS - pin 4   :  but still initialization failed!

not 11, 12, 13 !!! they don't have a number on Arduino Micro. only labels. see the picture I added to the Answer. on your board there is MO and MI

Arduino Mini is not Arduino Micro

I'm confusing. why do you keep editing old comments? Just was curious. unfortunately, I don't have the same as the one micro you posted.

see on the board SCK is in the corner. MI is MISO and MO is MOSI

Alright, I see the editing photo, let me apply these changes.

Alright now I see this
Initializing SD card...Wiring is correct and a card is present.

This made it worked! Done!


text:
Mistaken Connect 5V to SCK Pin
i have old chinese old hotair station that controls by atmega8l 8ua chip..
and the board designer are clever enough to put 2 identical dc plug, 1 is 5v supply cable.. the other one is on off switch that connect ground pin to sck pin..
i was mistaken plug power cable to the on off side that supply 5v+  to sck.. now the station not powering up anymore..
is there anyway to copy the firmware to new chip?
it cannot be detected by usbasp since i believes the sck are toasted..
i'm just a beginners and English are not my native language. sorry if the word are hard to understand..

Welcome to Arduino! Please take the tour and visit the helpcenter to see how things work here. Retrieving the software from this AVR is - with any reasonably amount of effort - rather unlikely. It'll be easierer to guess the function of it and rewrite a "similar" software from scratch.

Both serial and parallel programming modes seem to require the SCK pin.

thanks for both of You.. i think the station manufacture intended to make the port identical to destroying they product if someone try tampered their product.. so there is no chance to duplicate the firmware as Gerben told that both connections required sck pin.. As Ghanima solution to rewrite similar software from scratch it's seem a little difficult to me.. i'm totally noob about arduino, i brought the uno couple of years ago for calibrate drone esc board. then i have never touch the uno again.. i think i need to dig deeper..


text:
Arduino Fio and Solar Pairing
I'm creating a weather station and want the station to be completely power independent. I'm using the Arduino Fio (https://www.arduino.cc/en/pmwiki.php?n=Main/ArduinoBoardFio) and have estimated the power requirements of the station to be an average of 273 mAh / day with a max load of .06A. I'm pretty sure I'll use the 850 mAh battery (https://www.sparkfun.com/products/13854) but need to know if a solar panel will work to charge the battery. Based on my current home location, I have about 3 hours of good sun per day during the winter.
The Arduino Fio has a Mini USB that seems like its sole purpose is to charge the battery but will a solar panel work or is the Fio designed to have that be a more regulated power supply? If so, will this 2W Panel (https://www.voltaicsystems.com/2-watt-panel) be compatible with the Fio to charge the battery and suite my needs.
Thanks for the help

The open circuit voltage of that panel (7.7V) is above the absolute maximum rating of the MCP73831. So when the battery is full, the voltage coming from the panel will be too high.

Note that Arduinos typically use linear voltage regulators (After a quick search I couldn't tell if the MCP73831 does or not. Linear regulators waste power by converting excess voltage to heat. You could both increase the efficiency of your setup and solve the over-voltage problem mentioned by Gerben by using a switching 3.3V supply and feeding the 3.3V pin on your MCP73831 directly.

Also note that Lithium Polymer cells require special charging circuits. You can't just trickle-charge them like you can lead-acid cells. Quoting the docs for the battery you linked: "These batteries require special charging. Do not attempt to charge these with anything but a specialized LiPo charger."


text:
Can arduino interrupts occur in a middle of if statement?
I got an issues from few days, got some code which reset millis time on successful i2c communication, if not it restart an relay after specified period of time. Here is part of the code:
 if ((unsigned long)(i2c1Millis1 - i2cpreviousMillis1) >= i2cset1 )  // check if not restarted soon
        {

i2c1Millis1 are updated every run of the loop and on successful i2c communication.
i2cpreviousMillis1 is updated on successful i2c request (coming from interrupt)
I manage to debug when false restart occur and looks like i2c1Millis1 is lower than i2cpreviousMillis1
So question is: can an interrupt occur while those two millis are compared when value of i2c1Millis1 is taken for compare and then come interrupt where i2cpreviousMillis1 is updated to current millis and it become greater and trigger the condition?
(I already modified my code i2cpreviousMillis1 is updated with i2c1Millis1  value on successful communication to prevent that, but it is not working, from time to time it made false restarts).

Did you declare i2c1Millis1 as volatile?

nope,never used that, when you mention that i read about that, looks like it not gonna help since millis is long.

You should still use it!!! I think that's more likely to cause the issues you have. Both are problems, but one is more likely to occur than the other.

After I moved millis update out of interrupt function, all works stable now.

You then might want to add the volatile to the flag set in the interrupt.

it is ok that way, when use the flag i prevent updating millis while comparing it, that fix it, nothing more is neccessary, this question is not about how to fix my problem, but to understand how interrupts may accur. When I understand that, there is lot of ways to fix it.

Yes. And it's even worse. Because your variables are longs, they are 4 bytes long, and most Arduinos are only 8-bit processors, the code only checks one byte at a time. So for example, after checking the first byte, an interrupt could occur, changing the 2nd, 3rd, and 4th byte. So you end up comparing the first byte of the old value, and other bytes of the new value.
To prevent this you could disable interrupt for a very short time, and make a copy the variable.
cli();//disable interrupts
unsigned long temp = i2c1Millis1;
sei();//enable interrupts

Or use the util/atomic.h macros
#include <util/atomic.h>

...

ATOMIC_BLOCK(ATOMIC_FORCEON)
{
  unsigned long temp = i2c1Millis1;
}

I have too many disable interrupts at my code, if increase them too much gonna start to mess with i2c communication, I changed code,raising a flag (byte variable) to trigger updating millis in main loop, not inside interrupt routene, so far works stable

Depending on how large i2cset1 (<250) you could use single byte variable, instead of 4-byte longs. That way there is no need to disable interrupts.

@user3503519, so you you used the flag recommendation from chrisl's answer and accepted Gerbens answer

1st i read this answer and got idea to use a flag and do it. after that i read other anwers

You can change the accepted answer to chrisl's, if I'm not mistaken.

Yes, an interrupt can occur at any time and can change the values during a calculation. And since you work with unsigned long variables (which are 4 bytes as I remember), it is also possible, that the calculation uses the old value for the first bytes and the new value for the other bytes, meaning that the used value for calcuation is totally garbage.
To prevent that your checks must either be atomic (meaning consisting only of 1 base instruction, which cannot be interrupted, e.g. handling only 1 byte) (that is not possible here), or you must prevent the calculation from being interrupted. For this you can turn off all or only the corresponding interrupt. To turn off all interrupts you can use noInterrupts() and interrupts() to turn them on again.
But it is questionable, why you need to update this time directly in the ISR. Instead you could only set an atomic flag (1 byte) and check this flag in the loop. If the flag was set, reset it and save the millis value. If you loop runs fast enough (which seems the case, since you already use it to set a millis timestamp) that should be sufficient
Both ways can be used and it depends on you, if it's ok to turn of interrupts for a short time, since you might miss an I2C interrupt this way.

Yes. An interrupt can occur pretty much anywhere.
Interrupts are processed between each assembly language instruction. That if will be made up of many many ASM instructions, so there are many many places where an interrupt can occur.
To avoid it you use what are called critical sections where you disable interrupts before performing some operations, then enable them again afterwards.
It is recommended to keep critical sections as short as possible to avoid breaking your interrupts. For this reason most critical sections generally involve copying values to or from local variables before then doing operations on them.
noInterrupts();
uint32_t localPreviousMillis = i2cpreviousMillis1;
interrupts();

if ((unsigned long)(i2c1Millis1 - localPreviousMillis) >= i2cset1 )  // check if not restarted soon

On an 8-bit system even assigning a simple value like that can be interrupted. A 32-bit value is made up of four 8-bit values, and an interrupt can occur between the copying of any of those 4 bytes.

thank you for your answer, mentioning assembler I remind old Apple ][ days where I used to write in assembler and basic :)


text:
Will the Duemilanove bootloader work in the Uno?
Similar to Will the Uno bootloader work in the Duemilanove? but the other way around.
I have an Arduino Uno. I require a slower upload speed than the 115200 baud rate used in the Uno's Optiboot bootloader.
The Arduino Duemilanove uses the ATmegaBOOT_168_atmega328 bootloader which has an upload baud rate of 57600. The Arduino Duemilanove also uses the ATMega328P like used on the Arduino Uno.
Will the Duemilanove bootloader work in the Uno?

you could use Optiboot compiled for a different baud rate

@Juraj Quite true. Why not turn that into an answer. Personally, the ATmegaBOOT_168_atmega328 bootloader appeals to my lazyness.

Yes it will.
Both the Arduino Duemilanove and Arduino Uno use the ATMega328P microcontroller. (There is also a version of Arduino Duemilanove ATMega168 that uses the Diecimila bootloader and that is not compatible, so just watch out).
The main difference between the Arduino Duemilanove and the Arduino Uno is that the Duemilanove uses FTDI FT232R IC, whereas the Uno uses the Atmega8u2 microcontroller fto handle the USB to serial UART interface.
Also important is that both boards both have the same 16MHz clock rate.
The schematic for the Arduino Duemilanove can be found here.
The schematic for the Arduino Uno can be found here.
Of course, instead of selecting Arduino Uno as the board type, you need to always select Arduino Duemilanove or Diecimila and the ATmega328 processor.

The question asks about Y problem. Here is the solution for the problem X in this X->Y situation.

I require a slower upload speed than the 115200 baud rate used in the Uno's Optiboot bootloader.

The Optiboot bootloader can work on different UART baud rates. The baud rate is configurable as parameter of the make command at build.
If don't want to setup the toolchain for compilation of the bootloader, MCUdude has on GitHub ready Optiboot hex files compiled with many options.
I recommend to use a custom boards definition for boards with not standard settings to burn the bootloader and to upload to the board. Here I have my https://github.com/jandrassy/my_boards as example.

Thanks for the answer. MCUdude looks like a good resource.


text:
Communicating with Arduino Mega 2560 Serial ports through x2 RS232
I am trying to drive a stepper motor using an Arduino Mega 2560. There will ideally be two RS232 signals being read into / written from the Arduino, each using male USB 3.0 connectors; one of these is for configuring and controlling the driver of the motor and the other is simply getting an output torque measurement from a torque meter connected to the motor's shaft.
I am simply wondering if Arduino would be able to handle these two functions, and how I might go about connecting each of the two streams of data. I have looked into this question through Arduino documentation, tutorials, and forums for hours, and finally figured I would contribute to the posts on my own.
Thank you!

a confused college student

You have 4 serial ports. The obvious option would be to use Serial1 and Serial2, while keeping Serial for debugging output. I can't quite see where you see a problem.

More information please!  The part you have chosen should be more then fast enough to do what you want. A big portion of the interface will be the sensors and their capabilities as you have indicated. The serial channels on the Mega are buffered so you have some time. The driver, are you controlling each phase or just command a module on what to do? Where does the serial channels come into play, there are a lot of sensors that do not need them. Posting links to "technical" information on each of the hardware items will help a lot as would a simple annotated schematic or block diagram.

Your main problem seems to be confused by all the information. I will give you some more.
The Arduino speaks UART (Universal Asynchronous Receiver Transmitter) with it's Serial interfaces (there are 4 of these on the Mega). This is partly the same protocol as RS232, but it uses TTL logic levels (in this case the levels 5V and 0V), while RS232 has different voltage levels and more lines (like control lines). When you connect your Arduino to a PC, the PC is not directly talking to the Arduinos chip (here the Atmega2560). Instead every Arduino with a USB port has an extra chip. It will handle the (very complex) USB communication, so that you can see an emulated COM port on your PC. The data, that the PC sends to that COM port, get's transmitted over USB to that extra chip, which in turn will convert it to UART signals and send them to the Atmega2560.
All Arduinos, that I know of, have only 1 USB-to-UART chip. But you can add your own USB-to-UART chip to one of the other Serial interfaces. You can use a FTDI chip, an Atmega16U2 or (if you don't want to program an extra chip) simply an USB-to-UART converter cable/module, which you can buy and use directly by just connecting their pins to the Arduinos Serial pins.

By the way, it doesn't really matter here, if you use USB3.0 ports, since chips this small cannot work with speeds that high. All these chips use USB2, more is not necessary, they aren't fast enough.


text:
Fail to return int value from a function
I have created myJSON library to simplify read and write values from/ to FLASH of my ESP8266 NodeMCU/ Wemos Mini.
I do not want to "mess up" the question, posting my entire code/ library - but to try to explain what happens -
I get a 0 value when reading a specific key (and not its saved value ). My assumption is that is has nothing to do with myJSON library, but my understanding in returning a value from a function.
Code is as follows:
(some explanations first):
1) json is an instance of myJSON library.
2) json.setValue(key, value) - gets a key and a value ( char/ int) and save it to FLASH.
3)json.getINTValue(key, return_var)- gets a key and return its int value to return_var. function return 1 - for successful read, and 0 when not.
inside setup()
int int_val;
// json.setValue("int_key",343); // commented out after first run - to be sure is is saved and read from flash.
Serial.println(json.getINTValue("int_key",int_val)); // NOTE 2
Serial.print("Value is: "); // NOTE 3
Serial.println(int_val);   //  NOTE 3

myJSON ( only relevant code )
bool myJSON::getINTValue (const char *key, int retval){
        StaticJsonDocument<DOC_SIZE> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        bool hasKey = tempJDOC.containsKey(key);
        if (hasKey){
          retval = tempJDOC[key];
          Serial.print("retval :"); // NOTE 1
          Serial.println(retval);  // NOTE 1
          return 1;
        }
        else {
          return 0; // when key is not present
        }
}

void myJSON::setValue(const char *key, char *value){
        StaticJsonDocument<DOC_SIZE> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        tempJDOC[key]=value;
        myJSON::saveJSON2file(tempJDOC);
}
void myJSON::setValue(const char *key, int value){
        StaticJsonDocument<DOC_SIZE> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        tempJDOC[key]=value;
        myJSON::saveJSON2file(tempJDOC);
}

result is (SEE NOTATIONS):
21:01:03.198 -> retval :343  // OUTPUT NOTE 1
21:01:03.198 -> 1            // OUTPUT NOTE 2
21:01:03.198 -> Value is: 0  // OUTPUT NOTE 3

As far a I could understand :
1) setValue works as needed ( inc. saving to flash ).
2) unexplained besides getting value = 0, is when setting a char value ( there are 2 myJSON::setValue functions to deal with int and char), code works as needed.
Appreciate any help ( and sorry for my English ).
Guy

bool myJSON::getINTValue(const char *key, int &retval){

@Juraj can you explain why? and why is it different from char variable ?

it is not an Arduino question. & is 'reference'. the parameter with & is not a value, but a reference to a variable

@Juraj - I know the mean of &, but why it doest not pass its value a to retval?

the parameters of a function call are copied into parameters in the function. if the pointer is copied it still points to a memory where you write the data. if int is copied then changing the value changes the copy, not the variable used as parameter. reference is kind of pointer
how to make an in-out parameter by passing a parameter by reference
void setup() {

  Serial.begin(115200);
  int x = 3;
  fnc(x);
  Serial.println(x);
}

void loop() {

}

void fnc(int &x) {
  x = 5;
}

prints 5
example with a complex type
#include <IPAddress.h>

void setup() {

  Serial.begin(115200);
  IPAddress ip(192, 168, 1, 5);
  fnc(ip);
  Serial.println(ip);
}

void loop() {

}

void fnc(IPAddress& ip) {
  ip = IPAddress(192, 168, 1, 3);
}

with &ip it prints 192.168.1.3. without & it prints 192.168.1.5

Tnx ! and the reason char behaves differently is because it points to a pointer ?

char* is a pointer. and char[] is a pointer too. it is copied so assigning a different pointer to it would not work. but if you change the memory where it points you will read outside of the function the same memory location with the changed content

Your problem is not directly how to return a variable, but how to give a variable from outsite the function as parameter to be filled by the function. There are basically 2 types how you can give a variable to a function: by value or by reference
The definition of getINTValue() says
getINTValue (const char *key, int retval)

so retval will be an integer and is called by value. This means, that a local variable with that name is created and filled with the value from the function call parameters. You are writing to this variable, but it get's thrown away when the function returns. And the writing to the local variable didn't change the outsite variable.
You need to use a call by reference. Your function must take a pointer to an integer variable. Then you dereference it and write to it:
getINTValue (const char *key, int *retval){
    ...
    *retval = tempJDOC[key];
    ...
}

When you call the getINTValue() function, it must be done like this:
int value;
bool result = getINTValue("int_key", &value);

The & operator gets you the pointer to the variable value, which the function then uses to write a value at that memory location.

char* is different, because you give an array to the function in this case. The compiler sees, that the used variable is an array and uses the pointer to the first element of the array as parameter. That is a common way, because you can iterate over an array by using pointers (without index numbers). You can do the same with any array of any type, but in this case you only have a single variable, not an array.

Oh, sorry, have read it wrong. Can you elaborate your comment shortly or give me a hint for what to google here? I learned it the way I've shown in my answer and while googling I couldn't find your way of doing it (though I didn't google for long). Would be great to learn more.

I wrote it as answer


text:
Possible to live-control an Arduino microcontroller from any Linux IoT board?
I'm working on a home project that centers around a non-Arduino Ubuntu IoT board but I'd like to add an ATmega32U4 chip for USB HID.
I'm thinking about using an Arduino Micro.
The signals to the Micro would have to come from my other board (maybe a Python script), but I haven't found instructions on how to send instructions in real-time from Other Board to Arduino Micro so they go straight through the Micro to the computer it's attached to.
How can one do this?

Am I right that your structure is Ubuntuboard --> Micro --> PC? Why do you need the Micro to communicate with the PC? What do you try to achieve?

@chrisl The Ubuntu board doesn't have a microcontroller and it doesn't work as a HID (mouse). That's what I need the Micro for.

@Juraj I don't understand what you mean by that comment.

can you just use a usb2serial adapter and the micros tx/rx?