text:
Problem using Optiga Trust X I2C
Did someone ever used the Infineon Optiga Trust X module with Arduino using any I2C library ?
Here is the technical documentation of the Trust X module.
I'm trying to get the I2C_STATE register data but I don't receive anything after the Wire.requestFrom().
I also tried with the DSS Circuits I2C Master Library, same results.
Thanks
Full code :
#include <Wire.h>
#define PIN_RST 8
#define PIN_VDD 9

void setup() {
  pinMode(PIN_RST, OUTPUT);
  pinMode(PIN_VDD, OUTPUT);
  digitalWrite(PIN_RST,LOW);
  digitalWrite(PIN_VDD,LOW);

  Serial.begin(115200);
  delay(2000);
  Wire.begin(); // join i2c bus (address optional for master)

  digitalWrite(PIN_VDD,HIGH);  // sartup the Trust X module
  digitalWrite(PIN_RST,HIGH);

  delay(15);  // startup min delay
}

long val = 9999;

void loop() {
  Wire.beginTransmission(48); // transmit to device #48 (0x30)
  Wire.write(byte(0x82));            // sends instruction byte
  Wire.endTransmission();     // stop transmitting

  Wire.requestFrom(48, 4);
  while(Wire.available()==0){}

  val = Wire.read(); // Reads the data from the register
  Serial.print("val = ");
  Serial.println(val);

  delay(5000);

}

Testing a new sensor always starts with the i2c scanner https://playground.arduino.cc/Main/I2cScanner Use the address that the i2c scanner finds. Avoid that the sketch stops in the while statement. Test if 4 bytes are received, but don't use the while.

Hi and thank you for your answer. I have already tried the scanner and it did not found any device. The problem is I think at the startup of the Trust X module as specified in the documentation. But i can't see what I'm doing wrong.

If the i2c scanner does not find it, then no other code will work. What was the result of the i2c scanner? it was not 48. Adapt the i2c scanner to set the pin levels in the setup(). You could make the time after the reset 1 second instead of 15ms and also add a long delay between setting the pins vdd and reset high. You could show a photo of the wiring. I trust Infineon that they use the standard i2c. The first thing to do is to make the i2c scanner work. After that you can start to write good code, for example removing the while and reading 4 bytes.

What value are the pull up resistors you are using on the two I2C lines?

@Jot The i2c scanner answered with "No device". I know I will receive 4 bytes by reading the 0x82 register but as it didn't worked I just wanted to receive at least 1 byte this is why I used the while loop. I'll try to add longer delays and if it still not work, I will share a photo of the wiring. Thank you for your answer.

@CodeGorilla I'm using the Arduino internall pull up resistors, I assumed that the internal resistors were compliant with the i2c protocol (~5K). I have an example code that works fine with the Raspberry Pi 3 without adding external resistors so i tought that it will work the same with the Arduino.
So i will try to add external pull up resistor and disable the internal resistors. Unfortunately I do not have the equipment to visualize the signal. Thank you for your answer

I'm now using the Trust X EVAL KIT that I think should have the pull up resistor included and I still can't receive anything. The I2C scanner can't even find the device.

You need 4.7k pull-ups on both the data and clock lines.  It the scanner doesn’t show the device then can you try a different device.  I once spent hours chasing a fault which turned out to be I had wired the ic backwards.

@CodeGorilla I have tried with external pull up resistor (4.7K) and nothing changed.Today,  I have finally been able to read a register. Honestly i don't know what changes made it possible. I'll post my code if it can help someone

It looks like the answer is a bit delayed, but if somebody else sees this issue once again.
It might not be directly visible in the documentation (Datasheet or Solution Reference Manual), but here what you can find in the Trust M Datasheet Annex B (Section 11):
"The OPTIGA™ Trust M will not acknowledge the slave address sent by a host if it is either busy or in idle state. Hence the host must retry or repeat the transaction until it is successful or timed out for 100 milliseconds (extreme case).
The specified guard time must be applied between each attempt of write / read operation by the Host I2C driver."
The chip always goes into an idle or sleep state if no command is issued in a defined time period, unless a Sleep Activation Delay isn't changed.

So I finally succeeded to read a register value. I don't really know where was the problem. Here is the code if it can help someone (the scanner still does not work btw) :
#include <Wire.h>

#define DEVICE_ADDRESS 0x30

#define PIN_RST 8
#define PIN_VDD 9

void printOutput(byte *out, int out_len){
   int y=0;
  Serial.print("out = ");
  for(;y<out_len;y++){
    Serial.print(out[y],HEX);
  }
  Serial.println("");
}

void coldReset(){
  pinMode(PIN_RST, OUTPUT);
  pinMode(PIN_VDD, OUTPUT);
  digitalWrite(PIN_VDD,LOW);
  digitalWrite(PIN_RST,LOW);
  delayMicroseconds(2000);
  digitalWrite(PIN_VDD,HIGH);  // sartup the Trust X module
  digitalWrite(PIN_RST,HIGH);
}

int I2C_get(byte reg, byte *out, int out_len){
  int i=0, nbSend=0, nbAvailable=0, ret=0;
  Wire.beginTransmission(DEVICE_ADDRESS); // transmit to device #48 (0x30)
  nbSend=Wire.write(reg);            // sends instruction byte
  Wire.endTransmission();     // stop transmitting
//  Serial.print("nb send = ");
//  Serial.println(nbSend);

  delayMicroseconds(50);
  Wire.requestFrom(DEVICE_ADDRESS, out_len);

//  nbAvailable=Wire.available();
//  Serial.print("nb available = ");
//  Serial.println(nbAvailable);

  if(Wire.available()==out_len){
    for(;i<out_len;i++){
      out[i]=Wire.read();
    }
  }
  else ret=-1;

  return ret;
}

void setup() {

  Serial.begin(115200);
//  Wire.begin(); // join i2c bus (address optional for master)
//  coldReset();
//  delayMicroseconds(15000); // Startup time
}

void loop() {
  int y=0, out_len, ret;
  byte res1[]={0x00,0x00,0x00,0x00};

  Wire.begin(); // join i2c bus (address optional for master)
  Wire.setClock(400000);
  coldReset();
  delayMicroseconds(15000); // Startup time

  out_len=4;
  ret=I2C_get(byte(0x84),res1,out_len);
  if(ret!=-1){
    printOutput(res1,out_len);
  }
  else{
    Serial.println("Error I2C_get");
  }

  Wire.end();
  Serial.println("");
  delay(5000);
}


text:
How to have compiler know whether Arduino or ESP8266?
I am doing some work for both Arduino Mini Pro and for a NodeMCU style ESP8266 board. Within the Arduino IDE I tell it what board I am compiling for and downloading to.
How do I access which board in my scripts?
Some sections are for one or the other exclusively. Right now I'm using a #define at top of the script, but changing this to switch between boards not the best. For example, version control keeps on thinking I'm in a new branch when I'm not.

There are a number of macros defined to help you with this:

__AVR__ for any board with AVR architecture.
ARDUINO_AVR_PRO for the Arduino Pro or Pro Mini selection in the Tools > Board menu.
ESP8266 for any ESP8266 board.
ARDUINO_ESP8266_NODEMCU for the NodeMCU 0.9 (ESP-12 Module) or NodeMCU 1.0 (ESP-12E Module) selections in the Tools > Board menu.

This allows you to do things like this:
#if defined(__AVR__)
// AVR specific code here
#elif defined(ESP8266)
// ESP8266 specific code here
#endif

source: Stack Exchange

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

sort: votes


text:
Electronically, should single or several ground pins be used?
I have heard two theories of grounding: pretty much ground a board at single point, or ground everything in sight.
With the Mini Pro, is it better to provide one source of ground through the Gnd pin next to the Vraw pin, or ground with multiple Gnd pins on the board?

All GND pins on the Arduino board are interconnected, so it doesn't matter which one you use.

There are times when you want a single ground point (star grounding), separate grounds with filters (separate analog and digital grounds, for instance), or you just don't care (99% of the time).
Regardless, this is usually a concern when you are laying out a circuit on a PCB. When you already have a PCB the grounds become a moot point because the PCB dictates how they operate.
For a module like an Arduino, unless otherwise stated, all grounds are equal and can be used for whatever whenever.

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


text:
Arduino Mega 2560 with SIM808 module
I have a SIM808 module like this: https://www.banggood.com/SIM808-Module-GPS-GSM-GPRS-Quad-band-Development-Board-For-Arduino-p-1063106.html
The output header has 5 pins: GND/RX/GND/TX/VCC and I connected them as:
GND/VCC to a LiPo battery, 7.4V@1000mAh
RX->pin 14 (written on it TX3)
GND->to arduino GND
TX->pin 15 (written on it RX3)
and uploaded this code
#include <SoftwareSerial.h>

SoftwareSerial GSMSerial(15,14);    // RX, TX

void setup()
{

  GSMSerial.begin(19200);
  Serial.begin(19200);
  Serial.println("START");
}

void loop()
{
  if(Serial.available())
    GSMSerial.print((char)Serial.read());
  else  if(GSMSerial.available())
    Serial.print((char)GSMSerial.read());
}

But I'm not getting anything on it (when sending "AT" or anything else).
Any help is appreciated.
Thank you!

Don't use SoftwareSerial on the HardwareSerial pins.  Instead of this:
#include <SoftwareSerial.h>
SoftwareSerial GSMSerial(15,14);    // RX, TX

Just do this:
#define GSMSerial Serial3


text:
Error using Adafruit Feather M0
I am trying to upload an empty program on the Adafruit feather to see if it connects to my PC. So far, it isn't. I'm running a Windows 10 and I followed this guide:
https://learn.adafruit.com/adafruit-feather-m0-wifi-atwinc1500?view=all
But I get this error:
Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.
And the PORT submenu is greyed out.

Were you able to get this working? I am having the same issue..

I found out the issue I was having, though I have a Gemma.
What worked for me:

Selecting the correct board under "Tools" -> "Board:" (in your case, the Adafruit Feather 32u4 is probably the one you want)
Selecting the "USBtinyISP" under "Tools" -> "Programmer:"

Then it was able to upload to the Gemma, after hitting it's reset button twice to get it into a 'programming mode' (I don't know if the feather has such a feature).
If you are still having problems make sure that you have properly set up your arduino IDE for adafruit boards, and just play around with settings (try different programmers).
I don't know why it was so hard finding this info out, and why it is not more visible on the documentation to set these things up. I think I found out the 'hitting reset twice' thing somewhere buried in a forum... I digress, but Adafruit does need to consolidate their documentation to make it clearer.
Hope this helps

A common problem on Windows for people who may be encountering this type of issue is actually having the wrong USB to UART Bridge drivers or none at all. You can download the most up to date ones here

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


