text:
Gratuitious instantiation of `Serial`, why?
Let's take a very simple sketch, any simple one-.ino sketch. Say, just a led blinker like this

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop()
{
  static bool on;
  digitalWrite(LED_BUILTIN, (on = !on) ? HIGH : LOW);
  delay(1000);
}

Once compiled in Arduino IDE, compiler reports using 10 bytes for global variables. This is perfect for our purposes.
Now let's add an extra .cpp file to it. Let's call it foo.cpp. The file looks like follows
#include <Arduino.h>

int foo()
{
  return Serial.available();
}

Compile it all together. Now the compiler reports using 185 bytes for globals. But why?!
Clearly, this extra global memory usage is Serial. It is brought in by the fact that global object Serial is referenced from foo. In the original sketch Serial is not instantiated (or discarded) by the linker as an unreferenced symbol. In this case it is referenced from foo, so the linker keeps it.
But... But GCC linker is usually smarter than this. I'd expect it to see that symbol foo is not referenced anywhere, so the reference to Serial inside foo also "doesn't count" and should not require an instance of Serial in final code.
In fact, if I tried using my own "heavy" class, my own global variable of that class and reference it in foo (instead of Serial), GCC would work as expected: regardless of how "heavy" my global variable is, GCC linker would discard my global variable from the final code and report the same 10 bytes for globals, as expected. The global memory usage would remain at 10 until I'd actually reference foo from somewhere.
But Serial is somehow special. Even an "unused" mention of Serial causes it to appear in global memory. What is so special about it? What makes it behave that way?

I am sure there is some volatile in the implementation of Serial

@Juraj: What specific occurrence of volatile do you have in mind? The compiler is supposed to preserve each occurrence of volatile access. But if the function is never called, there's no access to preserve. If Serial makes volatile access in its constructor, then it should always be preserved, regardless of whether the client code uses Serial or not. This is not the behavior we are observing.

Did you check the command line for compiler and linker? There might be some option that stops the linker from discarding. And did you look into the object files to see what uses the space? objdump is a big help here.

at linking HardwareSerial.o is in an .a archive. if it would by a single .o on linker command line it would be always linked. if it is in .a it is linked only if it is required. this is not an answer, only a lead. I don't know how 'required' is determined

My guess (though I didn't check) is that it is a side effect of the fact
that the same file contains the instantiation of Serial and the
associated ISRs. The definition of the ISR macro looks roughly
like this (slightly simplified):
#define ISR(vector) extern "C" \
    void __attribute__((signal, used, externally_visible)) vector(void)

The key here is the “used” attribute. It tells the compiler that the
symbol should be considered to be used, even though no code calls the
ISR (for a good reason: it's called by the hardware).
When your program is linked, the object file foo.o pulls in
HardwareSerial0.o. The linker then sees the serial ISRs which are
labeled as “used”. These in turn make use of the Serial object which
then appears to also be used.

In my original program, foo.cpp is actually a part of my Arduino library. AFAIK, during Arduino build process libraries are compiled and archived into genuine static libraries. And then object files are pulled out of them only if they are needed (per standard ln behavior). So, in my example foo.o should not get pulled out of the library and therefore should not pull HardwareSerial0.o with it. However, the strange behavior still persists: once the library is used by a sketch, Serial immediately grabs a chunk of memory.

@AnT, has your library dot_a_linkage in library.properties? without it it .o files are put on linker command line

@Juraj: No, it did not have that. And this actually solves the problem immediately.

I compiled the examples with the microCore/attiny13 which has a different Serial implementation there the compiler behaves as expected.
So reducing in HardwareSerial.h the
 #define SERIAL_RX_BUFFER_SIZE 64

 to

#define SERIAL_RX_BUFFER_SIZE 0

does exactly 121 bytes used (which is 185-64) the same for
 #define SERIAL_TX_BUFFER_SIZE 64

 to

#define SERIAL_TX_BUFFER_SIZE 0

gives 57 bytes (121-64). This is used by Stream protected:
unsigned char _rx_buffer[SERIAL_RX_BUFFER_SIZE];
unsigned char _tx_buffer[SERIAL_TX_BUFFER_SIZE];

I did not go through all the used libs to find the rest, but I guess its the global defines (buffers) for the global object Serial. The microCore lib has all buffers set to 0 so thats how I found it.


text:
How can I hook up multiple MMA8451 accelerometers, (I2C protocol) using one Arduino Mega?
How can I hook up four (adafruit) MMA8451 accelerometers (using I2C protocol) using one Arduino Mega? What I'm confused about is I only have one SDA and SCL on the Arduino Mega obviously. So how can I connect these all? Multiplexer? I need four because I have one on each leg of a robot. Or is perhaps this impractical to put an accelerometer on each leg of robot? I'm a little new to electronics so please explain in depth if you could. Thanks.
Note to moderators: I just would really love an answer to this even if this doesn't meet the super strict question guidelines. It seems every time I post here there's always that one person who takes it down for any number of trivial reasons. Please let me get an answer at least. Thank you!

Looking at the datasheet for the MMA8451Q, factory default it has two distinct I2C addresses 0x1C and 0x1D, selectable with the SA0 pin, but if you want more to share a bus, they can factory program other IDs, so you could share 4 on one bus if you could buy a couple non-default chips.  Otherwise you need two busses to differentiate 4 chips.

Brief explanation: When you talk to the slave device through I2C you start with (slave) device address. Then you send the message. It is like calling your colleague in an office with many other people. You say: "John", and when he is aware you continue with message, like "let's go for coffee".
This arrangement allows for adding up to 127 devices on one I2C bus. Each device must have different address (sorry, you cannot have two John's in the office, it will cause conflict). Generally two different type of devices will have different I2C addresses, but it may happen you need to use two (or more) of the same (like in your example). In this case, see below.
Many devices with I2C interface allows for address change. Using this facility you are able to communicate with many of the same devices through the same pair of cables.
You can check if your chosen accelerometer has possibility for address change: On picture below there is one with Address tab. When jumper is not fitted, you will get one address, when is fitted, the address of this device will be different, allowing of two of this accelerometers on one I2C bus. Unfortunately in this example there will be possibility of maximum of two of the same devices.

Of course there are devices with more than two possible addresses, you need to search for them.
And, yes, it is fine to use one Arduino to communicate with many I2C devices.
EDIT:
Looking after some of Adafruit accelerometers, I have found this page: https://learn.adafruit.com/i2c-addresses
And small off topic note: If you struggling on finding I2C with more than 2 addresses, check if it is easier to use SPI protocol. In this case you need (edited to correct bus lines names after user CrossRoads comment) MISO, MOSI, SCK and CS (chip select) wires. Chip select is individually connected to each slave device. This allows selecting particular device without addressing issue.

SPI would also be faster to query all the devices.  SPI uses SCK, MISO, MOSI and a unique chip select per device. Communication with a Mega can be at up 8 MHz clock rate, 20 times faster than the 400 KHz of I2C.

Talking about I2C protocol. The slave Address is of 7 Bits that means one I2c can handle 127 Slave I2C devices of different address. So you can connect 127 devices with Single I2C Port just make sure there slave address is different from each other.
Some I2C devices are provided with the option to select salve address by setting some pins high and low. If you are using some identical sensors you are set their slave address different.

The general technique for addressing multiple I2C devices is:

If the device(s) have only one address: use an I2C bus multiplexer.
If the device(s) have two addresses controlled by an addressing pin: use digital output pins from the Arduino to select which device to address, e.g., set the control pin for the selected device low and others high and use the corresponding address to address the device.

With MMA8451Q, factory default it has two distinct I2C addresses 0x1C and 0x1D, controlled by the SA0 pin, use digital output pins on the Arduino Mega to address the selected device (address 0x1C) by setting the corresponding output pin low for the selected device and the control pin for the others to high (address 0x1D). Use address 0x1C to interact with the selected device.
Cheers!

Simple just connect all SCK and SDL accelerometer lines together and then u just need to get a specific code address in your use to get a data from any of the accelerometers

source: Stack Exchange

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

sort: votes


text:
Cannot POST to server. HTTP code -1. NodeMCU
I am trying to make a POST request with NodeMCU, but I get a HTTP status code -1.
Code:

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

#ifndef STASSID
#define STASSID "Wifi"
#define STAPSK  "123"
#endif

const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "https://laimonasjanutenas.000webhostapp.com/wifidata.php";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.println("trying to post ");

  HTTPClient http;

  http.begin(host);
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");

  int httpCode = http.POST("temp=1337");
  Serial.println(httpCode);
  http.end();
}

Serial monitor outputs this:
connecting to Wifi
........
WiFi connected
trying to post
-1

I can confirm that I can actually make a POST to the server. I tested in Postman using this:
https://laimonasjanutenas.000webhostapp.com/wifidata.php?temp=159

I have no clue what I am doing wrong. Feel free to make POST requests to the this server if needed. Thank you.

what status were you expecting? .... why do you say that you are doing something wrong?

Does it work if you use http instead of https? It looks like extra params are required for https: https://github.com/esp8266/Arduino/issues/1941

Yes it works! I changed the link from https to http and it worked :). Thanks

To elaborate on @ChrisCombs comment, you have work to do if you want to talk HTTPS. Please read : https://forum.arduino.cc/index.php?topic=515541.0

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


text:
WifiEsp client TIMEOUT when put on a loop
Hello I have been using the WifiEsp to send and receive data from Thingspeak.
All is well until I put my http request on the Void Loop() section.
My Goal: I want to receive data every loop not on only on setup.
Here is my code
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <SoftwareSerial.h>
SoftwareSerial Serial1(6, 7); // RX, TX
WiFiEspClient  client;
int status = WL_IDLE_STATUS;

#define SSID "Benok4G"
#define PASS "password"
char reply;
char server[] = "184.106.153.149";

void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial1.begin(9600);
WiFi.init(&Serial1);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(SSID);
// Connect to WPA/WPA2 network
status = WiFi.begin(SSID, PASS);
}
Serial.println("You're connected to the network");

}

