text:
First Uses of Digispark can't get past upload error
Windows 7 (64Bit) Parallels VM on Macbook Pro running BigSur. Arduino version 1.18.19, Digispark ATtiny85 Micro USB.
Loaded Boards Manager http://digistump.com/package_digistump_index.json and updated all.
Installed Windows Driver DPinst64 from digistump.
Device Manager shows:

libusb-win32 USB Devices
Digispark Bootloader

This a first-time use of Digispark.
I have written a couple of successful programs for the ESP32 devkit v1.
Test Program

    void setup() {
      // initialize the digital pin as an output.
      pinMode(0, OUTPUT); //LED on Model B
      pinMode(1, OUTPUT); //LED on Model A
    }

    // the loop routine runs over and over again forever:
    void loop() {
      digitalWrite(0, HIGH); // turn the LED on (HIGH is the voltage level)
      digitalWrite(1, HIGH);
      delay(5000); // wait for a second
      digitalWrite(0, LOW); // turn the LED off by making the voltage LOW
      digitalWrite(1, LOW);
      delay(5000); // wait for a second
    }

Compiles OK. Upload immediately goes to the following error: (with the Digispark not plugged in).

Running Digispark Uploader...
Plug in device now... (will timeout in 60 seconds)
Assertion failed: res >= 4, file library/micronucleus_lib.c, line 100

I can find no relevant information on the error, I need help.

Welcome to SE/Arduino! Please take the [tour] to learn how this site works. You might want to read some of the pages of the [help], too, while you wait for an answer. -- Granted, my experiences with Digisparks on Windows 10 and Linux are limited. But this error, especially since it appears immediately, points to a problem between the VM and one of the drivers, not the Digispark. Did you consider to use native drivers? -- Please [edit] your question to add new information, this is not a forum.

The device is only in bootload mode for a brief moment after power-up, therefore you have to unplug the device before hitting upload, and only connect it once it tells you to. This way the programmer can hit the bootloader in time to halt normal bootup, before execution is handed off to your code.
Literally stumbled over the same issue today, dunno why it won't just tell you this in the console right away.

This "brief" moment is about 5 seconds long, IIRC. ;-)

However, since the OP did not connect the Digispark at all, this does not answer the question. The posted error appeared immediately.


text:
Programming ATtiny1616 error: A programmer is required to upload
I have this ATtiny1616 breakout board, and I'm attempting to upload an Arduino sketch to it following this documentation, but I'm getting the error "A programmer is required to upload" upon uploading a simple blink sketch. I have the following parameters set in the IDE:

Board: ATtiny
Chip: Attiny1616
Programmer: Serial UPDI: Slow 57600 baud

I am using this USB-Serial adapter and it is connected to the ATtiny like so:

USB Vcc -> Vin

USB GND -> GND

USB RX -> 1k OHM

USB TX -> 1k OHM

1k OHM -> UPDI

And I have an LED connected to pin 5 of the ATtiny:

PIN 5 -> LED -> 220 OHM -> GND

Below is the circuit. I also thought that maybe I had RX and TX mixed up, so I tried switching those connections but that didn't work either.

Using Arduino IDE 1.8.19 I get this error:
pymcuprog.pymcuprog_errors.PymcuprogError: UPDI initialisation failed

The error message seems to imply that you have not selected an appropriate programmer from the list available in the IDE tools menu ( bottom of page). The Adafruit recommendation (your link) is SerialUPDI - SLOW: 57600 baud.

Thank you for your response, however as per my OP I have that parameter set.

are these header pins soldered on the PCB or you simply plug the header pins to the breadboard?

I just have male header pins connected from the jumper cables to the breadboard.

I guess then you are using Arduino IDE 2.x. There is a known behaviour difference between that and 1.x which can cause confusion leading to your error message. See https://forum.arduino.cc/t/a-programmer-is-required-to-upload/1101631 . If this solves it then write your own answer with a bit more detail.

Thank you for that. Using IDE 1.8.19, no longer is there the programmer error but I get a different error now in the updated OP.

If you Google for that error message you find some variants of the circuit added between the usb/uart adaptor and the attiny. Some with a Schottky diode and some with other resistor values. The values may also depend on whether the usb/uart adaptor has resistors in series with TX and RX. If that usb/uart adaptor is 3v3 like the Adafruit version, you could also try powering tha attiny at 3v3

Please make sure that your USB to serial adapter is working well. If the adapter itself is faulty, it can create problems. Also, check if you have all the necessary drivers installed.
Here is another tutorial regarding how to program the ATTiny1616  Breakout board using the MegaTinycore library. You can find it here :
https://www.pcbway.com/project/shareproject/ATTiny1616_Minimal_Breakout_board_QFN_bad990fc.html

In order to use a USB-Serial adapter as a SerialUPDI programmer, it needs to wire it as the diagram shown below
                        Vcc                     Vcc
                        +-+                     +-+
                         |                       |
 +---------------------+ |                       | +--------------------+
 |                     +-+                       +-+                    |
 |                     |      +----------+         |                    |
 |                  TX +------+   1k     +---------+ UPDI               |
 |                     |      +----------+    |    |                    |
 | USB-Serial Adaptor  |                      |    |  Target AVR Board  |
 |                     |                      |    |                    |
 |                  RX +----------------------+    |                    |
 |                     |                           |                    |
 |                     +--+                     +--+                    |
 +---------------------+  |                     |  +--------------------+
                         +-+                   +-+
                         GND                   GND

Thank you for your response, however upon connecting the ATtiny as described in your post I'm still getting the same error. I'm updating my OP with a picture of my connections.

What IDE are you using? Arduino IDE with MegaTinyCore? or something else?

Yes, I'm using the Arduino IDE with MegaTinyCore. I also would like to note that in attempt to getting it to work, I pressed the "Burn bootloader" button, when using an Arduino to try to connect to the ATtiny. Could that have messed something up?

No idea. I never use the boot loader. In fact, I nowadays don't even use MegaTinyCore and Arduino IDE often, I mostly just have VS Code, AVRDude and  bare metal. I think you should consider soldering the header to the board, the problem you are facing might just be bad connection.

"burn bootloader...". This can cause a problem if it succeeds in uploading a bootloader because it has the potential to convert the updi pin to a reset pin preventing further updi programming and needing a high voltage programmer to undo it. However, if you chose the board variant something like "attiny 1616 without optiboot " then "burn bootloader..." simply updates fuses. On these Attinys with a low pin count a bootloader is not recommended. The term "burn bootloader" in the IDE causes much confusion because it may not mean burn bootloader.

Errata: With the MegaTinyCore, loading the bootloader does not automatically convert the UPDI pin to a reset pin on the attiny 1616. See https://forum.arduino.cc/t/programming-and-implementing-attiny1616-with-breakout-board-error-a-programmer-is-required-to-upload/1232433/14

source: Stack Exchange

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

sort: votes


text:
Confusing Pinouts on MH-ET ATTiny88
I am a little bewildered about the analog pins on the Arduino ATTiny88.
First of all, am I correct in thinking the functions analogRead() and analogWrite() can use either the string A0 - A7 or a decimal number as inputs?  Since I need to use the pins A7, A0, A1, A2m A3, and A4 - in that order - as analog inputs and A6 as an analog output, it would be much more convenient to use decimal digits instead of the aforementioned strings.
If so, then there also is a bit of a question in my mind about the numbers themselves.  It looks to me as if the pin numbers start with 0, rather than 1, so the right hand pins start with 15, and the analog pins start with 17 (A6) through 24 (A5).  So can I simply scan the analog pins starting with analogRead(18) and increment each pin by one through analogRead(23) and use analogWrite(17), or do I have to build a table of strings and iterate through the table?
I have looked through the documentation on various boards, and it just is not quite clear to me.  The digital pins are a bit more consistent, although not fully so.  D0, D1, and D2 are on what would normally be pins 30 - 32, adn digital pins 3 - 25 are all offset by 1 from the usual numbering scheme.  Some other Arduino boards have even stranger numbering schemes.  (And yes, I understand why the pinouts on the board do not match up exactly to those on the MCU chip.)

So far, I have been unable to get the analog inputs to work, no matter what I try.  I have tried:
Value = analogRead(A0);
Value = analogRead(A7);
Value = analogRead(17);
for (uint8_t x=17; x < 24; X++)
{
    Value = analogRead(x);
}

Obviously, I prefaced all of these calls by defining the ports with  pinMode(xx, INPUT) using identical target values.  None of them appeared to return an appropriate value given the voltages on the inputs. (Roughly 3 volts on each pin, which should have returned a value around 600.)

You didn't mention what framework you are using. if you are referring to ATTinyCore Arduino framework, the A0-A7 is defined here, if you trace up a few lines, it matches the pin17-pin25.

I am not sure what "framework" means.  The board definition I am using in the IDE is "MH-ET LIVE Tiny88(16MHz)".

This still seems quite odd, to me, but I have gotten an answer that works.  In an effort to discover the correct ports to use for the analogRead() and analogWrite functions, I created this test sketch:
#include <Arduino.h>
#include <TM1637Display.h>

// Create a display object of type TM1637Display
TM1637Display display(4, 3);

int BatteryValue = 0;

void setup()
{
    // Note: Setting up the analog pins as inputs is not required
    display.setBrightness(0x0f);    // Initialize display
    display.clear();                // Clear display
}

void loop()
{
    // Move through battery cells
    for (int  x = 1; x < 26; x++)
    {
        display.showNumberDec(x, false);            // Using the TM1637 to show the pin number
        delay(1500);
        BatteryValue = analogRead(x);               // Read the value of the pin number
        display.showNumberDec(BatteryValue, false); // Display the analog value of the pin
        delay(2000);
    }
}

I first tried initializing the pins as inputs, but it turns out this is unnecessary, and as it turns out would cause problems.  The output of the sketch made it perfectly clear which pins are the analog inputs.  This board uses pins 11 - 16 in code to read the pins labeled as A7 and A0 - A4 on the board, respectively, and pin 10 to write to A6 on the board.  This does make sense in a sort of twisted way, if we take the numbers to be Hexadecimal values, rather than Decimal.  In any case, this code now works perfectly:
#include <Arduino.h>

int BatteryValue = 0;

void setup()
{
    analogWrite(10, 128);       // Send PWM to analog pin 10
}

void loop()
{
    // Move through battery cells
    for (int  x = 11; x < 17; x++)
    {
        BatteryValue = analogRead(x);
    }
}

All attempts to use A0, 17, etc failed.

I need to use the pins A7, A0, A1, A2, A3, and A4 - in that order

If you want to read the ADC from the channels in the order you want, all you need to do is to create an array that has the pins in the sequence as per your order and access each of it with an index.
int adcChannels[]{A7, A0, A1, A2, A3, A4};