text:
My arrays are possibly causing the program to not enter loop?
I'm working on a project to make a digital clock with an 8x32 ws2812 LED grid, arduino uno, and a RTC module.
Everything works great separately, but when I integrate it all together the code never seems to reach the loop function. I have print statements in the setup and start of the loop, and the setup statement triggers but the first print in the loop does not. Nothing in the loop seems to occur. Commenting out line by line I've identified that the problem somehow is caused by my arrays of neopixel locations. When I comment out lines that refer to certain arrays, the code works, all print statements are called and every other functionality works fine. When I restore the lines that call the problematic arrays and remove some of the values, it will eventually start working when I remove so many values from the end. Weird.
Array examples:
int left_min_zero[] = {145,146,147,148,149,150,153,166,169,170,171,172,173,174,161,158};
int left_min_one[] = {158,157,156,155,154,153};
int left_min_two[] = {145,158,161,174,173,172,171,164,155,148,149,150,153,166,169};

The full code is here: https://github.com/SupaTreadz/Pixel-Clock/blob/master/PixelClock.ino
The offending lines are related to the following arrays:
"left_min_four", "left_min_five", and all of the "right_min_" arrays (possibly, I only checked the first three)
ALL of the other arrays work fine. WHAT THE HECK IS GOING ON HERE???
Just to reiterate, those arrays worked perfectly before adding the clock stuff. So right now all of the hour digits function perfectly, the first digit of minutes work except for 4 and 5, and none of the right minute digits work.
Any insight into this problem that is driving me crazy would be much appreciated.

Have you checked the memory status (build, run-time, etc)?

Just 256 LEDs and 402 numbers in those int arrays = ~1.572kB of memory. An Uno has only 2kB of memory.

The code linked has the problematic lines commented out and works, those lines are 317, 326, 339, 348, 357, 366, 375, 384, 393, 402, 411, 420. And the code uploads to the board fine, says it only uses 31% of program space and 54% of dynamic memory. Should I try a larger board?

It looks like a memory problem, and using the String class probably does not help...

Commenting out the Strings does not solve the problem. I will try a larger board I guess, but I don't understand how it can be a memory problem when the IDE says it has so much memory remaining?


text:
Using 5V microphone module with Wemos D1 Mini Pro 3.3V analog pin
I want to read values from this microphone module using Wemos D1 Mini Pro analog pin. Unfortunately, this module operates on 5V, but the analog pin on Wemos has range 0-3.3V. I have tried to use a voltage divider on microphone module output, but I am getting very low values which don't reflect sound power (to get values greater than zero I have to knock on the microphone). In the voltage divider R1 = 500 Ohm and R2 = 1000 Ohm. Is there some way to make this work correctly?

What are the output impedance of the module and the input impedance of the Wemos pin?