void loop() {
Serial.println();
Serial.println("Receiving Data...");
if (client.connect(server, 80)) {
Serial.println("Connected to server");
client.println("GET /channels/344468/fields/3/last?key=ABCDEFGH
HTTP/1.1");
client.println("Host: api.thingspeak.com");
client.println("Connection: close");
client.println();

while (client.available()) {
char c = client.read();
Serial.write(c);
}

if (!client.connected()) {
Serial.println();
Serial.println("Disconnecting from server...");
client.stop();
while(true);
 }
}

I can receive the letter "a" properly. However, I want it too loop and give me updated value every loop.

BUT! when I put the code from the void setup() to the the void loop().
I get this error..

Any ideas on how can I loop it without getting the error? I tried adding delays and putting it on another function, still the same. It will only work when I put in inside the void setup()
Thanks!

@MarkSmith Thank you for pointing that out. I have posted my complete code. The code i posted is when I put the request in the loop and gives the timeout error.

By "this error", do you mean the timeout? It looks to be working regardless... What's the actual problem?

When I put it in the loop.I don't see the picture with OK response. It's just blank and sometimes it returns the one with square. Is this normal?

Could it be that your setup() is taking too long to execute and is timing out?

"Host: api.thingspeak.com"  Some of the free services provided by Thingspeak prohibit multiple consecutive transactions unless there is an intervening  pause of X seconds which could cause the timeout you appear to be experiencing. Check the rules of your subscription.

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


text:
Using ESP8266 Adapter with Temperature/Humidity Sensor
Good Day. I am currently following a project where I can send data to my firebase database using an ESP8266-ESP01 wifi module and DHT11 temp/hum sensor.
I am using this adapter to enter the boot mode already with a program. Everything seems fine.

When I need to upload a program I am just tweaking the adapter using jumper cables to put the GPIO0 to GND and It works fine. My problem now is I have to use the DHT11 Sensor which is supposed to be connected to GPIO2. I tried to go to bootmode so  I connected DHT11(data) directly to the ESP8266(GPIO2) leaving the slot in the adapter empty in which I cant enter the boot mode for some reason.
But when I plug ESP8266(GPIO2) to the adapter slot, I can enter bootmode. Currently confused on how to tweak the adapter to be able to use the GPI02 to the DHT11. Any tips would really help. thanks!

Possible duplicate of NodeMCU does not boot up when GPIO pin is high

it's a little vauge how you're wiring it up, but does it boot with the DHT outside of the adapter?

Please provide information how you're wiring up the DHT to the ESP. Reviewers please hold a bit with the duplicate votes, the question just needs clarification at the moment.

@Avamander The question clearly states he's using GPIO2. GPIO2 is one of the "special boot mode" GPIOs as detailed in the duplicate question. What further clarification can you want?

DHT has four (three different) pins, is he powering it correctly? And would a DHT really pull GPIO2 low for the ESP to not boot properly?

@Avamander: you mean LOW right? regardless, since the data pin uses a PULLUP, i don't see how a DHT11 would prevent normal booting as described, if it's wired correctly.

@dandavis Yes. Fixed.

Thank you everyone for the tips. I have found a way to use the esp8266 adapter with the DHT11 sensor. First of all it was on boot mode all along, I had some code mistakes where my target url includes an 'https' tag on it thus not functioning as expected.
For those who would like to use this specific adapter with DHT11 attached in boot mode.
-Connect all female jumper wires end to the Esp8266 and the male jumper ends to the adapter except for the GPI02.
-The GPI02 slot on the adapter will be empty but the ESP8266 GPI02 end must be connected to the data pin of the DHT11.
Make sure that the ESP8266 and DHT11 sensor have enough power for both devices.

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


text:
Can the Leonardo Arduino be used as a USB HOST for CDC Com devices?
I am trying to connect a CDC communication device to the Leonardo USB port and have communication with it via the TTL com port. Basically I want to echo to the TTL port whatever is transmitted over USB and vice-versa.
ASCII data is transmitted out the USB from the CDC device into the USB port of the Leonardo Aurduino. The Arduino needs to xtransfer this info over to the UART pins D0 (RX) and D1 (TX) that are connected to the UART of another micro-controller. I should be able to test it by connecting an FTDI TTL-RS232 cable and see results and have comms in my terminal program.
I came across this sketch that appears to be basically what I want, but I think the "hosting" portion is not being set up:
void setup() {
  Serial.begin(9600);  // rx/tx pins
  Serial1.begin(9600); // USB port
  Serial1.write("2nd Version");
}

void loop() {
  // copy from virtual serial line to UART and vice-versa
  if (Serial.available()) {
    char c = (char)Serial.read();
    Serial1.write(c);
  }
  if (Serial1.available()) {
    char c = (char)Serial1.read();
    Serial.write(c);
  }
}

What am I missing? Note I am NOT trying to do HID but CDC. Basically I want to eliminate using a PC as a Host device and use the "bridge" between my CDC device and another micro-controller.

Nothing to it really....ASCII data is transmitted out the USB from CDC device into USB Port of the Leonardo Aurduino.  The Aurduino needs to xtransfer this info over to the UART pins D0(RX) and D1(TX)  that is connected to the UART of another microcontroller.  I should be able to test it by connecting an FTDI ttl-RS232 cable and see results and have comms in my terminal program

No, the Leonardo cannot be a USB Host. You may be able to use a USB Host Shield in conjunction with the Leonardo, though I have never tried it and cannot vouch for compatibility with the Leonardo.
USB is a host->device protocol, not a peer-to-peer protocol. You cannot just connect two devices together. Only a USB Host can communicate with a USB device.

No. The Leonardo cannot be a USB Host.


text:
Nested for loop used to evaluate a two dimensional array of integers
I am trying to use a nested for loop to evaluate and change numbers within the two dimensional array. Basically these numbers are minutes, or hours. This function is meant to reset the button controlled numbers when they go above 23 (hours) or above 59 (minutes) and also from going below 0. The two dimensional array that I made also has three arrays that need to be skipped (P1[0], P1[2] and P1[10] because they do not contain any time variables. When I click the buttons and increment the numbers nothing unusual happens they just don't bounce back like they are supposed to.
Here is the two dimensional array:
int P1[][12] = { //0-10
  {0}, //MODE
  {0, 0, 0, 0,}, //TOD variables
  // OnHR, OnMin, OffHr, OffMin
  {0}, //DOW
  {0, 0, 0, 0,},  //Sunday
  {0, 0, 0, 0,},    // OnHR, OnMin, OffHr, OffMin
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},  //Saturday
  {0, 0, 0, 0, 0,} // Temperature variables
  //Sensor, GreaterThan/LessThan, Temp, Buffer, State
};

Here is the for loop that doesn't seem to work:
void HrMinBounce() {
  int i = 0;
  int q = 0;

  for (int i; i < 10; i++) { //iterating down Plug arrays
    for (int q; q < 4; q++) {
      if (i != 0 || i != 2) { //non time arrays
        if (q == 0 || q == 2) { //hours
          if (P1[i][q] > 23) {
            P1[i][q] = 0;
          }
          if (P1[i][q] < 0) {
            P1[i][q] = 23;
          }
        }//End of hours
        if (q == 1 || q == 3) { //minutes
          if (P1[i][q] > 59) {
            P1[i][q] = 0;
          }
          if (P1[i][q] < 0) {
            P1[i][q] = 59;
          }
        }//End of minutes
      }
    }
  }
}

I have 5 of these arrays, so I was hoping to make one loop that could take care of all 5 at once. Here is my previous loop that works but I would have to copy and paste a whole lot to get the result without the extra for loop.
void MinHrLimit() {
  int i = 0;

  for (int i; i < 3; i++) {
    if (i == 0 || i == 2) {
      if (P1[1][i] > 23) {
        P1[1][i] = 0;
      }
      if (P1[1][i] < 0) {
        P1[1][i] = 23;
      }
    }
  }
}

            if(i != 0 || i != 2){ //non time arrays

Let's see.

If i is 0 then that is true (it isn't 2)
If i is 1 then that is true (it isn't 0 or 2)
If i is 2 then that is true (it isn't 0)
If i is 3 then that is true (it isn't 0 or 2)

In fact that expression is always true. You probably want:
            if(i != 0 && i != 2){ //non time arrays

   void MinHrLimit(){
      int i = 0;

      for(int i; i < 3; i++){

You don't need the declaration of i there, because it is redefined in the for loop. In the for loop the variable i has an undefined value. You really want:
   void MinHrLimit(){

      for(int i = 0; i < 3; i++){

a few pointers:
1) your array has unevent number of items. so an array of struct is likely more useful here;
2) use brackets liberally, if you want to be sure of sequence of computation, like:
if ((i == 0) || (i == 2)) {

3) if you are going to use a lot of date / time types, think about unix time_t data type. it simplifies coding considerably, and makes your code much more portable.

I will definitely look into Unix time_t. Thank you!

Your problem here is not in your code. It's in the data structures: you
are doing it the wrong way. Of course, it can work, but not only is
your approach wasteful of RAM, it will also inevitably lead to code that
is difficult to write, to understand, to debug and to maintain.
You should really try hard to make your data structures as clean as
possible. I would argue that clean data is even more important than
clean code. If your data mode is clear and makes sense, then clean code
flows naturally. If your data model is contrived, your code will always
look awkward.
Here is how I would go about structuring your data. First thing: you are
using (hour, minute) pairs to represent times. Thus, here is the obvious
way to put them:
struct Time {
    int8_t hour, minute;
};

Notice the variable type: uint8_t takes only one byte, and it can
represent numbers from −128 to +127. Now, this is the right place to
write a function that clamps the numbers to the allowed values. In C,
this would be a plain function. But since we are writing C++, it makes
more sense to make it a method of the struct. Thus:
struct Time {
    int8_t hour, minute;
    void limit() {
        if (hour > 23)   hour = 0;
        if (hour < 0)    hour = 23;
        if (minute > 59) minute = 0;
        if (minute < 0)  minute = 59;
    }
};

It seems all your times come in pairs, with an “on time” and an “off
time”. So here is a data structure for such a pair:
struct OnOffTime {
    Time on_time, off_time;
    void limit() {
        on_time.limit();
        off_time.limit();
    }
};

I added the convenience method limit(), so you can limit an
OnOffTime rather than having to always explicitly limit moth times.
Then, you have a “mode” variable. A mode is normally represented as an
enum, where each possible mode is given a name. Using names instead of
numbers makes everything clearer. For the temperatures and the day of
week, I would use the type uint8_t, which takes only one byte and can
represent a number from 0 to 255. Then, your 2D array becomes an
instance of this:
struct Settings {
    enum { MODE_FOO, MODE_BAR, MODE_BAZ, MODE_QUX } mode;
    uint8_t doy;
    OnOffTime tod, days[7];
    uint8_t temperatures[5];
};

You can probably find better names for the fields of the struct. And you
should.
So, back to the original problem: how to apply the limit() method to
all the times in all your 5 settings. Here it goes:
const int settings_count = 5;

Settings P[settings_count];

void HrMinBounce()
{
    for (int i = 0; i < settings_count; i++) {
        P[i].tod.limit();
        for (int j = 0; j < 7; j++) {
            P[i].days[j].limit();
        }
    }
}

As you see here, the code is short and easy to understand. This is the
benefit of well though data structures: the code that follows is more
natural.


text:
Multiple devices on SPI
Whenever I use multiple devices on SPI, TFT Screen, and the BME280 breakout board from Adafruit, the Arduino fails to detect the devices.
Code of the screen separately (works)
// include the necessary libraries
#include <SPI.h>
#include <SD.h>
#include <TFT.h>  // Arduino LCD library

// pin definitions
#define sd_cs  7
#define lcd_cs 10
#define dc     9
#define rst    8

// Define screen pins
TFT TFTscreen = TFT(lcd_cs, dc, rst);

//Define variables
char sensorPrintout[4];
char sensorPrintout2[4];

// this variable represents the image to be drawn on screen
PImage logo;

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

  Serial.print("Initializing SD card...");
  if (!SD.begin(sd_cs)) {
    Serial.println("failed!");
    return;
  } else {
    Serial.println("OK!");
  }

  // Start and clear TFT screen
  TFTscreen.begin();
  TFTscreen.background(0, 0, 0);

  // Lookup image on TFT screen
  logo = TFTscreen.loadImage("Logo.bmp");
  if (!logo.isValid()) {
    Serial.println("error while loading Logo.bmp");
  }
  if (logo.isValid() == false) {
    return;
  }

  //Draw logo on the screen
  Serial.println("drawing image");
  TFTscreen.image(logo, 0, 0);

  // Change textcolor to white
  TFTscreen.stroke(255,255,255);

  //Write some text
  TFTscreen.setCursor(0,25);
  TFTscreen.print("Schuif 1: ");
  TFTscreen.setCursor(75,25);
  TFTscreen.print((char)247);
  TFTscreen.print("C");

  //Write some text
  TFTscreen.setCursor(0,50);
  TFTscreen.print("Schuif 2: ");
  TFTscreen.setCursor(75,50);
  TFTscreen.print((char)247);
  TFTscreen.print("C");
}

void loop() {
  // Read value of A0
  int value = analogRead(A0);
  Serial.println(value);
  float voltage = value * (5.0/1023.0);
  Serial.println(voltage);
  String sensorVal = String(analogRead(A0));
  String sensorVal2 = String(voltage);

  // Change sensor value to a character array
  sensorVal.toCharArray(sensorPrintout, 4);
  sensorVal2.toCharArray(sensorPrintout2, 4);

  // Change text color to white
  TFTscreen.stroke(255,255,255);

  // Write value of sensor 1
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout);

  // Write value of sensor 2
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);

  // wait  500ms
  delay(1000);

  // Change text color to black
  TFTscreen.stroke(0,0,0);

  // Write value of sensor 1
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout);

  // Write value of sensor 2
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);
}

Code of the BME280 separately (works)
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 6

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme(BME_CS); // hardware SPI

unsigned long delayTime;

void setup() {
  Serial.begin(9600);
  Serial.println(F("BME280 test"));

  bool status;

  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  status = bme.begin();
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
  Serial.println("-- Default Test --");
  delayTime = 1000;
  Serial.println();
  delay(100); // let sensor boot up
}

void loop() {
  printValues();
  delay(delayTime);
}

void printValues() {
  Serial.print("Temperature = ");
  Serial.print(bme.readTemperature());
  Serial.println(" *C");

  Serial.print("Pressure = ");
  Serial.print(bme.readPressure() / 100.0F);
  Serial.println(" hPa");

  Serial.print("Approx. Altitude = ");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println(" m");

  Serial.print("Humidity = ");
  Serial.print(bme.readHumidity());
  Serial.println(" %");
  Serial.println();
}

Code of the TFT screen with the BME280 (doesn't work)
// include the necessary libraries
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <SPI.h>
#include <SD.h>
#include <TFT.h>   // Arduino LCD library
#include <Wire.h>

// pin definitions
#define bme_cs  6
#define sd_cs   7
#define rst     8
#define dc      9
#define lcd_cs 10
#define mosi   11
#define miso   12
#define sck    13

//var definitions
#define SEALEVELPRESSURE_HPA (1013.25)

//Define hardware SPI connection with BME280
Adafruit_BME280 bme(bme_cs); // hardware SPI

// Define screen pins
TFT TFTscreen = TFT(lcd_cs, dc, rst);

//Define variables
char sensorPrintout1[6];
char sensorPrintout2[6];
unsigned long delayTime;

// this variable represents the image to be drawn on screen
PImage logo;

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

  bool status;

  // Initializing SD card
  Serial.print("Initializing SD card...");
  if (!SD.begin(sd_cs)) {
    Serial.println("failed!");
    //while (1);
  } else {
    Serial.println("OK!");
  }

  //Initializing BME280
  Serial.print("Initializing BME280");
  status = bme.begin();
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  } else {
    Serial.println("BME 280 sensor found");
  }

  // Start and clear TFT screen
  TFTscreen.begin();
  TFTscreen.background(0, 0, 0);

  // Lookup image on TFT screen
  logo = TFTscreen.loadImage("Logo.bmp");
  if (!logo.isValid()) {
    Serial.println("error while loading Logo.bmp");
  }
  if (logo.isValid() == false) {
    return;
  }

  //Draw logo on the screen
  Serial.println("drawing image");
  TFTscreen.image(logo, 0, 0);

  // Change text color to white
  TFTscreen.stroke(255,255,255);

  //Write some text
  TFTscreen.setCursor(0,25);
  TFTscreen.print("temperatuur 1: ");
  TFTscreen.setCursor(100,25);
  TFTscreen.print((char)247);
  TFTscreen.print("C");

  //write some text
  TFTscreen.setCursor(0,50);
  TFTscreen.print("luchtvochtigheid 2: ");
  TFTscreen.setCursor(100,50);
  TFTscreen.print((char)37);
  TFTscreen.print("C");
}

void loop() {
  // Read value of temperature
  int value1 = bme.readTemperature();
  int value2 = bme.readHumidity();
  String sensorVal1 = String(value1);
  String sensorVal2 = String(value2);

  // Change sensor value to a character array
  sensorVal1.toCharArray(sensorPrintout1, 6);
  sensorVal2.toCharArray(sensorPrintout2, 6);

  // Change text color to white
  TFTscreen.stroke(255,255,255);

  // Write value of temperature sensor
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout1);

  // Write value of humidity sensor
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);

  // wait  500ms
  delay(1000);

  // Change text color to black (aka overwrite text)
  TFTscreen.stroke(0,0,0);

  // Write value of temperature sensor
  TFTscreen.setCursor(55,25);
  TFTscreen.print(sensorPrintout1);

  // Write value of humidity sensor
  TFTscreen.setCursor(55,50);
  TFTscreen.print(sensorPrintout2);
}

Now this is the serial output:
Initializing SD card...failed!
Initializing BME280Could not find a valid BME280 sensor, check wiring!

At first it only showed the first line, then it stopped because of the while(1) loop. So I put it in comment to see if the BME initializes on its own.
I also tested the screen+SDcard and the BME280 separately, which worked just fine.
Update
I tried to test the programs with the complete circuit. The program of the TFT screen works fine that way but when I try the program of the BME280 it doesn't work. I have to remove the TFT screen from the breadboard to make it work.
Update 2
After some measurements with the scope I determined that the MOSI is pulled to 0V when I connect the 5V to the TFT screen. I also saw that the MOSI output on the BME280 board is 3.3V instead of 5V.
Could it be that the conflict in voltages is the cause for all my troubles?

And your question is...?

Have you examined the libraries to see if they initialize the SPI hardware in conflicting ways?

@IgnacioVazquez-Abrams i have not how can i fix this

Could you post the Serial output you get?

I will edit the original to add the serial output

It seems that it failed in setup for two out of three devices. It is kind of difficult to figure out whats wrong, it could be conflicts in different libraries, or simply due to wrong wiring. The easier way is to comment out your code and only active one device at a time, to make sure it works before adding another device.

I will add the code of the devices working seperately.

@hcheung both the BME program use the SPI library. so i don't think it's a conflict

Please check my blog post about this issue exactly.
The main idea is that the different SPI components do not respect the chip select and interfere with each other on the SPI bus. The way I solved it was to toggle between the different components using an array of switches- transistors in a way that in any given time only one component is connected to my Arduino (or any other master) through the SPI.
How to use multiple SPI devices with Arduino
While building my SmartHomeDIY project I encountered a problem trying to use multiple SPI devices connected to the same Arduino. Although the SPI bus should support multiple devices at the same time (toggling the Chip-Select line), this does not always work (mostly due to the part using the bus not respecting the chip select or other configuration issues). So after reading for some time and experimenting I came up with the following solution.
The above station is an IR recorder and sransmitter station. It can be set into recording state, which then saves the recorded IR-in data into and SDCard connected over SPI. But when not in recording mode it will listen over the RF24 (also connected via SPI) for commands. Once a command is given it will try to send the IR code request (for example turn TV on). To do that it will again have to move to SDCard mode and read the previously recorded data and retransmit it over the IR out LED.
So to solve this I have connected the SPI lines to couple of transistors/switches, then just CUT the lines of the part not being used at the moment and there for prevent the SPI lines collision.
Attached is the code and hardware layout to do just that.
Note that it does not matter which type of project you have. You can always do the same transistor-switch trick to cut of the problematic SPI lines while using the others.
A special note for the transistor configurations. It will not work if you pass as usually suggested, which means to set a logic level by design at the output of the transistor so that the base will toggle the out voltage (same as an amplifier).
Instead I set the signal to go trough the transistor, which is needed, so testing to select the transistor, which does not affect the actual signal (it will depend on the transistor type, spec and configuration...). So it took me some time to figure out the right transistor values and configuration.
For trial and error I used a logic analyzer with 8 logic lines or an oscilloscope.
I inspected the incoming signal and the outgoing signal to make sure the transistor does not temper with the incoming signal, so everything will continue to work as expected (the transistor is transparent to the actual data).
You could also use this logic multiplexer [8 Channel Logic Level Converter Convert TTL Bi-directional] to do the same job, which I have not tested yet. But I think my way is more fun! :)

Connect the BME280 board by I2C, it cannot be used in a multi-SPI setup. The problem is that the MISO line it not decoupled from the bus if CS is HIGH but constantly pulled HIGH. This will disturb other bus members.

Thank you very much. Is there another solution possible because in my project i need to use 2 BME280 boards. so I2C won't be much of a solution.

most i2c devices will support more than 1 address, usually with a couple of pads on the board, connecting or breaking connections can change the address, so then you would be able to use 2 sensors on i2c

The BME280 supports two I2C slave addresses by tying SDO to either GND or Vddio. If you need to connect more than 2 devices to the same master use an I2C multiplexer as the PCA9547.


text:
Can I improve this code (replacing delays with something else)?
Building upon my previously solved question Ultrasonic Sensor range finder help (Solved).
Is there a better way to make the LED blink than using a delay and stopping all the rest of the code? For example, the LED is set to turn on, then shortly after turn off. Is there a better way to do this?
For example, if the LED is turned on, it then delays the code, which means it has to wait for the delay to be over, turn off, then change its pattern. For example, allow the Arduino to interrupt the blink with a new interval blink, mid blink? I'm sorry if this is confusing, it's tough to explain.
Simply put, is there a better function than delay() that can allow the Arduino to suddenly change the state of the LED while it is waiting on a delay() to finish?
The code I'm working on is this:
#include <NewPing.h>
#define TRIGGER_PIN  15
#define ECHO_PIN     2
#define MAX_DISTANCE 500
int LED1 = 3;
int LED2 = 16;
int LED3 = 9;
int LED4 = 6;

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
}

