text:
Run Time Error in arduino
I am trying to communicate multiple clients to a server, all using nodeMCUs. I am getting a weird run time error at the Server Serial Monitor of Arduino IDE when I upload the code.
Here's my server code:
#include <ESP8266WiFi.h>
#define Max_Clients 5

WiFiServer server(80);
WiFiClient *clients[Max_Clients] = {NULL};
String inputs [Max_Clients] = {""};                           //Initializing to store the string received from clients

void setup() {
  pinMode(D1,OUTPUT);                                         //Intializing pins for showing output and input
  pinMode(D2,OUTPUT);
  pinMode(D3,OUTPUT);
  pinMode(A0,INPUT);

  Serial.begin(9600);                                         //Start communication between the ESP8266-12E and the monitor window

  WiFi.mode(WIFI_AP);                                         //This ESP8266-12E is an AccessPoint
  WiFi.softAP("NodeMCU_js", "12345678");                      //Provide the (SSID, password)

  IPAddress myIP = WiFi.softAPIP();                           //Obtain the IP of the Server
  Serial.println("Server IP is: ");                           //Print the IP to the monitor window
  Serial.println(myIP);
  server.begin();                                             //Start the HTTP Server
}

void loop() {
  WiFiClient client = server.available();                     //Check if a new Client has connected to the server

if (client) {
Serial.println("A new Client has connected :)");

for (int i=0 ; i<Max_Clients ; ++i){              //Acknowledges and sets up new clients
  if (NULL == clients[i]){
    clients[i] = new WiFiClient(client);          //nothing in clients[i] means it is a new client
    break;
    }
  }
}

for(int i=0 ; i<Max_Clients ; ++i){                           //For available clients
  if (NULL != clients[i] && clients[i]->available()){
    String request = clients[i]->readStringUntil('\r');
    Serial.println("The string of client "+String(i+1));    //Print client's message
    inputs[i] = request;
    Serial.println(inputs[i]);

    int duty[4];
    duty[i] = inputs[i].toInt();

    if (i == 0){
      analogWrite(D1, duty[i]);
      clients[i]->println("To client 1.\r");
    }
    if (i == 1){
      analogWrite(D2, duty[i]);
      clients[i]->println("To client 2.\r");
    }
    if (i == 2){
      analogWrite(D3, duty[i]);
      clients[i]->println("To client 3.\r");
    }

    clients[i]->flush();                                    //Waiting for transmission to complete
    clients[i]->stop();
   }
  }
 }                                                                 //void loop closure

Here's my client code (which will be same for all clients):
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

char ssid[] = "NodeMCU_js";
char password[] = "12345678";

WiFiClient client;                // Creates a client that can connect to to a specified internet IP address and port as defined in client.connect()

IPAddress server(192,168,4,1);

void setup() {
  pinMode(A0,INPUT);
  pinMode(D6,OUTPUT);

  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);

  Serial.begin(9600);                 //Serial connection
  WiFi.begin(ssid,password);          //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {         //Wait for the WiFI connection completion
    delay(500);
    Serial.println("Connecting...");
  }
  Serial.println("Connected.");
  client.connect(server, 80);   // Connection to the server
  }

void loop() {

  if(WiFi.status() == WL_CONNECTED){   //Check WiFi connection status

    int sense = 200;
    client.println(sense+"\r");  //Client's message to the server
    String answer = client.readStringUntil('\r');         //Reading response from the server
    Serial.println("from server: " + answer);             //Printing the response
    client.flush();

    delay(3600000);
    }
  else{
    Serial.println("Error in WiFi connection");
    }
  }

On uploading this code, the Serial Monitor at the server shows:

A new Client has connected :)
  The string of client 1
  nt8_t* BufferedStreamDataSource::get_buffer(size_t) [with TStream = >ProgmemStream; uint8_t = unsigned char; size_t = unsigned int]
  The string of client 1

While the Serial Monitor at the client shows:

Connecting...
  Connecting...
  Connecting...
  Connecting...
  Connecting...
  Connecting...
  Connecting...
  Connected.
  from server: To client 1.

I have no clue of the source of this error. Any help is appreciated.
Thanks in advance.

do not use port 80 if it is not HTTP. use port 23 or 2323, which indicates plain socket communication (telnet). and you can test the server from a telnet client.

You shouldn't use 23 since that implies an interactive connection. You should use any port but 80 - ideally not use a port associated with any known protocol. But it really doesn't matter on an embedded system what port you use...  Btw - telnet can connect to any port - even 80.

Well, I have used the port successfully before to establish the connection. What other ports are available?

ports until 1023 are reserved https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

I suspect the problem stems from the client side.  This line:
client.println(sense+"\r");  //Client's message to the server

doesn't do what you think it does.
sense is a number (200).  "\r" is a string constant located at an address in memory.  When you add the two together you are not concatenating two strings, but you are adding 200 to the address of the string constant - and then sending whatever it finds at that location.
The "\r" is actually redundant anyway, since you are using println which adds \r\n to the end of a print. However if you do want to do it manually you just need to split it into two prints:
client.print(sense);
clienr.print("\r");

Can I just make 'sense' a string? It should pass as a String and will make changes at the client.

You could, but why? It's wasteful of resources and would have no benefit.

Research WL_CONNECTED, I think you find that is the connection state to your Access Point not the state if a device has connected, also their are issues with this variable.
It doesn't change state when the connection is dropped.
to make a connection you need to make a GET or POST request to a page on your server something like...
if (client.connect(server, httpPort)) {
    // connected to resource
    // send data
    client.print("GET /myfile");
    client.println(" HTTP/1.1");
    client.println("Host: IPADDRESS");
    client.println("Connection: close");
    client.println();
  } else {
    // No connection to server
    // should maybe keep retrying else waits till next call
  } // end if connect
Your server code needs to server a page and keep checking for connection with
webServer.on("/", doRoot);
Then have a function that writes the HTML back to client like...
void doRoot() {
    // write HTML
    String html;
    html = "";
    html += "My Page";
    // and send it
    webServer.send(200, "text/html", html);
  }

Sorry I cant work the formatting out for this site, I use enter code and it says enter code here but when pasted its trash

Yes, code blocks and enumerated lists don't work well together.

WiFiClient is a TCP socket. it can be used as it is. there is no need to use HTTP protocol between two devices. but it is not nice to use port 80 which is in standard reserved for HTTP.

This might work good for web server based communication. However, in my case, one of the nodeMCUs is the server.


text:
Waterlevel sensor disrupts PH reading
I have a water level sensor and a PH sensor connected to my nodemcu via an ADS1115 . When I insert only the PH sensor into the water then everything works fine. But when I insert the waterlevel sensor into the same container the PH sensor seems to shortcircuit and I get 5V no matter the actual PH level. Is there anything im missing or a way to prevent that from happening?

You might find this video very interesting: www.youtube.com/watch?v=udmJyncDvw0

That water level sensor uses bare metal which is in contact with the water. The PH sensors are sensitive for that kind of voltage in the water, even if it would be 0V.
There are isolated PH sensor amplifier modules. On forums are often discussions whether to ground an aquarium or not for a PH sensor. With a isolated PH sensor, you avoid most of those problems.
There are also non-contact water level sensors. For example capacitive sensor or even sensors that can be attached on the outside. Some sensors use the water pressure, but I don't know if this one is isolated: https://www.sparkfun.com/products/10221

You could also electrically isolate the water sensor so it's neither powered nor grounded unless you are actively reading it.

source: Stack Exchange

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

sort: votes


text:
Programming Arduino for Mindflex
I am learning brain wave programming from Tinkernut tutorial.
#include <IRremote.h>
#include <IRremoteInt.h>
#include <Brain.h>
IRsend irsend;
Brain brain(Serial);
const int ledPin = 3;
long interval = 500;
long previousMillis = 0;
int ledState = LOW;
int medValue;

void setup() {
  // Set up the LED pin.
  pinMode(ledPin, OUTPUT);
  // Start the hardware serial.
  Serial.begin(9600);
}

void loop() {
  // Expect packets about once per second.
  if (brain.update()) {
    Serial.println(brain.readCSV());
    // Attention runs from 0 to 100.
    medValue = brain.readMeditation();
  }

  // Make sure we have a signal.
  if(brain.readSignalQuality() == 0) {
    // Send a signal to the LED.
    if (medValue < 50) {
    irsend.sendNEC(0x10EFA05F, 32);
    delay(40);
    }
  }
}

The above code by tinkernut controls a single button of a tv remote only if the meditation value drops below 50.
My question is,
How to program arduino to control all the buttons of a tv remote ?

Get more probes. Or move up to a real neural control tool.

@IgnacioVazquez-Abrams can you please mention a real neural control tool ?

If I used more probes for different buttons then fluctuating meditation values could go out of control and tv goes crazy. Please correct me if I'm wrong

Instead of having more input sensors you could do some pattern matching? (Think morse code, but tbh I don't know much about these "mind control" sensor thingies, seems kind of limited to me)

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

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


text:
(Arduino + official GSM shield + ultrasonic HC-SR04 sensor) inaccurate measuring
I'm using an Arduino Uno, 1.0.5 r2 version of the IDE with and ultrasonic HC-SR04 sensor for measuring a tank water level. I want to send the data obtained over internet using the official arduino GSM shield sending them on the plot.ly servers with their API using a GPRS connection. When I'm doing all the tasks I get inaccurate values as these:

When I use the only ping sensor without the GSM shield all works well getting good data. The same using a potentiometer + GSM shield + plot.ly.
The function I use for getting the distance is:

long distCalc() {
  long durata, distanza;
  digitalWrite(TRIG_PIN, LOW);  // TRIG_PIN = pin 12
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  durata = pulseIn(ECHO_PIN, HIGH);  //ECHO_PIN = pin 11
  distanza = durata / 29.1 / 2 ;
  return distanza;    // in uscita la distanza in [cm]
}

and the one for posting the data on plot.ly servers is (loop function):
void loop() {
  long distanza;
  distanza = distCalc();  //fase di calcolo distanza
  Serial.print(distanza);
  Serial.println("cm");
  graph.plot(millis(), int(distanza), tokens[0]);  //fase di invio su plot.ly
  delay(20);
}

Could it be a software serial interrupt that hangs the pulseIn measurement?
How could I avoid this?

Hi @em1lio189, could be an issue with delay / delayMicroseconds. You may try to put another delay between distCalc() and Serial.print().
On a separate note, how are you going to install this setup in the tank? Water-proofing, etc.
I am also working on a similar project and planning to use Bluetooth / Wifi for transmitting data. This is a personal project not commercial for my home.

hi @theghostofc, I tried with the delay with no results. I think that the measure is noisy because the softwareserial library uses interrupts. I solved powering off the gsm shield, making the measure, starting it again and sending data in the main loop.

That's great that you got it working, even though with a hack :)

Could you please let me know how you are going to place the hardware (in the tank or outside). In my case it is placed outside under the Sun, with no power outlets nearby. Main concern that I have is to make the setup weather-proof. Any suggestions?


text:
Read from the SD card - ACMD41 times out
I'm trying to read from the SD card using an Arduino Pro Mini (3.3 V), Pololu micro-SD reader (the 3.3V one) over a SPI protocol.
I've tried both the SD library from Arduino SDK, and the Adafruit one.
Connections:

Arduino pin 10 -> CS,
pin 11 -> DI
pin 12 -> DO
pin 13 -> SCLK.

I've also connected VCC and GND of course.
This call (from the DumpFile example) fails:

// I've tried SD.begin(), SD.begin(10) as well.
if (!SD.begin(10, 11, 12, 13)) {
  // I can see this print statement in serial monitor.
  Serial.println("Card failed, or not present");
  return;
}

I've also tried manually setting pin 10 to OUTPUT, as well as to set it to HIGH.
Now, with the Adafruit SD library, I investigated this issue a bit more. It seems, that SD.begin() invokes the card.init(SPI_HALF_SPEED, csPin, mosi, miso, sck) (of the Sd2Card class).
I added print statements and discovered this exact piece fails:
while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) {
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
     // This is being printed.
     // status_ is 1
     Serial.println("init err here!");
     Serial.println(status_);
     error(SD_CARD_ERROR_ACMD41);
      goto fail;
    }
}