for (int i=0; i<sizeof(adcChannles; i++) {
  int adcValue = analogRead(adcChannel[i]);
}

BTW, based on your comment, I have found the Arduino Core (a.k.a Arduino framework) that you are using on the internet. Based on the board definition for MH-ET LIVE Tiny88, the analog pins definition can be found here. They are partially in sequence with pin19-24 for A1-A5, and pin 17-18 for A6-A7.
One more thing, the naming of the pin A0 is not a string. It is just a name for a variable as
static const uint8_t A0 = 19;

I don't know why, but this does not seem to be correct.  I was able to get it working, but not with those values.  Please see my answer.

Expectations

First of all, am I correct in thinking the functions analogRead() and analogWrite() can use either the string A0 - A7 or a decimal number as inputs?

This requires dissection to explain what is correct (or rather should have been correct) and what isn't. A0, A1, are "identifiers" rather than strings and typically evaluate to some value of int type. These pins are connected to usage of analogRead(). analogWrite() doesn't have any strict relationship to these pins. In some cases none of the A0, A1, etc pins are PWM or DAC output capable.
For analogRead() you are more or less correct. It's the norm for the numbers used A0, A1, etc to be larger than the largest ADC channel number. And that allows analogRead() to be written in such a way as to accept either an ADC channel number or one of those identifiers starting with an A.
Core bug
However, the MHEtLiveArduino core code to do that is broken. And if you're curios as to how:
#elif defined(__AVR_ATtiny88__)
    if (17 <= pin <= 18) pin -= 11; // allow for channel or pin numbers
    else if (19 <= pin <= 24) pin -= 19;
#else
    if (pin >= 14) pin -= 14; // allow for channel or pin numbers
#endif

In the #else section you can see the code that is used for the more common UNO R3 (and a few others) which have ATmega8/168/328 chips with 14 (0 to 13 inclusive) "digital"-but-not-"analog" pins. The analog pins are mapped to numbers 14 upwards. They subtract off 14 to convert the pin number to an ADC channel number that later goes into the ADMUX hardware register.
The code that MHET bolted onto the original AVR core code (in the #elif defined(__AVR_ATtiny88__) section) contains some if-statements with conditions that take the form A <= B <= C. This is normal math notation that would work in Python, but for C (or C++) needs to be rewritten as A <= B && B <= C.  C (and C++) treat A <= B <= C more literally as  (A <= B) <= C; they check whether or not the truth-value of A <= B (a 0 or 1) is less than C which is rarely what someone would want.
So, MHET have if (17 <= pin <= 18), which is always true irrespective of the value of pin. 17 <= pin is either 0 or 1. Both 0 and 1 are <= 18. So, no matter what number you give for pin it will pin -= 11. pin is of uint8_t type. So, they subtract 11 from it and allow it to reduce modulo 0x100. Later the take the lower four bits for the ADC channel number.
Patching the core
If you want, you can find and fix your installed MHET core's wiring_analog.c by fixing the if conditions:
if      (17 <= pin && pin <= 18) pin -= 11;
else if (19 <= pin && pin <= 24) pin -= 19;

ATtinycore
It is probably better to switch to ATTinyCore. They seem to support the MHtiny pin mapping.

I am not sure I want to switch at this point.  It might break something else.  Assuming I do take that on, does it support the Micronucleus upload, which does not employ a serial port?  Also, I am having some trouble with the PWM output on A6.  So far I am not able to get it to work. You say in some cases none of them work.  How can I know for certain which pins will work?

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


text:
How can I display an image on a Waveshare ILI9486?
I am using STM32 and 3.5 inch TFT display (Waveshare ILI9486) and I want to display an image and I have connected the SD card. How to do using the Arduino IDE?
For now I am trying to fetch a word from a text file and trying to display on the LCD.
#include <SPI.h>
#include <SD.h>
#include <Adafruit_GFX.h>
#include <Waveshare_ILI9486.h>

#define SD_MOSI_PIN PC12 //MOSI Pin
#define SD_MISO_PIN PC11 //MISO Pin
#define SD_SCLK_PIN PC10 //Clock Pin
#define SD_SS_PIN PB6 //Chip Select or Slave Select Pin

//#define SD_CS_PIN PB0
#define TFT_CS_PIN  PB6
#define TFT_DC_PIN PA8
#define TFT_RST_PIN PA9

#define  BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

#define BUFFER_SIZE 50

char textBuffer[BUFFER_SIZE];

// Assuming the constructor in your library takes no arguments
Waveshare_ILI9486 tft;
uint16_t color565(uint8_t r, uint8_t g, uint8_t b)
{
  return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}

static int bufferIndex = 0;
File myFile;
HardwareSerial SerialPrint(PC5, PC4);
/*  void setup()
  {
    Serial.begin(115200);
    Serial.println("Initializing SD card...");
    SPI.setMISO(SD_MISO_PIN);
    SPI.setMOSI(SD_MOSI_PIN);
    SPI.setSCLK(SD_SCLK_PIN);

      SPI.begin();
      tft.begin(); // Assuming the library's begin function doesn't require arguments

    if (!SD.begin(SD_SS_PIN))
    {
      //SerialPrint.println("SD card Initialization failed!");
      Serial.println("SD card Initialization failed!");
      while (1);
    }
      //SerialPrint.println("SD Card Initialization done.");
       Serial.println("SD Card Initialization done.!");

       myFile = SD.open("test5.txt", FILE_READ);

}

void clearBuffer() {
  for (int i = 0; i < BUFFER_SIZE; i++) {
    textBuffer[i] = 0; // Set all characters to null terminator (0)
  }
  bufferIndex = 0; // Reset the buffer index
}

void loop()
{
  if ( myFile.available())
  {
    char nextChar = myFile.read();

     while (nextChar >=0 && bufferIndex < BUFFER_SIZE)
     {
      textBuffer[bufferIndex] = nextChar;
      Serial.println(textBuffer);
      Serial.println(bufferIndex++);
      nextChar = myFile.read();

    }

    Serial.println(textBuffer);
    Serial.println(bufferIndex);
    Serial.println(sizeof(textBuffer));

    // Check for buffer overflow and handle it (optional)
   if (bufferIndex >= sizeof(textBuffer))
    {

       clearBuffer();
    }

  }
 else
{
    // Display the content of the buffer on the LCD
    tft.fillScreen(BLUE);  // Clear the screen before displaying text
   tft.setTextSize(2);
   tft.print(textBuffer);
   bufferIndex = 0;  // Reset buffer index for next file read
  myFile.close();    // Close the file after reading
  }
 delay(1200); // Adjust delay based on desired reading speed

}*/

what is the problem that you are trying to solve? ... the code you presented does not compile ... please update it

You are using PB6 as the chip select for both SD Card and  TFT. For SPI communication, if you have two devices connecting to the same SPI bus, you need one CS pin for each device.

You have to use the image2LCD software. Link is given in the software section here: https://www.waveshare.com/wiki/3.5inch_TFT_Touch_Shield


text:
unable to find string literal operator 'operator"" stylesheet'
I am new to programing in C and I get this error:
unable to find string literal operator 'operator"" stylesheet'.

I am making a website for NodeMCU 0.9. My code:
 String message2 = "<!DOCTYPE html>";
      message2 += "<head>";
      message2 +=  "<title>Bootstrap Example</title>";
      message2 += " <meta name="viewport" content="width=device-width, initial-scale=1">";
      message2 += "<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">";
      message2 +=  "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>";
      message2 +=  "<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>";

possible duplicate alright, same author, same code

I think I answered a similar question in a previous answer.
You use "before/after viewport in the fourth line, which should be prefixed with \ to make it an escape code to be treated like a " character instead of the start/end of a string.
Also afaik String is C++, as is the += operator, not C.
See answer

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


text:
serial is print twice?
I have a problem , when send 1 or 0 by Bluetooth module the serial monitor print two time (RECEIVED SMS) . what's the wrong ?
This is my code  :
   char BluetoothData = 0 ;
void setup() {
  // initialize serial communication:
  Serial.begin(9600);
    for (int pin = 1; pin <= 13; pin++)
     {
       pinMode(pin, OUTPUT); // sets the digitals pin  as outputs
       digitalWrite(pin, LOW); // sets the digitals pin off defult intial states
     }
       Serial.println("ALL LEDs NOW OFF \n ");
       Serial.println("Please, Enter : ( 1 to Turn on All LEDs )  or ( 0 to Turn off LEDs ) \n");
}
void loop() {
  // read the sensor:
  if (Serial.available() > 0) {

        BluetoothData = Serial.read();
            Serial.print("*** RECEIVED SMS *** : ==>> ");
            Serial.println(BluetoothData);

        if (BluetoothData == '1'){
        for (int Pin = 1; Pin <= 13; Pin++) {
          digitalWrite(Pin, HIGH);
          }
          Serial.println("ALL LEDs NOW ON");
         }
        // turn all the LEDs off:
   else if (BluetoothData == '0') {
        for (int Pin = 1; Pin <= 13; Pin++) {
          digitalWrite(Pin, LOW);
          }
          Serial.println("ALL LEDs NOW OFF");
         }
  }
   delay(100);
}

This is photo for serial monitor

Please do not post photos of the output, rather select the text, then copy/paste the text into the question, as indented code

for ease of readability and understanding: 1) please consistently indent the code.  Indent after every opening brace '{'.  Unindent before every closing brace '}'.  Suggest each indent level be 4 spaces.

the posted code does not contain a main() function, not the necessary #include statements.  So how are we to reproduce the problem?

I cannot understand all the functions and terms of the site.  I weak in that, is there a video that explains the matter?

Probably the first time because you received the character '1' or '0'.
The second character is probably a '\0' or '\d', an end-of-string or end-of-line character.
You can easily check this by printing the value of each received character, like
Serial.println((int)(BluetoothData));

You probably see the value for '0' (48), '1' (49), end of string '0' of end of line '13' or maybe '10' (new line).

thanks a lot man , true solution :)

you're welcome.

In the Arduino IDE you should select "No Line Ending" from the menu, instead of "New line". Otherwise you are sending an extra "\n".


text:
Execution of functions at the "same time"
everyone
I'm designing a vehicle security system, basically I can already read amd i control all the components (GSM, GPS, Magnetic Sensor, Giroscop, buzzer...) connected to the microcontroller.
But then the functions are basically three main ones  (at void loop) that I need to be working in "simultaneous", any idea of how I can do that?
Below the code, half long but that's all I need...
there are some comments in portuguese. i apologize for that, but the important thing is in the code
thanks in advance
#include <SoftwareSerial.h>
#include <TinyGPS++.h>
SoftwareSerial sgsm(3,2);
String number = "25884xxxxxxx" ;
unsigned char Buff[250];
unsigned char BuffIndex;