Wemos: < 100 Kohm (http://www.esp8266.com/viewtopic.php?p=61759#p61759). About the module I am not sure, but I have found page with more info: http://sensorkit.en.joy-it.net/index.php?title=KY-038_Microphone_sound_sensor_module . I can tell you the resistance of that potentiometer: 66.4 Kohm


text:
Arduino Mega 2560 with SIM808 module - Incomplete SMS response
I have this code to read a SMS:
String read_SMS(int index)
{
  Serial.println("--START READ SMS POSITION" + String(index) + "--");
  delay(400);
  sendATcommand("AT+CMGF=1", "OK", 1000);    // sets the SMS mode to text
  delay(2000);
  String tmp;
  tmp = readATcommand("AT+CMGR=1", 4000);
  Serial.println("Content: " + tmp);
  Serial.println("--END READ SMS POSITION" + String(index) + "--");
}

String readATcommand(String ATcommand, unsigned int timeout)
{
  char response[800];
  unsigned long previous;
  memset(response, '\0', 800);    // Initialice the string

  int x = 0;

  GSMSerial.println(ATcommand);
  delay(3000);
  previous = millis();
  do {
    if (GSMSerial.available() > 0) {
      response[x] = GSMSerial.read();
      x++;
    }
  } while ((millis() - previous) < timeout);   // Waits for the asnwer with time out

  return (String) response;
}

// sending AT commands to the Sim808 module
int8_t sendATcommand(String ATcommand, char* expected_answer, unsigned int timeout) {

  uint8_t x = 0, answer = 0;
  char response[200];
  unsigned long previous;

  memset(response, '\0', 200);    // Initialice the string

  delay(100);

  // Clean the input buffer
  while (GSMSerial.available() > 0 ) GSMSerial.read();

  if (ATcommand[0] != '\0') {
    // Send the AT command
    GSMSerial.println(ATcommand);
    //Serial.print(F("AT Command: "));
    //Serial.println(ATcommand);
  }

  // Waiting for the answer
  x = 0;
  previous = millis();

  do {

    // if there are data in the UART input buffer, reads it and checks for the asnwer
    if (GSMSerial.available() > 0) {

      response[x] = GSMSerial.read();
      x++;
      // check if the desired answer (OK) is in the response of the module
      if (strstr(response, expected_answer) != NULL) {
        answer = 1;
      }
    }

  } while ((answer == 0) && ((millis() - previous) < timeout));   // Waits for the asnwer with time out

  //Serial.println(F("START RESPONSE:"));
  //Serial.println(response);
  //Serial.println(F("END RESPONSE"));
  //if (answer == 0) {
  //  Serial.println("Could not get the expected answer!");
  //}
  //else {
  //  Serial.println("Found expected answer!");
  //}

  return answer;
}

What can be wrong in the readATcommand function as it replies with an incomplete response:
--START READ SMS POSITION1--
Content:
AT+CMGR=1

+CMGR: "REC READ","+407245402XX","","17/06/29,10:
--END READ SMS POSITION1--

But, when I run it from a terminal, the AT+CMGR=1 replies with:
AT+CMGR=1

+CMGR: "REC READ","+40724540234","","17/06/29,10:03:06+12"
Salut

OK

As you can see the message body is not there + the time of the SMS is also incomplete.
Thank you!

What is GSMSerial?

@Majenko #define GSMSerial Serial3

My guess is that your gratuitous use of the delay() function is making the serial buffer overflow. There is never any call to use delay() when reading from serial. The AT protocol has proper handshaking signals that you should use, such as looking for "OK". There is no need to delay() while waiting for them, that's just silly.

Works now. At first I got to reply so I put the delays. After the delays I got the partial messages. Now without any delays .. I get the full messages. Thanks!

Don't delay.
In the three seconds that you wait between sending the AT command and reading the response the entire response has arrived and been placed in the serial RX buffer - which has overflowed because there's more than 64 bytes in the response. So you lose data.
You should never use delay() when reading from serial, it's dangerous (as you see).
Instead you should be just immediately reading until you see the correct response from the command you sent - which will either be "OK" or "ERROR". Everything before that is the content of the response to your command.


text:
No output from PCM5102 I2S DAC
I'm trying to connect a HiLetgo PCM5102 I2S DAC to a Teensy 4.0, but I'm not getting any audio out.  I have it wired as:
SCK - GND
BCK - BCLK1 (21)
DIN - OUT1A (7)
LCK - LRCLK1 (20)
GND - GND
VIN - +3.3v

The datasheet confirms that if I don't set SCK then it will use a phase-locked loop from BLK to sync its clock.
The red light on the audio board does come on:

Checking with the oscilliscope, I see plausible values for the three digital inputs.  Here's the left-right clock showing 44.1kHz as it should:

Here's the bit clock, showing 2.85MHz:

Dividing, this is 64 bits per sample, which I guess is four bytes each for left and right.  This seems high to me, though the datasheet says it can take it.
The VIN also looked plausible, though I forgot to take a picture.
Is there anything else worth trying before deciding that the audio board is defective?

Here's my code, which should be putting out a sine wave:
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>

// GUItool: begin automatically generated code
AudioSynthWaveformSine   sine1;          //xy=212,327
AudioOutputI2S           i2s1;           //xy=566,307
AudioConnection          patchCord1(sine1, 0, i2s1, 0);
AudioControlSGTL5000     sgtl5000_1;     //xy=449,467
// GUItool: end automatically generated code

void setup() {
  Serial.begin(9600); // Initialize serial communication
  while (!Serial) {}  // Wait for serial monitor to open

  Serial.println("Initializing audio...");

  AudioMemory(10);
  sgtl5000_1.enable();
  sgtl5000_1.volume(1);  // adjust the volume if necessary
  sine1.frequency(440);    // set the initial frequency to 440 Hz (A4)

  Serial.println("Audio initialized.");

}

void loop() {
  // nothing to do here, sine wave is generated continuously in the background

  Serial.println("Running loop...");
  delay(10000);
}

After reading the Amazon reviews more carefully, the problem was that there are four pads that need soldering:

1 / FLT - Filter select : Normal latency (Low) / Low latency (High)
2 / DEMP - De-emphasis control for 44.1kHz sampling rate: Off (Low) / On (High)
3 / XSMT - Soft mute control(1): Soft mute (Low) / soft un-mute (High)
4/ FMT - Audio format selection : I2S (Low) / Left justified (High)

I soldered 3 high and 1, 2, and 4 low.  Now it works!

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


text:
GPS(Incorrect time showing)
Anyone help? It shows incorrect time. Please help.
  /* Conexion pines
     Arduino        GPS
        D3           RX
        D4           TX
  */

  #include <SoftwareSerial.h>  //incluimos SoftwareSerial
  #include <TinyGPS.h>         //incluimos TinyGPS

  TinyGPS gps;  //Declaramos el objeto GPS
  SoftwareSerial serialgps(10,11);      //Declaramos el pin 4 (Tx del GPS) y 3 (Rx del GPS)

  //Declaramos la variables para la obtención de datos
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long chars;
  unsigned short sentences, failed_checksum;

  void setup()
  {
   Serial.begin(9600);  //Iniciamos el puerto serie
   serialgps.begin(9600); //Iniciamos el puerto serie del gps

   //Imprimimos en el monitor serial:
   Serial.println("");

  }

  void loop()
  {
   while(serialgps.available())
   {
    int c = serialgps.read();
    if(gps.encode(c))
    {
     float latitude, longitude;
     gps.f_get_position(&latitude, &longitude);
     Serial.print("Latitud/Longitud: ");
     Serial.print(latitude,5);
     Serial.print(", ");
     Serial.println(longitude,5);
     gps.crack_datetime(&year,&month,&day,&hour,&minute,&second,&hundredths);
     Serial.print("Date: "); Serial.print(day, DEC); Serial.print("/");
     Serial.print(month, DEC); Serial.print("/"); Serial.print(year);
     Serial.print(" Time: "); Serial.print(hour, DEC); Serial.print(":");
     Serial.print(minute, DEC); Serial.print(":"); Serial.print(second, DEC);
     Serial.print("."); Serial.println(hundredths, DEC);
     Serial.print("Altitud (metros): "); Serial.println(gps.f_altitude());
     Serial.print("Rumbo (grados): "); Serial.println(gps.f_course());
     Serial.print("Velocidad(kmph): "); Serial.println(gps.f_speed_kmph());
     Serial.print("Satelites: "); Serial.println(gps.satellites());
     Serial.println();
     gps.stats(&chars, &sentences, &failed_checksum);

     delay(10000);
    }
   }
  }

how far was it off?

nope its not :(

I meant what was the time when you ran that code? What time should it have shown.

it should be 10:15 pm

And what time zone are you in?

GPS time is in UTC, not UTC+8, where you seem to live (not accounting for daylight savings time)

UTC +8 . how can i do it? :(

http://www.instructables.com/id/Adjusting-GPS-Date-and-Time-to-your-Time-Zone/

I already try that but it give me error "'setTime' was not declared in this scope"

Like Majenko's comments suggested, you must shift the UTC time to your local time.  The Time library can help you do this.
There are some other problems:

You cannot wait 10 seconds without processing the characters. The Arduino receive buffer only has room for 64 characters. The GPS device could have sent 10000 characters during that time, so most of them will get dropped. This prevents the GPS library from parsing a GPS data successfully.  It will eventually "see" a complete set of data, sometime after the 10 seconds.  You may see data once every 11 seconds, not 10.
You are printing the several values even though they may not be valid.  For example, if you are not moving, or you do not have good satellite reception, the GPS device may not provide a speed.
The Arduino millis() clock will not be synchronized with the GPS clock. You could use the GPS updates as an exact 1-second clock. Simply count 10 fixes as they arrive, and this will mean that 10 seconds have elapsed.
You should use a different serial port and/or library. This answer describes the various choices: HardwareSerial (i.e. Serial on pins 0 & 1), AltSoftSerial (8 & 9 on an UNO) or NeoSWSerial (any two pins).

Here is a NeoGPS version of your sketch that addresses these issues:
#include <NeoSWSerial.h>
#include <NMEAGPS.h>

NMEAGPS gps;  //Declaramos el objeto GPS
gps_fix fix;  // all GPS fields, including date/time, location, etc.
uint8_t fixCount;
NeoSWSerial serialgps(10,11);

void setup()
{
 Serial.begin(9600);  //Iniciamos el puerto serie
 serialgps.begin(9600); //Iniciamos el puerto serie del gps

 //Imprimimos en el monitor serial:
 Serial.println( F("Test") );

}

void loop()
{
 // Check for GPS characters and parse them
 if (gps.available( serialgps ))
 {
  // Once per second, a complete GPS fix structure is ready.  Get it.
  fix = gps.read();

  // Count elapsed seconds
  fixCount++;

  if (fixCount >= 10)
  {
    fixCount = 0; // reset counter

    // adjust from UTC to local time
    if (fix.valid.time)
      adjustTime( fix.dateTime );

    printGPSdata();
  }
 }
}

void printGPSdata()
{
  Serial.print( F("Latitud/Longitud: ") );
  if (fix.valid.location) {
    Serial.print( fix.latitude(), 5 );
    Serial.print( F(", ") );
    Serial.print( fix.longitude(), 5 );
  }
  Serial.println();

  Serial.print( F("Date: ") );
  if (fix.valid.date) {
    Serial.print( fix.dateTime.date  ); Serial.print('/');
    Serial.print( fix.dateTime.month ); Serial.print('/');
    Serial.print( fix.dateTime.year  );
  }

  Serial.print( F(" Time: ") );
  if (fix.valid.time) {
    Serial.print( fix.dateTime.hours ); Serial.print(':');
    if (fix.dateTime.minutes < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime.minutes); Serial.print(':');
    if (fix.dateTime.seconds < 10)
      Serial.print( '0' );
    Serial.print( fix.dateTime.seconds );
    Serial.print('.');
    if (fix.dateTime_cs < 10)
      Serial.print( '0' );
    Serial.print( fix.dateTime_cs );
  }
  Serial.println();

  Serial.print( F("Altitud (metros): ") );
  if (fix.valid.altitude)
    Serial.print( fix.altitude() );
  Serial.println();

  Serial.print( F("Rumbo (grados): ") );
  if (fix.valid.heading)
    Serial.print( fix.heading() );
  Serial.println();

  Serial.print( F("Velocidad(kmph): ") );
  if (fix.valid.speed)
    Serial.print( fix.speed_kph() );
  Serial.println();

  Serial.print( F("Satelites: ") );
  if (fix.valid.satellites)
    Serial.println( fix.satellites );
  Serial.println();
  Serial.println();
}

//--------------------------

void adjustTime( NeoGPS::time_t & dt )
{
  NeoGPS::clock_t seconds = dt; // convert date/time structure to seconds

  // Offset to the local time
  const int32_t          zone_hours  = +8L;
  const NeoGPS::clock_t  zone_offset = zone_hours * NeoGPS::SECONDS_PER_HOUR;
  seconds += zone_offset;

  dt = seconds; // convert seconds back to a date/time structure

} // adjustTime

If you want to try it, NeoGPS, AltSoftSerial and NeoSWSerial are available from the IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries. NeoGPS is smaller, faster, more reliable and more accurate than all other GPS libraries.
Even if you don't use it, there are many suggestions on the Installation and Troubleshooting pages.


text:
LCD display weird characters
Im a newbie. I have a problem with displaying text in LCD (16x2). It shows incorrect message in the lcd. Here is the code and the picture that gives the wrong output : Kindly help Thank you.
#include "SIM900.h"
#include <SoftwareSerial.h>

#include "sms.h"
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

//gsm
SMSGSM sms;

int numdata;
boolean started  = false;
char smsbuffer[160]; //message
String newsms;
char n[20];
unsigned char i;
//lcd
int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
int outputValue = 0;   // value output to the %
int outputValue1 = 0;   // value output to cursor

void setup()
{
  //Serial connection.
  //gsm
    lcd.begin(16, 2);

  Serial.begin(9600);

//  lcd.setCursor(0, 1);
//  lcd.clear();
//  lcd.print("   Wireless Public       via GSM"); //55 chars
//  lcd.setCursor(0, 2);
//  lcd.print("    Notice Board "); //55 chars
   Serial.println("GSM Shield testing.");
  if (gsm.begin(2400)) {
    Serial.println("\nstatus=READY");
    started = true;
  }
  else Serial.println("\nstatus=IDLE");

  //lcd
  // set up the LCD's number of columns and rows:

};

void loop()
{

  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  // map it to the range of the analog out:
  outputValue = map(sensorValue, 0, 1023, 0, 100);
  outputValue1 = map(sensorValue, 0, 1023, 0, 200);

  //scroll = lcd.scrollDisplayLeft();
  if (started) {
    //Read if there are messages on SIM card and print them.
    if (gsm.readSMS(smsbuffer, 160, n, 20))
    {
      //lcd
      lcd.clear();
      lcd.setCursor(0, 2);
      lcd.print("SMS Received!");
      delay(2000);
      lcd.clear();
      lcd.setCursor(0,1);
      Serial.println(n);
      Serial.println(smsbuffer);
      lcd.print(smsbuffer);
      delay(1000);
//      lcd.clear();
    }
    delay(1000);
  }
}

What characters does Serial.println(smsbuffer); print to the serial monitor?

Yes In Serial Monitor it display the correct message that being send by the sender but when i print it in lcd it did not display the same output as what serial monitor display It only display the image that i upload.

Please edit your question to show the wireup of the LCD to your Arduino. Are you sure you didn't exchange one of the data line wires? (https://www.arduino.cc/en/Tutorial/HelloWorld) Is every message displayed wrong or just the contents of smsbuffer? Have you tried running a minimal sketch to just test the LCD with a 'hello world'?

I did print the smsbuffer in serial so that i can see the content of the message that being receive. Well in Serial it gives the correct output/content that the sender message. but when i print it in lcd it shows incorrect content.

@Megumichan, when i print it in lcd it shows incorrect content .... you are misunderstanding the problem ... the LCD is displaying exactly the correct content .... it is displaying what you are telling it to display ..... you have to figure out why your program is sending content that you do not want to see .... start by running the "helloWorld" demo

we start running the hello world demo in the lcd and yeah it runs perfectly in lcd. but when it comes to this code it didnt. it display only that in the picture that i upload

I print the smsbuffer content when its already receive a message and when i print the smsbuffer in the serial monitor the content is right and correct. but why when it comes to the lcd it isnt?]

Can you give an example of the string contained smsbuffer? What exact characters are those? The LCD library probably can only handly ASCII only, for the rest you would need to define custom character sets.

The first thing to try is replacing lcd.begin(16, 2) with lcd.begin(20, 4). The image of your LCD looks like a 20 char by 4 line display. Based on your comments, it seems that the SMS part of your code is working because it's outputting the correct characters to the serial monitor. I would focus on the LCD code and connections to your Arduino.

Yeah in serial it shows the correct content of the message but in lcd it shows degree symbol(extended ascii code) Is it possible to convert this ascii code to string?  or how can i remove this degree ascii code and change it to text? Thank you

What would you like to replace the degree symbol with?

can i possibly replace the degree symbol to string ??

I'm not sure what you mean, "to string". An empty string? A space character?

Hello I had the same problem and noticed that if you setup the lcd screen in this order:
LiquidCrystal lcd (d7, d6, d5, d4, , en, rs) ;

you get some weird character showing up...
but if you do this way:
LiquidCrystal lcd (rs, en, d4, d5, d6, d7) ;

you don't get any weird character.


text:
How to connect Sparkfun M6E Nano UHF Rfid reader and ESP8266 NodeMCU 0.1
I am using an ESP8266 NodeMCU v0.1 and Sparkfun M6E Nano UHF Rfid reader. How to connect NodeMCU to M6E Nano UHF Rfid reader?

did you see my answer?

sorry for late reply, yes i saw your answer.

@Juraj can you tell me that is there any way to post an array (20 byte) using nodemcu on MySQL data base which is on my localhost. because i am getting my RFID tag id into an array! Like this
FF, DE, 3E, X, X, X....... till 20 bytes

it is possible, but that is a different question. you would need to have a server on a computer to write the data to MySQL. and you would send data from esp8266 to this server.

Thanks, yes i already have a server(xampp) on a computer. Could you provide the resource/link that how to insert array into a single cell of database?

Yes i had insert  the temperature sensor data into a MySQL database using nodemcu, but don't know how it could be done for an array!!

The interface of Sparkfun M6E Nano UHF Rfid reader is Serial TTL. So you should connect it to Serial pins of the NodeMcu. Don't use USB then, because it is connect to Serial too.

worked fine with Arduino Uno when I am trying to use with Uno+Rfid reader+NodeMcu it doesn't work!

how did you wire it to nodemcu?

Like this
(Reader->NodeMCU),
GND ->GND,
VIN->VIN,
RST->RST,
2->D2,
3->D3,

this answer above says you should connect it to RX and TX

use the pins on the short side of the reader board, VCC, Gnd, RX and TX and connect to Gnd, 5V, Rx and TX of NodeMcu

https://learn.sparkfun.com/tutorials/simultaneous-rfid-tag-reader-hookup-guide/all#hardware-hookup

You are saying about TX/RX pins which are used for Arduino Shield, not for FDTI.

it is not only for FTDI. it is Serial. and you need Serial. With Uno, you used pins 2 and 3 with SoftwareSerial. you can't do that with NodeMcu. you could connect the NodeMcu to pins 0 and 1, but why. those are the same RX and TX pins as 'for the FTDI'


text:
Arduino self programming
I have noticed that some atmel chips can do "self programming" and I'm doing a hobbyist project where I need to change the "setting" of my arduino without code-reuploading through Arduino IDE.
Is it possible to do that ?
If it's possible. Please give me some basic though about how to do it.
Thanks in advance !

There are two areas of non-volatile storage in an Arduino: Flash and EEPROM.
Flash is where your program and constant values are stored. Variables with default values also have their default values stored in Flash.
EEPROM is a much smaller area with no real fixed purpose - you can store whatever values you want in there.
Flash can only be written to by code that is in the bootloader area of flash. This is important. A program cannot modify itself. Only the bootloader can modify a program - and then only in chunks ("pages"). It has to erase a whole page before it can write data to it.
The reason why you can't modify Flash from your main program is simple: Flash is the only place code can be executed from. If you erase the page of flash that contains the code that is programming the Flash then everything dies. Horribly. So it's stopped in its tracks by not allowing it to happen in the first place.
EEPROM, conversely, can be written to by anything - the bootloader or the main program. And on top of that individual values can be modified at will - no need to erase pages.1
So to answer the question behind your question ("How can I store and modify settings?"): it's quite simple - store them in EEPROM.
The IDE has examples of how to use the bundled EEPROM library, and there are more details in the Arduino reference manual.

1: Some systems don't have EEPROM, so they emulate it using Flash. These systems still have to erase the Flash in pages, but they try to do it transparently. Some (such as the ESP8266) use a commit() method to update a batch of values. Others, such as chipKIT boards, use wear levelling and separately indexed writing to reduce the need to erase pages.

Yes, you can self-program these.  There are several different bootloaders you can use to do this - here's one: https://bitbucket.org/talk2/talk2boot

You can write to the non-volatile memory of the microcontroller and then read it again during setup.
Another (perhaps simpler) option is to have an external eeprom chip in a socket to hold the settings so you can program that separately from the module. That way you don't need to have a menu in your project.

Self programming is used by Arduino bootloader. If you want something special, you have to change bootloader, because you can't call SPM instruction outside of BOOT sector (the only exception are AVRs with a small program memory).
I'd recommend to use internal EEPROM storage instead.

You can do something simple - say have 2 pins to select 1 of 4 sets of values for the code to use.  Read the pins in setup(), and change values to use in loop() accordingly.
void setup(){
change = PIND & 0b1100000; // say D7/D6 used on a Uno.
switch (change){
  case 0b00000000:
  // set values for D7/D6 = 00
  break;
  case 0b01000000:
  // set values 01
  break;
  case 0b10000000:
  // set values 10
  break;
  case 0b11000000:
  // set values 11
  break;
  }
}

Or wait in setup() for the choice to come in a Serial message.
Maybe store the sets of values in EEPROM for selection via whatever source, and then let the code change the values if needed.
Or think of other ways to select the values without having to change the existing bootloader.


text:
Basic Arduino Question. Trying to turn off leds turned on through the serial monitor by using a push button
I'm new to using the serial monitor. I have a code set up so that LEDs turn on when I type an input on the keyboard. I know how to turn them off using a keyboard but I and can't figure out why the leds won't turn off when I press a push button.
    #define led1 10 //10th,
    #define led2 11 //11th
    #define led3 12 //12th
    #define led4 13 //13th
    #define ButtonA 9

    int ButtonState;
    int ButtonState2;
    int state;
    int StateNow;
    int PreviousState = HIGH;

    void setup(){
      pinMode(led1,OUTPUT);
      pinMode(led2,OUTPUT);
      pinMode(led3,OUTPUT);
      pinMode(led4,OUTPUT);
      pinMode(ButtonA,INPUT_PULLUP);
      Serial.begin(9600);
      Serial.println("Enter ch a, b, c, or d:");
    }

    void loop() {
    if (Serial.available())
    {
      ButtonState = digitalRead(ButtonA);
      delay(10);
      ButtonState2 = digitalRead(ButtonA);  //debounce
      if (ButtonState != ButtonState2)
      {
        StateNow = ButtonState2;
      }
      else
      {
        StateNow = ButtonState;
      }
      if(StateNow == LOW && PreviousState == HIGH)
  {
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
    digitalWrite(led3,LOW);
    digitalWrite(led4,LOW);
    Serial.println("Turned off all LEDs");
    PreviousState = LOW;
  }
  else if(StateNow == HIGH && PreviousState == LOW)
  {
    PreviousState = HIGH;
  }
  state = Serial.read();
  if (state == 'a' || state == 'A')
  {
    digitalWrite(led1,HIGH);
    Serial.println("Turned on led 1");
  }
  else if (state == 'b' || state == 'B')
  {
    digitalWrite(led2,HIGH);
    Serial.println("Turned on led 2");
  }
  else if (state == 'c' || state == 'C')
  {
    digitalWrite(led3,HIGH);
    Serial.println("Turned on led 3");
  }
  else if (state == 'd' || state == 'D')
  {
    digitalWrite(led4,HIGH);
    Serial.println("Turned on led 4");
  }
}

}

The LEDs turn on properly and I know the circuit is wired correctly so it's definitely something I'm missing in the software

you check the button only when serial is connected

So should I check the button outside of serial being connected?

why would you even ask? just try it.

To turn off all leds when button is pressed, you must detect a rising or falling in the button signal.

In your code you detect the change only if serial is available, but you should do it in the loop.
The simple way to detect the change is doing this in every loop:
if (StateNow != PreviousState) {
  if (StateNow == LOW && PreviousState == HIGH) //button pushed
  {
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);
    Serial.println("Turned off all LEDs");
  }
  PreviousState = StateNow;
}

I simplify your code and add some comments:
#define led1 10 //10th,
#define led2 11 //11th
#define led3 12 //12th
#define led4 13 //13th
#define ButtonA 9

int state;
int StateNow;
int PreviousState;

void setup() {
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(ButtonA, INPUT_PULLUP);
  Serial.begin(9600);
  Serial.println("Enter ch a, b, c, or d:");
  PreviousState = digitalRead(ButtonA);
}

void loop() {
  //detect changes in button signal to turn off leds
  StateNow = digitalRead(ButtonA);
  if (StateNow != PreviousState) {
    if (StateNow == LOW && PreviousState == HIGH) //button pushed
    {
      digitalWrite(led1, LOW);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      Serial.println("Turned off all LEDs");
    }
    PreviousState = StateNow;
  }

  //check serial biffer to turn on leds
  if (Serial.available())
  {
    state = Serial.read();
    if (state == 'a' || state == 'A')
    {
      digitalWrite(led1, HIGH);
      Serial.println("Turned on led 1");
    }
    else if (state == 'b' || state == 'B')
    {
      digitalWrite(led2, HIGH);
      Serial.println("Turned on led 2");
    }
    else if (state == 'c' || state == 'C')
    {
      digitalWrite(led3, HIGH);
      Serial.println("Turned on led 3");
    }
    else if (state == 'd' || state == 'D')
    {
      digitalWrite(led4, HIGH);
      Serial.println("Turned on led 4");
    }
  }
}


text:
How do I turn lights on & off manually along with home automation?
Need some help regarding HomeAutomation
I was doing my room automate via Arduino with the help of relay , but a little problem I am facing,that when I switched on the light via relay then I cannot turn it off via switch board manually ,the switch is now useless & I have tried two way switch but it's not a better solution.
So please can anyone tell me how to solve this problem so that I can turn lights on manually & automatic too
Thanks

This question is better suited to https://electronics.stackexchange.com/ because your question's root has nothing to do with Arduino, but everything to do with wiring and switches.

A relay with both NO and NC contacts could function as one of the two switches in a conventional two-way switch setup, but you need to be very careful when wiring mains circuits - there are real hazards there.  Likely that subject matter belongs on Home Improvement SE, not on Electronics Stack Exchange.

you can use super caps to record manual offs, keeping the system in sync. if you set it to turn on when powered-on, a flip of the switch (or two) can result in your desired state.

Thank you so much , I will also add this question to https://electronics.stackexchange.com/

You would need to create something like in the picture, one switch will be the relay.

The switch already in place is probably not a three way switch, however it could be switched out for one.

He said he already tried a two way switch.

how would the arduino detect the state of the light?

Yes sir, already did that but any possible way to detect switch is turned on/off ? This will help me to turn the relay state

the state does not matter in this case, the relay can be either in on or off possition to set the light on, depending on the state of the lightswitch.
You could determine if the light is on or off by measuring current just before the lamp.


text:
Arduino Mega 2560 LED is dim when powered from digital output
My circuit is a simple one, I am using an arduino atmega 2560.
One 5mm red LED connected in series with a 150 ohm resistor.
If I didn't make some kind of goof, a red LED has a voltage drop of 2 volts and operates at 20 ma.
So my calculations were, 5-2=3volts.
3V/150=20 mA. So I put a 150 ohm resistor.
My code to control it is the following:
int red = 48;

void setup() {
pinMode(OUTPUT,red);
}

void loop() {
digitalWrite(red,HIGH);
}

When I run the code the red LED is dimly lit, when connected to the 5V on the board it lights brightly.
When I measured the voltage between pin48 and ground I got 1.7 volts.
When connected directly to the 5V and GND the voltage between them is 4.95V.
Measuring a pin with nothing connected set at HIGH results in a 4.99V reading.
Is my board malfunctioning or have I missed something?

The pinMode() arguments are backwards. As it is the LED is powered through the input pullup resistor, which is about 20-50kohm.

You sir deserve a pizza, thank you so much!
I noticed it now, what a dumb mistake :D
Well I fixed it now and it works.
Cheers again for the help.


text:
Arduino R3 Uno Clone - When barrel plug connected there is 5V on USB. Why?
I have been using Arudino Megas for some projects and never had this problem.
Simply enough - I am powering arduino with 12V in via barrel and take power out via VIN to 12V low very low current small fans.
I want operating model, where when USB is disconnected it shuts itself down.
I have made some plan with R3 Uno. Build it up, it behaved well. However when I disconnected USB I noticed there is still 5V on USB.
Why? I understand there might be some small voltage but full 5V as if connected? Something is fishy to me and not sure what. Mega did not behave like this.

Is this a real Arduino R3 Uno or perhaps a clone? It does not sound like it is behaving correctly (see my answer below for details as to how I believe it should work). Maybe the transistor T1 is shorted?

Hang on, can you try removing the fans and testing the USB for voltage again? Also, if you have a volt meter, can you check to make sure the supply voltage is actually 12 volts with and with out the fans? (If the fans draw enough current and the supply can not handle it, the voltage may drop. If it drops below about 6.6 volts there might be some voltage seen at the USB port.)

st2000:
Yes, I have tested all with my trusty midrange-multimeter.
I have sw logic to slowly ramp up PWM to avoid overcurrent and fans in cage to avoid human factor. But I unsealed another unit to verify it was not me -> And yep, this batch works like this.
Good on me to verify everything before shipping this as release candidate.
Tested one D1 W2 (R2 clone) and one R4 original, plus couple of Mega 2560 boards and non of them bring up 5V on USB.
One Mega2560 brings some 300mV on USB rail, but then this has been study Mega... it went through hell.

"there is still 5V on USB" I'm just guessing you're measuring this VBUS and GND on a disconnected A plug. For your own sanity and for anyone helping, you should probably take that measurement with some load between the meter positive and negative, e.g. 10k. In other words, take a "Low Z" measurement. Some meters have a setting for this sort of thing.

Another posibility for 5V backfeeding USBVCC is for example combination of 7-9V VIN and shorting 3V3 to 5V - threshold jumps to 10V instead of 6.6V

It's not recommended to connect fans with Arduino directly. Use a BJT or MOSFET in between.

Looking at this part of the Arduino UNO Rev3 schematic, it appears that if half the voltage of the unregulated power (12 volts (shown in green) according to your post) is above 3.3 volts, then transistor T1 (circled in red) will disconnect the net "+5V" from the net "USBVCC".

If this is the case, there should be no voltage seen at the USB port when powering the Arduino UNO Rev3 with a supply greater than 6.6 volts.

Thanks, this makes sense to me and what I thought. Thanks for ref to schematics, will make more use of that.
I am not primary from low-voltage world, I come from world of "if are honest about making software, you make your hardware", so was trying to verify.
Nope these are clones have 4x of this batch at home and all behave the same (incl ones I have not tried to push.)


text:
No DFU capable USB device available
I was making an obstacle avoiding car with my Arduino R4 Minima, and it was going great, but I tried to upload new code and I got this error:
No DFU capable USB device available
An error occurred while uploading the sketch
but what is confusing is that I was using that same cable for a few days now and it was working fine, and when I use that same cable on my R4 Wifi it works fine.
How can I fix this?
Thanks!

what leads you to believe that it is a cable problem?

I dont think it is the cable because it worked fine on my R4 Wifi, maybe I did something to the board to make it not work? Because when I give it power all it does is power the motors randomly with no connection to what I programmed it to do.

What happens if you double-tap reset per Board Recovery in official documention?

Thank you timemage! I can upload the code again!

It's fixed now i just needed to double tap the reset button on the Minima.

I'm voting this up to satisfy the stackexchange system, particularly where this is (I think) the first time the double-tap-reset-thing has come up in the context of the Arduino UNO R4. But, please do read the official documentation. You might be surprised how useful it can be. Double-tapping reset is something that works on a lot (some not all) of the Arduino boards.


text:
Communication protocol and hardware for 50-100 feet of communication between 2-3 arduino megas
Newish person here.  Have done a few smaller projects, looking at something a bit bigger and need direction on where to start.
I'm building a guitar effects pedal board that I want to be able to remotely toggle with a board by me.  The master would be the board by me.  I would press one switch, and that would toggle a bunch of things on the pedal board.
I intend on having all of the logic of what gets flipped when I press a certain button to be on the board by me.  I press a button, the master sends commands to the slave "toggle relays 1, 4, 5, and 6" or whatever gets decided.
Most of the time, I would be doing this over about 10 feet, but there would be situations where 50-100' would be more appropriate.
The question - what communications protocol should I use, and what type of cable should I use?  It would be ideal if I could use an ethernet cable or a microphone cable (2 conductor plus a ground and a shield) as those are laying around everywhere.  What terminals on the Mega do I use?  I know the Mega has serial 1, 2, and 3, not sure what else.
I say 2-3 arduinos in the title because there's a chance that I could end up with a second slave board in the future, but one thing at a time for now...
Thanks!

this might help ... https://youtu.be/caMit7nzJsM?si=SyBdavyQN3niKYqH

There are probably quite a few options. For the hardware layer, my first
choice would be to try RS-485. This is typically carried by a
twisted pair of copper wires, like one of the four pairs of an Ethernet
cable. You may also try a microphone cable (is that twisted pair?). This
tends to be reasonably robust against environmental noise, and is
supposed to work at distances up to 1,200 m.
For using RS-485 with an Arduino Mega, you will have to find a suitable
transceiver shield. You need one serial port for sending and receiving
the data, and a digital output for switching the transceiver between
transmit mode and receive mode.
At the software level, if you have just one master device and one slave
device, the only difficulty is that you have to know when to switch
between transmit mode and receive mode. If you have more than one slave
device on the same link, then you will have to designs some kind of
addressing scheme that lets each slave device know when the master is
talking to it.

You can connect two devices using RS-485 using modest inexpensive hardware as I describe here.


text:
Error declaring two-dimensional array: 'x' was not declared in this scope
I'm trying to declare a 2-D array where each letter in the alphabet is keyed to a corresponding LED in my LED strip. But when I try to declare the array, Arduino flags the values and gives me a "not declared in this scope" error. I have no idea why. Am I missing a library or is it incorrect syntax?
Some of the places I've looked say to make sure it's declared globally. I've declared the array before void setup but it still doesn't work. Here's what I've got before void setup:
#include <Adafruit_NeoPixel.h>

#ifdef __AVR__
  #include <avr/power.h>
#endif

#define PIN 6

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(50, PIN, NEO_GRB + NEO_KHZ800);

//Create a 2-D array to store each letter and
//its corresponding LED number
char charKey[26][2]={
  {a, 0},
  {b, 2},
  {c, 4},
  {d, 6},
  {e, 8},
  {f, 20},
  {g, 18},
  {h, 16},
  {i, 14},
  {j, 12},
  {k, 10},
  {l, 22},
  {m, 24},
  {n, 26},
  {o, 28},
  {p, 30},
  {q, 40},
  {r, 38},
  {s, 36},
  {t, 34},
  {u, 32},
  {v, 42},
  {w, 44},
  {x, 46},
  {y, 48},
  {z, 50}
};

Without quotes, a, b, c etc. are just names. You didn't declare any of them, so the compiler complains.
Put single quotes around the letters to let the compiler know that they are char literals.


text:
Adding music to loop
Im newbie. I just wanted to ask how can i put my tmrpcm.play into loop. Im trying to put it in a loop but the problem is it didn't play. I also try adding a method and call the method into the loop but it give me the same problem also. It will just only play in the void setup.
Here's my code.
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

void setup(){
tmrpcm.speakerPin = 9;
Serial.begin(9600);
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD fail");
return;
}

tmrpcm.setVolume(5);
tmrpcm.play("Yeah.wav");
}