void loop() {
  delay(50);
  unsigned int uS = sonar.ping_median(10);
  int IN = sonar.convert_in(uS);
  if (IN <= 5) {
    analogWrite(LED4, 255);
    delay(100);
    analogWrite(LED4, 0);
  } else if (IN >= 5 && IN <= 12) {
    analogWrite(LED4, 1);
    delay(200);
    analogWrite(LED4, 0);
  } else if (IN >= 13) {
    analogWrite(LED4, 100);
    delay(300);
    analogWrite(LED4, 0);
  }
}

Look into Timer/Counter interrupts.

There is a standard Ardiono tutorial on this: Blink Without Delay.

You can use millis() to get a timer:
millis() Returns the number of milliseconds since the Arduino board began running the current program.
void loop(){
    if(millis() % 100 == 0){//%(modullo) is the rest of a division. 19%10=9 because10/10 = 1 and the rest is 9
        //you have wait 100 millisecond. When millis()%100 == 0 millis() is a multiple of 100.
    }
}

For your code you can do this:
int LED1 = 3;
int LED1 = 3;
int LED2 = 16;
int LED3 = 9;
int LED4 = 6;

//Ligth on -> 1 light off -> 0
int LED1Stat = 0;
int LED2Stat = 0;
int LED3Stat = 0;
int LED4Stat = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(LED1, OUTPUT);    //every 100 ms
  pinMode(LED2, OUTPUT);    //every 250 ms
  pinMode(LED3, OUTPUT);    //every 500 ms
  pinMode(LED4, OUTPUT);    //every 1000 ms

}