#include<Wire.h>
int sensorMag = 5;  //SENSOR MAGNETICO

TinyGPSPlus gps;
double latitude, longitude;
String response;
int lastStringLength = response.length();
String link;

const int MPU6050_addr=0x68;
int16_t AccX,AccY,AccZ,Temp,GyroX,GyroY,GyroZ;

#include <IRremote.h>
int RECV_PIN = 4;   //REMOTE
IRrecv irrecv(RECV_PIN);
decode_results results;

int Sirene = 6;     //BUZZER
int Motor = 7;      //MOTOR

/////===================================================================== Inicializacao do sensores =============================================================================================================================
void setup()
{
Serial.begin(9600);
sgsm.begin(9600);
delay (1000);
Wire.begin();
Wire.beginTransmission(MPU6050_addr);
Wire.write(0x6B);
Wire.write(0);
Wire.endTransmission(true);
delay (1000);
pinMode(sensorMag, INPUT); //SENSOR MAGNETICO
pinMode(Sirene, OUTPUT);  //Sirene
pinMode(Motor, OUTPUT);   //MOTOR
irrecv.enableIRIn();
Serial.println("SISTEMA INICIALIZADO");
}

/////=====================================================================  Inicio do Loop  =============================================================================================================================
void loop()
{
 //GPS();
 remote ();
 ReceberComando();

 }

/////=====================================================================   Remote controle  =============================================================================================================================

void remote (){
 if (irrecv.decode(&results))
{
Serial.println(results.value, HEX);
Serial.println("  ");
if (results.value== 0xFF6897)
{
//while (results.value==0xFF5AA5){
Serial.println("SISTEMA INACTIVO");
digitalWrite(Motor, LOW);
Serial.println("  ");
//Acelerometro();
delay(500);
}
else
{
 while (results.value==0xFF10EF)
  {
    Serial.println("Sistema Armado");
    digitalWrite(Motor, HIGH);
    delay(1000);
    Serial.println("  ");
    SensorMagnetico();
    delay(1000);
    Acelerometro();
    delay(1000);
  }
}
}

irrecv.resume(); // Receive the next value
delay(1000);
}

void SensorMagnetico()
{
int EstadosensorMag = digitalRead(sensorMag);
if (EstadosensorMag = digitalRead(sensorMag)== HIGH){
 Serial.println("A porta N. 1 da sua viatura foi aberta!");
 digitalWrite(Sirene, HIGH);
 delay(1000);
 mensagem2();
 delay(1000);
 enviolink();
 delay (1000);
}
else
 Serial.println("Portas Fechadas");
 digitalWrite(Sirene, LOW);
 delay(100);
 //digitalWrite(Motor, HIGH);
}

void Acelerometro(){
Wire.beginTransmission(MPU6050_addr);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU6050_addr,14,true);
AccX=Wire.read()<<8|Wire.read();
AccZ=Wire.read()<<8|Wire.read();
Serial.print("AccX = ");
Serial.print(AccX);
Serial.print(" || AccZ = ");
Serial.println(AccZ);
delay(1000);

if (AccZ > 2000){
digitalWrite(Sirene, HIGH);
delay(2000);
}
else
digitalWrite(Sirene, LOW);
}

/////====================  coordenadas/ GPS=============================

 void GPS(){
 if(Serial.available()) {
   gps.encode(Serial.read());
 }
 if(gps.location.isUpdated()) {
   Serial.print("latitude:");
   latitude = gps.location.lat();
   Serial.print("longitude:");
   longitude = gps.location.lng();
   link = "www.google.com/maps/place/" + String(latitude, 6) + "," + String(longitude, 6) ;
   Serial.println(link);

 }
}

/////=========  Receber Comandos de texto + localizacao ======================
void ReceberComando()
{
Serial.begin(9600);
sgsm.begin(9600);
Serial.print("Inicializado o GSM e apagando SMS");
clear_SMS_Memory();
delay(3000);
sgsm.println("AT+CMGF=1");
delay(3000);
sgsm.println("AT+CNMI=2,2,0,0,0");
memset(Buff, '\0', 250);// Initialize the string    BuffIndex=5;  }
delay (9000);

pinMode(Motor, OUTPUT); // controle do motor

while(1)
{
 if(sgsm.available()>0)
 {
  Buff[BuffIndex] = sgsm.read();
  if( (Buff[BuffIndex-2] == 'D') && (Buff[BuffIndex-1] == 'M') && (Buff[BuffIndex] == '1'))// Desativar Motor Agora
  {
  digitalWrite(Motor, HIGH);
  send2("Motor da sua viatura desligado! aguarde pelas coordenadas...");
  Serial.println ("Set sgsm Number");
  delay(10000);
  GPS();
  delay(10000);
  enviolink();
  Serial.println(" ");

  }
  if( (Buff[BuffIndex-2] == 'A') && (Buff[BuffIndex-1] == 'R') && (Buff[BuffIndex] == 'M'))//Ativar Motor Agora
  {
  digitalWrite(Motor, LOW);
  digitalWrite (Sirene, LOW);
  send2("Motor Ativo....A viatura esta segura!, Aguarde a localizacao!");
  Serial.println ("Set sgsm Number");
  delay(1000);
  GPS();
  delay(1000);
  enviolink();
  Serial.println(" ");

   }

   if( (Buff[BuffIndex-2] == 'L') && (Buff[BuffIndex-1] == 'O') && (Buff[BuffIndex] == 'C'))//Retorna coordenadas
  {
  send2("Buscado a localizacao actual!");
  GPS();
  delay(10000);
  enviolink();
  Serial.println(" ");
  delay(10000);

   }
       /// Pode se acrescentar mais condicoes
  BuffIndex++;
  if(BuffIndex>250)
   {
    BuffIndex=5;
    }
 }
}
}

/////===============  Mensagens de Texto =======

void send2(String SMS)
 {
 Serial.println ("Sending Message");
 sgsm.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
 delay(1000);
 Serial.println ("Set sgsm Number");
 sgsm.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
 delay(1000);
 sgsm.println(SMS);
 delay(100);
 sgsm.println((char)26);// ASCII code of CTRL+Z
 delay(1000);
 }

void mensagem()// mensagens das variaveis; e inicializacao do carro
{
 Serial.println ("Sending Message");
 sgsm.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
 delay(1000);
 Serial.println ("Set sgsm Number");
 sgsm.println("AT+CMGS=\""+ number + "\"\r"); //Mobile phone number to send message
 delay(1000);
 String SMS = "Sistema de Alarme habilitado";   //sgsm content
 sgsm.println(SMS);
 delay(100);
 sgsm.println((char)26);// ASCII code of CTRL+Z
 delay(1000);
}

void mensagem2()// mensagens das variaveis; e inicializacao do carro
{
 Serial.println ("Sending Message");
 sgsm.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
 delay(1000);
 Serial.println ("Set sgsm Number");
 sgsm.println("AT+CMGS=\""+ number + "\"\r"); //Mobile phone number to send message
 delay(1000);
 String SMS = "Alerta de intrução! Verifique a sua viatura.";   //sgsm content
 sgsm.println(SMS);
 delay(100);
 sgsm.println((char)26);// ASCII code of CTRL+Z
 delay(1000);
}

////=========================   Apaga mensagens no cartao  ===========
void clear_SMS_Memory()
{
unsigned short i = 0;
for (i = 0; i <= 30; i++)
{
sgsm.print("AT+CMGD=");
sgsm.println(i);
delay(100);
}
while (sgsm.available() > 0) sgsm.read();
}

/////=====================  Leitura  de Inputs do GSM ==========

void updateSerial()
{
 delay(500);
 while (Serial.available())
 {
 sgsm.write(Serial.read());//Forward what Serial received to Software Serial Port
 }
 while(sgsm.available())
 {
 Serial.write(sgsm.read());//Forward what Software Serial received to Serial Port
 }
}

/////======= localizacao ========================================
void enviolink()
{
  sgsm.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  sgsm.println("AT+CMGS=\"+25884xxxxxxx\"\r"); // Replace x with mobile number
  delay(1000);
  sgsm.println(link);// The SMS text you want to send
  delay(100);
  sgsm.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
}

Since you put "simultaneous" in quotes, I'm assuming you realize that one MCU can only do one thing at a time, but cleverly programmed, it can do small pieces of several things faster than you and I can perceive the difference. (I state this for completeness, for the benefit of readers who may not have thought this out yet.)
A couple of techniques will help you here.
One is what I call "maybedo" functions - functions you call frequently, that do or do not do something (depending on conditions such as time or input signals) but they do it quickly and return immediately. See my answer here for more explanation of "maybedo" functions.
Another and very important one is to avoid delay() calls. Try a timer library such as SimpleTimer. This lets your loop() function and those it calls, keep short. The SimpleTimer library entry is a "maybedo" for up to 10 timer-driven functions. All you have to do is call mytimers.run() frequently. Mostly it won't do much, but occasionally it will find one or more timers have expired and will call their associated functions for you. You just have to have set up the timers to call some simple - and again, short - functions to do something. And to be clear, we're talking about software-based timers, not the MCU's hardware timers. The library's work is based on the millis() function, but it automates that for you.

For my apps, I created a class ArduinoObject. Each ArduinoObject has a setup() function and a loop() function, as well as an active boolean flag. My apps manage an array of ArduinoObjects. If an object's active flag is true, the app's loop calls its loop function on each pass through. If not, it isn't called at all. This makes it very easy to manage a whole bunch of what you call "MaybeDo" tasks dynamically.

The app uses a fixed-sized C array with enough elements for the max number of ArduinoObjects my app needs. If I need to add another task, I add an ArduinoObject to the array. If I want one of the objects to go to sleep, I set its active flag to false.  The code that manages the array of ArduinoObject ignores NULL values, so I can set one of them to NULL if I'm completely done with it. The code that adds a new object searches for the first empty slot in the array. Each ArduinoObject is written to take very little time on each pass through its loop.

Interesting task structure - thanks!

Without analyzing the complete code, the steps to go are:

Remove the delay function calls. These mostly delay the program in such a way that other parts are not executed in time or 'at the same time'.
Instead use the millis command and check again time stamps (of unsigned long int type) to reach the delays you need.
Create a state machine. This means in simple form that you use an enumeration (enum type) which can have one out of a set of values (like Stopped, Accelerating, Decelerating), for each 'states'  you can define in your sketch.
Use these state machines and times to move from one state to another, and while changing state (or during a state) you can perform the actions you need.

You have a minor typo in your answer. The function is millis() not milli. A newbie might not know that, and might fail to find the function with that typo in it.

@DuncanC Thanks for the notification, I updated my answer. I also added a reference to the page.