void loop(){  }

The TMRpcm library is non-blocking. That means, when you start playing it keeps playing in the background. If you put the play function in a loop it will just keep restarting what you are playing over and over again and you won't get to hear anything.
As Michel says, you can get it to loop automatically (tmrpcm.loop(1);), in which case you just leave it in setup() and leave loop() empty.
If you want to do it manually you should check to see if the sound has finished playing or not. The simplest way is:
loop() {
    if (!tmrpcm.isPlaying()) {
        tmrpcm.play("Yeah.wav");
    }
}

That is - if it's not playing then start it playing. When it finishes it'll not be playing any more, so it will start playing again.

The library has a built in loop function:
audio.loop(1);             0 or 1. Can be changed during playback
                           for full control of looping.

See WIKI page of the library.
Btw, it is unclear if you mean by 'a loop' a while(true) loop or the void loop() function. Although it should not make a difference.


text:
No Matching Function for call to Ultrasonic:Ultrasonic(int,int)
Good Day! I am trying to code the distance of Ultrasonic Sensor but the problem is it gives me this error. Any idea? Please help.
#include <Ultrasonic.h>

// HR-SC04 SENSOR
#define TRIGGER_PIN   5
#define ECHO_PIN      6

Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);

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

// Global variables
int lastDistance = 0;
int thisDistance = 0;