I've prepared a card (2GB one) - it's FAT16 formatted, and contains one partition. On this partition there's a single file ony, named "a.txt".

EDIT: After trying another SD card, I got some progress. Now, the following call fails:
volume.init(card) // in SD.cpp

After digging in, I discovered that this invokes the cacheRawBlock(volumeStartBlock, CACHE_FOR_READ), which invokes sdCard_->readBlock(blockNumber, cacheBuffer_.data) and then Sd2Card::readData(block, offset, count, dst).
In readData(), the following fails:
if (!inBlock_ || block != block_ || offset < offset_) {
    block_ = block;
    // use address if not SDHC card
    if (type()!= SD_CARD_TYPE_SDHC) block <<= 9;
    if (cardCommand(CMD17, block)) {
      // ****************************
      // FAIL IS HERE - cardCommand(CMD17, block) fails.
      // ****************************
      error(SD_CARD_ERROR_CMD17);
      Serial.println("SD_CARD_ERROR_CMD17");
      goto fail;
    }
    if (!waitStartBlock()) {
      goto fail;
    }
    offset_ = 0;
    inBlock_ = 1;
}

What the issue can possibly be?

Have you tried a different SD card?

if (!SD.begin(10, 11, 12, 13)) { - that does not compile. expects 1 argument, 4 provided. Please post the entire sketch you tried, which compiles, but does not successfully open the card. Also try another card, you must have another SD card lying around. Internally some of them work better than others, connected to the Arduino.

The SD.begin(10,11,12,13) works with Adafruit SD library. Anyway. I just tried it with a different SD card (FAT-32 this time, 4GB) and I got some progress! Now it fails on volume.init(card) call. I'll update the question in a second.

Sounds like you were using a cheap (Chinese, eBay) card that doesn't support the SPI protocol.  Works fine on a PC with SDIO but not an Arduino on SPI.


text:
Works with gcc, not with Arduino. error: taking address of temporary array
I need to hard code 8 byte addresses into char arrays of length 8. This must be done many places in my code (in function scope), so I have tried to come up with a one-liner. The following works perfectly in C when compiling with gcc.
char a[8];

void cpaddr(char target[], char *source) {
    int i;
    for (i=0; i<8; i++)
        target[i] = source[i];
}

int main() {
    char b[] = {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D};
    cpaddr(a, b);

    // line below does not compile with Arduino IDE
    cpaddr(a, (char[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
}

When compiling on Arduino the last line, which is the one-liner I was aiming for, does not compile. It gives:
/home/bob/Desktop/ate/Ate.ino: In function 'int main()':
Ate:101: error: taking address of temporary array
cpaddr(a, (char[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
^
exit status 1
taking address of temporary array

What is the problem here, that apparently is not a problem with gcc?
How do I fix it?

Have you tried
void cpaddr(char target[], const char *source)

I tried your exact code with g++ (and gcc) version 4.8.4 and got the exact same error message you got.

I'm using 4.9.3. Screenshot of result: http://i.imgur.com/2RJbGwg.png

( type[] ){val, ues} is not a valid way to create a temporary in C++: http://stackoverflow.com/questions/15458883/using-array-init-list-as-temporary-in-c11#comment26614881_18163000 The solution is to typedef it.

It is quite right, using that kind of syntax is not allowed. It's a bit of a pain, but it's ok since there is an alternative method - kind of a "trick" if you will.
That trick is to use a string, not an array. After all, a string is just an array, it's just handled slightly differently by the compiler.
Instead of using {...} use "..." and use the hexadecimal character escape sequence \xNN, such as:
cpaddr(a, "\x00\x10\xFF\xCA\x00\x00\xA2\x7D");

You could even lose your custom function and use a standard library function - memcpy():
memcpy(a, "\x00\x10\xFF\xCA\x00\x00\xA2\x7D", 8);

On the 8-bit AVRs you can save RAM by using the progmem variant and the F() macro:
memcpy_P(a, F("\x00\x10\xFF\xCA\x00\x00\xA2\x7D"), 8);

I think that it should be PSTR() instead of F(). F() is a very special Arduino String hack.

F() just imposes a type to PSTR() for overloading. You can use either.

Because of the type you cannot use F() directly without a cast. The compiler will say "cannot convert 'const __FlashStringHelper*' to 'const char*'".

Mine didn't. It compiled perfectly fine. I always test before posting code. It's not a cast, it's a reinterpret_cast.

But apparently not on memcpy_P as it takes whatever, i.e. const void*.

In any case F() is part of the "black-listed" String class. That should be enough to use PSTR() instead :)

This is true ;)

No it isn't. The define #define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal))) is in WString.h, however there is no connection between F() and the String class except that the String class uses it in certain cases (as does the Print class). In fact as you can see from the #define saying to use PSTR() instead doesn't make any sense. F() already uses PSTR(). It's purpose is just to create a new type that can be used to detect if a string is in PROGMEM or RAM. That's all.

@NickGammon Isn't that mainly for overloading, like I mentioned above? ;)

Er, yes it turns # define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];}))  (which is still type const char []) into another type, which then assists with overloading. So I agree that (after casting) they would be the same thing. However neither PSTR nor F() are "part of the black-listed String class". I see no objection to using F() here. In fact your suggestion would save RAM compared to what I did in my reply, although mine is probably "cleaner" in that you aren't throwing in a memcpy_P (and making sure you get the length right).

See Using array init list as temporary in C++11?
You can solve it by using const. This compiles:
char a[8];

void cpaddr(char target[], const byte *source) {
    int i;
    for (i=0; i<8; i++)
        target[i] = source[i];
}

int main() {
    byte b[] = {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D};
    cpaddr(a, b);
    cpaddr(a, (const byte[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
}

Note I had to change your array from char to byte because I was getting (valid) warnings that things like 0xCA don't fit into a char.

As Majenko said, memcpy would be better than doing a byte-by-byte copy.

I hate it when people use non-standard arduino specific types like byte, when there is a perfectly good and standard uint8_t available...

As explained in the very thread you linked, ( type[] ){val, ues} is not a valid way to create a temporary in C++: http://stackoverflow.com/questions/15458883/using-array-init-list-as-temporary-in-c11#comment26614881_18163000 The solution is to typedef it.

Recent versions of the IDE use C++11, so whether or not it is valid in C++ doesn't really matter.

How do I fix it?

"Char []" shouldn't compile under c. It is just invalid.
You can use string, cast to char * . or just another pointer as you did already.

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


text:
Exception Handling with the Arduino IDE
I'm using a port of the STL found here and trying to debug with a simple try{...}catch{...} statement. When compiling with the Arduino IDE, I get the following error message:

exception handling disabled, use -fexceptions to enable.

I'm not quite sure what this means. Does the Arduino simply not support exceptions? Or is -fexceptions a compiler flag I can enable?

It's just disabled and if you want to use it, you have to provide -fexceptions flag to the compiler.

Great, thanks for the help!

As you have already found out, add -fexceptions to the compiler flags. This can be done by modifying the platform.txt of your Arduino IDE installation.
See https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L28. There is -fno-exceptions defined, so you have to remove that, too.

Perfect, this is the (complete) answer I was looking for.

Arduino is a very limited platform, and handling exceptions requires quite a bit of hidden code to properly unwind the stack wherever the exception occurs.
So the default is to turn it off and teach users to not use exceptions in arduino and instead other type of error handling.

The default is not to use STL neither.

It's not just the default; Arduino has no built-in support for the STL.


text:
External EEPROM Read and Write Issues: Junk Values in I2C Communication
I have an ESP32 controller and am using AT24C1024 for communication. In my code, I am trying to access an external EEPROM at positions writing data from 0 to 10000 position data is = '1'. However, when I read data from position '1', I sometimes get junk values, such as 0, 255, or old written values. I have already tried changing the clock speed with Wire.setClock(100000), and I have attempted multiple writes to that location, but these modifications did not resolve the issue.
#include <Wire.h>

#define EEPROM_ADDR 0x50
#define SDA_PIN 21
#define SCL_PIN 22
#define DATA_LIMIT 10000
#define VALUE 1

void setup() {
  Serial.begin(115200);
  // Wire.begin(SDA_PIN, SCL_PIN);

  Wire.begin();

  for (uint16_t i = 0; i < DATA_LIMIT; i++) {
    writeEEPROM(i, VALUE);
  }

  for (uint16_t i = 0; i < DATA_LIMIT; i++) {
    uint8_t value = readEEPROM(i);
      Serial.print(i);
      Serial.print(" -> ");
      Serial.println(value);
    delay(30);
  }
  Serial.println("End");
}

void loop() {
}

void writeEEPROM(uint16_t memAddress, uint8_t data) {
  Wire.beginTransmission(EEPROM_ADDR);
  Wire.write((int)(memAddress >> 8));
  Wire.write((int)(memAddress & 0xFF));
  Wire.write(data);
  uint8_t result = Wire.endTransmission();

  if (result != 0) {
    Serial.print("'W'- F : ");
  }
  delay(10);
}

uint8_t readEEPROM(uint16_t memAddress) {
  Wire.beginTransmission(EEPROM_ADDR);
  Wire.write((int)(memAddress >> 8));   // MSB of memory address
  Wire.write((int)(memAddress & 0xFF)); // LSB of memory address
  Wire.endTransmission();

  Wire.requestFrom(EEPROM_ADDR, 1);
  if (Wire.available()) {
    return Wire.read();
  }

  return 0;
}

Wire.beginTransmission(EEPROM_ADDR);

Although this code might work when you are addressing the first page of the memory, however if you read the datasheet carefully under the section of Device Addressing and Figure 7 Device Addressing.
|  1 |  0 |  1 |  0 |  0 | A1 | Pg | R/W |
  MSB                                LSB

The I2C addressing includes the memory page address bit and the status of A1 pin. So assuming A1 is 0 with internal pulldown or hardware unconnected, the correct addressing should be
Wire.beginTransmission((uint8_t)(EPROM_ADDR | (uint8_t) (dataAddress >> 16));

The Wire library itself will be responsible to convert the 7-bit I2C  addressing to 8-bit I2C addressing and the R/W bit.
BTW, although code like Wire.write((int)(memAddress >> 8)); because the compiler might take care of it. But since Wire.write() take an argument of uint8_t as the parameter, so the casting should be (uint8_t) (memAddress >> 8) instead of (int) (memAddress >> 8).

Since the range of memAddress is [0, 9999], the bits above 2^13 are all zero. So this cannot be the reason for the problem.

@thebusybee, datasheet (page 3) say memory is "internally organized as 512 pages of 256 bytes each".

Wire.beginTransmission((uint8_t)(EPROM_ADDR | (uint8_t) (dataAddress >> 16)); and (uint8_t) (memAddress >> 8)  . I changed this configuration, this configuration is correct,  but now also 0 to 10000 position write the data is '1' comming junk character (0, 255 and old data) ,approximately 9500 data only correct, another data has junk character

Did you make the change to the readEEPROM(uint16_t memAddress) accordingly and the Wire.requestFrom(EEPROM_ADDR, 1);?

"512 pages of 256 bytes" Yes, and 10000 bytes need 40 pages. So the page number calculated from memAddress will never change the most significant bit P0, which is always 0.

@hcheung , I Already changed the  readEEPROM(uint16_t memAddress) method also, And also a refer [AT24C1024_lib] (https://github.com/jwhiddon/AT24C1024/blob/master/AT24C1024.cpp) , this also junk value is coming , And my esp32 and AT24C1024 connection is
[NC, A1, NC, GND, WP  - GND ] [VCC - 5V] [SCL - 22] [SDA - 21]


text:
ESP8266 (Mini D1) does not come back after deep sleep but NodeMCU does
Kind of desperate here. I tried every solution found on this forum / google and others.
My sketch works perfectly with a NodeMCU 1.0
The same script should work on a Lolin Mini D1, everything works except the wake up after deep sleep.
Wiring is clearly identical.
That pinMode(D0, WAKEUP_PULLUP) is the latest addition, found in a post here. Nothing changed.
The program reads the values from a sensor and then goes to sleep. Changing the sleep mode does not chenge the results.
In ESP.deepSleep I tried every possible value I found around. No luck.
After the 15 seconds the built led flashes, something weird appears in the serial monitor, and then the only solution is the reset button.
I even thought it was bad soldering, so I tested the RST with an external pushbutton and the D0 with a led. Electrically it's allright. If I press the external pushbutton (NOT the builtin) the D1 mini resets.
Last, I've put a resistor between D0 and RST, which helps with the frequent flashing, but did not solve.
Any help super appreciated.
Edit after some of the comments below (thank you all).
Set the baud rate to 74880 and here's the result
At second 02 I pressed manually the reset button.
At second 19 the board wakes, but the program does not restart
17:12:02.002 ->  ets Jan  8 2013,rst cause:2, boot mode:(3,6)
17:12:02.002 -> load 0x4010f000, len 3424, room 16
17:12:02.045 -> tail 0
17:12:02.045 -> chksum 0x2e
17:12:02.045 -> load 0x3fff20b8, len 40, room 8
17:12:02.045 -> tail 0
17:12:02.045 -> chksum 0x2b
17:12:02.045 -> csum 0x2b
17:12:02.045 -> v000421a0
17:12:02.045 -> ~ld
17:12:02.088 -> rf cal sector: 1020
17:12:02.089 -> freq trace enable 0
17:12:02.135 -> rf[112] : 0�xx
17:12:02.135 -> Wating some moments before going to sleep
17:12:04.099 -> Now going to sleep for 15000000 microseconds
17:12:19.009 ->  ets Jan  8 2013,rst cause:2, boot mode:(3,6)

#define LED D4 // built in led on board
#define RED_LED D2
#define WHITE_LED D1

#define DHTPIN D7 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <DHT.h>
#include <DHT_U.h>

// WiFi parameters to be configured
const char* ssid = "hfghjfjfghj"; // Write here your router's username
const char* password = "fghjfghjf"; // Write here your router's passward

DHT dht(DHTPIN, DHTTYPE);

void setup(void)
{
  pinMode(LED, OUTPUT);    // LED pin as output.
  pinMode(RED_LED, OUTPUT);    // LED pin as output.
  pinMode(WHITE_LED, OUTPUT);    // LED pin as output.
  pinMode(D0, WAKEUP_PULLUP);  // doesn't change anything

  Serial.begin(115200); // or 9600
  while(!Serial) {}
  Serial.println("xx"); // this starts a new line in the console after all the rubbish during the connection
  Serial.println("Connecting to WiFi");
  // Connect to WiFi
  digitalWrite(RED_LED, LOW);
  digitalWrite(WHITE_LED, LOW);
  digitalWrite(LED, HIGH); // this actually switches OFF

  WiFi.begin(ssid, password);

  // while wifi not connected yet, print '.'
  int k = 0;
  while (WiFi.status() != WL_CONNECTED) {
    digitalWrite(LED, HIGH);
    delay(100);
    digitalWrite(LED, LOW);
    delay(100);

  }

  // Print the IP address
  Serial.println(WiFi.localIP());

  dht.begin();

}

void go_to_sleep(float minutes) {
  blink_times(LED,5,30);
  Serial.print("Now going to sleep for ");
  long msecs = minutes * 60 * 1000 * 1000;
  Serial.print(msecs);
  Serial.println(" microseconds");
  ESP.deepSleep(msecs, WAKE_RF_DEFAULT); // or WAKE_RF_DISABLED, doesn't work either
}

void loop() {
  Serial.println("Main loop");
  delay(2000); // Wait a few seconds between measurements
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" *C");
  go_to_sleep(0.25);
}

the pull-up resistor maybe too strong

not an electronic expert, so I tried two that normally come with builder kits. It does not work even with a direct wire. Actually I found on various forums, my exact problem, unsolved mostly. People suggesting:

resistor
led
adding delay(2000) after deepSleep
changing the wake up mode (I tried all the available values)
adding pinMode(D0, WAKEUP_PULLUP)

None of these have worked. I'm starting to think the board is simply defective

the reset pin has a pull-up resistor on "Wemos D1 mini". that one maybe too strong for the io 16 to pull it down

On a further note, after having spent hours searchign the web, it seems that the garbage is normal. Data sent at a different baudrate when the board starts. So the first line is when I power it, the second after the wake. So it does wake, only the program does not restart (this even in my stripped version, with an empty loop()

Do you have the same problem when you use a much simpler test setup like the one described in this tutorial: https://randomnerdtutorials.com/esp8266-deep-sleep-with-arduino-ide/  ?  Note that there is a timeout on the serial connection so it does not block permanently if serial is unavailable at wakeup.

You may want to change to Serial.begin(74880) and likewise change the serial monitor to use that rate so that you may see both your sketch output and the boot reports (the "garbage") correctly without switching baud rates.

Please check the main description, I added the trace of the Serial @74880 baud


text:
Cannot obtain reading from meter (Modbus)
I have a system in which I am taking readings from a meter and processing it through an Arduino Nano. My code looks as follows:
#include <SoftwareSerial.h>

#define SerialControl 7
#define RS485Tx HIGH
#define RS485Rx LOW

SoftwareSerial RS485Serial(11, 12);
uint8_t window[8]; // Initialising window of 8 bytes

byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };

// 0x01: Meter Address, 0x03: Read Function Code, 0x40: Register Address Variable (Start address high bit)
// 0x34: Register Address Variable (Start address low bit)
// 0x00: Register Quantity (High Bit), 0x02: Register Quantity (Low Bit)
// 0x90: CRC check code (CRC code Low bit)
// 0x05: CRC check code (CRC code High bit)

void dumpWin() {
  for (int i = 0; i < 8; i++) {
    Serial.print(window[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

void ReadRx() {
  // Sliding Window Implementation for reading data
  if(RS485Serial.available()) {
    uint8_t b = RS485Serial.read();
    dumpWin();
    // Slide the contents of the array down
    for (uint8_t i = 0; i < 7; i++) {
      window[i] = window[i+1];
    }
    window[7] = b; // Next frame inserted at the top of previous
    if ((window[0] == 0x01) && (window[1] == 0x03) &&
      (window[2] == 0x40) && (window[3] == 0x34)) {
      // Doing something with window[4] and window[5] here
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(SerialControl, OUTPUT);
  RS485Serial.begin(9600);
}

void loop() {
  static uint32_t ts = millis();
  if (millis() - ts >= 2000) {
    ts = millis();
    digitalWrite(SerialControl, RS485Tx);
    RS485Serial.write(SendKWh, sizeof(SendKWh));
    RS485Serial.flush();
    digitalWrite(SerialControl, RS485Rx);
    RS485Serial.listen();
  }
  ReadRx();
}

The ReadRx() is behaving odd and dumpWin() is giving 0 0 0 0 0 0 0 0 output. I have been trying but I'm not able to figure out where am I going wrong. Your help is appreciated!
EDIT 2: I changed the code as suggested by @Majenko but still window[] O/P is 0 for all. I am not able to understand as to why it is not able to read the values from RS485Serial.

Don't have all those delays. You don't want any delays anywhere.

Delay in ReadRx after digitalWrite ?

ReadRX only reads one byte. It needs to be run repeatedly and fast. Leave the rs485 in RX mode all the time except when you specifically want to transmit.

I removed delay(1500) and still the O/P for dumpWin() remains 0 for all.

Is there anything wrong in this statement RS485Serial.write(SendKWh, sizeof(SendKWh));

I think your whole method of working is wrong. In loop you should have a bit of code that decides if it's time to send. That then switches to send mode, sends, then switches back to read mode. Then all that is left in loop is the reading function, which just reads, adds to the array, and processes if it matches. Nothing else.

You need to stop thinking quite so linearly. You are working with asynchronous systems, so your code has to be asynchronous too.
Something more like this:
#include <SoftwareSerial.h>

#define SerialControl 7

#define RS485Tx HIGH
#define RS485Rx LOW

SoftwareSerial RS485Serial(11, 12);

byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };

// 0x01: Meter Address, 0x03: Read Function Code, 0x40: Register Address Variable (Start address high bit)
// 0x34: Register Address Variable (Start address low bit)
// 0x00: Register Quantity (High Bit), 0x02: Register Quantity (Low Bit)
// 0x90: CRC check code (CRC code Low bit)
// 0x05: CRC check code (CRC code High bit)

uint8_t window[8]; // Initialising window of 8 bytes

void dumpWin() {
  for (int i = 0; i < 8; i++) {
    Serial.print(window[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

void ReadRx() {
  if(RS485Serial.available()) {
    uint8_t b = RS485Serial.read();
    dumpWin();
    // Slide the contents of the array down
    for (uint8_t i = 0; i < 7; i++) {
      window[i] = window[i+1];
    }

    window[7] = b; // Next frame inserted at the top of previous

    if ((window[0] == 0x01) && (window[1] == 0x03) &&
        (window[2] == 0x40) && (window[3] == 0x34)) {
          // Doing something with window[4] and window[5] here
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(SerialControl, OUTPUT);
  digitalWrite(SerialControl, RS485Rx);
  RS485Serial.begin(9600);

}

void loop() {
  static uint32_t ts = millis();

  if (millis() - ts >= 2000) {
      ts = millis();
      digitalWrite(SerialControl, RS485Tx);
      RS485Serial.write(SendKWh, sizeof(SendKWh));
      RS485Serial.flush();
      digitalWrite(SerialControl, RS485Rx);
      RS485Serial.listen();
  }

  ReadRx();
}

Notice how I use millis() to send the command every 2 seconds asynchronously (i.e., without delay()). The RS485 is kept in READ mode except for the brief moment while you send. Also note the use of flush()  to wait until the last symbol has been transmitted by the UART (software in this case) interface. It's important, otherwise you may cut off the transmission part way through (I don't think it's such a problem with SoftwareSerial, but with a hardware UART missing it out would be fatal).
The reading just reads one character and returns to the loop. Each iteration through the loop will (if a character is available) read just one character. Only when all 8 have been received and the contents of the window match up can you process anything (which you would put in place of the comment).
This method also leaves you free to implement other things in loop(), as long as they don't use delay() as well.


text:
Bluetooth communication not working with DC power but works with USB power?
I am running an HM-10 Bluetooth Low Energy (BLE) module to transmit serial data (using SoftwareSerial) from an analog sensor onboard my Arduino Uno to a serial terminal app on my Android phone. When I power the Arduino with a USB power bank, the data transmits flawlessly.
When I tried to power the Arduino with a 9V battery through the DC power jack instead of USB power, the BLE module connects to my phone, but no data is transmitted when a serial connection is established.
Any ideas why this would be?

"9V battery" as in little wimpy PP3 that can't power ****?

@Majenko yes, correct. Is the implication of your reply that the (brand new) battery is not powerful enough? If so I could try to source a battery box to attempt to get it running on AA batteries as a test.

PP3 batteries are the laughing stock of the battery world. You want at least 6V of AA batteries  for what you are doing - and if you value your battery life you want to bypass the Arduino's on-board regulators and use switching regulators instead.

@Majenko thanks! I am putting the Arduino onboard a drone and it'll only need to work for 10 mins at a time; the biggest concern is weight and not battery time. But I will give it a try.

In that case you would be better using Li-Ion batteries since they have a higher energy density for their size/weight.

@Majenko Thanks - so there is no practical reason other than a lack of power being supplied to the unit that the 9V PP3 would not cause the SoftwareSerial data to be sent?

Transmitting takes a lot of power. The Duracell datasheets consider 250mA to be a heavy load (it's the heaviest they characterise it for). Transmitting typically takes hundreds of mA, and needs it delivering rapidly - something a PP3 is not good at due to the massive (comparatively) internal resistance.

@Majenko - BLE transmit power is a brief pulse at a few tens of milliamps.  It's within the capability of a CR2032 coin cell.  Advertising fairly frequently mine drew an average of around 200 uA.  Likely the Arduino draws more, at least on average.

@ChrisStratton A well designed one is, yes. A cheap HM-10 from China? Who knows what that might draw. I wouldn't trust it to be less than a few hundred milliamps.

What I measured was an HM-10.  Running essentially the TI example.  Not sure if there's any software in them by default.

@ChrisStratton Also a CR2032 isn't crippled by the linear regulators of the Arduino throwing away about 50% of the power of the battery.

@ChrisStratton As a general rule of thumb though - PP3 + LDO + Transmitter (of any kind) = a bad mix. Change the PP3 for something with more grunt and less voltage, or swap the LDO for an efficient switcher, and things improve massively.

As a "quick fix" you could try "buffering" the power to the HM-10 with a large electrolytic capacitor (in the order of hundreds or thousands of µF).

Your whole line of reasoning here is based on a grossly erroneous guess at what these things draw.  Check the TI data sheet  if you don't want to believe me.

No it isn't. I don't give a damn what they draw. A PP3 on an Arduino with the wildly inefficient LDO can barely power itself and maybe an LED. Add even a low power transmitter and you're asking for trouble.

There are exactly two scenarios that account for "it works on usb but not battery". One is they forgot to connect the grounds between two parts of their circuit, and ground is making its way through a convoluted route via the computer. That is not the case here, since it works with a nice powerful USB powerbank. So it must be the second scenario, which is attempting to use a PP3 battery, instantly confirmed by the OP. Ergo, improve the battery and/or the regulation, and fix the problem.

It may be that the BLE is actually functioning fine but some other unspecified part of the setup is failing. It's impossible to tell from here. Suffice it to say, though, the battery is the cause of the problem, and has been many times before on Arduinos.

Take two 9 volt batteries with same specifications and connect them in parallel. By using this efficiency of current increases and it may full fill the current requirement at the time of data transmission, and for others modules you are using with the Arduino.

While this likely wouldn't meet the OP's design requirements, it's a perfectly reasonable benchtop test to confirm that the 9v batter is (or isn't) the problem.

A PP3 battery is not a suitable power source for an Arduino.
For battery powered operations I would recommend a set of AA batteries with between 6 and 8 volts (if you don't care about bulk) or a Li-Ion battery (or two) and a suitable buck or boost (depending on number of cells) regulator to bypass the inefficient linear regulators on the Arduino.


text:
Arduino Due unable to access library
I am unable to run code on Arduino Due that I earlier ran on an Arduino Uno. The error indicates it is unable to recognize the library. Could this library access problem be due to difference of the micro-controllers of the 2 boards?

Quite possibly. The modern library format contains a list of board types it runs on (in library.properties). If the Due (SAM) isn't listed then it won't be included in the list of libraries.
For instance the SD library has:
name=SD
version=1.1.1
author=Arduino, SparkFun
maintainer=Arduino <info@arduino.cc>
sentence=Enables reading and writing on SD cards.
paragraph=Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card.
category=Data Storage
url=http://www.arduino.cc/en/Reference/SD
architectures=*

However the AVR specific SPI library has:
name=SPI
version=1.0
author=Arduino
maintainer=Arduino <info@arduino.cc>
sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus.
paragraph=SPI is a synchronous serial data protocol used by microcontrollers for communicating with one or more peripheral devices quickly over short distances. It uses three lines common to all devices (MISO, MOSI and SCK) and one specific for each device.
category=Communication
url=http://www.arduino.cc/en/Reference/SPI
architectures=avr

Note the last line of each - architectures=... - that defines what the library can work with. If your (unspecified) library doesn't have * or include sam in that parameter then there is no way that library will work with the Due.

Yes, Due wasn't listed earlier. I installed Due from the Boards Manager. It is able to run other programs . Currently it is not able to access a DFT library which I had earlier ran on Arduino Uno.

I am not talking about board support. I am talking about whether the library can ever support the Due. If it's a modern layout with library.properties and it's not designed to run on the Due then the IDE won't even see that it exists - no matter what you do.

"the IDE won't even see that it exists". This is incorrect. The Arduino IDE will still attempt to compile for the library even though the architectures value in library.properties doesn't match the architecture of the selected board. If compilation can proceed past preprocessing then the Arduino IDE will display a helpful warning: "WARNING: library FooBar claims to run on (avr) architecture(s) and may be incompatible with your current board which runs on (avr) architecture(s)." The examples of the library will also appear under File > Examples > INCOMPATIBLE.

Now libraries such as SPI that are bundled with hardware packages are only seen by the IDE when a board of that hardware package is selected but this has nothing to do with the architectures value in library.properties, it is solely controlled by the folder the library is located in.


text:
Arduino FIFO queue for with potentiometer values and 7 segment display
As of now I have code that takes a value from a potentiometer and maps it from 0-9. Based on this mapped value a number will be displayed on the seven segment display.
Currently, if I quickly turn the pot completely then back to zero it will show everything very quickly and then show 0 until I change the pot value again. What I am trying to do is make it so if it's quickly turned completely then back to 0, after a second it will display all the number from 0-9 then back down to 0, each for a second.
I was given a hint to use arrays to create a FIFO queue but I am not sure how to go about doing this and I have been stuck on this for a while. Here's my code:
// Pin 2-8 is connected to the 7 segments of the display.
// Pin 0 is for potentiometer
int potval;
int pinA = 2;
int pinB = 3;
int pinC = 4;
int pinD = 5;
int pinE = 6;
int pinF = 7;
int pinG = 8;
int i;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pins as outputs.
  pinMode(pinA, OUTPUT);
  pinMode(pinB, OUTPUT);
  pinMode(pinC, OUTPUT);
  pinMode(pinD, OUTPUT);
  pinMode(pinE, OUTPUT);
  pinMode(pinF, OUTPUT);
  pinMode(pinG, OUTPUT);
}

void loop() {
  potval=map(analogRead(A0),0,921,0,9);
  if (potval==0){
    //0
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, HIGH);
  }
  if (potval==1){
    //1
    digitalWrite(pinA, HIGH);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, HIGH);
  }
  if (potval==2){
    //2
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, HIGH);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, LOW);
  }
  if (potval==3){
    //3
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, LOW);
  }
  if (potval==4){
    //4
    digitalWrite(pinA, HIGH);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==5){
    //5
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, HIGH);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==6){
    //6
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, HIGH);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==7){
    //7
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, HIGH);
  }
  if (potval==8){
    //8
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==9){
    //9
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
}

Without seeing the code it is bit difficult to help. Please edit your answer and include the relevant parts of the code, otherwise we will end up (re)writing your code for you.
Hint: why not, when you detect a change in the pot, take the new reading, and then count down/up slowly (at the rate that you desire) from the currently displayed reading to the new measured reading - using a for loop, which contains a delay()? With each iteration of the loop you can display the new value. Easy!
However, this sounds like a terrible idea
Note that your code won't do anything else whilst the display is incrementing and decrementing, using this method. So, if you were to spend a lot of time twiddling with the knob, then the code wouldn't get much time to actually do any real work, apart from displaying the updated value.
In order for your code to do real work, whilst displaying the new updated value, you would either need interrupts, or integrate the display updating procedure into the loop(), such that each iteration of the loop() updates the display (or upon each n iterations of loop(), as loop() will probably be looping to quickly. You will probably need to use millis()).
NOTE: From a UX aspect, although it all sounds very 1960's-James-Bond-evil-guy-equipment, the whole notion of the displayed value slowly following the actual location of the knob sounds, at best, extremely infuriating, if not down right dangerous (depending upon the context). Human feedback should be as fast as possible. Else the user will constantly be turning the knob to reach the value that they which to achieve, when in fact they have already passed that value, and may be over compensating, and it is just the fancy display graphics that is showing the wrong value.
Assuming that the knob is controlling something else (actuator, motor, heater, etc.), and not just a pretty display in itself, unless, you are actually outputting the delayed displayed digital value, and not the knob's actual current analogue value, I would seriously recommend against doing this.
I may be wrong, and it would probably require a separate question on SE.UX, although, I would imagine that it has been asked already.

Code was added and the pot is just being used to control a 7 segment

Usually anything with a slower refresh rate than 100-60ms is considered laggy and should be avoided. So you could implement some smoothing (say only allow decreasing values) to make the counter seem smoother, otherwise it's quite pointless, human motion itself is rather smooth already if you sample fast enough.

First of all, that way of writing the displays is quite horrible to me ;) Better to use a matrix (and, please, no ints for small variables like pin numbers, and make them constant). This is the code fixed with these improvements:
// Pin 2-8 is connected to the 7 segments of the display.
// Pin 0 is for potentiometer
int potval;
const byte pinA = 2;
const byte pinB = 3;
const byte pinC = 4;
const byte pinD = 5;
const byte pinE = 6;
const byte pinF = 7;
const byte pinG = 8;

byte Matrix[][7] = { { LOW , LOW , LOW , LOW , LOW , LOW , HIGH}, // potval 0
                     { HIGH, LOW , LOW , HIGH, HIGH, HIGH, HIGH}, // potval 1
                     ... fill with the other rows ...
                     { LOW , LOW , LOW , HIGH, HIGH, LOW , LOW }  // potval 9
                    };

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pins as outputs.
pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
pinMode(pinC, OUTPUT);
pinMode(pinD, OUTPUT);
pinMode(pinE, OUTPUT);
pinMode(pinF, OUTPUT);
pinMode(pinG, OUTPUT);
}

void loop() {
    potval=map(analogRead(A0),0,921,0,9);

    digitalWrite(pinA, Matrix[potval][0]);
    digitalWrite(pinB, Matrix[potval][0]);
    digitalWrite(pinC, Matrix[potval][0]);
    digitalWrite(pinD, Matrix[potval][0]);
    digitalWrite(pinE, Matrix[potval][0]);
    digitalWrite(pinF, Matrix[potval][0]);
    digitalWrite(pinG, Matrix[potval][0]);
}

You can further improve it by not having seven variables but only an array to iterate over, but .. ok, let's keep this.
Ok, now you want to do a "slow movement". In order to do this you can use a variable to track the current position, and let it move towards the target value once every XX ms. This is the approach used, for instance, in CNCs and 3d printers movements.
// Pin 2-8 is connected to the 7 segments of the display.
// Pin 0 is for potentiometer
int potval;
const byte pinA = 2;
const byte pinB = 3;
const byte pinC = 4;
const byte pinD = 5;
const byte pinE = 6;
const byte pinF = 7;
const byte pinG = 8;

unsigned long int prevMillis;
const int delayBetweenMovement = 200;

byte Matrix[][7] = { { LOW , LOW , LOW , LOW , LOW , LOW , HIGH}, // potval 0
                     { HIGH, LOW , LOW , HIGH, HIGH, HIGH, HIGH}, // potval 1
                     ... fill with the other rows ...
                     { LOW , LOW , LOW , HIGH, HIGH, LOW , LOW }  // potval 9
                    };

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pins as outputs.
pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
pinMode(pinC, OUTPUT);
pinMode(pinD, OUTPUT);
pinMode(pinE, OUTPUT);
pinMode(pinF, OUTPUT);
pinMode(pinG, OUTPUT);
prevMillis = millis() - delayBetweenMovement;
}

void loop() {
    if ((millis() - prevMillis) >= delayBetweenMovement)
    {
        prevMillis += delayBetweenMovement;

        potval=map(analogRead(A0),0,921,0,9);
        static int CurrentPotVal = potval;

        if (potval > CurrentPotVal)
            CurrentPotVal++;
        if (potval < CurrentPotVal)
            CurrentPotVal--;

        digitalWrite(pinA, Matrix[CurrentPotVal][0]);
        digitalWrite(pinB, Matrix[CurrentPotVal][0]);
        digitalWrite(pinC, Matrix[CurrentPotVal][0]);
        digitalWrite(pinD, Matrix[CurrentPotVal][0]);
        digitalWrite(pinE, Matrix[CurrentPotVal][0]);
        digitalWrite(pinF, Matrix[CurrentPotVal][0]);
        digitalWrite(pinG, Matrix[CurrentPotVal][0]);
    }
}

The delayBetweenMovement constant makes a delay between the readings. With this method, if you quickly turn it to 9 and then to 0 you will not arrive to 9. For instance you put a 9, the display starts doing 0..1..2..3, then you switch to 0 and the count will not reach 9, but start going back to 0. Reaching 9 will require some more structures; if you need it ask and I'll make some modifications
EDIT: as requested, here is a version that can memoryze up to 20 states and reproduce them. If you need them just increase the FIFO size.
Note: I haven't tested these programs. In the other two I was pretty confident I hadn't made any major bug, but this one is a bit more complicated. There can be some bugs left..
// Pin 2-8 is connected to the 7 segments of the display.
// Pin 0 is for potentiometer
const byte pinA = 2;
const byte pinB = 3;
const byte pinC = 4;
const byte pinD = 5;
const byte pinE = 6;
const byte pinF = 7;
const byte pinG = 8;

unsigned long int prevMillis;
const int delayBetweenMovement = 200;

byte Matrix[][7] = { { LOW , LOW , LOW , LOW , LOW , LOW , HIGH}, // potval 0
                     { HIGH, LOW , LOW , HIGH, HIGH, HIGH, HIGH}, // potval 1
                     ... fill with the other rows ...
                     { LOW , LOW , LOW , HIGH, HIGH, LOW , LOW }  // potval 9
                    };

const byte FifoSize = 20;
byte TargetFifo[FifoSize];
byte FifoHead = 0, FifoTail = 0;

byte potval;

// the setup routine runs once when you press reset:
void setup() {
    // initialize the digital pins as outputs.
    pinMode(pinA, OUTPUT);
    pinMode(pinB, OUTPUT);
    pinMode(pinC, OUTPUT);
    pinMode(pinD, OUTPUT);
    pinMode(pinE, OUTPUT);
    pinMode(pinF, OUTPUT);
    pinMode(pinG, OUTPUT);
    prevMillis = millis() - delayBetweenMovement;
}

byte FifoAvailableForWrite()
{
    if (FifoTail > FifoHead)
        return (FifoSize - FifoTail + FifoHead);
    else
        return (FifoHead - FifoTail);
}

void loop() {
    potval=map(analogRead(A0),0,921,0,9);
    static byte prevPotVal = potval;
    static int CurrentPotVal = potval;

    if ((prevPotVal != potval) && (FifoAvailableForWrite() > 1))
    {
        TargetFifo[FifoTail] = potval;
        prevPotVal = potval;
        FifoTail = (FifoTail + 1) % FifoSize;
    }

    if ((millis() - prevMillis) >= delayBetweenMovement)
    {
        prevMillis += delayBetweenMovement;

        if (FifoHead != FifoTail)
        {
            if (TargetFifo[FifoHead] > CurrentPotVal)
                CurrentPotVal++;
            if (TargetFifo[FifoHead] < CurrentPotVal)
                CurrentPotVal--;
            while (TargetFifo[FifoHead] == CurrentPotVal)
                FifoHead = (FifoHead + 1) % FifoSize;
        }

        digitalWrite(pinA, Matrix[CurrentPotVal][0]);
        digitalWrite(pinB, Matrix[CurrentPotVal][0]);
        digitalWrite(pinC, Matrix[CurrentPotVal][0]);
        digitalWrite(pinD, Matrix[CurrentPotVal][0]);
        digitalWrite(pinE, Matrix[CurrentPotVal][0]);
        digitalWrite(pinF, Matrix[CurrentPotVal][0]);
        digitalWrite(pinG, Matrix[CurrentPotVal][0]);
    }
}

Thank you for this! However, I do need it to go to 9 then back to 0 so if you could grab back to me on how to do it or with the code that would be greatly appreciated. Thanks once again.

@TahaA I tried to develop a fifo based solution.. See if that works..


text:
Can't upload any code to my Arduino board
I have an Arduino Uno R3 with an ATmega238 microchip. I can't upload any code to it: the green led and pin13 LED are always on (without flashing ) and the RX and TX LEDs don't flash when I upload code or press the reset button. Is the microchip malfunctioning?
And what happens when a reverse current returns to Arduino from a relay?

You basically have 2 questions here.
1: Why is my Uno not uploading code.
2: How does back EMF effect a microcontroller. We'll address 2 first
When a relay module is activated, it energizes a coil to close a switch. This coil is an inductor, which is an energy storage device. When the signal to the relay tells it to turn off, your trying to de-energize the coil. Whereas before you let current run through the coil to establish a magnetic field, now you cut the current supply and let the magnetic field die out.
The problem this creates is back EMF. As Faraday's law will tell us, a change in a magnetic field causes a voltage (an EMF) in a coil. When we were charging the circuit, this was the voltage applied to the coil. When we discharge the inductor, this voltage is back EMF, and is in the opposite direction as charging voltage.
How does this affect your arduino? Well, it can be anything ranging from harmless to catastrophic. It may simply reset your arduino (as one I was working with did on a past project [where an occiliscope showed back EMF spikes in excess of -30V]) or it might straight-up burn the ATMega328p that acts as the Uno's brain. Or it might take out the voltage regulator, or cause a host of other problems.
The simplest fix for back EMF is to put a diode in parallel with the relay with cathode to your positive terminal and anode to your negetive terminal. This creates a short for the relay's coil to discharge through. Some better solutions (especially for sensitive digital equiptment) involve entirely isolating the relay's power supply form the rest of your circuit with an optoisolator.
Problem 1: Assuming that these problems were related to the use of a relay without the proper safeguards, you might try a few things to verify your chip is still alive. If  you have a second arduino you might try using it to build an ISP, which will allow you to both reburn the bootloader and upload sketches independently of the uno's onboard usb com port programmer. If that works but the onboard programmer still does not, you may need to reflash the programmer (which I've read can also be done with an ISP, though I've never tried it.)
Hope that helps!

Thank very much your answer relay very useful i well try to build an ISP and tell what happened if you have no problem .

Sorry but what happened when ISP doesn't work ?

If ISP isn't working (double check your ISP hookup circuit because it is easy to mess up--I've done that myself a few times) then its time to look at replacing the ATMega328p chip. If you have one of the boards with DIP chip, this is as simple as pulling out the old one and dropping in a new one. If you have the smd version, you'll have to re solder it.
You might also, if you have multimeter handy, probe the different parts of the power system and make sure that that is all working okay before you go thru the hassle of getting a new ATMega328p.


text:
Powering 3.3V Arduino and 12V peripherals from single 12V power supply?
Given:

I have some home alarm peripherals (motion detectors, glass break sensors) which operate at 12V and draw a nominal current of 20mA when in alarm state.
I have a Particle Photon (3.3V logic level) which will accept up to 5.6V on its VIN pin.
I have a 12V @ 2A switching power supply.

Can someone describe to me an efficient circuit which would allow me to power all of the peripherals @ 12V and the Arduino (Particle Photon) at 3.3ishV?
I have on hand an LM7805 linear regulator, which I believe will work, but will be inefficient. I also have on hand a DC-DC step down converter (4.5V-28V IN, 0.8V-20V OUT @ 2A) but I am a novice and don't know how to use it for the scenario described here.

"I am a novice and don't know how to use it for the scenario described here." - Put 12V on the IN, connect the OUT to a volt meter, twiddle the knob till it reads 5V. Disconnect the volt meter. Connect it to the VIN of your photon.

You could use the arduino's built in regulator, no?

How inefficient will the 7805 be, in the big picture? Depends on the current draw. How much current will be drawn?

@Dampmaskin For the 3.3V Arduino (Photon) current draw will not exceed 500mA. For the 4x 12V peripherals, if all were in an "alarm" state simultaneously, current draw will not exceed 110mA.

Ok, dropping 8.7V at 500mA wastes 4.35W so OK you're right, that is inefficient. A buck converter is probably the best approach  then.

Not just inefficient, but remember that the dissipated power has to go somewhere.  7805s are generally designed (physically) to handle 1 Amp of throughput, though some can handle 1.2-1.5..  If you start dissipating such large amounts of current it will generate heat and require ever-larger heat sinks.  Yes, a voltage converter is the way to go instead.  If you use a screw-terminal barrier block you can have both 12V and your lower voltages available at the same time.


text:
Question about include statements and details in Arduino.h file from core library
This is more of a C/C++ question. However the files I am asking about are a part of the Arduino library.
In /arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/Arduino.h :
#ifndef Arduino_h
#define Arduino_h

#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>

#include <avr/pgmspace.h>
#include <avr/io.h>
#include <avr/interrupt.h>

#include "binary.h"

#ifdef __cplusplus
extern "C"{
#endif

How are these blocks found at compile time in the main sketch?
#include <avr/pgmspace.h>
#include <avr/io.h>
#include <avr/interrupt.h>

Does #include <avr/somelibrary.h> mean that this is a standard library from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc compiler?
One last question, how can there be an Arduino.h without an Arduino.c? I searched through the project but could not find an Arduino.c. All of these are probably stupid questions, as I am in the process of learning C/C++. I am completely new to it.

why the two down-votes on this recently? And 3 months later...

Does #include <avr/somelibrary.h> mean that this is a standard library from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc compiler?

No. It simply means that the compiler should check both its built-in include paths as well as any passed via the -I command line option (or its local equivalent) for a file called "avr/somelibrary.h". That AVR GCC knows where AVR Libc is located is incidental.

One last question, how can there be an Arduino.h without an Arduino.c?

There is no obligation to match each header file with a .c/.cc/.cpp file, or vice versa.

So the function signatures within Arduino.h are defined by the libraries referenced, via the include statements shown in OP?

The headers referenced, yes.

Suppose there is an include in an include, so to speak. Would the header file pick up functions to the second level?

Does avr/someLibrary.h mean to that someLibrary.h is contained in a directory called avr?

@skywalker: That is correct.

Maybe there is no obligation to match a header file with a .c/.cc/.cpp file, but the functions have to exist somewhere when you call them

I think after all this time, you may found the answers for your question.
But to add some information to this topic incase if anyone opened this question.

Does #include  mean that this is a standard library
  from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc
  compiler?

Yes, what is included with avr/ is related to avr standard libraries, which is also found in avr standard compilers.

One last question, how can there be an Arduino.h without an Arduino.c?

Because, as Mr @Ignacio Vazquez-Abrams answered that there's no obligation for connecting the header file for anything else. You can write multiple header files and use them for one source file.


text:
i2c slave write to ARM powered device master
I want to communicate to an ARM microprocessor via I2C protocol (Multitech mDot, which uses Mbed platform). I successfully receive data from it (and got it displayed on Arduino's serial monitor), but when I want to send data from the Arduino I don't receive nothing on the other end. This is my sketch:

#include <DHT.h>
#include <Wire.h>

// Sensor temperatura, humedad DHT11 (test).
#define DHTPIN 10
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// Comunicacion i2c con nodo lora. 7bitaddress 010 1001 (r/w)
#define SLAVE_ADDRESS 0x29

// Variables globales de sensores
float h;
float t;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveEvent);
  dht.begin();
  Serial.begin(9600);
}

void loop() {
  delay(5000);
  h = dht.readHumidity();
  t = dht.readTemperature();

  // Comprobamos si ha habido algún error en la lectura
  if (isnan(h) || isnan(t)) {
    Serial.println("Error obteniendo los datos del sensor DHT11");
    return;
  }

  Serial.print("Humedad: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperatura: ");
  Serial.print(t);
  Serial.println(" *C ");

  Wire.onReceive(receiveEvent);
}

// Total de bytes del arreglo de datos a transmitir: 28 bytes.
void receiveEvent(int howMany) {
  Serial.print("Mensaje recibido por i2c desde MDOT LoRa Node: ");
  while (Wire.available() > 0) {
    Serial.print(char(Wire.read()));
  }
  Serial.println();
  char enviar = "Cacatua";
  Wire.write(enviar);
  return;
}

I wanted to know if this schematic is correct and if the wire write as it is written is performed. If so, I will need to see what is wrong with the code on my ARM device.

Are you requesting the data from the Arduino slave in your master code?

For sure I am, according to the documentation https://os.mbed.com/docs/mbed-os/v5.12/apis/i2c.html I'm performing an i2c.read(addr, pointer, length); but I am not getting any fetched data that's why I wanted to know if the sketch was ok so that I needed to check on what's going on with the way I'm handling the read instruction on the ARM device

You can implement an onRequest callback function and trigger an LED there, so that you can check, if the request is actually reaching the Arduino

I did it, and indeed I get a request notification. And to my surprise, if I perform a write in there the message is sent! Thanks dude! Post it as an answer and I vote it. Thanks again!

It is important to understand, that Wire.write() will not actually send data over the I2C bus. It will only put the data bytes into the send buffer of the library.
The normal way of the Wire library to send data as a slave is to implement the onRequest callback function. It will be called from an I2C ISR when a master on the I2C bus requests data from this slave. In the callback, you use Wire.write() to fill the buffer with data, which then get's send out to the master.
I'm not quite sure about the following: My guess regarding your previous code is, that the Wire library clears the send buffer at some time during the send or read code. That would mean, that the data written in the onReceive callback will simply be lost, instead of used for transmission of requested data. That might be meant that way, so that the users will stick to implementing the onRequest callback, which is the correct way of doing it.

Note: In your code, you call Wire.onReceive(receiveEvent) on every void loop() iteration. That isn't necessary. The Wire.onReceive() method only set's a function pointer to the callback function. It does NOT execute this callback function, which only will be called by the corresponding I2C ISR, when data is actually received. You should use this line only once in setup() to setup the callback function. Though using it multiple times does not break things here. It's just useless.


text:
Problem using an array inside a switch statement
I am having a problem when using a switch statement to check for something inside an array. I am using an int as my switch, then I compare the character arrays using strstr. So it reads like this:

void function(char *buffer, uint32_t size){
  char *p=(char*)malloc(compareSize); //compareSize is the size of the text to be compared
  #define TXTCOMPARE1 (char*)"Sample Text 1"
  #define TXTCOMPARE2 (char*)"Sample Text 2"
  #define TXTCOMPARE3 (char*)"Sample Text 3"
  switch(intCompare){
    case COMPARE1 :
      p = strstr(buffer,TXTCOMPARE1); break;
    case COMPARE2 :
      p = strstr(buffer,TXTCOMPARE2); break;
    case COMPARE3 :
      p = strstr(buffer,TXTCOMPARE3); break;
  }
  if(p!=NULL) { Serial.println("Success!"); }
  else { Serial.println("No match"); }
    memset(&p,0,sizeof(p);
}

This method does not work and p is always NULL. However, when I write it out without the switch() it compares just fine:
//using the same p declaration as above
p = strstr(buffer,TXTCOMPARE1);
if(p != NULL) { Serial.print("Success:"); }
else { Serial.print("No Match"); }

Why would the switch statement give me different results for what is basically the same function call?
Edit: Actually it seems to break everywhere when I set more than one call to p = strstr(...). When there is only one strstr it works, when two or more are used, it does not...

Have you defined COMPARE1, COMPARE2 and COMPARE3 ? Where is your value assigning statement for intCompare ?

Yes, I appologize for leaving that out. But that is almost exactly what I'm doing, except that intCompare is being passed into function(char *buffer, uint32_t size, int intCompare). But when I have multiple cases, p is always NULL

I don't understand three things in this code: 1) Why are you doing a malloc() into p, and then overwriting p before doing a free()? That is not what strstr() needs to work. 2) Why do the TXTCOMPARE strings have (char *) before them? This shouldn't be necessary. 3) Why are you doing a memset(&p,0,sizeof(p));? This is an extraordinarily long-winded way of saying p = NULL; - and then p goes out of scope anyway...

Thanks @JohnBurger. 1) I'm trying to put in an expected size for p from the comparison text I am expecting. 2) The compiler was giving me warnings for converting the strings into char* when defining them, so I cast them as char*. Is there a better way to do this? 3)I thought I was trying to clear the p pointer.

One big problem is that you forgot the break statements for those cases.  So if it compares in the first one and finds it, you'll still get null because it is going to go look for the third one afterwards.

I solved this problem, there were a few problems with the code that I found, so thanks for your comments.
Basically, it lies in the #define# statements.
First, in Arduino it's not such great practice to use #define for strings/chars, only for int. This is because the compiler applies the text every time they appear in the code, so it uses up a lot more memory. The problem here is solved by using
static char TXTCOMPARE1 = {"Sample Text 1"};
Another problem was that there was no NULL terminated character at the end of the #define statement, so the program kept looking to the end of the stack when using strstr() and finding no termination, I think I was just getting lucky that it worked occasionally at all.
Furthermore, there is no need to clear p using memset. It needs to be declared as NULL and then reset after the switch by
if(p){p = NULL;}.
And now it works!

Good that you found it - and thank you for the caution about #define and strings. Note that you should have used static const char TXTCOMPARE1[] = "Sample Text 1";, and also that if (p) { p =NULL; } wastes an if. Just do p = NULL; - it's smaller and faster. Oh, and completely unnecessary. p is about to disappear anyway when it goes out of scope: no need to zero it out.

Another problem was that there was no NULL terminated character at the end of the #define statement - that's not true. It's hard to tell from your snippet but a #define just does a textual replacement.

There is no need to malloc memory for p, just declare it as a char *p = NULL; strstr then returns a pointer to the existing strings. All the malloc line is doing is leaking memory.


text:
LCD5110 - How to make Direct Draw via 2D-array of boolean?
How to draw 2D-array directly on LCD 5110 (PCD8544)?
I have tried libraries like AdaFruit and several others.
But I need draw there via pixel 2D-array, something like this:
bool picture[48][84] = {
 {0,1,0,0, ... to 84 elements},
 {1,0,1,0,0, ...},
 ... to 48 elements
};

I haven't used charset table or geometry figures drawing library functions. Simplest and smallest drawing by pixel - 0 - not draw, 1 - draw pixel.
The "picture bitmap" will generate on the mini-pc board via Python and send to Arduino, which will draw it as "video card".
What is the simplest way to draw pixel in any site of the display without using powerful libraries?
Something about this:
// Send boolean bitmap 48x84 to LCD 5110
// Rows
for (int i=0; i<48; i++) {
 // Columns
 for (int j=0; j<84; j++) {
  // PIN 5 is Din on the 5110 module
  digitalWrite(5, picture[i][j]);
 }
}

Have you successfully drawn anything on the display? Could you post the code you used to do that, please?

No problem with this. Please see the Cosa PCD8544 driver for inspiration; https://github.com/mikaelpatel/Cosa/blob/master/libraries/PCD8544/PCD8544.cpp#L150 and example sketch https://github.com/mikaelpatel/Cosa/blob/master/libraries/PCD8544/examples/CosaPCD8544temp/CosaPCD8544temp.ino

Hi all!
Thanks for your answers!
Yep, drawing geometry and texts is OK.
I think, I need use symbol-sites 8x8 pixels as "small displays" and send there fragments of picture / count of symbol-sites. It like small 506-bytes one-dimension array, not 4096 pixels matrix.

For a start the Arduino Uno is incapable of storing that array in RAM. You're using twice as much memory for that array as the Arduino has in total. You will have to place it in PROGMEM and use the right functions to access it.
Secondly, you have to use a special library to control the display properly. That library will contain functions to draw on the screen. So your function to draw it would look something (though not exactly) like this:
const bool picture[] PROGMEM = {
    1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,
    ... etc ... ... 4032 numbers in total ...
};

for (int i=0; i<48; i++) {
    for (int j=0; j<84; j++) {
        lcd.setPixel(j, i, pgm_read_byte_near(picture + (i * 84 + j));
    }
}

Refer to the manual for the library for the actual function to run and how to configure and set up the LCD screen.

bool seems like a waste of memory. And the device has byte level transfer to the display memory. The memory requirements for an off-screen bitmap is only 48*84/8 = 504 bytes.

// PIN 5 is Din on the 5110 module
digitalWrite(5, picture[i][j]);

with that kind of code, I would suggest that you spend a little bit more time on understanding the libraries you are trying to use, or the datasheet if you aren't using any libraries and ask more directed questions.
embedded engineering is one that ties software with hardware and it is not possible for you to understand software without understanding, very well, the hardware first.


text:
Mac shortcut for next window - IDE 1.8.7 problem
How do I use the keyboard to cycle through Arduino windows on a mac?
In my System preferences, I have (default):
Keyboard -> Shortcuts -> Move focus to next window =  Cmd ⌘   `
It works perfectly in all other programs, but in the Arduino IDE, it only swaps between the last two windows. If I have three(or more) windows open, it is a real pain to find the one in the background.
I am using fully updated MacOS 10.14 and Arduino IDE 1.8.7

That shortcut works for me. Which version of the IDE and OSX are you using?

@VE7JRO: See edit. Have you tried to cycle through three or more windows?

Yes, I am able to cycle through 3 or more windows. I am using an old version of OSX and an old version the IDE.

@VE7JRO: Thank you for your help. I now found that by adding shift (normally used for reverse cycle), I can get all windows.

In MacOS 10.14 and Arduino IDE 1.6.12, cmd` cycles through 5+ IDE windows properly, for me.
Update:

When you upgrade to Arduino 1.8.7,

I won't be. I've tried a couple of its point releases and have given up on it because its launch performance is so p...-poor. Maybe 1.9 will finally fix it.
Sloeber/Eclipse is my serious code-crunching IDE. I keep the A-IDE around for reference and for quick knock-off experiments because it's quick to launch.
Update 2:
The OP asked me to note that he

found that  Cmd ⌘   Shift   `  cycles
  through all windows (maybe in reverse).

Update 3:

In older IDE the reverse cycling with Shift doesn't work?

It works in both directions for me (shifted/unshifted).

My comment is gone. I did not delete it myself - I have no idea what is happening. Could you add the workaround for IDE 1.8.7 - for completeness?

In older IDE the reverse cycling with Shift doesn't work?

Just by trying, I found that  Cmd ⌘   Shift   `  cycles through all windows (maybe in reverse).

So cmd doesn't work on current IDE but cmd shift does? Shift should only change direction.

@Juraj: I do not know why you find it hard to understand, or why you reject a well meant edit. JRoberts and I found the same thing: in the new IDE 1.8.7 cmd+ does not work(as expected) while cmd+shift+ does. Now JRobert has made the change, that collects and completes the answer.

JRobert has only old IDE, he can't confirm your problem with new IDE, where according to you only the reverse cycling works as expected. (you should add the update about reverse cycling to the question)

@Juraj: I can not figure out if you are trolling. Please go ahead and change what you want - I will not be spending more time on this.


text:
Weird text when pressing a certain touch button
I have written a code that remaps the 16-Key touch keypad. When 2 key is pressed, it writes weird characters in the serial monitor even on my 16x2 LCD

But the other keys work fine.
Here's the code:
#define SCL_PIN 11
#define SDO_PIN 12

struct keymap {
    int     kCode;
    String  kValue;
  };

keymap keys[] = {
  {1, "1"},
  {2, "2"},
  {3, "3"},
  {5, "4"},
  {6, "5"},
  {7, "6"},
  {9, "7"},
  {10,"8"},
  {11,"9"},
  {14,"0"},
  {13,"CLEAR"},
  {15,"ENTER"}
  };

void setup()
{
  Serial.begin(9600);
  pinMode(SCL_PIN, OUTPUT);
  pinMode(SDO_PIN, INPUT);
}

void loop() {
  int Key = Read_Keypad();

  if (Key != 0) {
    for (int x = 0; x < 16; x++) {
      if (Key == keys[x].kCode) {
        Serial.println(keys[x].kValue);
      }
    }

    delay(300);
  }
}

byte Read_Keypad(void)
{
  byte Count;
  byte Key_State = 0;

  for (Count = 1; Count <= 16; Count++)
  {
    digitalWrite(SCL_PIN, LOW);
    if (!digitalRead(SDO_PIN))
      Key_State = Count;
    digitalWrite(SCL_PIN, HIGH);
  }
  return Key_State;
}

It seems by changing 16 to 12 on
for (int x = 0; x < 12; x++) {
      if (Key == keys[x].kCode) {
        lcd.print(keys[x].kValue);
      }
}

fixed it.

You might want to explicitly explain why this fix worked, in case it might help others.
Your keymap array had only 12 elements, and your loop was examining undefined memory beyond the bounds of the keymap array when it was accessing elements 12-15.
I think that the trigger on kepress of "2" was coincidence due to the undefined nature of the memory values you were checking every time through the loop.


text:
How many modules can an Arduino Nano v3 support (in code)?
I'm planning to use an Arduino Nano v3 for a simple project plus some devices like capacitive touch buttons, an LCD display and a Bluetooth module on an I²C. Will these devices require (like classes or function in programming) that might take up the entirety of the 30KB space?
Devices:
HC-SR04 Distance Sensor
TTP229 Capacitive touch sensor
LCD1602+HD44780 LCD Display
HC-06 Bluetooth module

Please edit question and specify model number of LCD and Bluetooth module.  Graphic LCDs use rather more memory than text LCDs.  That aside, without details about the application, the question isn't particularly answerable.

The number of modules isn't really relevant; your PC deals with that during compilation and linking. The unbreakable requirement is that the total size of all the modules not exceed the size of available Flash memory.
The Bluetooth module won't need a library module unless you use SoftwareSerial to make another port for it. The two sensors' library footprints won't be too big. The LCD probably has at least one character table and maybe several sizes of each of several fonts. That's likely to be your largest one.
I always find microcontrollers' RAM size to impose much more stringent requirements than their Flash sizes.

The devices will require some code to make them work and there is a chance, depending on how you write the code, that this may consume all the available RAM on the chip.  However I doubt you will go to more than 60% if you use the standard libraries for those devices, but there is only one way to find out...
Get the libraries for the devices and look at the examples for each device.  You should be able to hack an "example" of your own that calls all 4 examples in the main loop().  This should give you an idea of how much memory you are going to use.
If you use too much it might be possible to snip pieces away from the libraries, the LCD will probably have font tables that you don't need for instance.  Or you could use an alternative Arduino.

If that so, I mignt refactor the library. Had an rpi but it consume alot more power.

I doubt you will need to.


text:
Reading Serial Data Using readBytes() and Use of Serial.read()
I'm trying to mix Serial.read() and Serial.readBytes() when reading over one of the Serial ports on my Arduino Due.
I thought that using Serial.read() would clear what is on the serial, and then subsequent reads by readBytes() would not pick up what has already been read by the Serial.
The main reason I'm trying this approach is because large Serial reads can be unstable using the Arduino supplied Serial.read() - I've checked the Serial buffer with a logic analyzer, so I know that the data is on the Serial line, but Serial.read() drops some bytes.
Hence why I want to use Serial.readBytes().
Here's what I'm doing:

#define FIXED_LENGTH 10
char * buffer, * bp;
int index, i, bufSize;
while(1)
  {
  if(Serial3.available())
  {
    data = Serial3.read();
    Serial.print(data,HEX); //Check the data received
    buffer[index]=data;
    index++;

    if(index == FIXED_LENGTH){
       //...code to calculate bufSize from buffer...//
       bp = (char*)calloc(1,bufSize); //calloc bp size
       Serial3.readBytes(bp,bufSize); //read the rest of what's on the serial
       break;
    }
  }
  }

I get the correct output from the first part of the code - that is, it correctly calculates bufSize from buffer. But when I try to store the following length into bp, it gives me more or less the first output that I have already read on the first few passes!
Example:
Data coming in over Serial3.read() [10]: 0123456789
The next characters in Serial3 are [6]: ABCDEF
Stored into bp using Serial3.readBytes() [6]: 000045
Do I need to flush Serial3 before attempting to read the next set of bytes off of it? Do I need to wait/set a timeout before advancing to the next operation?

You did not initialize buffer: you are going to corrupt your memory.

Sorry but your code is full of bugs, its going to blow up in you face.  index needs initialising, you don't check to see if the calloc fails, you don't free the calloc.  I would approach it a different way, use readByte into a static buffer of fixed size, process the data, read again.

You're right, this code would be full of bugs, but it's just a snippet as part of a larger portion of code. Please assume that I am properly initializing buffer and setting up the rest of the variables correctly. My question is dealing with readBytes and reading from the Serial line.

You should probably check out create a minimal working example to enable people to help you.


text:
Since double and float represent the same data type (usually), which is preferable?
It looks like on ATMega based boards, float and double are equivalent 32-bit (4-byte) data types.
However, on the Arduino Due, doubles are 64-bit (8-byte) where floats are 32-bit (4-byte), same as the ATMega boards.
I also saw one source on avr-gcc that listed double as non-standard.
So, when writing code for ATMega based boards are floats preferable to using doubles, since that would make the code equivalent for Due boards? Or are doubles preferable for any reason?

I would use float so that anyone reading my code, who may not know about the non-standard AVR double, knows what precision to expect. But this is more personal preference than a hard rule (hence I do not consider it a “real” answer).

I think that's fairly solid reasoning; one might not expect the 'double' to really be a float if they're coming from another platform.

See avr-gcc

Deviations from the Standard
double
double is only 32 bits wide and implemented in the same way as float

when writing code for ATMega based boards ...

They are the same, therefore.

(Edited to add)

When writing code, is it then preferable to using one over the other?

I don't really understand your question. You asked about writing code for the ATMega based boards. Do you really mean, if you are writing code for the Due? The quick answer would be, on the Due, double takes twice the RAM, however it is over twice as precise - around 7.2 decimal digits for float compared to 15.9 for double. (I'm not sure about the speed, probably double would be slower, unless it is implemented in floating-point hardware - however I cannot see any reference to that on the AT91SAM3X8E datasheet).
See: https://en.wikipedia.org/wiki/Floating_point
If you want more precision (however slower and taking more RAM) then you could use double - which won't make any difference on the ATmega based boards, but will on the Due.

As Edgar Bonet said:

I would use float so that anyone reading my code, who may not know about the non-standard AVR double, knows what precision to expect.

That makes quite a bit of sense.

I warn you though that "preferable" is subjective. It is close to asking "what is best"? To which the reply is: "best for what?"

On ATMega boards, yes, they are the same. If you then take the code to an Arduino Due, they are no longer the same if using double, but the same if using float. When writing code, is it then preferable to using one over the other? Why or why not?

See amended reply.

Well, strictly speaking I'm only targeting ATMega architectures right now, I thought I was writing code that was consistent across all arduinos. I did not ask which was best, though I think I'm answering my own question in that float is more well known, a better cross-architecture description of the datatype, and consistent across more arduinos.

Would it make more sense if I added "When writing Arduino code for an unknown board, is it then preferable to use one over the other?"

I suppose. *shrug* - when dealing with boards which may have limited RAM and Flash, it isn't always possible to code generically.

At the outset of Arduino programming, I thought they were at least attempting to make the code as hardware-agnostic as they could. In this spirit, I think I'll use floats from here on.

This answer is no more up to date with avr-gcc, which suports 64-bit double (and long dounble) since v10.  See for example the avr-gcc wiki page you linked.

@emacsdrivesmenuts Well, yes, but using a configuration option, not the default. In avr-gcc v10 and higher, the layout of double and long double are determined by configure options --with-double= and --with-long-double=, respectively. Bear in mind that using more precise floating point will take longer, so your application would need to choose precision over speed.

And take more memory, which you may not want to take on a processor with limited RAM.

@Nick Gammon: Of course it's about precision, which was not the point of my comment.  Besides that, avr-gcc v10+ supports -mdouble=64.  The only reason to default it to 32 bits was to align with older (not standard-compliant) versions of avr-gcc.

Neither are preferable.
Unless your microcontroller has a hardware floating point unit using float or double results in huge overheads for your program.
So instead use integer mathematics whenever possible.
Instead of working in Volts, work in millivolts, for example.
However, if your MCU does have an FPU, and some modern more powerful ones do, then you should use the size of float or double that is native to the FPU. If it is a 32 bit FPU then use float. If it is a 64 bit FPU then you can use double.

do you have any actual benchmarks of the "huge overheads"? less efficient sure, but I've never really had it be a problem to use floating point on arduino.

int a; void setup() { a = 1; } void loop() { a = a * 2; } uses 482 bytes. Change the int to a float it slmost doubles to 878 bytes. Even worse if you change the 2 to 2.0, while it's int - you end up with 1086 bytes. Massive increases. And that's not even mentioning how long it takes to run. I'll do a crude benchmark.

Multiplying 1 by 2 until it exceeds 32768 (1, 2, 4, 8, 16, etc) with int takes 12 microseconds. Using float it takes 148 microseconds. That's more than ten times longer for just that one simple operation.

Interestingly, multiplying an integer by 2.0 takes even longer - 208 microseconds. 17 times longer.

Fixed point takes more ops than just integer multiply, and we should be comparing 32-bit values on both sides. in a test of float (a*b) and long (a*b/1000), as would be the case if you did operations in mV, floating point is faster. That's not calculating the extra high byte that's necessary for real fixed point, then again fixed point would benefit from an easier divisor. Addition will certainly remain faster in fixed point. I don't think float vs fixed is as clear cut as the arduino SE community makes it out to be.

@BrettAM: When doing fixed point, you would never scale by 1000, always by a power of two. And no, you should not compare at 32 bits: you should compare 32-bit floats vs. fixed point of the smallest size that is precise enough for the job, which will often be 16 bits, and sometimes even 8. I've done a 16-bit fixed-point implementation of cos() and sin() that is 15.7 times faster than the standard <math.h> functions.

@EdgarBonet I mentioned that the divisor is bad, its taken from the answer that suggested it. A 6.10 fixed point multiplication results in a 12.20 (32 bit) result; so unless their numbers fit in 8 the multiplication would need to take place in 32 bits. The overhead of writing a custom fixed point cos() (or even downloading one) is much greater than having a few slow trig functions for most applications here on arduino SE.

@BrettAM: The answer did not suggest a division, it suggested using millivolts, which is not the same. Typically you would either analogRead(pin) * 39U >> 3 or analogRead(pin) * 1250UL >> 8, depending on the required precision. And you do not need to multiply in 32 bits: you can do a 16×16→16 multiply in assembly, or use the _Fract or _Accum data types. But then I agree that many projects have enough CPU cycles to spare to make fixed point irrelevant.


text:
SdFat: Why does the first write to the file take so long?
I have tested this problem on 6 micro-SDHC cards of 3 different types. 3 are 32-GB Sandisk, 2 are 16-GB Kingston, and 1 is 16-GB Samsung. These cards are used in data loggers and typically contain hundreds or thousands of 5-MB text files whose names are formatted like FILE1234.TXT.
The problem is that when a logger containing such a card (containing data) is started, the first write takes a long time--from 7 to 30 seconds. Opening the file (the smallest available filename) doesn't take too long. Subsequent writes don't take long. Just the first write.
Now, the plot thickens: this delay can be eliminated by first opening FILE0000.TXT and immediately closing it. Further, once this is done, that disk is never affected by this delay again. This has happened with each of the disks.
Here is some minimal code demonstrating the issue:

#include <SdFat.h>
SdFat sd;
SdFile file;

void setup(){
  Serial.begin(57600);
  sd.begin();
  int m = millis(); // just to time everything

  // critical line that prevents delays
  file.open("FILE0000.TXT", O_WRITE | O_TRUNC | O_CREAT); file.close();

  // file we actually want to write to
  file.open("FILE6005.TXT", O_WRITE | O_TRUNC | O_CREAT);
  Serial.println(millis()-m); // print how long it took to open

  file.println(F("test"));
  Serial.println(millis()-m); // print how long it took to write
  file.close();
}
void loop(){
}

When the "critical line" in the code is commented out, I get a big delay in the first write to the file. When it's uncommented, there's no delay, and I never get a delay on that disk again even with the line commented. I saw this on all six disks.
One further bit of mystery: at first, this did not work on one of the cards. I checked and found that this card alone had a hidden ".Trash-1000" directory. I removed that directory and tried again, and this fix did work that time.
Does anyone have any idea what's going on here?

That's really interesting, I'd like to know what exactly is going on too.

Sounds like the SD-FAT library is loading the directory structure, File-Allocation tables, building it's 'representation' of the SD cards usage/layout.  Do you experience the delay during the FILE0000.TXT opening?  The .Trash-1000 subdir likely triggered a full scan of the directory layout as SD-FAT looked for FILExxxx.TXT.  Remember you're on a memory constrained device, and the SD-FAT library must keep it's memory usage minimal, so blocks/sectors are repeatedly read and dumped instead of being cached as is done on (much) larger memory systems. This will slow access dramatically.

You would probably get a huge speed increase by splitting your files into directories, such as 3/6/FILE3672.TXT

Most file systems exhibit poor performance if you store many files in one directory. 'Normal' desktop computers are perhaps so fast, that you don't notice the performance impact, but accessing the file system from a relatively slow micro-controller, which also have limited means of caching the file system data structures in RAM, you may have to consider for this and either write a smaller number of files or build a tree of directories, so that you only have a limited number of files in each directory.

Why to change the file structure if, as stated in the question, the delay can be eliminated with just one line of the code?

I have observed this as well, but with bare-metal programming rather than arduino. I use an STM32F7 chip to write to a class 10 SD card using block writes from the SD card standard. I use a custom file system rather than FAT. My first write to the SD card takes roughly 8-10 times longer than all of my other writes. This is each time I remove power and resupply power to the device. This doesn't happen if I reset the processor without removing the power supply. If I only reset the processor (which means I reconfigure and initialize the SD card) this write delay doesn't happen.
The only thing that doesn't happen to the SD card before the first write is the configuration of the data path state machine (DPSM). Could the DPSM being in a state that isn't conducive to writing on start-up be the culprit?

authors: محمد مثنى رحمان ابراهيم