As others have said, Arduinos are single-threaded, real mode computers. They only do one thing at a time. However, they do that one thing fast enough that you can make your apps switch between things rapidly enough that they keep multiple tasks running, like a circus clown keeping lots of plates spinning on sticks.
You have to use "roll-your-own" cooperative multitasking, where each time through your app's loop, you look for work to do on each of the tasks you're juggling. You have to make each pass through the loop fast so you don't miss things.
You should avoid the delay() function entirely if at all possible. The delay() and delayMicros() functions bring your app to a complete halt for the entire duration of the delay.
Search on "Arduino blink without delay" and look at the sample app that points to. It shows how to use millis() to manage timed actions without using delay(). You should apply that approach to everything you do.


text:
Compile Error for Arduino Sketch
I am attempting to increase the volume of a Max9744 20 watt amplifier from Adafruit using an Arduino sketch. I am just a very beginner and working with my grandson, this may be more than I am capable of doing.
Our project is to have music play when a sensor determines a door is opened.
I wonder if someone can help with this compile error.  I stripped the code of any code not related to issue - basically the sensor code.
Thanks in advance for any help you can provide.
exit status 1
'VS1053_CONTROL_SPI_SETTING' was not declared in this scope
Here is the code
#include <SPI.h>[code][/code]
#include <Adafruit_VS1053.h>
#include <SD.h>
#include <Wire.h> // Amp Code

#define BREAKOUT_RESET 9 // VS1053 reset pin (output)
#define BREAKOUT_CS 10 // VS1053 chip select pin (output)
#define BREAKOUT_DCS 8 // VS1053 Data/command select pin (output)
// These are the pins used for the music maker shield
#define SHIELD_RESET -1 // VS1053 reset pin (unused!)
#define SHIELD_CS 7 // VS1053 chip select pin (output)
#define SHIELD_DCS 6 // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4 // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3 // VS1053 Data request, ideally an Interrupt pin

#define MAX9744_I2CADDR 0x4B

int8_t thevol = 63; // I want Max Volume Always

Adafruit_VS1053_FilePlayer musicPlayer =
Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

void setup() {
SD.begin(CARDCS);

Wire.begin();
if (! setvolume(thevol)) {
Serial.println("Failed to set volume, MAX9744 not found!");
while (1);
}
}

boolean setvolume(int8_t v) {
// cant be higher than 63 or lower than 0
if (v > 63) v = 63;
if (v < 0) v = 0;

Serial.print("Setting volume to ");
Serial.println(v);
Wire.beginTransmission(MAX9744_I2CADDR);
Wire.write(v);
if (Wire.endTransmission() == 0)
return true;
else
return false;
}
void Adafruit_VS1053::setVolume(uint8_t left, uint8_t right) {
uint16_t v;
v = left;
v <<= 8;
v |= right;

noInterrupts(); //cli();
sciWrite(VS1053_REG_VOLUME, v);
interrupts(); //sei();
}

void Adafruit_VS1053::sciWrite(uint8_t addr, uint16_t data) {
#ifdef SPI_HAS_TRANSACTION
if (useHardwareSPI) SPI.beginTransaction(VS1053_CONTROL_SPI_SETTING);
#endif
digitalWrite(_cs, LOW);
spiwrite(VS1053_SCI_WRITE);
spiwrite(addr);
spiwrite(data >> 8);
spiwrite(data & 0xFF);
digitalWrite(_cs, HIGH);
#ifdef SPI_HAS_TRANSACTION
if (useHardwareSPI) SPI.endTransaction();
#endif
}
void loop() {

while (counter < 3) {
musicPlayer.begin();
Serial.println(F("Playing track 001"));
musicPlayer.playFullFile("track001.mp3");
delay (100);
}

delay(1000);

musicPlayer.stopped();
}

The functions Adafruit_VS1053::sciWrite and Adafruit_VS1053::setVolume are functions from the library. They are in the Adafruit_VS1053.cpp file.
You should not copy those functions to your own sketch.
The library has a few examples. Try to stay close to those examples.


text:
how to increase the range of KY-005?
I am using a KY-005 with an Arduino Uno. I have the knowledge that Arduino can provide a forward current of 40 mA. How can I make it to 55 mA or above upto 60 mA to unlock its full potential, so as to get efficient IR communication without data being distorted at the KY-022 IR receiver?

First, I think 40 mA to output from a GPIO is not a wise idea, because those are Arduino Pin Current Limitations.
What you can do is:

The VCC pin can handle 200 mA. So you can use this pin to power your KY-005 and use a transistor to switch it via a GPIO (much less than 40 mA is needed for that).
Or (high likely not needed): use an external power source and use a transistor in the same way.

For knowing all details about using a transistor this way, google for "transistor as switch".


text:
Need little bit of help on testing I2C sketch
I have this code I got from YouTube for communicating between two Arduinos. By typing 'R' manually into the serial monitor of the 'master' Arduino, the 'slave' will print "Success". I'm trying all this for the basis of a project I'm starting.
After success with the code, I am now trying to make it automatic. I want the 'master' Arduino to print "R" itself and for the 'slave' to read this and print "Success". println doesn't work here, maybe it'll work if the slave code is changed? Both original codes are below, any ideas on how to do what I need?
Master:
#include <Wire.h>
char incomingByte;
int x = 0;

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

void loop()
{
  Wire.beginTransmission(9);
  if (Serial.available()) {
    while (Serial.available() > 0) {
      incomingByte = Serial.read();
      Wire.write(incomingByte);
      Serial.println(incomingByte);
      Wire.endTransmission();
  }
  }

}

Slave:
#include <Wire.h>

int x = 0;

void setup() {
  Wire.begin(9);
  Wire.onReceive(recieveEvent);
  Serial.begin(9600);
}

void recieveEvent(int bytes) {
  x = Wire.read();

}

void loop() {

  if (x == 'R'){
    Serial.println("Success");
    delay(100);
  }
}

Your Master supposedly should send 'R'. Where is the place in the code this happen?

Look at what the master is doing. It's reading from serial and writing what it reads to Wire. How do you think you would make it send an R rather than what it reads from serial?

make x volatile. volatile int x = 0;

@MarkSmith That's what I'm unsure of. I am new at this so I don't know what to change in either codes.

@smajli I have to manually type 'R' into the serial monitor.

Josh, what is your project? What problem are you trying to solve by using two arduino boards?

@Josh. You're getting these types of comments because StackExchange requires you show an effort at understanding the question you're asking. If you can't answer how to change the Master where the variable that is received is sent to the I2C device, you'd just be copying and pasting someone else's code that you don't understand, as appears to be the case with the code you managed to get working already.

The I2C communication is not easy and there are many things that can go wrong. Two Arduino boards instead of one board are often used for the wrong reason in the first place.
Using a serial port is easier. The Arduino Leonardo has an extra hardware serial port, you could use the serial port to communicate between two Arduino boards. The Arduino Mega 2560 has three extra serial ports.
Sometimes two Arduino boards are used because multiple things have to be done at the same time.
When you use the Blink Without Delay example with millis, then the Arduino can do many things at the same time.
Sometimes two Arduino boards are used because there is some distance between the Arduino boards.
The I2C bus is a "bus", but that does not mean that you can use a long cable. You can go up to 20 inch (50 cm).
When two Arduino Uno boards are connected with the I2C bus, then three wires are needed:

GND to GND
SDA to SDA  (plus pullup resistor)
SCL to SCL  (plus pullup resistor)

For a small test with short jumper wires, it is possible to do that without pullup resistors. For the final project pullup resistors should be used for SDA and SCL, for example 4k7 or 10k.
The example below uses a flag in the Slave Arduino. That extra variable makes it easier.
In the Slave receiveEvent function, there is a extra check to check if exactly one byte is received. That extra check is not required, but it can be useful.
I show this example as something to start with, because there are too many bad examples for I2C between Master and Slave.
Master
#include <Wire.h>

byte dataTransmit;

void setup() {
  Wire.begin();
}

void loop() {
  Wire.beginTransmission(9);   // sending to slave with i2c address 9
  Wire.write(dataTransmit);    // the data to send
  Wire.endTransmission();

  dataTransmit++;              // all numbers from 0 to 255

  delay(250);                  // 250ms delay, to send 4 times per second
}

Slave
#include <Wire.h>

volatile byte dataReceive;
volatile bool newData;    // a flag to indicate that new data has arrived

void setup() {
  Wire.begin(9);          // create i2c slave at i2c address 9
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}

void loop() {
  if(newData) {           // is there new data?
    Serial.print("Received: ");
    Serial.println(int(dataReceive)); // convert to integer to print the number
    newData = false;      // reset flag
  }
}

void receiveEvent(int howMany) {
  if(howMany == 1) {      // extra check, to check if one byte is received
    dataReceive = Wire.read();
    newData = true;       // set flag, there is new data
  }
}

Here is my proposal to solve your issue:

Use the second Serial communication line of the master by connecting Rx and Tx Pins of Serial2 (this done only on master, practically a shortcut between Rx and Tx on Master)
Setup Serial2 if necessary: HardwareSerial Serial2(2); (that how it
is necessary/done for my M5Stack)
Define baud rate for Serial2: Serial2.begin(9600);
Start your Automation by Serial2.write("R\n"); at an appropriate place in your code
Change conditions of if(..) and while(..) in your master's code from Serial.available() to Serial2.available()
Change incomingByte = Serial.read(); to incomingByte =
Serial2.read();

With that solution you can still see your start signal printed out on your Serial monitor via the first Serial communication line. The communication to the slave is still working over IC2, Serial2 is only the proposal for the automation solution on master. Looks complicated, but this is how I understood the question, of course you also could directly use incomingByte="R\n"; to start your Automation and skip all that stuff with Serial2 :-)


text:
Due : DMAC BTSIZE trimmed modulo 8192?
On Arduino Due, I set-up DMA transfers using direct control of memory mapped hardware registers.
There is a 16-bit BTSIZE field in CTRLA which indicates the number of (width sized) transfers.  If I specify larger than 8191, the value of btcount is trimmed to 13 bits after the DMA channel is enabled.  I set chunk size src/dest to 1.
The ATMEL data sheet for the sam3x (linked from the due page) does not mention this 'limitation' (section 22.7.16), or possibly I'm using it wrong.
What reference is canonical and correct for the DMAC (dma controller)?

As noted in the links in the comments, multi-buffer transfer can work around this, but since I don't know why it works or fails, it's hard to decide if that solution will work in all cases.

Please post the code that does this transfer.

This looks relevant: http://community.atmel.com/forum/synchronous-serial-controller-ssc-or-i2s-using-dma-controller-sam3x8e-incomplete-data-transfer

Thanks for the link, I moved to multi buffer continuous transfer too, which works around the issue, but doesn't really answer the question:where can I get good/correct documentation for the Dmac.  Note that there are other problems with the datasheet Dmac documentation relating to multi buffer transfer.