void loop()
{
  // Copy over last distance
  lastDistance = thisDistance;

  // Get new this distance
  thisDistance = ultrasonic.Ranging(CM);

  if (outlierCheck(lastDistance, thisDistance)) {
    Serial.println("Outlier found: " + String(thisDistance));
  } else {
    Serial.println(String(thisDistance) + " cm");
  }

  delay(10);
}

// Check for significant jumps and outliers in sensor reading
bool outlierCheck(int lastDistance, int thisDistance) {

  // if the difference between measures is greater then 20cm, outlier found
  if ((lastDistance - thisDistance) > 20) {
    return true;
  } else {
    return false;
  }
}

look at the demo code that comes  with the library

I did already but it still give me this error "Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);"

the error messages tell you where the problem is ..... take another look at the demo code

You are very likely to have confused the libraries.
When using your code with the library at https://github.com/JRodrigoTech/Ultrasonic-HC-SR04, the code compiles perfectly fine. The constructors match up with your code.
//Constructor 1
Ultrasonic(int TP, int EP);
//Constructor 2
Ultrasonic(int TP, int EP, long TO);
//methods.. (used in your source)
long Timing();
long Ranging(int sys);

I think you have installed this Ultrasonic library: https://github.com/ErickSimoes/Ultrasonic. It has the same header file and class name but the class is constructed differently
//Constructor 1
Ultrasonic(uint8_t sigPin) : Ultrasonic(sigPin, sigPin) {};
//Constructor 2
Ultrasonic(uint8_t trigPin, uint8_t echoPin, unsigned long timeOut = 20000UL);
//Note that a constructor with only 2 arguments is not directly visible

You should go into the Arduino IDE and uninstall your current "Ultrasonic" library from the library manager. Then download the zip file from the first given github repository and add that ZIP file to your libraries.
Alternatively of course, you can use the second library and its correct example code.
Also note that your Arduino IDE 1.0.6 is extremely outdated, current one is 1.8.5