void loop() {
    //for no Delay
    if(millis()%100 = 0){
        LED1Stat = !LED1Stat;
        digitalWrite(LED1, LED1Stat);
    }
    if(millis()%250 = 0){
        LED2Stat = !LLED2Stat;
        digitalWrite(LED2, LED2Stat);
    }
    if(millis()%500 = 0){
        LED3Stat = !LED3Stat;
        digitalWrite(LED3, LED3Stat);
    }
    if(millis()%1000 = 0){
        LED4Stat = !LED4Stat;
        digitalWrite(LED4, LED4Stat);
    }
}

[EDIT]
long prevMillis = 0;
void loop(){
    if(millis()-prevMillis >= 100){
        LED1Stat = !LED1Stat;
        digitalWrite(LED1, LED1Stat);
        prevMillis = millis();
    }
    //...

}

This does not work well if 1) you can't ensure 1 millisecond between calls to loop or 2) you can't for any reason call the loop function once a millisecond or 3) the millis skips one of the milestones (remember that about every 42 milliseconds the millis jumps). Much better to track the time in the usual way (if ((millis() - prevMillis) >= PERIOD) { prevMillis += PERIOD; do_stuff() })

In general, if you want two separate tasks (like controlling the LED and do something else) 'simultaneously', you should not use delay.
Instead use a long int variable to keep the time since something happened (like switching the LED color in your case). Than check in the loop how much time has passed and act on it.
E.g.
When you call analog writes with non zero values, set the variable to the current time. Than instead of the delay check if the current time minus the variable < 100 or 200 or 300 depending on the value you need and than set the analog write back to 0 (switching off the LED). In the rest of the loop you can do other tasks.


text:
What is FaryLink? [Access Point]
When powering up my WeMos D1 ESP8266, I suddenly find this hotspot named "FaryLink". What is this? I programmed the ESP to work as a web server, thus connecting to an existing hotspot and not providing any beacons or acting as an access point.
Google could not provide any information to this behaviour.

What is the purpose of this AP and how can I use / disable it?

look again ... it does not say FairyLink

wow, i guess i only see what i want to see. will edit question for future readers


text:
I2C LCD Serial Interface Board not displaying text
The code dont gives error, but not displays "Hello World"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  // initialize the LCD
  lcd.begin();
  // Turn on the blacklight and print a message.
  lcd.backlight();
  lcd.print("Hello, world!");
}

void loop() {
}

Are you sure you have the same display as that library is designed for?

This can be due a lot of reasons, among:
Most common:

Backlight is set too low (there should be a small dial)
Circuit problem (recheck), and post it.
The I2C address is wrong, there are sketches to check it.

Less common:

Broken LCD
Broken Arduino
No power on Arduino (check LED)


text:
How to connect an Arduino via an ethernet cable to a laptop directly?
Maybe a silly question, because it is a usual topic, but I have a problem with my Arduino Leonardo ETH.
I want to create a web server on the Arduino with the example sketch File > Examples > Ethernet > WebServer. I plugged in the ethernet cable directly to my laptop. So there is no router or switch between them.
I also set the configuration to my ethernet port to the following IPv4 properties:

Then in the example sketch, I changed the MAC address according to the bottom sticker of my Arduino.
byte mac[] = {0x90, 0xA2, 0xDA, 0x11, 0x33, 0xD6};
IPAddress ip(192, 168, 1, 177);

Now when I compile and upload the sketch to the Arduino, everything is working fine until it prints the IP address. According to the IP address which I have set in the code (192.186.1.177), it shows me 0.46.46.46 as you can see in the picture:

This happens when I print that:
Serial.println("server is at ");
Serial.println(Ethernet.localIP());

Do you have any ideas how I could fix this? And why does it show me that invalid IP address?
Thank you in advance.

Are you using the correct type of cable? Might want to check that first.

@MikaelPatel I'm using a CAT. 5e S/UTP cable.

The Leonardo ETH has the W5500 Ethernet controller, which doesn't do auto-MDIX so you will need to use a crossover cable.

I am sure the Ethernet card in computer makes the auto-MDX

use the Ethernet2 library for W5500

Thank you very much. You've saved my day. For a reference, here's an example of implementation: http://platformio.org/lib/show/261/Ethernet2


text:
Sending a union from Arduino via serial communication and parsing it in python
I want to send a union from Arduino to a python script running on a pc, and I want to parse the received union. I have read lots of topics online but I am stuck on how to do it in the most efficient way.
Specifically, the union contains a struct of a string containing a sensor name, and a 32 bit integer containing a sensor value.
I use the union as I understood is one of the best ways to deal with binary struct data as the ones I want to send.
Here my Arduino code

int32_t analog_input0 = 0;

// Variables to send data
struct serial_message {
  char sensor_name[20];
  uint32_t sensor_value;
};

union serial_message_union {
   serial_message ser_msg;
   uint8_t serial_message_bytes[sizeof(ser_msg)];
};

union serial_message_union ser_msg_u;

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

void loop() {
  analog_input0 = analogRead(0);
  strcpy(ser_msg_u.ser_msg.sensor_name, "analog_input0");
  ser_msg_u.ser_msg.sensor_value = 100;
  Serial.write(ser_msg_u.serial_message_bytes, sizeof(ser_msg_u.ser_msg));
}

Here my python code:
import serial
ser = serial.Serial('/dev/tty.usbmodem1225061', 115200, timeout = 2)

while True:
    if(ser.in_waiting > 24): #I set 24 because the message is composed by 20 char + 4 bytes for the uint32_t value
        incoming_data = ser.read(24)
        print('Incoming data: "{}" '.format(incoming_data))

# Here I want to parse the incoming data, where the first
# 20 bytes are the sensor name and the last 4 bytes are the sensor value

Can anyone suggest how can I proceed? Do you see any error/bad software practice so far in my code?

what is the question?

First question: is my code correct so far? Second question: how can I proceed from there? Once I received the data in the variable incoming_data (assuming that I am doing it right) how can I parse it in the way that allows me to have a variable containing the first 20 bytes and a second variable containing the last 4 bytes?

Try your code and then let us know what's the issue you had faced with clear definition of issue.

Why are you using a union? Why not just cast serial_message to uint8_t?

if(ser.in_waiting > 24): - don't you mean >= 24?

thanks, yes, it is >= 24. Could you please give me an example with code about what you intend when using the casting to uint8_t?


text:
Parsing and comparing strings on Arduino: different behaviour from gcc?
I am trying to parse a simple string, print the result of the parsing via serial.println, and trigger a function on the basis of the received command. I wrote the code below, which perfectly works in c (see the c file attached). However, the behaviour of the same code on the arduino IDE is completely different and I really can't figure out why.
#include <string.h>