I have made two or three bug reports direct to Atmel about their documentation. In each case they acknowledged it was wrong and said they would fix it. Possibly there is no good/correct documentation on this point. Contacting Atmel and submitting a ticket might help correct this situation.

Thanks for your help, hopefully this will help the next person.  I'll add more working Dmac code in this and other questions when I get some time.

It is probably a nightmare for them to keep the documentation exactly and precisely synchronized to what the chip actually does. If people don't report things, little errors are likely to stay there.

By the way, 2^12 is 4096, not 8192.

I'll quote the answer given in this link to help make this question more useful for future people who search this problem.

The dmac.h file in asf library has a macro named DMA_MAX_LENGTH set to 0xFFF = 4095. We tried changing it to higher values but still Buffer Transfer size (BTSIZE) register was showing only values till 4095. This seemed to us to a hardware limitation of the DMAC in Atmel SAM3x8E (which we did'nt see mentioned in the datasheet). So this closed the option of single buffer transfer for us and we moved to multi-buffer transfer
It was a simple way out (even though I took some time to figure it out :P ) - Use multi-buffer transfer with contiguous source address! (see table 22.4 Row 3)

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


text:
Can I detect with software when a PIR sensor is physically connected to Arduino?
I'm creating a circuit using an Arduino Nano + ESP8266 to allow LED remote (via mobile app) activation and configuration (RGB colour, timeout, etc.). The circuit also has an optional PIR sensor to switch on the LED when someone enters the room.
I'd like the circuit to behave differently when the PIR is physically connected to the Arduino (i.e. to light the LED in a different colour) but I have no idea of how detect if the sensor is physically connected to the circuit.
I tried reading the value of the Arduino PIN but (obviously) the signal is LOW whether nothing is detected by the PIR or is not physically connected.
I have two different PIR detectors that I can use for the project:

Arduino Compatible PIR Motion Detector (Description)
DFRobot PIR Detector (Description, Schematic)

Thank you for your time. If there is missing information in my question, please tell me and I will add it.

Which PIR sensor are you planning to use please?

Hi @MarkSmith, I've edited the post to include the information about the sensors. Thank you!

Will the PIR always be connected at power-up?

Yes @sa_leinad, you can assume that the PIR will be connected at power_up.

The PIR sensor I have will overpower the internal pull-up resistor of the ATmega328P used on the Arduino Nano. This means if you turn on the pull-up and then get a read of LOW you know something is connected to that pin because the unconnected pin will always read HIGH with the pull-up on. With this approach you can get false negatives because the pin will also read HIGH if the PIR is triggered but you won't ever get false positives for PIR sensor detection. This means you can't rely on just doing a single test in setup() because the PIR might be triggered then so you will need to repeatedly run the test until the PIR sensor is detected. Example sketch:
int PIRpin = 2;    //the input pin for the PIR sensor
boolean PIRconnected = false;

void setup() {
  Serial.begin(9600);
  pinMode(PIRpin, INPUT);
}

void loop() {
  if (PIRconnected == false) {
    pinMode(PIRpin, INPUT_PULLUP);
    if (digitalRead(PIRpin) == LOW) {
      Serial.println(F("PIR sensor detected"));
      PIRconnected = true;
    }
    pinMode(PIRpin, INPUT);  //turn off the internal pull-up to reduce power consumption
  }
  Serial.println(digitalRead(PIRpin));
  delay(500);
}


text:
ESP8266 Switching firmware on the fly
Can you help me out to understand if this is possible with ESP8266 / 32 ?
I have a main binary that i upload to the chip, let's call it A - that's done from arduino.
A starts to work, but communicates every couple of minutes with central server polling for a task.
If there is a task - let's call it B
A downloads it and stores it on SPIFFS.
Now what should happen is that A uploads it, reboots and B starts to work.
When B finishes it loads up again A and the circle closes - this process goes on forever.
Questions:
1) Is it possible that a stored on SPIFFS binary file can be uploaded to the chip? Like OTA does via www.
2) Can i somehow store A onto the SPIFFS, so that when B finishes i reupload A ?
Thanks for any input into this

why don't you have a single program that does both A and B?

Look at what ArduinoOTA does.

@Majenko - right, but i would then have to ask for firmware via WWW i don't speak to Web server, i download the binary from a dedicated grid computing system.
So maybe you know if i can i download binary to SPIFFS and upload to chip other way than OTA?

@jsotola because B changes and is sent from a distributed system, has nothing to do with A. Binaries sent from distributed system will be different all the time.

Look at what ArduinoOTA does. I say again. Look at what it does. Don't use it. Just look at what it does.

@Majenko got your point now, thx.

I think i've found an answer to my question here
https://www.esp8266.com/viewtopic.php?f=32&t=11324
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

#include "FS.h"

void setup() {
  Serial.begin(115200);
  Serial.println();
  SPIFFS.begin();
  Dir dir = SPIFFS.openDir("/");

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

  File file = SPIFFS.open("/blinkESP.bin", "r");

  uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  if (!Update.begin(maxSketchSpace, U_FLASH)) { //start with max available size
    Update.printError(Serial);
    Serial.println("ERROR");
  }

  while (file.available()) {
    uint8_t ibuffer[128];
    file.read((uint8_t *)ibuffer, 128);
    Serial.println((char *)ibuffer);
    Update.write(ibuffer, sizeof(ibuffer));

  }

  Serial.print(Update.end(true));
  digitalWrite(BUILTIN_LED, HIGH);
  file.close();
}

void loop() {

}

Will give it a try and revert back to confirm if it answers my question.

Confirmed,works like a charm. Flashes firmware with a file from SPIFFS.

The esp8266 Arduino package has 3 libraries for firmware update.

ArduinoOTA for upload from Arduino IDE
ESP8266HTTPUpdateServer for upload with web browser
ESP8266httpUpdate library to check a web server for new version of the
firmware


text:
How to combine strings and text together?
I'm trying to combine two strings (strings/int) together with text in below code:
int foo = String((char*)payload).indexOf(' ');
int message1;
int message2;

message1 = String((char*)payload).substring(0, foo).toInt();
Serial.print(message1); // Returns 1

message2 = String((char*)payload).substring(foo + 1, length).toInt();
Serial.print(message2); // Returns 0

client.publish(msg, String(message1 + " " + message2).c_str(), true);
// published value: 1 0

Instead of publishing "1 0" its publishing some weird values, what am i missing?

message1 + " " + message2? you know what operator + does on int

What type is payload? Is it a dynamically allocated char array?

I wouldn't use the String class, but instead use the C functions to concatenate strings (like strcat, strncat).
You can use the itoa function to convert an integer to a string, see:

https://stackoverflow.com/questions/9655202/how-to-convert-integer-to-string-in-c

Or use the sprintf function.
These are all standard C functions which gives you complete control of the buffer sizes to use. Handy because the Arduino Uno has just 2 KB.


text:
Sending .wav via network
I'm working in a project and part of this project is sending a .wav file from an Arduino to other device (for example anther Arduino).
I already am able to send a .txt file from an SD which was included in the Ethernet Shield to other Arduino SD card, but it doesn't work when I try to send a .wav file.
Any idea ?
void loop() {
if(digitalRead(push1) == LOW){
    writeanddeletSDcard();
      Serial.println("i will send now");
      Udp.beginPacket(destIp, port);
     Udp.write(a);
      Udp.endPacket();
      Serial.println("Sending UDP message");}}

void writeanddeletSDcard(){
    SD.remove("S13.txt");
   myFile = SD.open("S13.txt", FILE_WRITE); // boolean
   data = myFile.size();
  // if the file opened okay, write to it:
  if (myFile) {
    Serial.println("i will Write now ");
    delay(2000);
    Serial.println(data);
    myFile.println("HELLO WORLD");
    myFile.close();

    // close the file:
  }
else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");}

// ---------------- here end of Writing an a massege on the SD Card
  // re-open the file for reading:
  myFile = SD.open("S2.WAV");
  if (myFile) {
    Serial.println("inside the file there's");

c= 0 ;
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      a[c] = myFile.read();
      c++;
    }
    Serial.println(c);

   // close the file:
    myFile.close();
  } else {
   // if the file didn't open, print an error:
    Serial.println("error opening test.txt");}}

What is a? How big is the WAV file?

hello, a is an array of char type i want to store the data on it , and then send it , the size of the wav file is  49289 Byte

And you want to store 49289 bytes in an array on an Arduino with only 2K of memory...? Good luck...

i don't want to store it in the Arduino, i want to Store it in the SD card, then dived it to small byte and send it as a Stream of byte

At the moment you're just "reading from the file until there's nothing in it". I see no attempt at only reading a portion of the file and sending it.

You should look at: https://www.arduino.cc/en/Reference/StreamReadBytes


text:
Is it possible to connect miband2 and arduino nano (?)
I want to make an IOT project using an Arduino nano and I need heart rate sensors. I I have a miband2. So, is it possible to connect them ?

First find out what communication protocol the miband2 uses.

Mi band use BLE

You need to connect as a central device.
I've had good luck with the adafruit nrf52 feather.  Also see: https://github.com/Freeyourgadget/Gadgetbridge for the protocol.

To use BLE on Arduino, I tried google and found this Article:
Examples:

HM-10 (HM-11) BLE Module
BLE Nano
BLE Mini
BLE Shield v2.1
RFduino
Bluno series
BLE WT51822-ABS
Grove – BLE
BLEduino

Chose one that fits best, and use it.


text:
Trying to use an LCD 1602 to display, but I don't have a 10 KOhm potentiometer
I'm following this tutorial page and I don't have a 10k ohm potentiometer on hand. Could I replace it with resistors to simulate a manual setting and replace the resistors to adjust to a new settings.
From what I was reading this pin is for contrast and I'm sure I could manually set the contrast once and be happy with it for quick prototyping. I'll be ordering a 10k ohm potentiometer on Monday.

Yes. All a potentiometer is, is two resistors end to end.  The "wiper" is the join between the two resistors.
It doesn't matter too much what value potentiometer (and hence what value resistors) you use, as long as it's "around" the 10kΩ mark (100kΩ should be fine, 50kΩ, 1kΩ etc - anything below 1kΩ may not work) - what matters is the ratio of the values of the resistor.

Would this work + ---[10K]--[connection to wiper]--[100K]--- -

It may. It depends if that is the resistor ratio that you need. You will have to try it and see. If it's not right then change the resistors. But that arrangement of resistors is the right idea, yes.

Yes, you always can do that, depending on the resistors you have at hand, you can combine them to make e.g. 1 KOhm, 2 KOhm etc resistors.
Probably you need a linear potentiometer (which means halfway is 5 KOhm).
In a linear potentiometer, you can use the following resistance (made up by a single or a combination of resistors in series or parallel):