text:
Saving a .txt file to SD Card and Reading each content data to txt file then save it to a variable
I am new to arduino I am trying to create an arduino project that Saving a .txt file to SD Card and Reading the txt file then save it to a variable data type "Long" named 'savednum'. I had successfully can save the txt file and read it, however the problem lies in storing the read txtfile, when I read the txtfile and stored it in savednum and then serial print the savednum it gives different/ random numbers which is not equal to the data in the .txtfile that I store and read. I am wondering what seem to be wrong? Any suggestion is really appreciated. I thank you in advance.
#include <TMRpcm.h>
 #include <SD.h>
 #include <SPI.h>
 #define SD_ChipSelectPin 4 //using digital pin 4 on arduino nano 328

 TMRpcm tmrpcm; // create an object for use in this sketch

File myFile;

char serialData;

int i = 0;
long n1 = 123456789;
long n2 = 245678918;

long savednum =0;

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

 }

Serial.print("Initializing SD card...");

 if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("initialization failed!");
 while (1);
}
Serial.println("initialization done.");

 myFile = SD.open("NEWDATA.txt", FILE_WRITE);

if (myFile) {
Serial.print("Writing to NEWDATA.txt...");
myFile.println(n1);
myFile.println(n2);

myFile.close();
Serial.println("done.");
} else {

Serial.println("error opening NEWDATA.txt");
}

myFile = SD.open("NEWDATA.txt");
if (myFile) {
Serial.println("NEWDATA.txt:");

while (myFile.available()) {
  Serial.write(myFile.read());
// here the code I tried to read .txt file and store it in long
savednum = myFile.read();
Serial.println(savednum);
}

myFile.close();

}

}

void loop()
 {

  }

Side note: Do yourself and your readers a favor and format the code properly, either by using Arduino IDE features (tutorial here) or some online beautifier. It'll be much easier to spot errors this way.

myFile.read() reads just one byte from the file - not the whole file or even a whole line.
You're reading one byte, then printing it. Then reading a second byte, storing that in a variable, then printing the variable. Then you loop back to the beginning again.
So you're printing alternate "odd" bytes, and storing / overwriting the variable with "even" bytes. So you just get nonsense.
You're storing the data in your file as ASCII text, so it's necessary to read the entirety of each line and then convert that string of characters into a number. Or read each character in turn and manipulate your total value for the line.
For example:
long savedNum = 0;
long numberOne = 0;

while (myFile.available()) { // Something left to read
    char c = myFile.read(); // Get the next character
    if (isdigit(c)) { // It's a number 0-9
        savedNum *= 10; // Make room by decimal shifting to the left
        savedNum += (c - '0'); // Convert the character to a number and add it to the total
    } else if (c == '\n') { // End of line
        Serial.print(F("The number is: "));
        Serial.println(savedNum); // Show us the number
        numberOne = savedNum;  // Store it somewhere else - enhance this for multiple numbers.
        savedNum = 0;  // Reset to 0 ready to read the next line
    }
}

The Arduino API (Stream class) also includes some handy helper functions, such as:
int num = myFile.parseInt(); // get the next integer

There's no parseLong() though, but despite its name, parseInt() actually returns a long.  That reads characters up until it gets a non-numeric character and converts them to a long using the same method as in my example. It doesn't distinguish lines, though, so can be used to get separate numbers on the same line, such as 32847,2345534,12,-43.
With your file though you may need to filter out the extra \r that may be in there from the line endings or you'll get missing numbers.

Hi thank you very much for your answer it really helped me alot now I am successfully store the data from the .txt file to a variable however I have one last question because here I saved 18characters in the txt file I wanted it to split by 9 characters then distribute it in to two data type long variable named Storenum1 and storenum2 is it possible? Hope you can help me. I am really thankful for your help.

You're not storing 18 characters. You're storing 2 strings of up to 9 characters each, plus line endings (because you wrote with println).  So you get two lines in your file of nnnnnnnnn\r\n.  My example will read each line in turn - it's up to you to decide what to do with the savedNum value for each line.

Thank you now I understand thank very much for you good explanation and answer  I tried to study how to store in two variables. I really appreciate your help thank you

Is this method the same as using an EEPROM ?

@R1S8K No. An EEPROM reads and writes individual bytes to memory locations. An SD card works with files and streams of data.

I'm working with the lcd128x64, I'm stuck these days in developing the most important function to set one pixel and how to deal with buffers. The SD card would be the perfect solution for loading pictures. I'm wondering what is the best way to develop a good GUI in the lcd128x64? Is it better to load images of the GUI instead of drawing each element ? Anyway, I might open a new thread about developing the perfect pixel set function.

It all depends exactly which display it is. I have spent lots of time writing drivers for LCD and TFT displays, and know that for most GLCD displays it is far better if you have the memory available to create a buffer internally to store the current image and update parts of it in bulk.


text:
I fried my arduino. Can I upload code wirelessly?
So, I'm a complete arduino newbie. I left a live wire close to my arduino and part of it burnt (underneath the USB output). The LED that indicates power still turns on when I plug it into my computer, and a simple LED circuit on my breadboard, when hooked up to the arduino, still works. The only thing that's wrong is that my computer doesn't recognize the Arduino serial port any more, so I can't upload any code onto it.
I also own a bluetooth HC-05 module. Is there any way I could upload code onto my Arduino wirelessly, using that? Or am I better off just buying a new one?

If the main MCU is still functioning fine then yes, sure you can.
The only caveat is that you may have to manually reset the Arduino at the right moment in order to enter the bootloader for programming.

Connect the bluetooth module to TX/RX/GND (TX->RX, RX->TX)
Configure the bluetooth module to work at the bootloader baud rate (115200 baud) - you may need to wire it to your PC to manage this part.
Connect a virtual COM port to it and program through that.
Press RESET just as it's about to run AVRDUDE in the IDE.

It sounds like you have fried the Atmega16U2  which is programmed as a USB-to-serial converter, as seen in the picture below.

You can still program the Atmega328P microcontroller using the ICSP and an appropriate Atmel programmer such as the Atmel Ice or the AVRISPmkII. Alternatively you can use another Arduino Uno as a In-System Programmer.
I cannot say about using a bluetooth HC-05 module,however I imagine it would be a fair bit of effort and hence would be easier to buy a new one. Keep the current one though because you can use the new one as an in-system programmer as per the link above.

You did not say which Arduino you are using.
Most Arduinos abstract the complexities of the USB interface, format and protocol by using a 2nd processor on the Arduino board.  If damaged, you will essentially have to replace this function.  It is unlikely that a Bluetooth radio will act similar enough to do this.
If the main processor and supporting circuitry is not damaged, it would be easier to program the Arduino from another Arduino such as described here.


text:
Problem with simple coding for PLDuino: trying to turn relay on and off
I am writing the following, simple code to try to turn a relay in the PLDuino on and off, and it is giving me warnings and not compiling/uploading. Any help would be greatly appreciated. Here is my code:
#include <PLDuino.h>
using namespace PLDuino;

void setup()
{
  // A necessary call.
  // It sets pin modes according to their function.
  PLDuino::init();
}

void loop()
{
  // Simple switch RELAY3 on and off with 2 second timeout.
  digitalWrite(PLDuino::RELAY3, HIGH);
  delay(2000);
  digitalWrite(PLDuino::RELAY3, LOW);
  delay(2000);
}

I have installed the proper libraries. Here are the warnings I am getting:
WARNING: Category 'Graphics' in library PLDTouch is not valid. Setting to 'Uncategorized'
WARNING: Category 'General' in library PLDuino-Library is not valid. Setting to 'Uncategorized'
WARNING: Category 'Graphics' in library PLDuinoGUI is not valid. Setting to 'Uncategorized'
Sketch uses 1702 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't open device "\\.\COM4": The system cannot find the file specified.

avrdude: ser_drain(): read error: The handle is invalid.

avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

For the library warning, you'll need to add / edit library.properties to those folders to specify a valid category.
This is an example library.properties to give you a feel for the structure (I found this particular one here).
name=TMRpcm_PLDuino
version=1.0
author=TMRh20
maintainer=digitalloggers
sentence=PCM/WAV Audio playback (USE_TIMER2 enabled)
paragraph=Play WAV audio files from SD card using AVR (UNO,Nano,etc) based devices.
category=Communication
url=https://github.com/digitalloggers/TMRpcm_PLDuino
architectures=avr

However, these are just warnings, and don't seem to be the cause of your problem.

Your actual problem in this case seems to be that it's trying to upload the sketch via COM4 and it can't find the PLDuino on that port.

Ok. So do you know how I can get it to find the PLDuino?

@CDDavis What operating system are you using?

Windows computer


text:
Arduino UNO dead with CNC shield
I have an Arduino UNO with a CNC shield. The Arduino is almost certainly a clone.
I installed GRBL with no issue and I have assembled a jig with CD-ROM motors. My first attempt to control this with UGS worked no problem.
I powered down to change the stepping with the jumpers and powered back up and was presented with a very hot smell after a few moments.
I removed the power quickly but now I can no longer program the UNO. It gets recognized in my devices but I can't send any code, even blink.
The jumpers were set like many examples I have seen on the web so I don't think this was the issue.
I am wondering if the way I powered it up was the issue? I am supplying the UNO with 12V 2A supply and I can't recall what order I plugged them in but I get the feeling it must have been supplying 12V to the Arduino.
I have now removed the shield and powering the unit solely from the USB and still can't communicate.
I have resigned to the fact this board is now toasted. Is it important which order you plug in the Arduino? USB first? Do you think it will be possible to recover this Arduino.

so many words, so little information .... all we know is that you plugged the arduino into something unknown, in some unknown way, and something, or other, got burned up. now you are asking if it is repairable? ............... did i sum that up correctly?

This sounds as the ATmega328p processor of the UNO was fried. As the UNO has a second processor (ATmega16U2) which is simply a USB-to-serial converter you only see the presence of this in the list of USB devices but it cannot communicate with the board's main processor anymore.
The plug-in order is not that important with the UNO board only but depending on the components you have attached it may be important. especially if the circuit does not have protection against induction current, p.e. fly-back diodes.

The same exact thing happened to me. I was using A4988 on a CNC shield which was mounted onto my arduino uno by rexqualis. A couple days ago it was working (inconsistently) to move my NEMA 17 motors. Today, I adjusted the potentiometers on the A4988 to try to improve consistency when my arduino would no longer connect to the serial port. I took the shield off and realized the arduino was very hot. Now it gets hot anytime I plug it even with no inputs or outputs. It will still not connect to the serial port.
I was using 12V of power going into the CNC shield. This and 9v seemed to work a couple days ago. I am not sure of how to avoid this problem in the future, but I am thinking that I need to put the potentiometers where they were before.

Genuine Arduino's have an input limit of 20v and a recommended voltage of 7-12v. I naively assumed that the same would be for the clone but it has a max input voltage of 9v. Supplying 12v to the unit worked for a short time but the regulator must have melted and cooked the main processor.