void rcv_msg(char *rcv_msg) {

  char *all_tokens[2];
  int i = 0;

  all_tokens[i] = strtok(rcv_msg, "{,}");
  while (all_tokens[i] != NULL) {
    all_tokens[++i] = strtok(NULL, "{,}");
  }

  char *command = all_tokens[0];
  char *value = all_tokens[1];

  /*
  //These printls do not work, they are ignored, why?
  Serial.println("all_tokens[0]: ");
  Serial.println(all_tokens[0]);
  Serial.println("all_tokens[1]: ");
  Serial.println(all_tokens[1]);
  */

  if (strcmp(command,"message_1") == 0 && strcmp(value,"1") == 0) {

    Serial.println("message 1: ");
    Serial.println(command);
    Serial.println(value);
    Serial.println(" ");

  }

  if (strcmp(command,"message_2") == 0 && strcmp(value,"0") == 0) {

    Serial.println("message 2: ");
    Serial.println(command);
    Serial.println(value);
    Serial.println(" ");

  }
}

void setup() {

    Serial.begin(115200);
}

void loop() {

    char msg1[] = "{message_1,1}";
    char msg2[] = "{message_2,0}";

    Serial.println("Send msg1: ");
    rcv_msg(msg1);
    delay(5000);

    Serial.println("Send msg2: ");
    rcv_msg(msg2);
    delay(5000);
}