Yes, but you need only one resistor to GND. The display has already one resistor inside the display. I forgot what the value should be and I don't have a display at hand right now, so you have to try which value is best.
In most examples with a LCD display, a potentiometer is used for the contrast. Not many people know that only a (variable) resistor to GND is needed.
With a fixed resistor, you are not able to quickly adjust the display when the temperature changes.

If I'm just prototyping where the temperature doesn't change am I right to understand that I could simply go. [GND] ---- [Resistor] ---- [LCD Pin for contrast]

@Tolure, yes, correct, that is all that is needed to set the contrast.


text:
How do you make a switch case run until another serial input is detected?
I am trying to create a Traffic Light Controller.
There are three modes to the controller:
Mode 1 - the traffic light operates RED-YELLOW-GREEN-YELLOW and should repeat
* (The other modes are not necessary apart from knowing the user can select the mode.)*
I want to loop the function of the mode until I receive an input from the serial monitor. If no input is detected, then it should continue with the current mode.
At the moment I am using Serial.read() at the start of the main loop function before my switch statement to select the mode. However, this needs an input, but I want the switch cases to loop until an input is received.
All help will be much appreciated.

use a variable to store the mode ..... run the display sequence depending on the value of the variable ..... update the variable when a command is received

Show us the sketch that you have so far. Do you know what a finite state machine is? https://majenko.co.uk/blog/finite-state-machine

Use something like this (it is pseudo code so convert it to your sketch):
enum EState { NORMAL, SPECIAL } _state; // States
enum ENormalState { RED, YELLOW1, GREEN, YELLOW2 } _normalState; // State only valid when _state == NORMAL
unsigned long _time; // _time only valid when _state == NORMAL