text:
How can I declare global array with its length stored in EEPROM?
I am working with Arduino UNO connected with BV4612 display.
I am working on a simple code that controls several water pumps. Each pump has several modes it can run in. I store these modes in an array.
The number of water pumps may vary, and I'd like to store that value in EEPROM (either arduino's or display's).
When the pump count is fixed, I use fixed value, defined by macro:
#define     PUMP_COUNT      18      //How many pumps we have

uint8_t pumpModes[PUMP_COUNT];

void setup(){...}
void loop(){...}

I'd like to get rid of fixed defined value of PUMP_COUNT, and rather load it from EEPROM, or save the new pump count into the EEPROM if needed.
However, I can't declare an array if I can't read from EEPROM before setup() function like this (from address 32 for example):
uint8_t pumpModes[EEread(32)];

void setup(){...}
void loop(){...}

Is there a solution to get the value from EEPROM so I can declare global array's length with it?
Thanks.

You can't create variable length arrays in C. That's not how C works.
Instead you have to create an array that is big enough to store the maximum number of pumps you want to be able to deal with.
The array "size" is then just a number in a variable obtained from wherever you like (including EEPROM).
It doesn't matter if you don't use all of the array. The rest just sits there twiddling its metaphorical thumbs.
The other option, if you are only going to define the array once at startup, or very rarely change the size, is to use malloc():
uint8_t *pumps;
uint8_t nPumps = 0;

void setup() {
    nPumps = EEPROM.read(32);
    pumps = (uint8_t *)malloc(nPumps);
}

You can change the array size then with:
nPumps = 8; // for example
pumps = realloc(pumps, nPumps);

And dispose of the array with:
nPumps = 0;
free(pumps);

It's best to try not to change the array size once created, since that can make swiss cheese of your heap, and is not a friendly thing to do on a small microcontroller. If you can decide the array size once in setup and keep it the same all the time the program is running this is a safe operation. Otherwise it becomes risky.

Thanks, that's what I thought and I used exactly this as a solution so far. I was just trying to save as much RAM as possible, but this has to suffice.

You could use a pointer and use malloc() and free() to change the array size instead. I'll detail it in my answer.

@MiragePV, save RAM for what? is there something that can use the extra RAM if there are less pumps?

Trying to save ram could be a problem, as you could en up with a program that works with 14 pumps, but as soon as you add a 15th the program runs out of RAM and you program starts behaving weirdly. By allocating the maximum number pumps needed, you’ll immediately notice if you run out of memory.

@Juraj: The less RAM used by static data (globals and heap), the more is available for the stack. Static data is assigned from the bottom of RAM upward; the stack starts at the top of RAM and builds downward during execution. What is left in the middle at any point during execution is the free RAM. If you only use malloc() and free() at most once, in setup(), then the top of static data doesn't change. The bottom of the stack changes frequently, building downward with each function call, and retreating upward again when the function returns.

and can the code for less pumps profit from more stack space?

It is possible to use a dynamically allocated array, with malloc and free.
To create such an array use:
uint8_t* pumpModes;

Somewhere in setup (preferably):
pumpModes = malloc(sizeof(uint8_t) * PUMP_COUNT);

Freeing the memory is not needed if you need it throughout the entire program, otherwise you can use
free(pumpModes);

However, take in mind that if you continuously malloc and free memory in the loop() function, you can get memory 'gaps' and you run out of memory really quickly since the Uno has only a few KB of RAM memory.


text:
Reading +IPD response from serial.read() using Arduino UNO and ESP8266
I have a python server running on my PC and I am using an Arduino Uno (wifi enabled by a ESP8266 chip) as the client.
I can make the the server and client communicate using AT commands as shown below:
SoftwareSerial esp (8,9);

   void setup()
   {
   esp.begin(9600);
   esp.println("AT+CWMODE=3");
   delay(100);
   esp.println("AT+CIPSTART=\"TCP\",\"192.168.8.100\",5555");
   delay(1000);
   esp.println("AT+CIPSEND=3");
   delay(100);
   esp.println("bbb");
   delay(100); }

The string "bbb" is recieved on the server and the server responds back, which is shown in the serial monitor as:
+IPD,19:the string is found

I want to read this response and use it back in the code for further conditional statements. But i am unable to do this. So far i have tried these methods.
1st method by using esp.readString() as shown below:
String buffer="";
while (esp.available()>0)
    buffer+= esp.readString();
Serial.print(i4);

2nd by using esp.read() as shown below:
String buffer="";
char c;
while (esp.available()>0) {
    c= esp.read();
    buffer+=c;}
Serial.print(buffer);    // i have also tried using esp.write() directly for prinitng here intead of storing it in a buffer

These two methods returned with incomplete information in the response string buffer ie i only get:
busy s...

Recv 3 bytes

SEND OK

+IPD,19:the string

I can not get the entire response in the buffer as mentioned in the start. On the other hand if i execute the command AT+CWLAP and store its response in the buffer string, i get the entire thing. So i cant understand why is there a difference between the two.
Lastly i have also used esp.readBytes() as shown:
char c[500];
esp.readBytes(c,400);
esp.write(c);

This code gives me the whole response sometimes but sometimes it just gives a long garbage value. But the times it does give me the complete +IPD response, it switches some of the alphabets ie the string is found becomes the strjng is gound
If anyone could help me out i'll be very thankful.

A while(Serial.available()>0) does not guarantee, that all bytes have been received. Sometimes there is a small delay between bytes, which you cannot control. The Arduino will exit the while loop, but short after that, more bytes are received, without the program ḱnowing. Somehow your Arduino has to know, when the message is complete (through a delimiter character or maybe a timeout).

@chrisl i have also tried this using a for loop like so:
esp.println("bbb");  delay(100);  char c[100];  for(int i=0;i<80;i++){     c[i]= esp.read();     delay(10);     Serial.write(c[i]);    }
Which gives me the following output:
`busy s...
Recv 3 bytes
SEND OK
+IPD,19:the string⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮`
I assumed after this that the buffer must be empty thats why the reverse question marks appeared. I still have no clue on what to do next

The reverse question marks depict a character, that has no meaning in ASCII, e.g. a value greater than 127. The read() function returns -1,  when the buffer is empty, which translates to an unsigned value of 255. So you are right, that the buffer is empty there. That is strange. How many bytes do you receive correctly with this method?

@chrisl When i run the command AT+CWLAP i can get upto 400B in the buffer variable. But in the commands that receive a response from the server i.e. i use AT+CIPSEND and my sever sends a response which includes +IPD i can only get max 64B. I have shown this in the original question. I dont understand why this is happening because i have used the same reading technique for both commands


text:
How do I create boundaries for the possible values of an integer?
I want to create an integer whose total value cannot go beyond a range of numbers when added to and subtracted from. For example, if the "total_value" started at 0 (of a total possible range between -5 and 5), and then, using a button that added 1 to the total value, I got to 5, if I was to press it again it would not go to six but either reset to 5 or block another input of +1.
How would I go about achieving something to this effect?
Liam

You are probably looking for the constrain() macro (an existing implantation of clamp logic, credit goes to @Edgar Bonet)
value = constrain(value + input, -5, 5);

If you get tired of writing constrain() you can even wrap it in a new type (which might be over-engeneering), producing something like following(code not tested)
template<typename T>
struct BoundValue {
    T value;
    const T vmin, vmax;
    //similar for other operators +,/,-=,...
    decltype(*this)& operator+=(T operand) { value = constrain(value + operand, vmin, vmax); return *this; }
    operator T() const { return value; }
    BoundValue(const T& vmin, const T& vmax) : vmin(vmin), vmax(vmax) {}
    BoundValue& operator=(const T& other) { value = constrain(other, vmin, vmax); return *this; }
};

and use like variable of its argument type
BoundValue<int> val(-5, 5);
val += 6;//val = 5

No need to write clamp(): you can use constrain().

@EdgarBonet good catch, kind of unusual name choice by Arduino though(at least for my computer graphics background) - no wonder I had trouble to finding it.

@LookAlterno kind of agree, there are people who love shiny code though (myself included), its interesting for fun projects. For serious ones not so much due to the other issue being its super-easy to introduce errors when not being careful with c++ constructors/operator overloading. The clamp/constraint is definitely the way to go though.

@LookAlterno reformatted the answer a bit to make the important part stand out.

For adding:
total_value = total_value + 1;
if (total_value > 5)
  total_value = 5;

And for subtracting:
total_value = total_value - 1;
if (total_value < -5)
  total_value = -5;

You may find a C or C++ tutorial very helpful.

Another method for adding:
if (total_value < 5)
  total_value++;

And for subtracting:
if (total_value > -5)
  total_value--;

Thank you for your response, I did try the first method before I posted but I must have mucked something up because it didn't work.

if (++total_value > 5) total_value = 5  and if (--total_value < -5 ) total_value = -5. The use of prefix operators can achieve the same effect and make the code more concise.

You can not create a number with arbitrary upper and lower limits.  It is common in the C language to create an integer comprised of 16 bits.  Such an integer has a minimum of:
-(2^15) = -32768

...and maximum of:
(2^15) - 1 = +32767

Instead, after pressing the positive button, consider testing if "total_value" is 5 and skipping adding 1 to "total_value" if TRUE.  Conversely, after pressing the negative button, consider testing if "total_value" is -5 and skipping subtracting 1 from "total_value" if TRUE.


text:
Creating a simple menu for Arduino LCD button shield
I am trying to create a very simple menu to use with my lcd keypad shield, I have tried looking into how tutorials say to do this but I don’t really understand them.
Would it be possible to do it by doing something like creating an integer I.e menuTotal, that depending on the what the value of menuTotal is a menu item would display, then have the the up and down buttons add or subtract 1  of the menuTotal value.
Any help you can give would be greatly appreciated.
Liam

Rather than using a LCD which has commonly 2 lines, I suggest to use a small Oled display. After that, your problem is pure code. Take a sheet of paper, simulate what you want to display and you'll find variable you need, when to inc, when to dec and so on.

I don’t really understand them ... you need to learn the basics first

Your approach of holding the "current" menu selection and incrementing or decrementing upon external input (button press) is a sound approach.
Consider writing a drawMenu() function that draws the screen, based on the current menu. In your program, keep a bool updateScreen variable. Then, any time you get an external input that would change the screen, set the updateScreen variable to true.  The actual drawMenu() function, after drawing the screen, should reset the updateScreen variable back to false.
In your loop() function, have a section like:
loop() {
  // [... other code ...]

  if (updateScreen) {
    drawMenu();
  }

  // [... other code ...]
}

In this way, the screen is updated when necessary, and your main loop can keep running, processing input, etc.


text:
What does drawmenu() mean
Can anybody tell me what drawmenu() means, I got an answer on here that has the term on and I don’t quite understand it, I’m very new to this.
Any help you can give will be greatly appreciated.
Liam