This code gives the following output on the serial monitor, which is wrong:
Send msg2:
message 2:
message_2
{message_2,0}
Send msg1:
message 2:
message_1
{message_2,0}
Send msg2:
message 2:
message_2
{message_2,0}
Send msg1:
message 2:
message_1
{message_2,0}
Firstly, I don't understand why at the beginning, message 2 is printed before message 1, although message 1 was sent first. Second it is not clear to me the comparison done with strcmp is always returning the message 2.
More importantly, why running the same code in c has instead the correct output? I wonder if there is any error in my arduino code. BTW, I am testing the code on Teensy 3.2 but I plan to use it also on Arduino Uno.
The c code (which is perfectly working is this:
#include <string.h>
#include <stdio.h>

void rcv_msg(char *rcv_msg) {

    char *all_tokens[2]; //NOTE: the message is composed by 2 tokens: command and value
    int i = 0;

    all_tokens[i] = strtok(rcv_msg, "{, }");
    while (all_tokens[i] != NULL) {
        all_tokens[++i] = strtok(NULL, "{, }");
    }

    printf("all_tokens[0] : %s \n", all_tokens[0]);
    printf("all_tokens[1] : %s \n", all_tokens[1]);

    char *command = all_tokens[0];
    char *value = all_tokens[1];

    printf("command : %s \n", command);
    printf("value : %s \n", value);

    if (strcmp(command,"message_1") == 0 && strcmp(value,"1") == 0) {
        printf("activating command : %s %s \n\n\n", command, value);
    }

    if (strcmp(command,"message_2") == 0 && strcmp(value,"0") == 0) {
        printf("activating command : %s %s \n\n\n", command, value);
    }
}

int main() {

    char msg1[] = "{message_1, 1}";
    char msg2[] = "{message_2, 0}";

    rcv_msg(msg1);
    rcv_msg(msg2);

}

Both versions of your code have undefined behavior. On the given input your code will call strtok three times and store its result into the array three times: for the first token, for the second token and, finally, for the null pointer. You store all three (including that null pointer!) into the all_tokens array, which has size 2.
You are obviously aware of the potential array overrun danger: you even wrote this comment in your code
char *all_tokens[2]; //NOTE: the message is composed by 2 tokens: command and value

and yet in the following cycle
int i = 0;

all_tokens[i] = strtok(rcv_msg, "{, }");
while (all_tokens[i] != NULL) {
    all_tokens[++i] = strtok(NULL, "{, }");
}

you still insist on storing more than two values into all_tokens array.

Also, the second version of your code uses completely different message key values (why is it suddenly "motor1_pattern1" instead of "message_1"?), which makes it unclear how you compared the functionality of the second version with the functionality of the first.

many thanks. I added while (i < 2 && all_tokens != NULL)  which solved the problem. Is this the best way of doing it? Also I edited the code removing motor1_pattern with message_1 (sorry that was a bad copy-paste I did).  I still wonder:
Why the serial monitor still displays first the second message although the first message was sent. It seems that the first message does not reach the serial monitor... what I am missing?
Finally, do you suggest to use strtok_r instead of strtok?

Suggest to have a look at the message about memory usage while compiling. Arduino have only a small amount of RAM and string functions are using a lot. If your code is very small, it can work, but the more you'll increase the size of code and the more you'll get strange results.


text:
Can I operate an arduino that has a file uploaded on it, without having the file myself?
I've been a massive idiot and accidentally deleted the sketch I need for a project at university, and I didn't create any backups. The sketch is already uploaded into the arduino, which operates using the serial monitor; when "1" is entered it does one thing, when "2" is entered it does another thing and so on. My question is: can I still use the serial monitor to operate the arduino without having the original sketch?
Any help would be appreciated, thank you.

Of course you can. The serial monitor has nothing to do with the sketch - it's just a very primitive serial interface program.
You don't even need the serial monitor. You can use any serial interface program ("terminal emulator") such as Teraterm, Putty, Hyperterminal, etc.


text:
Idenitifying pins in my code. which pin is which?
I'm new to arduino and knnow nothing about electronics.
How do I idenitify which pin is which in the coding?
eg- I have a pin on my esp8266 "D3"... how would I reference that in the code?

You could try google search ...

You could either call it as just D3 in your code, or you could use the GPIO number which in this case is 0, do not get used to calling it Dx most boards are not capable of doing this

If you select the right board in Tools menu, you can use constants corresponding to labels.
pinMode(D3, OUTPUT);
digitalWrite(D3, LOW);

and of course, you can google "nodemcu pinout" and you will find nice pictures with all pins specs


text:
Troubles with APDS-9900 proximity
So I've received few APDS-9900 sensors and found out, there's no library for it (9960 type is supported only). I took that library and device documentation, and created similar library.
Ambient light detection (without interrupts) works well, but there's trouble with proximity detection:
The "Auto-Increment protocol transaction" which should be initiated by writing (0xA0 | reg) to command register, does not work and returns two zeros instead of two bytes. See page 18 of the PDF docs (in repo).
0xE0 (Repeated Byte protocol transaction) returns at least second byte (seems so) of the ADC proximity integration result registers.
https://github.com/suculent/APDS9900_Ambient_Light_and_Proximity_Sensor

Do you have a 1.8v i2c bus? The function wireReadDataWord reads four bytes and the first two are ignored, why?

The APDS-9900 seems to have 1.8V I2C bus and I have it connected to 3.3V ESP8266. I don't have level-shifter, so I guess I could do that with some additional resistance. Single-byte transactions seems to work well.
As of the ignored bytes... first byte returns 0, second returns 10, attempt third returns 40 and the fourth seems to return mostly > 768, one of the ADC integration result registers (high or low, hard to tell, seems like low given the jitter...)

Is the function wireReadDataWord random code and you take two bytes and hope that those are the bytes that you need? Can you replace the contents of wireReadDataWord with two wireReadDataByte?

wireReadDataByte returns always zeroes from PDATAL and PDATAH registers.
There's additional issue, where the proximity data is a 2-byte value, that is constantly updated using the ALS proximity integrator. The wireReadDataWord should solve this by explicitly requesting multi-byte transaction that should safely provide both bytes from the same integration cycle.
This does not happen with the luminance, which is also a 2-byte. I'm seriously thinking about ditching those APDU-9900 and replace with more expensive but more predictable APDU-9960.

I think that is a good choice, because of the 1.8v i2c interface. Perhaps something is damaged with 3.3v. You also need to fix the software issue when requesting two bytes. It seems that you have made a workaround in the function wireReadDataWord, but that workaround is wrong anyway. While waiting for a new sensor, you could check every return value of Wire.requestFrom to see if you got the same number of bytes that you requested.

The workarond by fetching 2-bytes twice is more a debugging work in progress. I've already checked the return values... I suppose the problem will be in 1.8V I2C which will fail on multi-byte transaction attempt.


text:
Testing Conditions on Port Bytes - ignoring certain bits?
Being new to testing byte and bit conditions, I feel like there has to be a better way to test for conditions/values on a byte (read from a port).
For example, I'm reading 8 bits from PORTK. I need to test for a pattern of high bits. (Say, byte value of 207 - bits 7, 6, 3, 2, 1, 0 all high.) Bits 4 and 5 I don't care about. They CAN be high, or can be low. (Using datasheet terminology, they're "X - Don't Care".)
I could do an if, and test if the value equals 207, 223, 239, or 255, but that seems messy and like there would be an easier (and cleaner to read) way.
Edit to add: I've looked at Bit Operators, and .. something is telling me I should/could be using one of those. But I'm having a difficult time walking through which one would help me.
Thanks!
-Mike

You need to use boolean arithmetic.  Use the AND operator (&) to combine the incoming value AND the "mask" value (the value of the bits you do care about) and see if it equals the mask bit:
byte wanted = 0b11001110; // 207
byte incoming = 223; // for example 11011111

if ((wanted & incoming) == wanted) {
    // whatever
}

The AND operator compares each bit of the bytes in turn.  If they are BOTH 1 then the result is 1. Otherwise the result is 0.  So the above gives:
wanted:    11001110
incoming:  11011111
AND:       11001110

And the result matches "wanted". If you had some other value for incoming it could look like this:
wanted:    11001110
incoming:  01011011
AND:       01001010

And you can see that the result doesn't match.

AH! Okay, that makes sense - I would want my 'mask' value to have bits set to '1' I care about, and '0' I don't. This would effectively force the 'don't care' bits to 0.

That is correct.

There are ways to mask off the don't care bits.
Say your example, 0b11xx1111.
Then
incomingByte = Serial.read();
incomingByte = incomingByte || 0b00110000;  // make 4, 5 high
if (incomingByte == 0b11111111){
// got all 1s, do something
}
else {
 // some 0s received, do something else
}


text:
Why am I receiving this error: “expected unqualified-id before numeric constant”?
#include <LiquidCrystal.h>
LiquidCrystal 1cd(12, 11, 5, 4, 3, 2);
const int switchPin = 6;
int switchState = 0;
int prevSwitchState = 0;
int reply;
void setup() {
 1cd.begin(16, 2);
 pinMode(switchPin, INPUT);
 1cd.print("Interroga");
 1cd.setCursor(0, 1);
 1cd.print("la sfera!");
 // put your setup code here, to run once:

}

void loop() {
  switchState = digitalRead(switchPin);
  if (switchState != prevSwitchState){
    if (switchState == LOW){
      reply = random(8);
      1cd.clear();
      1cd.setCursor(0, 0);
      1cd.print("La sfera dice");
      1cd.setCursor(0, 1);
      switch(reply){
        case 0:
        1cd.print("si");
        break;
        case 1:
        1cd.print("probabilmente");
        break;
        case 2:
        1cd.print("certo");
        break;
        case 3:
        1cd.print("bene");
        break;
        case 4:
        1cd.print("forse");
        break;
        case 5:
        1cd.print("chiedi ancora");
        break;
        case 6:
        1cd.print("improbabile");
        break;
        case 7:
        1cd.print("no");
        break;// put your main code here, to run repeatedly:
      }
    }
  }
 prevSwitchState = switchState;
}

English only please. Also include the full error message (including the information, where the error happened) into your question

You're using an invalid variable name (1cd starts with the number 1).

Variables can consist of both uppercase (A-Z) and lowercase(a-z)
letters.
Variables can contain numbers 0 to 9, but cannot start with a number.
Variables may not have the same names as Arduino language keywords,
e.g. you cannot have a variable named float.
If you try and save a sketch with a space in the file name, the IDE will change the space to an underscore.


text:
Why does a function inside void set up is repeating after some minutes
I am trying to time sync my arduino hardware to NTP server. I have a `setSyncProvider(getNtpTime)´ function to do it and called inside the void setup. I have another function (mainFunction) inside the main loop, that calls every minute. I have added a function to display time inside this mainFunction so that time will update every minutes.  Code works fine for first five minutes. Then it calls the getNtpTime again even though it is not inside the loop. Why is it happening?

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

Arduino is resetting for some reason?

But no other functions inside void set was repeated. If Arduino was resetting, everything inside setup should have repeated, right?

i have this millis() function inside getNtpTime() and mainFunction(). any possibility of conflicts?

The setSyncProvider function of the TimeLib sets a function which will be called by the library every interval seconds. The interval is set with setSyncInterval. Default interval is 300 seconds.

I checked the time of calls in serial monitor. As i mentioned in the question, my main loop has a function that calls every minute. in the main loop getNtpTime called at 360.8 second   and then at 660.8. After first call, there was no display error. But after second call, there was display error. Display returned to normal in the next minute and the above cycle of error repeated. That means 3rd call was fine, 4 gives error. 5th was fine, 6th gives error! Any suggestions

try a little longer wait time


text:
Button to exit a running loop
I have a very basic circuit setup:

A button connected to pin 2
An LED connected to pin 9

Desired Functionality:
When the button is pressed, the user can toggle through 4 LED patterns.
The Problem:
Once the first fade pattern begins, the user has to wait until it has finished running before the button can toggle to the next pattern. What  I want is that the button push will move to pattern 2, even if pattern 1 has already started.
Attempted Solutions:
I've tried to insert a while function in a couple of places i.e while buttonstate =lastbuttonstate, but that doesn't seem to work.
Here's the code: (I realize all the fadeloops are the same right now, they will different in the working model)
//PROBLEM: The fade function has to complete a full loop before allowing toggle to next one

const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 9;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

int brightness = 0;    // how bright the LED is
int firstFadeAmount = 5;    // how many points to fade the LED by
int secondFadeAmount = 5;    // how many points to fade the LED by

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      buttonPushCounter++;
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  lastButtonState = buttonState;

  while (buttonPushCounter = lastButtonState) {
    if (buttonPushCounter == 1 && buttonState == HIGH) {
      fadeLoop1();
      delay(50);//JP Edit
    }

    else if (buttonPushCounter == 2 && buttonState == HIGH) {
      fadeLoop2();
      delay(50);
    }

    else if (buttonPushCounter == 3 && buttonState == HIGH) {
      fadeLoop3();
      delay(50);
    }

    else if (buttonPushCounter == 4 && buttonState == HIGH) {
      fadeLoop4();
      delay(50);
    }

  }
  if (buttonPushCounter == 4) {  //Resets back to zero after 4 presses
     buttonPushCounter = 0;
  }

}

void fadeLoop1()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

void fadeLoop2()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

void fadeLoop3()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

void fadeLoop4()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

You might want to expand on the description of the circuit. The button is connected to pin 2 and ???.

Thanks. The button is connected to pin 2 only and is only there as a counter.

The button is also connected to GND (or VCC) with a resistor? You might have connected a open circuit and therefore have erratic input values.

The issue is that the fadeLoopN functions occupy the CPU. There are two approaches to solving this: (1) rewrite the fade patterns in a way that they are performed using timer interrupts; or (2) create an interrupt for the button, and set some global flag in the interrupt service routine, then check for this flag in every loop in your fade functions. The first approach is preferred, but the second approach is less invasive.

all four fade patterns are the same, so you have no way of knowing if you selected a different pattern

Short Answer:
Switch from using a loop for the entire animation and convert to only tracking what needs to happen at a single point in time.
Long Answer:
The 'while' approach is a good way to test out an individual pattern but for the behavior you describe, you need to limit the use of loops inside of the 'loop()' function.
Essentially, if you use a while to control the entire pattern, as you encountered, you have to wait for the while to exit before the rest of the code can check for a button press.
Here is how I've done the same thing.  I don't have the code handy so I'll have to edit the answer later.  The basic form is something like this:
int pattern = 0;
int brightness = 0;
int maxBrightness = 100;

setup()
{
// your setup code here
}

loop()
{
   if (pattern = 0)
   {
      //increment brightness
      //call code to set the LED to the current brightness
      if (brightness => maxBrightness)
      {
          brightness = 0;
      }
   }
   checkforbuttonpress();
}

What you notice is I didn't use a for / while loop to do my animation, because the already existing loop() function already does that for me.  All I have to do is track what needs to happen right now, with variables for which pattern and the current brightness for the code to interact with the hardware.  Remember to handle the repetition manually (maxBrightness in this example) and now when the button is pressed, you can change the pattern anywhere because there is no secondary loop to wait for.

Rewrite the fade loops so they return immediately and instead use global state to adjust the LEDs and millis()-timestamp to set the timing.
You can use blinkwithoutdelay as inspiration.

Thanks. Please explain, what does it mean to "return immediately" and how do I include it in the code? I am reading about 'miilis' now, it looks like it's the way to go.


text:
Uno to Mega and where is the error for the interrupt that isn't delared?
I want to read a Omron E6B2-CWZ6C Incremental Rotary Encoder w/Index (360P/R).
A couple questions, I found out that an Uno can only handle 2 interrupt pins and I think I need 3 for the Index.  What do I need to do to the following code to get it to run on a Mega which I believe can handle 3 interrupt pins?
Also I am getting a 'outAChange' was not declared in this scope.
What am I missing here.
I will be using the data from the encoder value to run a NeoPixel 60 for a directional mast/antenna.
Here is the code I am trying to use:
// Wiring connections for my encoder:
// Brown : VCC = 5 to 24VDC
// Blue: 0V(Common) = GND
// Shield: GND
// Black: outA = Digital pin 2
// White: outB = Digital pin 3
// Orange: outZ = Digital pin 4 (Index)
// With these outA/outB/outZ connections and the interrupt code below
// clockwise rotation gives positive encoder counts

const int outA = 2;
const int outB = 3;
const int outZ = 4;

volatile long encoder = 0; // declare volatile since modified by interrupt routines
float encoder_save = 0;

void setup(){  // set encoder pins
pinMode(outA, INPUT_PULLUP);
pinMode(outB, INPUT_PULLUP);
pinMode(outZ, INPUT_PULLUP);  //Index

// attach interrupts to pins
attachInterrupt(digitalPinToInterrupt(outA), outAChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(outB), outBChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(outZ), outZChange, CHANGE);

// initialize serial
Serial.begin(57600);
}

void loop(){

if (encoder_save != encoder)  // only print if new value
encoder_save = encoder;

// If Index(Z) reads low reset encoder to 0
if (digitalRead(outZ) == LOW)
{
  encoder = 0;
}
}

{
Serial.println((encoder * 360)/360);
}
}

// interrupt routines
void outAChange(){
// when outA changes, outA==outB means negative direction
encoder += digitalRead(outA) == digitalRead(outB) ? -1 : 1;
if (encoder < 0)
{
  encoder = (encoder + 360);
}
}

void outBChange(){
// when outB changes, outA==outB means positive direction
encoder += digitalRead(outA) == digitalRead(outB) ? 1 : -1;
if (encoder >= 360)
{
  encoder = (encoder - 360);
}
}

Your brackets are all messed up.  If you pass your code through an autoformatter (such as the one included in the IDE) you end up with this:
// Wiring connections for my encoder:
// Brown : VCC = 5 to 24VDC
// Blue: 0V(Common) = GND
// Shield: GND
// Black: outA = Digital pin 2
// White: outB = Digital pin 3
// Orange: outZ = Digital pin 4 (Index)
// With these outA/outB/outZ connections and the interrupt code below
// clockwise rotation gives positive encoder counts

const int outA = 2;
const int outB = 3;
const int outZ = 4;

volatile long encoder = 0; // declare volatile since modified by interrupt routines
float encoder_save = 0;

void setup() { // set encoder pins
    pinMode(outA, INPUT_PULLUP);
    pinMode(outB, INPUT_PULLUP);
    pinMode(outZ, INPUT_PULLUP);  //Index
// attach interrupts to pins
    attachInterrupt(digitalPinToInterrupt(outA), outAChange, CHANGE);
    attachInterrupt(digitalPinToInterrupt(outB), outBChange, CHANGE);
    attachInterrupt(digitalPinToInterrupt(outZ), outZChange, CHANGE);
// initialize serial
    Serial.begin(57600);
}

void loop() {
    if (encoder_save != encoder) { // only print if new value
        encoder_save = encoder;
    }

// If Index(Z) reads low reset encoder to 0
    if (digitalRead(outZ) == LOW) {
        encoder = 0;
    }
}

{                                                << WHAT
    Serial.println((encoder * 360) / 360);       << IS
}                                                << THIS
}                                                << CODE?

// interrupt routines
void outAChange() {
// when outA changes, outA==outB means negative direction
    encoder += digitalRead(outA) == digitalRead(outB) ? -1 : 1;

    if (encoder < 0) {
        encoder = (encoder + 360);
    }
}

void outBChange() {
// when outB changes, outA==outB means positive direction
    encoder += digitalRead(outA) == digitalRead(outB) ? 1 : -1;

    if (encoder >= 360) {
        encoder = (encoder - 360);
    }
}

As you can see, after the end of your loop() function, you have an extraneous block of code with a bunch of random brackets.
You need to decide where in your program that should actually be and move it there, deleting those extra brackets.

I could use a little more help than that.  I am really new at coding.  thanks.

I cannot help you. Only you know where you want that bit of code.


text:
Servo motor not working properly with arduino
I have some problem with my fyp, which is auto serving of food using train.
I have 4 servo motors, first servo motor's function is to connect the track to table no.1, and second motor for table no.2 and third and fourth motor for table no.3.
All the motors are performing well at first time..
but when I reset and give command for second or third table, motors behavior changes and they start rotating in arbitrary directions which are not defined in code.
but sometimes it works good and sometimes motors are not performing as expected.
I have check all the grounds and powers. they are all good.
Please help me, as I have my final submission in two days.
The code is given below..
Please check and tell me if I have a logical error in my code or any other issue regarding to hardware also tell me is their any cache in arduino, which I need to clean or something like that.
#include <Servo.h>

Servo motor;  // create servo object to control a servo
// twelve servo objects can be created on most boards

const int button1 = A1;
const int button2 = A2;
const int button3 = A3;

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;

void setup() {

  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);

  servo1.attach(9);
  servo2.attach(11);
  servo3.attach(6);
  servo4.attach(5);

  Serial.begin(9600);
}

void loop() {

  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  buttonState3 = digitalRead(button3);

  if (buttonState1 == HIGH) {
    int pos1 = 180;
    int pos2 = 180;
    int pos3 = 90;
    int pos4 = 90;

    for (int pos2=90; pos2 <= 180; pos2 += 1) {
      servo2.write(pos2);
      delay(0);
    }
    for (int pos1=90; pos1 <= 180; pos1 += 1) {
      servo1.write(pos1);
      delay(50);
    }

    while (pos1 >= 0 && pos2 >= 0 && pos3 >= 0 && pos4 <= 180) {
//      servo1.writeMicroseconds (1000);

//      servo1.write(pos1);
//      servo2.write(pos2);
      servo3.write(pos3);
      servo4.write(pos4);
      delay(200000);                // 500ms delay
    }

  }
  else if (buttonState2 == HIGH) {

    int pos5 = 90;
    int pos6 = 0;

    for (int pos5=90; pos5 >= 0; pos5 -= 1) {
      servo1.write(pos5);
      delay(0);
    }
    for (int pos6=90; pos6 >= 0; pos6 -= 1) {
      servo2.write(pos6);
      delay(50);
    }

    while ( pos6 <= 180 && pos5 <= 180) {

//      servo2.write(pos6);
//      servo1.write(pos5);
      delay(200);
    }
//      while ( pos5 <= 180) {
//        servo1.write(pos5);
//        delay(200);
//      }

  }
  else if (buttonState3 == HIGH) {
    int pos9 = 90;
    int pos10 = 180;
    int pos11 = 0;
    int pos12 = 180;

    for (int pos10=90; pos10 <= 180; pos10 += 1) {
      servo2.write(pos10);
      delay(0);
    }
    for (int pos9=90; pos9 >= 0; pos9 -= 1) {
      servo1.write(pos9);
      delay(0);
    }
    for (int pos11=90; pos11 >= 0; pos11 -= 1) {
      servo3.write(pos11);
      delay(30);
    }
    for (int pos12=90; pos12 <= 180; pos12 += 5) {
      servo4.write(pos12);
      delay(50);
    }

    while ( pos9 <= 180 && pos10 >= 0 && pos11 >= 0 && pos12 >= 0) {

//      servo1.write(pos9);
//      servo2.write(pos10);
//      servo3.write(pos11);
//      servo4.write(pos12);
//      delay(200);
    }
//      while ( pos9 <= 180) {
//        servo1.write(pos9);
//        delay(200);
//      }
  }

}

Try to write a minimal example that works for only one of your "tracks" and then you may see where the problem lies.

I think reason for which you are not getting the expected result is because of you while loops in you if condition.
As you loops doesn't have any termination condition. In case of first button pressed you will get what you want because you have only single not terminating while loop, while in you Case of button 2 and button 3 there are two while loop's and both are not terminating.
In that case if you logic goes in first while loop, then it never comes out of it and won't go for second loop.
I don't know what are you up to so can't suggest on logic changes, but add termination in while loop might get you expected results.


text:
Splitting a string read from Serial into parts
Is there any method with which I can split a string given by Serial.read() into an array of 3 items: [command, address, message], to write it to EEPROM?
Thanks.

Serial.read() reads a single byte, not a string.

Ah!! , so How can i manage a string like : read 13; ps: 13 is address
or another string like: Write 13 15 where 15 is the message?

That's the code I used to fix this issue.
#include <EEPROM.h>

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

void loop() {
    while (Serial.available() > 0) {
      String command = Serial.readStringUntil(' '); // writes in the string all the inputs till a comma
      Serial.read();
      String addressStr = Serial.readStringUntil(' ');
      Serial.read();
      String messageStr = Serial.readStringUntil('\n'); // writes in the string all the inputs till the end of line character
      int address = addressStr.toInt();
      int message = messageStr.toInt();
      if (command == "Read"){
        Serial.print("Reading from EEPROM->Address: ");
        Serial.print(address);
        Serial.print("\n");
        Serial.print("Content of ");
        Serial.print(address);
        Serial.print("is: ");
        Serial.println(EEPROM.read(address));
      }else if(command == "Write"){
        Serial.print("Writing to EEPROM in Address: ");
        Serial.print(address);
        Serial.println();
        EEPROM.write(address, message);
      }
  }
}

The first thing you should do is to collect your serial input into a string.
If your incoming data use a separator, then you can take advantage of the useful function "readStringUntil".
For example, if your separator is comma (,):
while (Serial.available() > 0) {
  var1 = Serial.readStringUntil(','); // writes in the string all the inputs till a comma
  Serial.read();
  var2 = Serial.readStringUntil(',');
  Serial.read();
  var3 = Serial.readStringUntil('\n'); // writes in the string all the inputs till the end of line character
}

At this point you have your data in 3 different variables and you can use the standard eeprom library to store. Don't forget you will need to declare the variables and to initialize the Serial.
A faster way is to save the whole input in string and process it when ready.
Much better it will be if you use interrupts attached on the Serial input, so you can keep free your loop from waiting data. This can't be done with the standard Serial library but you can use this library:
https://github.com/SlashDevin/NeoHWSerial
It works really well, we use it to collect data from GPS receivers at very high speed and it's fast.
N.B. eeprom is limited in the numbers of reads and writes it can support before risk a failure. Even 100,000 reads/writes sounds a big numnber, if you write the data once every second your eeprom will die in just 27 hours, a day of life. Try to write data only when it's strictly necessary and read data as well only when you start the procedure that uses those data, once.


text:
Reading bmp images from SD card, converting it and displaying it on serial monitor in Arduino
Can someone please help me write code that can read a 24-bit BMP file from an SD card, save converted to 8-bit BMP internally, and display the 8-bit BMP pixel values on Arduino terminal as a 2D matrix. The program should align the bytes as two HEX values on the Arduino terminal. I am new to this and not sure how to go about it. Your help will be much appreciated.
The image is present in the SD card and coded as:
include <SD.h>
include <SD_t3.h>

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

void loop() {
  if (!SD.begin (BUILTIN_SDCARD)) {
    Serial.println ("NO SDCARD");
    while (1);
  } else {
    Serial.println ("YES SDCARD");
  }
  delay (1000);
  if (SD.exists("filename.BMP")) {
    Serial.println ("filename.BMP exists");
  } else {
    Serial.println ("filename.BMP missing");
    while (1);
  }
  delay (1000);
  File hFi = SD.open ("filename.bmp", FILE_READ);
  if (hFi == false) {
    Serial.println ("File open failed");
    while (1);
  }

You have to writeyour own routines. To get you started Look at this source code Add view-source:https://javl.github.io/image2cpp/. Although it is javascript, it can be transferred to C++ to a working conversion routine. The important part are the conversion routines.A word of warning: As the memory os limited you will have to do a line by line read from SD card convert line and write line by line back or you use maximum 16x16 size.Thats the reason why most converters run in browser or PC and the result is used in Arduino. An ESP8266 with 4MB memory would make life easier. For an implementation of graphic routines on Arduino Teensy look into this gaming library


text:
Arduino RTC - getting the time from RTC after the power is cut off
I have a new DS1307 (original, not a Chinese rip off), with a new battery. It is working great, but when I turn the Arduino off (it is currently connected to laptop) and then turn it back on, it resets the time.
The line that sets the time is (in setup part of code):
setDS1307time(30, 42, 21, 4, 26, 11, 14);

So, when the Arduino gets the power back it runs the program again and it overrides the correct current time.
How can I avoid this?

Remove that line of code. You only need to set the time once.

But how do I set the time for the first time? Upload the program with this line and then upload it for the second time without this line?

Make a time-setting function in your code, and in your loop() code watch for a specific command that sets the time. I use 'T20151201101010' in my own machines. When they get such a command, they adjust their clock. You will see that the DS1307 can grow slowly off-base, and having a time-setting function comes handy.

Alright, I'm a noob, can you please tell me more, or can you send me your source code?

How are you accepting commands for your application? Basically whatever that process is, add another command to set the time.

Yeah but set to what? I'm totally confuesed right now

Oh, you'd set it to whatever time the user (the issuer of the command) says it is. In the example above the time is 2015-12-01 10:10:10 (today at 10:10:10 in the morning, presumably local time). The string of numbers would need to be parsed into something that could be used to set the RTC.

I'm not sure if we understand each other. There will be no user, if power is cut off, arduino has to get time from either RTC or NTP as soon as possible, there is no chance of doing it manually.

Without knowing the DS1307 well, I think there are two options:

Make the setting of the clock a UI function (you should probably do this in any case since you will want users to have the ability to set the clock). The user would have to initiate the action (and put in the time to set) so there would be no problems the clock getting reset inappropriately, or
Do a check for sanity of the clock before you run that line. You might be able to do that through the clock API (e.g., make a call to check the time, or to get the clock status and see if it makes sense) or you could do it by storing the clock status in nonvolatile memory. The very worst case would be that you store the time of last boot and check that it seems reasonable (e.g., the time you get from the RTC is after the last boot and is within reason – say no more than a month or a year ago). If the time is too far off to feel confident you could issue a "check time" warning.

If you have a network connection using NTP as well as the RTC would be a very smart option. NTP can hold the time within a few milliseconds. The RTC would then provide you with protection against a network outage.
If you are using the Arduino to manage scheduled events one thing you'll want to think about is events that are scheduled in a moment of time that is either "skipped" as you advance the clock or that "repeats" if you set the clock back. One way to handle that is to never "jump" time, but to always just speed it up or slow it down.

The point is, I just need to set the time once and then let it be for indefinite amount of time.

No. You will see that you will need to readjust the time regularly. The DS1307 isn't that precise.

But since you have a network connection, it would be good to look into running NTP. NTP (network time protocol) will hold your time to within a fraction of a second.

No matter how good the RTC is there are reasons why you might want to set the time – battery failure, summer time, moving to a different time zone, initial setting error, …).

yeah but NTP server will not help at all if my connection falls. Maybe use NTP server if the power is cut off and maybe once a week to refresh the time?

NTP expects the network to go down from time to time. It will recover as soon as it can communicate with its peers again. In the mean time the RTC will help you stay close and will give you a good estimate of the time if you need to reboot. You could use NTP to update the RTC from time to time as well.

But I need to get time from NTP server every 30 seconds or so (it could be every minute, but I was trying NTP time before and there were some faults here and there and I didn't get the correct current time. Is this OK, or will it screw up with CPU usage too much? Or should I use RTC time, and refresh it once a day (at 0:00, get NTP packet and refresh RTC time with it)

I would just let it run. You could cut it down to every few minutes or even every day depending on how good a job the Arduino is doing of keeping time. But I don't think you'll have issues of CPU utilization.

So is constant RTC time with NTP packet refresh okay? Or are you talking about constant NTP time with RTC as backup?

I would probably do the later, but I think either one is fine. The one thing I'd want to confirm is whether or not NTP can work intermittently. Some of what it does is to measure propagation delays so that it can accurately set the clock. You might need to read the NTP spec or experiment a bit if you feel like you can't run in continuously.

Exactly, I was doing a test, and in like 2/100 of NTP packet request failed. And if I set to get the time every minute, every fail could mean bad things for me. I could set it to 30 seconds, but then again, who said there can be no two fails in a row? RTC is great so far and I think it should be fine if I would refresh it once a day (and if power is cut off). Even though I'll try to get the time from RTC (if power is cut off), because what is the point of RTC if it doesn't save the time when the power is cut off?

NTP should deal just fine with request failures. It should definitely not set a bogus time – the Internet is designed around the idea that the network is not guaranteed to be reliable. As you are testing a good thing to do would be to compare the RTC with NTP time over a decently long interval (at least long enough for the RTC to start to drift off). I think the DS1307 is good for a few seconds a day, so you could probably get by with running NTP every couple of hours (so that time would stay close even during a relatively long outage).

Great, then I'll just use RTC as primary time source, and run NTP method  every few hours to get exact current time. Then I'll just parse that time and set RTC. Btw, what is the easiest way to find out that the power was cut off? Like if(powerIsBack(){runNTPmethod()} ? And btw, you are a great person, this is not the first question you are helping me with, and you seem very patient with  noobs :)

If setup() runs, it is because the system has been restarted. It could becuase the reset button was pushed, or it could be due to a power-cycle. But either way, the code will start over completely. So you could

Deal with restart issues in setup() as it will only be called once per session (unless you call it in your own code); or
Make a variable static boolean PowerCycled = true; and clear it once your code has dealt with its re-start issues. After a restart, the initialzed data will get reloaded, including PowerCycled with it's initial value of true restored.

Yeah, I'll probably go with boolean variable and it should work just fine, thank you!


text:
Reading Arduino serial stream in Java using jSerialComm
I'm having issues reading the actual double values from my Arduino Serial.println() in my Java app. I've tried following usage examples found here but get what I guess is a hex value. The serial monitor within the Arduino program is displaying the correct values.
This is the code: I'm fairly new to this and would appreciate any comments regarding style/problems/inefficiencies within my code!
import com.fazecast.jSerialComm.*;
import java.util.*;
import java.io.*;

public class PortRead {
  public static SerialPort userPort;
  static InputStream in;

  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    /*
     This returns an array of commport addresses, not useful for the client
     but useful for iterating through to get an actual list of com parts available
    */
    SerialPort ports[] = SerialPort.getCommPorts();
    int i = 1;
    //User port selection
    System.out.println("COM Ports available on machine");
    for (SerialPort port : ports) {
      //iterator to pass through port array
      System.out.println(i++ + ": " + port.getSystemPortName()); //print windows com ports
    }
    System.out.println("Please select COM PORT: 'COM#'");
    SerialPort userPort = SerialPort.getCommPort(input.nextLine());

    //Initializing port
    userPort.openPort();
    if (userPort.isOpen()) {
    System.out.println("Port initialized!");
    //timeout not needed for event based reading
    //userPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 100, 0);
    } else {
    System.out.println("Port not available");
    return;
    }

    userPort.addDataListener(new SerialPortDataListener() {
      @Override
      public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
      }
      public void serialEvent(SerialPortEvent event) {
        if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
        return;
        byte[] newData = new byte[userPort.bytesAvailable()];
        int numRead = userPort.readBytes(newData, newData.length);
        System.out.println("Read " + numRead + " bytes.");
      }
    });
  }
}

Your code is reading characters and displaying the numeric value of the character codes.  You need instead to collect full strings (perhaps until a newline, not merely the amount of data vailable when your call returns!) and then parse numeric values out of that.  This is really a Stackoverflow question, not an Arduino-specific one.

Above code reading data sent by arduino and storing into byte [ ], instead of showing how much contents you have read, you need to show the total string.

related: Sending a floating point number from python to arduino

Since you are reading received data into array newData, you should replace System.out.println("Read " + numRead + " bytes."); with System.out.print(newData); (not sure about the syntax, since I dont know Java) if you want to print the actual data received and not just the number of bytes received.


text:
Wireless Communication Between Raspberry Pi 2 and multiple Arduinos
I have about 10 Arduinos that have sensors attached, which report information back around my house. I would like to have a RPi 2, because they have nice screen and GUI options, to collect the information and display it accordingly.
I am looking for success stories on what wireless parts you used to get these two working. The the wireless must be able to penetrate a brick wall about 120ft away.
Thanks for replying, I edited the response above.

The range requirement is going to be your main challenge.  If for some reason you end up with a radio technology that does not integrate readily with the pi, you can always use another arduino/atmega on USB-serial  or logic level serial as a gateway between the master radio and the pi.

Please check http://arduino.stackexchange.com/search?q=raspberry+multiple+arduino there might be a question that greatly resembles yours, read them first, dealing with the same project they can have other/better approaches or the same difficulties.

There's many options you could use.
The simplest, though most expensive, would be to equip all your Arduinos with WiFi shields and connect a USB WiFi dongle to the Pi.  The Pi could run in AP mode (investigate hostapd) so you don't have to connect them all to your internet router.
A cheaper option, though harder to work with on the Pi, would be to use the incredibly cheap but popular nRF24L01+ modules.  There are libraries aplenty for the Arduino, but I am not aware of code for the Pi (though there probably is somewhere if you google for it).
And then there are options in between which vary in price and complexity.
Of course, you haven't mentioned range, only a brick wall.  The right choice could well be affected by the range of communication you need - do you go for the bare nRF28L01+ with a range of maybe 10m, or the one with the power amplifier and SMA antenna with a range of many hundreds of meters? Is WiFi going to be long enough range? Would a 433mHz module be a better choice?  All these questions and more need to be answered, and the best way is for you to describe your setup in detail, including what the longest range is you need to deal with, what amount of data you will be sending, do you need ultra low power to save batteries, etc.

I only saw 3 Google results after clicking your nrf28l01 link.

That was a typo - should have been nRF24L01

Thanks. Those look like neat units. Have you ever seen anything that uses the 433 or 315 spectrum that has similar range-boosting features (the amplifier and SMA connection)?

@Jerry I can't say as I have, no.

That seems strange to me, since the lower frequencies should be able to go through obstacles better, and since they don't interfere with the noisy 2.4/5.8 GHz spectrum. I'm guessing maybe the FCC and other groups regulate it.

@Jerry They may well exist - I just have never seen or used them, but then I have never looked.

I use the ESP8266 to get the data from my arduino to my webserver using wlan. You could easy install a webserver on your pi and connect it to your wifi, or just use a server online.
So you can install on all places where you get WLAN. Also you could use a repeater if your wlan is not strong enough.
Thats how my projekt works (Water level messure)

Get range from ultrasonic sensor (every minute)
Send data to the ESP8266 using SoftwareSerial
Send getRequest with WLAN to my php page on the Server
Save Data to MySql Database
Show the Data Online with php and a javascript graph lib

My example is one way Arduino to Server, but you could easy communicate back to each of your arduinos.
good luck :)

You could use an xBee.
I have 2 of these and they are really easy to set up. Here is a link to the data sheet: https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-Datasheet.pdf
Link to site:
https://www.digi.com/lp/xbee
These I believe can interface to the GPIO of the pi - as i seem to recall doing that myself. Either I did that or used an arduio to get the readings and had the arduino feed the readings to the pi GPIO pins - either way the modules make sending data wireless super easy.