void loop()
{
   if ('serial input available')
   {
      if ('input == ...')
      {
         _state = NORMAL;
      }
      else if ('input == ...')
      {
         _state = SPECIAL;
      }
      ...
   }

   switch (_state)
   {
   case NORMAL:
       if (_time + ... > time())
       {
          // Change to next state
          switch (_normalState)
          {
          case RED:
              _normalState = YELLOW1;
              _time = time();
              break;

          case YELLOW1:
              _normalState = GREEN;
              _time = time();
              break;
          ...
          }

       setLight(_normalState); // Change the light according to the _normalState
       break;

   case SPECIAL:
       ...
       break;

   ...
   }
}

Ideas to improve/explain:

Try to make some specific functions for setting the light according to the current state
You do not need a delay
Split functions (like above, make a separate function for normal state, and specific state

thankyou for your responses.
I managed to solve this myself by using a while loop to store the code inside each switch case, my working code is below, utilising Serial.peek() and by changing the input ending in the serial monitor to no line ending.
while ((Serial.peek() == -1)){
          regularMode(ledRed, ledYellow, ledGreen);
}

Serial.peek() gets the next item from the serial stack, if there is nothing there, it returns '-1' so i can check against that as shown above.

Yes, you need a non-blocking operation to check if there is pending chars in the stream. peek() is correct, but Serial.available() is more stream-related.


text:
Audio Input into A0?
I saw a YouTube Video of someone who used an aux cord input into pin A0 on their Arduino to control a strip of LEDs. I have a strip of Adafruit's RGB NeoPixel LEDs, but I'm not sure how to input my audio into pin A0. If there is a way to do this without a separate shield or board, that'd be great because I'm on a tight budget, but if not possible it'll have to do. Also, would it be possible to send this audio to another Arduino via wifi or bluetooth using a different shield? Thanks.

Depending on how loud your audio signal is, you may be able to do it with just one capacitor and two resistors:

If your signal is quite quiet, though, you may need to amplify it using an op-amp. For instance:

That arrangement would double the volume of the audio. It also has the effect of inverting it, so you will need to invert your readings in software.
Also note that both of these methods will give you an AC waveform centred around 2.5V, so silence will be a reading of around 512, and it will go up and down from there. You can sample that audio waveform and do some basic (though quite slow on an Arduino) analysis of it, such as FFT to get the frequency content of the audio - great for visual effects...

Okay. I have these cheapy water speakers. You're suppose to plug the second speaker into the main one via mini usb, but I figured out that if you actually plug the Arduino into it, it has a constant green status led and the RX and TX LEDs glow to the beat of the music. Would it be possible to feed this to the code that was provided in the description of the video I linked in my main post above? I'm not quite sure how to analyze the connection. Since I'm kinda newly, I figured this he'd easier than the method you listed above.

authors: ธัญเทพ มีเรี่ยม


text:
Need help with parsing NWS JSON weather alerts causing reset on ESP8266
I'm trying to parse the JSON string from the National Weather Service Alerts and am encountering a problem where the code can't parse the value and the device auto-resets.  I've used this code before on a different API to get the current weather conditions, and that works fine - I'm not sure what I'm doing wrong and would greatly appreciate any advice or help.  Thanks!
Here is the error:

21:13:07.521 -> wdt reset
21:13:07.521 -> load 0x4010f000, len 3424, room 16
21:13:07.521 -> tail 0
21:13:07.521 -> chksum 0x2e
21:13:07.521 -> load 0x3fff20b8, len 40, room 8
21:13:07.521 -> tail 0
21:13:07.521 -> chksum 0x2b
21:13:07.521 -> csum 0x2b
21:13:07.521 -> v00045d00
21:13:07.521 -> ~ld
21:13:07.555 -> ����n�r��n|�l�l`b��|r�l�n��n�l`��r�l�l��

And here's my code:
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>

const char* ssid     = "mySSID";                      // SSID of local network
const char* password = "myPassword";                 // Password on network

WiFiClient client;
char weatherServerName[] = "api.weather.gov";
String result;

//For testing change this zone to any zone from the NWS that's currently experiencing a weather alert
//Find an active alert area by going to https://api.weather.gov/alerts/active and looking for the code in the "affectedZones"
String zone = "LEZ144";

bool hasAlert = false;

void setup() {
  Serial.begin(115200);
  Serial.println("=====================================================================================================");
  Serial.println("Connecting");

  WiFi.begin(ssid, password);

            while (WiFi.status() != WL_CONNECTED)
            {
            delay(500);
            Serial.print(".");
            }

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

void loop() {
  Serial.println(":D");
  getWeatherAlerts();
  delay(100000);
}

void getWeatherAlerts()
{
  String server = weatherServerName;

  if (client.connect(server, 443))
       {
          client.println("GET /alerts/active?zone=" + zone);
          client.println("User-Agent: ArduinoWiFi/1.1");
          client.println("Connection: close");
          client.println();
          }
  else {
         Serial.println("connection failed");        //error message if no client connect
         Serial.println();
       }

                                       //waits for data
  while (client.connected() || client.available())
       {                                             //connected or data available
         char c = client.read();                     //gets byte from ethernet buffer
         result = result+c;
       }

  client.stop();                                      //stop client
  result.replace('[', ' ');
  result.replace(']', ' ');
  Serial.println(result);
  char jsonArray [result.length()+1];
  result.toCharArray(jsonArray,sizeof(jsonArray));
  jsonArray[result.length() + 1] = '\0';
  StaticJsonDocument<8196> root;
  DeserializationError error = deserializeJson(root, jsonArray);

  if (error)
    {
      Serial.println("parseObject() failed");
    }

  String features = root["features"];

  Serial.println(features);

  if(features.length() == 0)
  {
    Serial.println(features);
    hasAlert = false;
  }
  else
  {
    String severity = root["features"]["severity"];
    Serial.println(severity);
    if(severity == "Moderate" || severity == "Severe")
    {
      hasAlert = true;
    }
    else
    {
      hasAlert = false;
    }
  }

  Serial.println(hasAlert);
}

print what is received before you start trying to alter it

By default, the size of the stack is limited to 4KB on ESP8266, so you cannot store an 8KB document there.
To fix this issue, replace the StaticJsonDocument with a DynamicJsonDocument to move the buffer to the heap.
See also: Why does my device crash or reboot?

There is a good clue in the first line of your reported error:
21:13:07.521 -> wdt reset

The ESP-8266 Watchdog Timer (WDT) will reset the device if it has not been correctly 'fed' for a period of time (the watchdog timeout).
As @Juraj noted, the ESP-8266 Arduino libraries 'helpfully' add WDT feeds at various points, suggesting the timeout is because your code is either crashing (overflowing into invalid program code) or is timing out (valid code, but stuck in a loop).
The backtrace information printed on the reset can be used to find where the WDT happened specifically in your code, so you can find the issue (which could be the one @Benoit Blanchon noted). I have found this exception decoder to be very useful to translate the code to the functions in your code.
Also worth noting that the 'garbled characters' after the WDT reset backtrace information is the bootloader startup message, which is fixed at 74880 baud, you can change baud rate of your serial terminal to see those (and 'garble' the other messages).
(Info about watchdog timers and feeding below isn't directly relevant in this case, as @Juraj noted, but is left in for context)
This is an example document from TI introducing watchdog timers. For the ESP8266, you might find this techtutorialsx document more useful. In summary, you need to either turn off the watchdog, or issue periodic
ESP.wdtFeed();

commands. Turning off the watchdog is an appealingly easy option, but it disables a really useful tool to help you to make your project/product handle unexpected conditions/bugs more gracefully, so I'd encourage you to learn how to use it and then feed it as above.
(As @Benoit Blanchon noted, there are other issues on the implementation, which should be addressed, and perhaps deserve a separate post in code review. However I wanted to explain the reason for the reset you asked about, which isn't specifically JSON-related, and will continue to occur unless you take action as above)

here the wdt is not fed after the crash

@Juraj the wdt is not fed at all, which is causing the reported wdt reset.

on esp8266 the wdt feeding is automatic if the loop() ends,in delays, in many function calls

Thanks @Juraj, updated accordingly.

so "the size of the stack is limited to 4KB on ESP8266, so you cannot store an 8KB document there." is for me a good explanation for the crash. the "wdt reset' is just a distraction. Benoit Blanchon is author of the ArduinoJson library


text:
Arduino SoftwareSerial - can't get data from NEO 6M-GPS module
I am using Mikael Hart's TinyGPS (v.13) library and example code to talk to my module. The LED on the GPS module is lit and flashing which I assume means it is receiving data from the GPS satellites. The module seller claims that the module has a default baud of 38400.
I'm pretty sure it's wired up correctly:

And my sketch says:
SoftwareSerial ss(4, 3);

So I read this as Orange (Rx) to pin 4 and Brown (Tx) to pin 3.
Any help appreciated

RX of the Arduino (pin 4, according to the SoftwareSerial statement) goes to the TX of the GPS.  Arduino pin 3 (ss TX) goes to the GPS RX.
And you should use pins 8 & 9 instead.  That would let you use AltSoftSerial, the best choice when you can't use HardwareSerial (i.e., Serial).
If you can't use pins 8 & 9, then NeoSWSerial is a better choice than SoftwareSerial.
And while I'm promoting NeoSWSerial, I'll mention a library I wrote, NeoGPS...  It's faster and smaller than all other GPS libraries, and very configurable.  It also has several diagnostic programs and a Troubleshooting section in the docs.

Thanks - I'll give it ago and report back. Your answer came a little after I'd put everything away for the day. . The chip specif library in particular sounds very useful.


text:
Good quality sound using a microcontroller
I am a hobbyist. Doing some experiments with sound quality. I'll pin point my problem and requirements.

Problem statement :I want to play audio files ( recorded in human voice, not music files, just some plain human speech files)
I have tried : a project with an Arduino microcontroller and MicroSD card but audio quality was not at all good from the link below
https://www.instructables.com/id/Audio-Player-Using-Arduino-With-Micro-SD-Card/
https://circuitdigest.com/microcontroller-projects/arduino-audio-music-player
It just used an arduino UNO board, microSD using SPI, a speaker and an LM386 Audio Amplifier.

I read about the details and got to know that I need a DAC for better quality (as PWM cannot serve the purpose), and a speaker also. But there are a number of things available and I dont understand which one to buy and start a project.
Can you share the details of some micro-controller board with a DAC which suffice my purpose, memory to store audio files (or I can use a microSD card device), and a speaker project which I can follow and make one.
I am looking for a board based solution, after getting some results, I can go for separate micro-controller and DAC.
Thanks in advance.

For what I read about it (no references readily available), it's mostly better to have a separate DAC since internal DACs are mostly 10 or 12 bits, for decent audio quality you need at least two channels of 16 bit DAC.

Hi and welcome to the Arduino SE community. It is good to see the effort you put into your question. I hope to see you more around this site.

There are boards that will read the SD, decode the audio, and amplify it, all-in-one. You micro-controller only has to "tell" the board to play sound file 1, 2, 3, or whatever number. For example the DFPlayer (or one of it's clones on eBay).

I really liked the DFPlayer and it seems that its a readymade solution for my problem. Can I find its circuit diagram and ICs used in this so that I can implement it in parts on breadboard.

You can buy a cheap MP3 player and use Arduino to "press" its buttons, works the best assuming the UI logic of the thing isn't too convoluted.

Here is the schematic and breadboard layout I was using.
Coding can be found in this Arduino.cc thread
https://forum.arduino.cc/index.php?topic=180769.60

One would think that single channel for voice would be enough.  Remember the old Sprint commercials? "So quiet you can hear a pin drop", that was only single channel.  12 bits at 16 MHz for max 8 KHz bandwidth would be good.  Per Wikipedia "In telephony, the usable voice frequency band ranges from approximately 300 Hz to 3400 Hz. It is for this reason that the ultra low frequency band of the electromagnetic spectrum between 300 and 3000 Hz is also referred to as voice frequency, being the electromagnetic energy that represents acoustic energy at baseband. The bandwidth allocated for a single voice-frequency transmission channel is usually 4 kHz, including guard bands, allowing a sampling rate of 8 kHz to be used as the basis of the pulse code modulation system used for the digital PSTN. "
I think several folks, such as Adafruit.com, DFRobot.com, and others make cards with DAC outputs.  Or you could get a DAC only card from Gravitech.us
I started a project at Arduino.cc to sample 16 bits at 44.1KHz, store to SD card, then play it back later. I used external SPI ADC and DAC, and member fatlib16 there helped me to code it.  You can find it by searching "sample, record, playback later" and it should pull it up.

Thank you for the answer and the details. I am thinking that I'll record audio with 16 bits depth at 44.1KHz and do some experiments with adafruit for sound quality and store in SD card. Arduino already has SPI to interact with SD card module. Can you please tell me that which DAC you have used and which speaker you have used.

Digitizing with ADC AD7680, sending it to DAC AD5662-1. Speaker, I was using self-powered PC speakers for playback. See answer for schematic.


text:
Is it possible to make an HTTP get request using AT Commands without knowing the IP address of the web server?
I have the following code that can read a web page using HTTP get but I can only do it because the website I am doing it to has a static IP address, but in my project I am just hosting it on a free service and IP changes rapidly. So is there a way to do the same with only the URL address?
#include <SoftwareSerial.h>

SoftwareSerial cell(2,3);  // Create a 'fake' serial port. Pin 2 is the Rx pin, pin 3 is the Tx pin. connect this to the GSM module

const String apn = "web2"; // access-point name for GPRS

const String ip = "212.26.27.181"; // IP address of server we're connecting to
const String host = "kfu.edu.sa"; // required in HTTP 1.1 - what's the name of the host at this IP address?
const String request = "GET /sites/Home HTTP/1.1";
const String useragent = "Mozilla/5.0"; // for our purposes the user agent doesn't matter - if I understand correctly it's helpful to use something generic the server will recognize

void setup()
{
  //Initialize serial ports for communication with computer
  Serial.begin(9600);

  Serial.println("Starting SM5100B Communication...");
  cell.begin(9600);

  waitTil("+SIND: 4"); // keep printing cell output til we get "+SIND: 4"
  Serial.println("Module ready");
}

void loop()
{
  Serial.println("Attaching GPRS...");
  cell.println("AT+CGATT=1");
  waitFor("OK");

  Serial.println("Setting up PDP Context...");
  cell.println("AT+CGDCONT=1,\"IP\",\""+apn+"\"");
  waitFor("OK");

  Serial.println("Activating PDP Context...");
  cell.println("AT+CGACT=1,1");
  waitFor("OK");

  Serial.println("Configuring TCP connection to TCP Server...");
  cell.println("AT+SDATACONF=1,\"TCP\",\""+ip+"\",80");
  waitFor("OK");

  Serial.println("Starting TCP Connection...");
  cell.println("AT+SDATASTART=1,1");
  waitFor("OK");

  delay(5000); // wait for the socket to connect

have you tried using a URL in place of IP? ....... ip="google.com";
cell.println("AT+SDATACONF=1,\"TCP\",\""+ip+"\",80");

Yes, but it does not give "OK" back.

you get absolutely nothing back?

the method getMessage() gives "⸮⸮⸮⸮⸮"

what are the bytes in the returned string?

It seems you're not using the proper at command. Don't know the SM5100B but init of HTTP, sending etc is commonly made using comands like AT+HTTPINIT, AT+HTTPACTION=0 and so on.

Short answer: of course. Long answer: depends on your AT interface.

Hi, an update to the question I have upgraded to premium and now they give me a static IP. The same code still works with the website given in the question but with my website I can't seem to get an acknowledgement from the server, even though I have a public + static IP.


text:
How can I get the count of pulses of two encoders on the serial monitor?
I have two encoders; I connected them to pin 2 and 3 and I want to count the pulses of them to make two DC motors to work until it reaches a specified number of pulses, than stop working. I have finished the code of one encoder, but the other one I can't put in the same code.
byte pin = 2;
volatile float elapsed;
volatile float previous;
float rpm;
volatile int pulses;
volatile bool flag;

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
  attachInterrupt(0, elapse, RISING);
  previous = millis();
}

void loop() {
  pulses = 0; // reset pulses counter

  attachInterrupt(0, elapse, RISING); // attach interrupt for rpm counter
  delay(500);
  detachInterrupt(0); // detach interrupt for rpm counter

  if (flag == true) {
    attachInterrupt(1, count, RISING); // attach interrupt for pulses counter
    delay(elapsed);
    detachInterrupt(1); // detach interrupt for pulses counter
    flag = false; // reset flag
  }

  rpm = 1000 / elapsed * 60;

  Serial.print("elapsed: "); // print resuslts
  Serial.println(elapsed);
  Serial.print("rpm: ");
  Serial.println(rpm);
  Serial.print("pulses: ");
  Serial.println(pulses);
}

void elapse() {
  elapsed = millis() - previous;
  previous = millis();
  flag = true; // set flag to activate pulses counter
}

void count() {
  pulses++;
}

what is preventing you from counting the pulses of both of the encoders? ...... this does not count as a description of a problem .... I can't put in the same code

if you think  that you cannot do multiple things  in your sketch, then look at the six Serial.print() lines ..... that is "doing multiple things" right there


text:
if(Serial) not working correctly on micro or pro micro
I have an arduino micro and several clone "pro micro"'s both of which are based on the 32u4, i'm trying to make my project have a debug mode which is only active when the serial port is open, the documentation states that using:
if (Serial)

on these boards should only return true if the port is open (on uart based connections it always returns true), i wrote my sketch to take advantage of that but it didn't seem to be working properly, so i stripped back to basics and wrote this sketch:
void setup() {
    // put your setup code here, to run once:
    pinMode(2, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
    if (Serial){
        digitalWrite(2, HIGH);
    }
    else{
        digitalWrite(2, LOW);
    }
}

I connected an LED to pin 2 and then tested it by connecting and disconnecting the arduino from the PC, and opening and closing the com port.
after freshly connecting the arduino to the PC the LED is off, when i open a connection to the virtual com port the LED turns on.
however i would expect the LED to go out once the port is closed, but it remains on.
My questions are:
1) have i got an out of date bootloader?
2) if so how do i check?
3) is this intended behavior and if so why?
4) is this a bug in the arduino bootloader or libraries?
5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?
Edit:
should have mentioned i'm seeing this behavior with or without a call to Serial.begin

Might need to call Serial.begin() first.

see edit to question, i get this behavior with or without a call to Serial.begin

I'd say this is intended behavior. https://www.arduino.cc/en/Serial/IfSerial

why would this be intended? "On 32u4 based boards (Leonardo, Yùn, ecc) , if (Serial) indicates wether or not the USB CDC serial connection is open. " that sounds to me that it should only return true while the port is open, so once i close it it should start returning false, yet it doesn't

It would be far simpler to enter debug mode if a certain pin was jumpered to Gnd, as that is something you can quickly set up, and test easily.

it would, if not for the fact that i'm using every last pin available for my project, thats why i'm after something else

1) have i got an out of date bootloader?

No. This has nothing to do with the bootloader.

2) if so how do i check?

See above.

3) is this intended behavior and if so why?

In a manner of speaking, yes - see below.

4) is this a bug in the arduino bootloader or libraries?

No. Elsewhere.  See below.

5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Yes, you can, but only once you understand exactly what is going on.
The problem with USB serial (AKA CDC/ACM) communication is that there is no way of knowing if the port has been opened by the computer or not.  That functionality was just never designed into the protocol.
However, there are two virtual modem signals that the computer can assert that the CDC/ACM device at the other end can examine - one is the equivalent of DTR and the other the equivalent of RTS.
The Arduino's CDC/ACM code examines those, and if either are asserted then it assumes the CDC/ACM port is open. If neither are asserted then it assumes the port is closed.
Now comes the tricky part:  You have little or no control over when those signals are asserted or not.  There are three separate factors that decide what happens:

The software being run can manually control the signals.  The Arduino IDE does this to ensure boards that use DTR to reset (like the Uno, etc) actually do reset.
The drivers on the computer can decide to automatically control the signals when the port is opened or closed
The operating system itself can control the signals when the port is opened or closed.

Some software will control the RTS/DTR signals properly, some won't. Some drivers will control the signals for you, some won't. Some operating systems (such as Linux) will, unless otherwise instructed, default to automatically controlling the modem lines properly. Others, like Windows, won't.
So the only way you can be sure that these signals are being controlled properly is to manually control them from your own software used for debugging, or to find a specific terminal emulator that controls the lines properly.

Thank you, this is exactly what i was trying (and failing) to find any information on

have you got any information on how i check the RTS/DTR lines in the arduino? i can't seem to find anything about it: https://www.arduino.cc/en/Reference/Serial

@JamesKent It took me many months (on and off) of research and experimentation, reading USB specifications, other peoples' source code, etc, to find just this out ;) It's not something that is commonly known.

@JamesKent The if(Serial) does it. The Arduino side is fine. It's the computer's end that is at fault.

if (_usbLineInfo.lineState > 0) result = true; is the bit of code in CDC.cpp that does it.

what does if(Serial) check? both asserted, both deasserted? how do i need to leave the port to have the arduino see it as closed?

If either are asserted (lineState is 1, 2 or 3) then it is true (connected). Otherwise if lineState is 0 (all de-asserted) then it is false (disconnected).

This is known as "hardware control" most terminal applications has support, but the default for enabled or not varies. If you want to know if USB is connected, checking for VBUS seems more stable?

I am experiencing the same problem. My environment is Windows 10 on the host side and Arduino 1.6.7 with a genuine Arduino Micro board.
In the OP's sketch, after compiling and uploading, the light does not go on until you open the serial monitor. This is as expected and shows that the Arduino side has some way of knowing that the serial monitor has started.
However if you close the serial monitor, the light stays on. It also stays on if you unplug the USB cable. It goes off when you plug the cable back in and goes back on when you restart the serial monitor.
With some further experimentation and poking around the code, I found that _usbLineInfo.lineState > 0 and thus Serial returns True if either DTR or RTS from the host is nonzero. DTR goes to 0 when the serial monitor is closed but RTS stays HIGH so Serial stays True.
The fix is to use the (undocumented) method Serial.dtr(). This is True only if the serial monitor is running.
[edit] If your system has external power so that it should keep working with the USB cable unplugged, testing Serial.dtr() works as long as you you always close the serial monitor before unplugging the USB cable. However it will remain True if the cable is unplugged before closing the serial monitor.
To detect the cable being unplugged, add the line
USBCON |= 1<<OTGPADE;
to setup(). This enables detection of an unplugged USB cable. Then in your loop
(USBSTA & (1<<VBUS))
will be True if the USB cable is plugged in and has power.

i wouldn't describe this as a fix, more of a workaround, long term i think that the CDC.cpp file needs modifying to handle different OS's ways of leaving the ports  better, which may well be only checking the state of the DTR line


text:
Sending data to a webserver with GPRS/GPS Shield (U-blox Sara G-350)
I am working on a project for tracking cars. I am using an Arduino UNO to receive the position from GPS/GPRS shield. I am OK on obtaining the coordinates position.
Now I need to send the position to a webserver and then show it on a webpage using the Google Maps API. Which accepts it in a POST or GET method.
Here is the shield model:
U-blox Sara G-350
and this is its manual here
Here is my approach:
#include <SoftwareSerial.h>
#include <String.h>

SoftwareSerial gprsSerial(7 ,8);

void setup() {
  // put your setup code here, to run once:
  gprsSerial.begin(19200);
  Serial.begin(19200);
  delay(2000);

 gprsSerial.println("AT+CGDCONT=3,\"IP\",\"weborange\"");
 toSerial();
 delay(2000);

 gprsSerial.println("AT+UHTTP=0");
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UHTTP=2,1,\"www.navtec.16mb.com\"");
                   //AT+UHTTP=<profile_id>,<op_code>,<HTTP_server_name>
 toSerial();
 delay(2000);

 gprsSerial.println("AT+UHTTP=0,5,80");
 toSerial();
 delay(2000);

}

void loop() {

 //gprsSerial.println("AT+UHTTP=2,1,\"submit\"");
                    //AT+UHTTP=<profile_id>,<op_code>,<param_val>[,<param_val1>]
 //toSerial();
 //delay(2000);

 gprsSerial.println("AT+UHTTPC=2,1,\"/add.php\",\"filename\"");  //Problem here!!!!!!!!
                   //AT+UHTTPC=<profile_id>,<http_command>,<path>,<filename>[,<param1>[,<param2>[,<param3>]]]
 toSerial();
 delay(2000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }

}

This is what I get:

+CGDCONT=3,"IP","weborange"
OK
  +UHTTP=0
OK
  +UHTTP=2,1,"www.navtec.16mb.com"
OK
  +UHTTP=0,5,80
OK
  +UHTTPC=2,1,/add.php,filename
ERROR
  +UHTTPC=2,1,/add.php,filename
ERROR
  +UHTTPC=2,1,/add.php,filename
ERROR
  +UHTTPC=2,1,/add.php,filename
ERROR ...

Thanks for your time, I am waiting for your support, any ideas could help. Sorry for my bad English

The examples in the manual have quotes around the PHP file and the filename - just like you have for the FQDN entry. Maybe you should add them...?

Thank you for your support, but my problem is in the meaning and  perpose of responseFilename and how could i work with it?

Your problem is that you have an error. The filename is where to store the response in the internal filesystem, and the word filename is perfectly valid - as long as you use quotes around your strings.

even when  i add the quotes it still giving me an error. please check my new modification in code.

Try using AT+UHTTPER to get the error code from the request, see if that helps.

it work perfectly for me right now,I just get my error with this command.Thanks again @Majenko .I will add the new code.

I worked on a project similar to yours. I think you forgot to establish a connection first.
Just add those lines of code at the top of setup() method:
 gprsSerial.println("AT+UPSDA=2,0"); //Reset connection
 toSerial();
 delay(2000);
  gprsSerial.println("AT+UPSD=2,1,\"weborange\""); //Establish a new one
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UPSDA=2,3");
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UPSND=2,0");
 toSerial();
 delay(2000);

I hope it works for you. Else, you can use AT+UHTTPER=2 after all to check for error source.


text:
Can't upload sketch to arduino Uno board
I'm trying to upload a simple sketch to my Uno board but get this error message: avrdude: stk500_recv(): programmer is not responding (full error message at the end).
I have other Uno boards who work fine so I guess it is something to do specifically with this board (which used to work) and not my system or cables (port,drivers,settings etc..).
I did a loop-back test (http://forum.arduino.cc/index.php?topic=73748.0) on  the board and it worked fine.
I read about possible solutions but nothing seems to solve this.
https://stackoverflow.com/questions/19765037/arduino-sketch-upload-issue-avrdude-stk500-recv-programmer-is-not-respondi
I also tried using an Arduino as an AVR ISP but it failed. (https://www.arduino.cc/en/Tutorial/ArduinoISP)
Any help will be appreciated, thanks in advance.
Full error message:
    avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd3

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

In Arduino IDE check that

correct port number is selected in Tools -> Port
correct programmer is selected in Tools -> Programmer (should be AVRISP mkII if you upload the code via USB cable)
correct board is selected in Tools -> Board (Arduino/Genuino Uno)

If above doesn't help, install the latest version of Arduino IDE.

Try the different boards in the menu.  I had that with one of my boards and then it worked fine when I used the Due in the IDE instead.  Something to do with one of the chip revisions I think.


text:
Understanding memory fragmentation due to char arrays in functions
This is similar to:
Is this function subject to memory fragmentation?
I am trying to get my head around Memory fragmentation in Arduino's and embedded systems in general.
Currently I have a function in a __lcdAux__ Class which is responsible for doing basic operation on the lcd.
One of the members of the class is a char array double2StrBuff1 which is used with __dtostrf()__ to create a double which is then passed to sprintf. So the following function (__lcdAux::UpdatePosition__) is responsible for updating the position on the lcd.
void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
}

Currently, I am under the impression that by defining once the class as a global variable and then using it throughout the program, then the char array is allocated only once memory space. Therefore by using it afterwards no memory fragmentation occurs.
However, I read that functions allocate space on the stack which is immediately recoved when the function is exited. Therefore I am curious if the following declaration is any different in terms of memory fragmentation.
void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    char double2StrBuff1[10];
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
}

To sum up:

by putting  the declaration for variable __char double2StrBuff1[10];__  inside the function, is the memory allocated from the stack and therefore recovered upon exiting the function (therefore there is no need to declarate a member variable on the class level),

OR

is the fact that __double2StrBuff1__ is a pointer means that the pointer is allocated in the stack but the values are located in the heap (therefore what I am doing makes sense)?

PS: Because some might point out that  __"X: %s"__ is worse in terms of memory usage and fragmentation, I'll state the following. Instead of the format string __"X:%s"__ I use a _PROGMEM const char_ array and __strcpy_P()_, but to simplify the question I replaced it with the literal string , since I feel that is another problem.

The term memory fragmentation refers to heap fragmentation (when using malloc/free or new/delete). https://en.wikipedia.org/wiki/Memory_management

by putting the declaration for variable char double2StrBuff1[10];
  inside the function, is the memory allocated from the stack and
  therefore recovered upon exiting the function

This is correct.

is the fact that double2StrBuff1 is a pointer means that the pointer
  is allocated in the stack but the values are located in the heap
  (therefore what I am doing makes sense)?

No, double2StrBuff1 is not a pointer, it's an array. In C and C++,
when you use an array identifier, it decays to a pointer in many
situations. However, for the purpose of memory allocation, an array is
very different from a pointer.
Heap allocation only happens when using malloc() and new.

Could you point me to some reading material which will improve my understanding of how array identifiers are different to pointers?

@NMech: Take a look at this question (and its answers, and maybe the linked references) on Stack Overflow: What is array decaying?.

The examples in the question above use 1) global and 2) local aka stack allocation and do not give heap fragmentation. The heap is not involved.
Below is a version that may give heap fragmentation (though a very low risk):
void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    char* double2StrBuff1 = (char*) malloc(10);
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
    free(double2StrBuff1);
}

Please not that heap allocation is very slow compared to stack allocation.
C/C++ does not have any implicit heap allocations (in the language). A local array in a function is allocated on the stack and removed when the function returns. The only library functions that can generate stack fragmentation are setjmp and longjmp if used to create a spaghetti stack.