It calls the function drawmenu() that is included in some code somewhere.  Does your code have any interesting #include ... statements?

the code I am writing is to create a simple menu for my Arduino LCD push button shield, so I will be using #include <LiquidCrystal.h>

Possible duplicate of Creating a simple menu for Arduino LCD button shield

I gave you that particular answer
The function drawMenu() has no meaning. I was suggesting that you create a function with that name, whose action is to write text to the LCD with your selected menu item. The name of the function is not relevant. It does not exist until you create it.

thanks for your answer, i wasn't sure whether i should ask this question in the comments on the other page or start a new thread. I understand now, thank you.


text:
Connect ESP-01 to USB Uart
for programming my ESP-01 chip I bought an "USB Uart", but it looks different to all the ones in all tutorials. I don't know how to connect the uart to the esp.
The uart i bought has following pins: 3V3, DTR, RXI, TX0, GND, +5V. The ESP01 has the known layout (http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family#esp-01).
Once connected: Do I need an external power source, or do i just connect the usb uart to my computer?
Many thanks

A Beginner's Guide to the ESP8266 Yes, you need an external power supply. Note that programming it would be much easier if you bought a USB-to-Serial adapter that breaks out both the DTR and RTS control lines. Or even better, get a WeMos D1 mini or similar.

@tttapa, why external power supply? I don't use one if connected to USB to UART.

@Juraj, the ESP8266 draws a lot of current, especially during WiFi transmission. The 3.3V from the USB to UART is just for the output drivers and maybe some external logic, it's not meant for driving any real loads. For instance, the 3.3V output from an FT232R is only rated for 50 mA. It can't handle the peak currents needed for RF communication. The ESP8266 can draw up to 300mA peak. Many people experience instability because of an incapable power supply.

Thanks so far for the answers. Recording to the "Beginner's Guide" i have connected the pins tx, rx and gnd to the esp01. Understanding this guide correctly i now need to connect the CH_PD and GPIO0 with a 10k resistor to Vcc, So after adding a power source i can start programming, right?

@tttapa, but for flashing is the 50 mA enough.

Just to give an anwser for users struggling with the same problem I will sum up what helped me.
To connect the UART to the ESP the Beginner's Guide to the ESP8266 from @tttapa was very helpful. Another helpful link was this one:
https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now/
So in my case I just needed the GND, 3V3, RXI and TX0 pins from my UART.
I needed no external powersupply for the flashing process and some simple examples.

You can program the ESP-01 whith described method in this page:
https://zinventor.wordpress.com/primeros-pasos-con-esp8266/
Its works fine!


text:
Arduino Nano problems with ESP8266
this is my first post here because I'm a bit lost at the moment.
I currently have my ESP8266-01 hocked up to the Nano like this:

The issue I'm having is that it won't even turn on, only when I'm using the 3.3V pin the red led on the ESP8266 turns on. If connected to 3.3V and I connect the CH_PD pin to 3.3V aswell, the blue led flashes 2-3 times and then the ESP8266 turns off.
I hope someone is able to help me

You have a level shifter, not a voltage regulator. That's fine for switching logic levels of different voltages, but it cannot supply a regulated reduced voltage from one side to the other.
All it does is allow one voltage to switch another on and off in a bi-directional manner.
And those voltages have to come from somewhere for it to switch. You are already giving it the 5V from the Arduino, but you're not giving it the 3.3V for it to switch from anywhere - and so there is no 3.3V - not for the level shifter, nor for the ESP8266.
You need to find some way of getting 3.3V with enough current to power the ESP8266 side of the circuit.

You need to supply power to the ESP to make it turn on.  What you have done at the moment is got the ESP to supply 3.3V to the level shifter, which you need to do.
You need to supply 3.3V to the ESP from somewhere other than the Arduino, it doesn't have the current necessary.

I'm not being sarcastic, I understand what you have done and why.  If I'd ever done this I would have probably done the same.


text:
Is it possible to query (or otherwise detect) if Arduino is connected to 60 NeoPixel strip vs 144 strip?
Is there any way to have an arduino detect how many LEDs are on a connected strip? I have a 60 strip and 144 strip. The code is identical for both, aside from setting the number of LEDs in a variable to iterate over.

Neopixels only have one-way communication. Some possible ways to detect the quantity are:

Bring the Data-Out of the last pixel back to the arduino and activate an interrupt on an input pin connected to that. If you write 144 LEDs worth of data to the 144-LED strip, the pin doesn't change. If you write 144 LEDs worth to a 60-LED strip, the pin changes. So your code has a startup routine to write data and detect it. You can even write all "black" colors, since the data will still have HIGH and LOW values, and your detect routine won't show any light patterns.
Pass the ground line that goes to the LED strip through a low-value resistor (A current-sense resistor) and use an analog input to read the voltage across the resistor. Write an all-white color to all NeoPixels and sense the current draw. Pre-calculate the 144-LED current draw and 60-LED current draw and set a cutoff value for knowing which strip is connected.
Make your LED-strip connector to have more pins than necessary strictly for the LED strip connections. For example, have 1 extra pin. On the 144-LED strip side of the connector, tie this connection to the 5V line. On the 60-LED strip, connect it to GND. Read HIGH or LOW on an extra digital input on your arduino.

Not without effort. You could take the DOUT from the last LED, feed it back into the MCU, and then detect how long it takes to get some sort of signal from it, but this requires either the end of the chain being very close to the MCU or a long wire to connect them. Easier to just have a DIP switch to set the number of Pixels in the chain and go from there.

Also see  Is it possible to infer the length of a neopixel string using 1-wire protocol?.  For example, one of Nick Gammon's answers includes code that detects   NeoPixel string length via a binary search; Craig's answer refers to a Bunnie  Huang blog with code and a library to detect lengths; and my answer includes datasheet links and quotes, and points out that if you put m packets of data into a chain and k packets come out the last unit, the chain length is m-k or more, using which fact can markedly speed up length detection.  (All of these methods depend on reading data that flows out of the last unit of the chain; some of them use interrupts, some don't.)


text:
ESP8266 OTA update with different flash size settings?
I have an ESP8266 in a project.  It's specifically this ESP8266 SMT Module - ESP-12F item.  It's been working great with OTA, but I realized belatedly that I didn't change the flash settings when I started compiling through the Arduino IDE several versions ago.  I had been using the setting "1 MB (FS:64KB OTA:~470KB)", and I've updated OTA over multiple versions with the same basic structure of firmware and using the same server-side set-up.
I can no longer update with that setting because my compiled sketch is now over the OTA size limit.  My chip actually has 4 MB, however, so this limit is artificial.  I tried changing to "4 MB (FS:2 MB OTA:~1019KB)", and that works under the following test conditions:

I compile the "old" program with the 4-MB settings and I re-upload the old program via wired connection.
I compile the "new" program that's to come via OTA with those same 4-MB settings.

That's fine for a test, but I already have one of these chips "deployed" in a location where it's hard to access it.  I'd like to update that deployed chip OTA while also changing the flash partition.  I'm willing to lose any files stored outside of the program itself.  So I'd like instead to have:

A deployed, OTA-enabled chip with firmware running on the 1-MB partition structure noted above:
(Any intermediate step needed)
OTA update to new firmware that has been compiled with the 4-MB partition structure.

I'm willing to upload a dummy sketch at "Any intermediate step needed" to work around the current size of the sketch, but, after some experimentation, OTA seems to fail when the partition structure is different regardless of the size of the binary.
That's consistent with #2 in the answer here: esp8266 OTA issue, but that older question took a different direction with the OP and the #2 point there is stated without any detail.  I understand that in a broad sense, the prior answer covers my case, but I'm looking for more detail on the specific aspect of the flash partition settings.  Especially for these related questions:

Is there any work-around strategy available to change the flash partitioning between different versions served OTA?
If no, is the limitation determined by the software in the current OTA framework in the public libraries, or is it somehow fundamental to how the program is laid out in the hardware memory?

In theory at least, it seems like I ought to be able to force the new program to be written OTA at the same location that it would have been written had the old program also had the 4-MB partition. (Again noting that I'm willing to lose any other data in the flash to make this update work.)

afaik, if your flash settings are wrong, you can only OTA once. (don't ask how i know).

The basic problem is that when you upload over OTA you don't upload the partition structure.
The ESP32's flash is split into a number of "partitions" or areas.  It might look something like:
+----+-+-------------+-------------+---------------------+
|BOOT|P|OTA Program 1|OTA Program 2| SPIFFS              |
+----+-+-------------+-------------+---------------------+

When you upload over UART you upload all that structure, and that structure can be changed.  When you upload over OTA you only upload one of "OTA Program 1" or "OTA Program 2". One of those is active and the other is inactive. You upload to the inactive one and then at the next reboot that becomes the active one. This allows the system to confirm that the program has been written correctly before running it to reduce the chances of bricking a device in the field.
Because of this you can never upload anything that doesn't fit into one of the OTA program partitions.
One risky option which you would have to do thorough local testing of first, is to write a program which, when executed, will change the partitioning. You would have to make sure that it runs in the lower OTA partition so that the inactive one is the one that gets both moved and expanded, which may take a little trial and error.
Once that has happened you should be able to upload a larger OTA program into the new, bigger, inactive OTA segment.
But that's only supposition and it's not something I have ever done or heard of anyone doing.

OK, fixed this using the ladder method.  Got out my ladder, climbed up, unscrewed casing, and uploaded fresh via UART.

Oh, I would have loved to hear that the proposed method works.


text:
How to rebuild Arduino core for ESP8266
I'm experimenting adding DHCP option 160 to dhcpserver.c in the Arduino core for ESP8266 and therefor need to rebuild the relevant parts.
I made an initial guess that I might be able to make the change by installing using git according to the instructions in the readme and just restarting the IDE. I wasn't surprised to learn that this didn't help. The modifications to dhcpserver.c did not make it to the device following restart of the IDE and a new upload.
From another forum I saw a suggestion that the following commands could be used to rebuild from source:
$ cd esp8266/tools/sdk/lwip/src
$ make install

Again the changes didn't make it to the device after restarting and uploading the sketch again.
Does anyone have any clearer instructions for how to build a new Arduino core for esp8266?

You do have the right LwIP variant selected in the menu don't you?

I'm away from the keyboard now but I don't remember even seeing a menu for lwip. I've selected a board from those available for esp8266 (nodemcu v1) and run a sketch that starts a WiFi AP.

@Majenko That would work as an answer; once I chose the "Compile from source" setting the additional DHCP option was seen in wireshark. Thanks!

There are four variants of LwIP bundled with the ESP8266 core:

V1.4 (Compile from source)
V1.4 (Precompiled)
V2 Lower Memory
V2 Higher Bandwidth

By default (for most boards) one of the V2 variants is selected. You need to change that to the V1.4 (Compile from source) for it to use the version that you have modified.