text:
ESP8266 Missing data from Serial
I'm trying to read all the available access points nearby with an ESP8266 module.
Whenever I try to read all the available data from the ESP module and write it to the Monitor Serial it truncates text. Text often also a bit messed up.
I'm using an Arduino Uno with the following scheme (I'm using pins 2 & 3 NOT 1 & 0):

#include <SoftwareSerial.h>

SoftwareSerial esp8266(2, 3);

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

  esp8266.begin(115200);
}

void loop() {
  while(esp8266.available()) {
     Serial.write(esp8266.read());
  }

  while(Serial.available()) {
    esp8266.write(Serial.read());
  }
}

The code prints something like the following:
AT+CWLAP

+CWLAP:(3,#SBanaan",-73,"4c:09:d4:d5:d6:f2",1,,2,0)
+CWLAP:(3,"UPC24923"CH7"0,L5-:d6Ai0:,
,,f5
44"f"CZ7f1
4-"6:0:4-95
,5-3d0

As @JoseCanUC has mentioned SoftwareSerial is not reliable at 115200 baud. This is because the bytes are sometimes too close together for the Arduino to start receiving a new one when the start bit arrives, and so the byte starts being received part way through, thus corrupting it.
You should investigate setting the baud rate of the ESP8266 to 9600, although this itself comes with its own set of pitfalls. You should be prepared to re-flash the AT firmware to reset the baud rate if it all goes wrong.  I would seriously suggest investing in one of the many cheap USB programming adaptors for the ESP-01 on eBay, since it makes working with these devices so much simpler.  It also opens up the possibility of creating and installing your own firmware for the ESP8266 instead of using the somewhat clunky AT firmware interface.

Even better might be to look at the Wemos D1 mini or NodeMCU products, which break out a lot more GPIO pins from the ESP8266, and have an on-board USB-TTL converter.

Indeed - though they are physically bigger. If you want to get into programming them then yes those are far more convenient. However if all you want is a small WiFi interface for an Arduino or similar board then the small size of the ESP-01 is quite convenient - just hard to program without an adaptor.

Thanks for the detailed explanation and suggestions, it helped a lot! The following command did the trick including changing the baud rate in code ass well: AT+UART_DEF=9600,8,1,0,0

For SoftwareSerial, at 115200 bps data rate is not going to be reliable. Try 9600 bps.

I'm a bit confused by your diagram showing no ATmega chip on the Uno board, but you posted Uno code that should properly communicate with your ESP (except for the baud rate being too high for SoftwareSerial).
See my answer to another ESP question for how to change the ESP's baud rate, especially the code fragment at the bottom of that answer.
Changing the ESPs parameters is not difficult as long as its AT firmware is intact (which it will be if you haven't attempted to re-flash the device). Changing baud rate is only slightly tricky, in that once the Uno has told the ESP to change its baud rate, the Uno must also change its baud rate to match before you can re-establish communication with it.

You are right, everything worked except the baud rate. That was the problem. Setting it to 9600 worked.


text:
Does analogueRead() change the way a number is represented etc?
Explanatory Comment: The ADC conversion result is a 10 bit number and is placed in two 8 bit registers: ADCH & ADCL. AnalogueRead() reads the output of the ADC. This, I believe is an unsigned number. But, generally taken as only a positive number.
I'm interested in what changes, if any, take place to the number (in it's representation, interpretation, or construction or whatever) when analogueRead() reads the number and presumably makes something of it, or sends it or stores it somewhere.

In other variants, like Mega, there is a possibility to configure ADC to measure differential value between two channels. In this case, the values insife of ADC are from -512 to 511. But It's not possible (supported) by analogRead() (note: there is no analogueRead).

There is no change in representation. analogRead() reads two I/O
registers, ADCL and ADCH, which on the Uno are memory-mapped to
addresses 0x0078 and 0x0079 respectively. It returns the result in a
register pair, r24 and r25, which per the AVR C calling
conventions is the
standard way of returning a 16-bit number. Thus, r24 holds the value
read from ADCL, and r25 the value read from ADCH. That's it. No
conversion whatsoever.
There is a change in interpretation... of sorts. The function is
declared as returning an int, which on the AVR is a 16-bit signed
integer, whereas it could be argued that the I/O registers contain an
unsigned number. However, since the sign bit will always be zero, the
signed/unsigned distinction is moot: either way the result will be
interpreted as a number between 0 and 1023.

Edit: As a clarification: the ADC register (which is another
name for the ADCL/ADCH register pair) is a 16-bit I/O register. At
the end of a conversion, it holds the 10-bit result right-adjusted into
this 16-bit space, zero-padded on the left, as follows:
-------- ADCH --------- --------- ADCL --------
0  0  0  0  0  0  r9 r8 r7 r6 r5 r4 r3 r2 r1 r0
----------------- ADC (16 bits) ---------------

where the bits r9..r0 represent the 10-bit conversion result. Since the
MSB is zero, it is irrelevant whether you interpret it as a sign bit or
as a regular unsigned bit.
Just for completeness, it could be noted that it is possible (though not
through the Arduino core library) to configure the ADC to left-adjust
the result, as follows:
-------- ADCH --------- --------- ADCL --------
r9 r8 r7 r6 r5 r4 r3 r2 r1 r0 0  0  0  0  0  0
----------------- ADC (16 bits) ---------------

In this case, the MSB could be one, at it would obviously be incorrect
to interpret it as a sign bit.
As a side note, the avr-libc defines ADC as
(*(volatile uint16_t *)(0x78)), which is unsigned. And it makes sense
considering that, unlike the users of Arduino core, the users of
avr-libc are supposed to know they have the choice to get a
left-adjusted result.

What I am understanding, is that the number in ADCH & ADCL (put together) is a 10 bit number. Unless it's held to be a 16 bit number because the register is 16 bits. Although that does not sound convincing to me. There is no sign bit in the ADC result register. But, an int store is 16 bit number. And the MSB is signed. That change from 10 bit to 16 bit, and unsigned to signed, seems to represent a change of some nature.  Maybe on a practical level, no difference, but on the level of theory - a change.

As I understand, it is nicely convenient that analogueRead() returns a 16 bit number, when reading a 10 bit conversion result, because there is then space for the sign bit. And I'm pretty sure whether the conversion result is left or right adjusted the MSB in int, will be a sign bit. A zero.

@RR.: You wrote: “I'm pretty sure whether the conversion result is left or right adjusted the MSB in int, will be a sign bit. A zero.” Not necessarily a zero if left-adjusted. Try this: Serial.begin(9600); PORTC|=_BV(PC0); ADMUX=_BV(REFS0)|_BV(ADLAR); ADCSRA=_BV(ADEN)|_BV(ADSC)|7; loop_until_bit_is_clear(ADCSRA,ADSC); Serial.println((int)ADC);.

It doesn't change anything, it just combines the two 8-bit register values to one 16-bit integer.
You can just look it up in the source code for analogRead.
int analogRead(uint8_t pin)
{
    uint8_t low, high;

[...]

    // we have to read ADCL first; doing so locks both ADCL
    // and ADCH until ADCH is read.  reading ADCL second would
    // cause the results of each conversion to be discarded,
    // as ADCL and ADCH would be locked when it completed.
    low  = ADCL;
    high = ADCH;

[...]

    // combine the two bytes
    return (high << 8) | low;
}

It is worth noting that this part of the code could be written more succinctly as return ADC;. The way it is actually written is inspired by the Atmel datasheets, which were probably written in ancient times, when gcc did not know how to properly handle 16-bit I/O registers.

I assume you mean AnalogRead, see AnalogRead.
What it effectively does is mapping 0 to 5V to values 0 to 1,023.
The unit is thus 5/1,024 V.
What this number means depend on the ADC used.
Probably the two bytes (ADCH as most significant bits and ADCL as least significant bits) contain this 0-1,023 value.

But, analogueRead() returns an int. Which is a 16 bit number, and the first bit is signed. Is that not a change in the original unsigned number?

It is indeed a 16 bit (signed) number. But according to the documentation it only returns values from 0 to 1,023. AnalogRead could also be have an uint(32) or uint(16) as return variable, but probably for novice users a 'simple' int is chosen.
So there is no need to change the original unsigned number. an unsigned 16 bit value perfectly fits in an integer type.

The way I am looking at things, as a novice, is that analogueRead() has taken an unsigned 10 bit number, and stored it (by way of default action) as a 16 bit signed number. And so, my answer to the question I posed (short form) would be yes.

Oh, I see that folks see the number is ADCH & ADCL, as a 16 bit number, even though it's only holding a 10 bit result.  So, it's not as if a 10 bit number is being turned into a 16 bit number.

True ... like e.g. the max value 1,023 is in binary 0000 0011 1111 1111 (16 bits) where ADCH is probably the first 8 bits and ADCL the last 8 bits.

source: Stack Exchange

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

sort: votes


text:
NodeMCU v1 keeps dropping out
I've created a homebridge server on a Raspberry Pi Zero and have configured it to use my NodeMCU v1 (Esp - 12E Module) as an accessory to control RGB strip lights.
All works normally until you don't use the home kit to control the lights for certain amount of time (~30 seconds). My iPhone says that the accessory is non responsive until I force a command to happen, this after some time activates the accessory and goes back to normal.
Is there a way of keeping the NodeMCU active to HTTP responses all the time?
The code I have used is a mashup of a tutorial I used but I've modified it with some more features. (All coded in Arduino)
//NodeMCU RGB-Controller for Homebridge & HomeKit (Siri)

#include <ESP8266WiFi.h>
#include <math.h>

#define redPin 13 //D7 - Red channel
#define grnPin 12 //D6 - Green channel
#define bluPin 14 //D5 - Blue channel
#define white 5 //D1 - Blue channel

WiFiServer server(80); //Set server port

String readString;           //String to hold incoming request
String hexString = "000000"; //Define inititial color here (hex value), 080100 would be a calm warmtone i.e.

int state;

int r;
int g;
int b;

float R;
float G;
float B;

int x;
int V;

///// WiFi SETTINGS - Replace with your values /////////////////
const char* ssid = "xxxxxxx";
const char* password = "xxxxxxx";
IPAddress ip(192,168,1,234);      // set a fixed IP for the NodeMCU
IPAddress gateway(192,168,1,1);  // Your router IP
IPAddress subnet(255,255,255,0); // Subnet mask
////////////////////////////////////////////////////////////////////

void WiFiStart() {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet); //Set a fixed IP. You can comment this out and set it in your router instead.
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print("_");
  }
  Serial.println();
  Serial.println("Done");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("");

  server.begin();
}

void allOff() {
  state = 0;
  analogWrite(redPin, 0);
  analogWrite(grnPin, 0);
  analogWrite(bluPin, 0);
}

//Write requested hex-color to the pins (10bit pwm)
void setHex() {
  state = 1;
  long number = (long) strtol( &hexString[0], NULL, 16);
  r = number >> 16;
  g = number >> 8 & 0xFF;
  b = number & 0xFF;
  r = map(r, 0, 255, 0, 1023);  //added for 10bit pwm
  g = map(g, 0, 255, 0, 1023);  //added for 10bit pwm
  b = map(b, 0, 255, 0, 1023);  //added for 10bit pwm
  analogWrite(redPin, (r));
  analogWrite(grnPin, (g));
  analogWrite(bluPin, (b));
}

//Compute current brightness value

//For serial debugging only
void showValues() {

  Serial.print("Status on/off: ");
  Serial.println(state);
  Serial.print("RGB color: ");
  Serial.print(r);
  Serial.print(".");
  Serial.print(g);
  Serial.print(".");
  Serial.println(b);
  Serial.print("Hex color: ");
  Serial.println(hexString);

  Serial.print("Brightness: ");
  Serial.println(V);
  Serial.println("");

}

void setup(){
  Serial.begin(9600);
  delay(1);
  pinMode(redPin, OUTPUT);  //declaration added
  pinMode(grnPin, OUTPUT);  //declaration added
  pinMode(bluPin, OUTPUT);  //declaration added
  setHex(); //Set initial color after booting. Value defined above
  WiFi.mode(WIFI_STA);
  WiFiStart();
  //showValues(); //Uncomment for serial output
}

void loop() {
  //Reconnect on lost WiFi connection (superfluous - will reconnect anyway)
  if (WiFi.status() != WL_CONNECTED) {
    WiFiStart();
  }

  WiFiClient client = server.available();

  if (!client) {
    return;
  }

  while(client.connected() && !client.available()) {
    delay(1);
  }

  //Respond on certain Homebridge HTTP requests
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }
        if (c == '\n') {
          Serial.print("Request: "); //Uncomment for serial output
          Serial.println(readString); //Uncomment for serial output

          //Send reponse
         client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          //On
          if(readString.indexOf("on") >0) {
            setHex();
            Serial.println("on");
            showValues();
          }

          if(readString.indexOf("xw") >0) {

            Serial.println("won");
            analogWrite(white, 1024);
          }

          if(readString.indexOf("yw") >0) {

            Serial.println("woff");
            analogWrite(white, 0);
          }

          //Off
          if(readString.indexOf("off") >0) {
            allOff();
            showValues();
          }

          //Set color
          if(readString.indexOf("set") >0) {
            hexString = "";
            hexString = (readString.substring(9,15));
            setHex();
            //showValues();
          }

          //Status on/off
          if(readString.indexOf("status") >0) {
          client.println(state);
          }

          //Status color (hex)
          if(readString.indexOf("color") >0) {
          client.println(hexString);
          }

          //Status brightness (%)
          if(readString.indexOf("bright") >0) {

          client.println(V);
          }

          delay(1);
          client.stop();
          readString="";
        }
      }
    }
  }
}

You are probably running out of RAM because you are using the String object instead of a fixed-size char[] buffer. This code, in particular:
if (readString.length() < 100) {
  readString += c;
}

Concatenating String objects using the overloaded plus operator allocates a whole new block of RAM for the new, longer string. It frees the previous memory, but since you keep adding one character at a time, new strings won't be able to be put into the once-used RAM.
You should instead use C-style strings (character arrays) and the standard functions for managing them, such as strnlen() and strncat(), etc. Note, I am suggesting the versions of string functions with a maxlen parameter, which helps avoid bugs due to unterminated strings.

I can't seem to implement this

Share what you’ve tried. Thus page has a good overview http://www.gammon.com.au/concat

I had to make a new question as the comment wouldn't let me copy all my changed code: https://arduino.stackexchange.com/questions/48066/nodemcu-keeps-dropping-out-implementation?noredirect=1#comment95555_48066

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


text:
Solution for two software serials
I've been working a while on a project using 3 Arduino Nanos, linked together using this tutorial Nick Gammon.
As I am not experienced with Arduino programming, I was making it step by step.
First I get all devices in one network, then managed to get the correct data sent from the correct device to one receiver. I added a Nextion display to visualize the received data. Then I have some physical buttons and some relays as well.
So far everything went fine until today. I wanted to send a command from the Nextion to the Arduino. Only then I realized that when using multiple software serial ports, only one can receive data at a time.
In my case I have an RS485 on SoftwareSerial and the Nextion.
I'm  feeling a bit upset now, as I soldered everything on a prototyping board as nice as I can. I tried to move the Nextion on to hardware serial, as that was quite easy to access, but the result was inconsistent.
Please, can someone suggest me how to change my project's hardware and what I need to program (Software Serial or Hardware Serial) to make it to work? Basically I am looking for the right direction now,  when I will get that I can figure out the rest by myself.

Please post your code and preferably your wiring. Hardware serial uses interrupts and should work OK with SoftwareSerial unless you are using a low baud rate. SoftwareSerial turns interrupts off and at low baud rates this might be long enough for hardware serial data to be missed.

If you have two different baud rates already try swapping the serial devices around. Put the faster one onto SoftwareSerial.

Thank you for your reply. At the moment i have both devices on 9600. How fast can i go with RS485? I will post code bit later, it is on my laptop at work. Also i want to say huge thank you to You, Nick Gammon for your website. For me being dumb beginner, finding lots of good stuff on it.

RS485 is really an electrical protocol. I don't see why it shouldn't work somewhat faster like 57600 baud.

Ok, now i broke everything, have to start from beginning. Will come back to this, when problems fixed. Thank you anyway. At least i know witch way to dig.

Cool bananas! All working now!

I turned my comments into an answer, which you can please accept if it helps you. That way, a future person with this problem will find an accepted answer, rather than an "unanswered question". Thanks!

Hardware serial, on the face of it, should be the more reliable because it uses hardware that can run simultaneously with other code. It uses interrupts to transfer a received byte from its internal register into program RAM.
Software serial, on the other hand, is somewhat more timing-dependent because it uses timing loops to detect each bit at the correct time. In order to do this, it turns off hardware interrupts in order to ensure that each timing loop runs at the expected speed.
If you use Software serial at the same time as hardware serial, the fact that Software serial turns off interrupts may mean that the processor doesn't get a chance to transfer the most recent byte from the serial hardware to RAM.
A work-around, if possible, is to use Software serial at the fastest possible baud rate. That means that interrupts are turned off for a shorter time. When they are turned back on the processor can recover the most recent hardware serial byte.
Thus, if you have two devices using serial, put the faster one onto Software serial, to reduce the time that interrupts are off.
RS485 does not, per se, specify a transfer rate. It is a balanced electrical protocol, which is designed to minimize the impact of noise over long cable runs.


text:
DHT11 Sensor Code Fatal Error
I recently tried using Hobbyist.co.nz's guide on the DHT11 sensor. I installed the Adafruit_Sensor and DHT11 Sensor libraries,  but it keeps returning with a fatal error.
Here is the code and the error:
#include <dht.h>

#define dht_dpin A0 //no ; here. Set equal to channel sensor is on

dht DHT;

void setup(){
  Serial.begin(9600);
  delay(300);//Let system settle
  Serial.println("Humidity and temperature\n\n");
  delay(700);//Wait rest of 1000ms recommended delay before
  //accessing sensor
}//end "setup()"

void loop(){
  //This is the "heart" of the program.
  DHT.read11(dht_dpin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");
  delay(800);//Don't try to access too frequently... in theory
  //should be once per two seconds, fastest,
  //but seems to work after 0.8 second.
}// end loop()

C:\Users\XXXXXX\Documents\Arduino\sketch_dec19c\sketch_dec19c.ino:2:17:

fatal error: dht.h: No such file or directory
#include <dht.h>

It doesn't look like you are using Adafriut's DHT library.

The examples I can see from Adafruit say
#include "DHT.h"

or
#include <DHT.h>

But you wrote
#include <dht.h>

They aren't the same.
Further, the examples for the Adafruit library show usage like:
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

But you call DHT.temperature and DHT.humidity.
If you are meaning to use the Adafruit library, you have to write your code according to their documentation.
Also of note, you have defined the type of the object as dht and the name as DHT, but for Adafruit, the type is DHT.
EDIT:
The example on the website you note has a downloadable zip file for the DHT library they use. You cannot assume that all libraries for interfacing a certain sensor will all have the same programming interface.


text:
RFID + LCD + Arduino Mega 2560 = RFID not printing correctly
My Arduino Mega isn't printing the RFID card's tag it simply prints the card's 2 digits at a time but deletes the previous prints. Can I get help with this?
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <LiquidCrystal.h>

Servo myservo;  //creates servo to control

const int rs = 26, en = 27, d4 = 28, d5 = 29, d6 = 31, d7 = 30;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int R=3;
int G=8;
int B=6;

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Approximate your card to the reader...");
  lcd.print("Place your card");
  lcd.setCursor(0, 1);
  lcd.print("Near reader");
  lcd.setCursor(0, 0);
  myservo.attach(7);//attatches servo to pin 7
  myservo.write(179);
}

void loop() {
  analogWrite(B, 255);
  // Look for new cards
  if (!mfrc522.PICC_IsNewCardPresent()) {
    return;
  }
  // Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial()) {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  byte letter;
  String content= "";
  for (byte i = 0; i < mfrc522.uid.size; i++) {
     lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     lcd.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
     lcd.setCursor(0, 0);
  }
  delay(1000);
  lcd.clear();
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "4F 60 3C D9") {
    //change here the UID of the card/cards that you want to give access
    Serial.println("Authorized access");
    lcd.print("Authorized");
    analogWrite(B, 0);
    tone(4, 900, 100);
    lcd.clear();
    Serial.println("Unlocking...");
    lcd.print("Unlocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(100);
    delay(15);
    Serial.println("Unlocked");
    lcd.print("Unlocked");
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 255);
    delay(5000);
    Serial.println("Relocking...");
    lcd.print("Relocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(179);
    delay(15);
    Serial.println("Locked");
    lcd.print("Locked");
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 0);
    delay(100);
  } else {
    Serial.println("Checking Card");
    lcd.print("Checking Card");
    lcd.setCursor(0, 1);
    delay(100);
    lcd.clear();
    Serial.println("Access denied");
    lcd.print("Access denied");
    analogWrite(B, 0);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(100);
  }
 lcd.clear();
 Serial.println("Ready");
 lcd.print("Ready");
}

you did not give a clear explanation ... what does this mean? deletes the previous prints

What it would do is display the two hexadecimal digits in rapid succession and only see the last two for a split second

still not a clear explanation ... are you talking about LCD or serial monitor window on your computer? ... you are sending data to both of those, and both of those can exhibit the behaviour that you describe

it is my lcd that is not doing what i want it to do

OK i fixed it. It is now this :
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <LiquidCrystal.h>

Servo myservo;  //creates servo to control

const int rs = 44, en = 45, d4 = 46, d5 = 47, d6 = 49, d7 = 48;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int R=3;
int G=8;
int B=6;

void setup()
{
  lcd.begin(16, 2);
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Place your card near reader");
  lcd.print("Place your card");
  lcd.setCursor(0, 1);
  lcd.print("Near reader");
  lcd.setCursor(0, 0);
  myservo.attach(7);//attatches servo to pin 7
  myservo.write(179);
}
void loop()
{
  analogWrite(B, 255);
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  lcd.clear();
  Serial.print("UID tag :");
  lcd.print("ID:");
  byte letter;
  String content= "";
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     lcd.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "4F 60 3C D9") //change here the UID of the card/cards that you want to give access
  {
    delay(5000);
    lcd.clear();
    Serial.println("Scanning Database");
    lcd.print("Scanning");
    lcd.setCursor(0, 1);
    lcd.print("Database");
    lcd.setCursor(0, 0);
    delay(5000);
    lcd.clear();
    Serial.println("Authorized access");
     lcd.print("Authorized");
    analogWrite(B, 0);
    tone(4, 900, 100);
    lcd.clear();
    Serial.println("Unlocking...");
    lcd.print("Unlocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(100);
    delay(15);
    Serial.println("Unlocked");
    lcd.print("Unlocked");
    delay(5000);
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 255);
    Serial.println("Relocking...");
    lcd.print("Relocking...");
    delay(1000);
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    myservo.write(179);
    delay(15);
    Serial.println("Locked");
    lcd.print("Locked");
    delay(100);
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 0);
  }else{
    delay(1000);
    lcd.clear();
    Serial.println("Scanning Database");
    lcd.print("Scanning Databas");
    delay(5000);
    lcd.clear();
    Serial.println("Access denied");
    lcd.print("Access denied");
    analogWrite(B, 0);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(100);
  }
 lcd.clear();
 Serial.println("Ready");
 lcd.print("Ready");
}

had to remove the lcd.setCursor(0, 1);
from line 57.


text:
Attempts with Sainsmart Motor Shield Not Working
I received the sainsmart motor controller a few days ago, and am now having trouble testing it. The Arduino I am using is an Arduino Mega 2560. I thought it was an I2C communication issue but that wasn't working. So here I am now asking for help.
Here is my wiring.

Here is my code:
#include <AFMotor.h>

AF_DCMotor motor(2);

void setup() {
 Serial.begin(9600);           // set up Serial library at 9600 bps
 Serial.println("Motor test!");

 // turn on motor
 motor.setSpeed(200);

 motor.run(RELEASE);
}

void loop() {
 uint8_t i;

 Serial.print("tick");

 motor.run(FORWARD);
 for (i=0; i<255; i++) {
  motor.setSpeed(i);
  delay(10);
 }

 for (i=255; i!=0; i--) {
  motor.setSpeed(i);
  delay(10);
 }

Serial.print("tock");

motor.run(BACKWARD);

 for (i=0; i<255; i++) {
  motor.setSpeed(i);
  delay(10);
 }

for (i=255; i!=0; i--) {
  motor.setSpeed(i);
  delay(10);
 }

Serial.print("tech");
motor.run(RELEASE);
delay(1000);
 }

I also tried this one:
#include<AFMotor.h>
 AF_DCMotor motor2(2);
void setup() {
 // put your setup code here, to run once:
 motor2.setSpeed(255);
}

void loop() {
 // put your main code here, to run repeatedly:
 motor2.run(FORWARD);
  }

None of the two worked. If someone could help me that would be great. Thank You!!!

the picture of your board is not a very good representation of the wiring. ... please draw a schematic.  ... there is a button for that when you edit your question

How am I supposed to represent the motor shield? I'll tell you the wiring. The sainsmart board connects all the pins on the side of the standard arduino uno except for pin 7 digital. The IC2 is connected to SDA(Digital 20) and SCL (Digital 21). The motor is connected to the M2 Terminal.
Thanks!!!!

I figured out the problem. One of the terminals was damaged during transportation. Now it's all good. Thanks for the help.


text:
Consequences of dynamically changing input/output configurations of digital pin?
I am creating an IC checker for a large chunk of the 74ls series (basic TTL logic chips), which means that I have 14 pins running to the IC to verify its functionality. One pin is power (+5V) and another ground (GND), which are both consistently in the same seven and fourteen pin positions respectively, but the remaining 12 are various inputs and outputs that vary depending on the IC type.
With that stated, will there be any consequences to dynamically reconfiguring a pin from input to output -- or vice versa -- as different IC types are selected? Weird behavior or electrical failure? What if the IC remains plugged in while the the pins reconfigure? What if said IC is powered on and providing power to a pin as it reconfigures?
If you were curious, I am using a joystick and LCD display as an interface to selecting the appropriate IC to check.

There's no problem reconfiguring pins.  It happens all the time.  One example is with ping sensors where the pin is used as an  output to send the ping and then switched to an input to wait for the response.  The only caveat is that you must be sure what you're connected to.  For instance, if you set a pin to OUTPUT and LOW and it just happens to be connected to a HIGH OUTPUT then you just fried your board.


text:
Sending a string from RPi to Arduino - Working Code
I've been researching for 2 days now trying to figure out how to receive a string via I2C on an Arduino. There are plenty of questions online but no real solutions or full tutorials... and sadly I threw my C++ book out years ago.
The code below compiles without error and receives the string correctly. (There are several commented out blocks that I've used to verify the data is being received.) The issue is printing the full received command string. I am unable to make it print in receiveEvent() or in the loop(). Ultimately I need it as a string such as "WIN-23-200" where I will explode the string by "-" to do something but I still can't get a hold of it.
If anyone can give me a nod in the right direction I'd appreciate it.
Thanks!
#include <Wire.h>

#define SLAVE_ADDRESS 0x04

volatile boolean receiveFlag = false;
char temp[32];
String command;

void setup() {
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);

  // define callbacks for i2c communication
  Wire.onReceive(receiveEvent);

  Serial.begin(9600);
  Serial.println("Ready!");

}

void loop() {
  delay(1000);
  if (receiveFlag == true) {
    Serial.println("inFlag");
    Serial.println(command);
    receiveFlag = false;
  }
}

void receiveEvent(int howMany) {
  //works as expected
  /*while (0 < Wire.available()) { // loop through all
    char c = Wire.read();
    Serial.print(c);
    }*/

  int count = 0;
  while (0 < Wire.available()) { // loop through all
    temp[count] = Wire.read();
    count++;
  }
  //temp[32-1]='\0'; //make sure its 0 terminated, didn't matter
  command = temp; //put char array into a string variable named command

  Serial.print(temp); // prints nothing....

  //Verify Array is Loaded..works great.
  //for (int i = 0; i < count; i++)
  //{
  //  Serial.println(temp[i]);
  //}
  receiveFlag = true;
}

We need to see both, the sketch of the master and the sketch of the slave. Please don't use the String object and certainly not in the function receiveEvent. Don't use Serial.print from within the receiveEvent as well. The receiveEvent is an interrupt function and the Serial.print uses interrupts. Use the howMany parameter or the Wire.available to fill the temp[] array. Be sure to zero-terminate the text in the array. Set the flag. In the loop read the flag and print the temp[] array. Remove the delay from the loop, you can check the flag as often as possible. Has the text a fixed length?

Thank you very much for the talkthrough.. super helpful to know what matters especially in a new(old) language.  Got it working thanks to this.

Here's the working code.  The hangup was my Raspberry Pi Master was adding a "cmd byte" to the string before transit. So when I would send "test" the Arduino received 5 bytes; "0test".  Based on feedback here I added the null after ea char and then shifted the array to eliminate the first byte and the Serial.print started working.
Here's the working RPi Master Python code:
# -*- coding: utf-8 -*-
import smbus
import time
# for RPI version 1, use bus = smbus.SMBus(0)
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

#http://www.raspberry-projects.com/pi/programming-in-python/i2c-programming-in-python/using-the-i2c-interface-2
def writeData(value):
    byteValue = StringToBytes(value)
    bus.write_i2c_block_data(address,0x00,byteValue) #first byte is 0=command byte.. just is.
    return -1

def StringToBytes(val):
        retVal = []
        for c in val:
                retVal.append(ord(c))
        return retVal

while True:
    print("sending")
    writeData("test")
    time.sleep(5)

    print('OPEN');
    writeData("OPEN-00-00")
    time.sleep(7)

    print('WIN');
    writeData("WIN-12-200")
    time.sleep(7)

And the Arduino Slave Code
#include <Wire.h>

#define SLAVE_ADDRESS 0x04

volatile boolean receiveFlag = false;
char temp[32];
String command;

void setup() {
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);

  // define callbacks for i2c communication
  Wire.onReceive(receiveEvent);

  Serial.begin(9600);
  Serial.println("Ready!");

}

void loop() {

  if (receiveFlag == true) {
    Serial.println(temp);
    receiveFlag = false;
  }
}

void receiveEvent(int howMany) {

  for (int i = 0; i < howMany; i++) {
    temp[i] = Wire.read();
    temp[i + 1] = '\0'; //add null after ea. char
  }

  //RPi first byte is cmd byte so shift everything to the left 1 pos so temp contains our string
  for (int i = 0; i < howMany; ++i)
    temp[i] = temp[i + 1];

  receiveFlag = true;
}

Hopefully this helps someone else, I searched for along time to put this together!

A couple resources that were helpful to me as well:
bus i2c command list:
link
Raspberry Pi bus cmd paramter explained well:
link

Well done. You don't have to shift it in receiveEvent. You can do "int cmd=Wire.read();" before the first for-loop. You can use the 'cmd' or not, and use it just to read the first byte. I would just read the data into the array and solve any problem or any cmd byte in the loop. When you are printing the received data, an interrupt with new data could occur during that, and you would print the first half of old data and the second half of new data. It can be avoided by copying the temp[] to a local array while the interrupts are turned off. Can you make temp[] also 'volatile' ? just to be sure.

Just one remark: your code is safe only because the Wire library has a 32 byte buffer, otherwise it can pollute the memory. My suggestion is to change the code in one of these ways: 1) char temp[32]; becomes char temp[BUFFER_LENGTH]; (BUFFER_LENGTH is defined in Wire.h) or 2) check that howMany is less than the length of the temp buffer. 2 is more robust, but 1 does less operations

onReceive is intended for use by slaves. master must request data from slave and wait for answer. look at MasterReader example from the Wire library

sorry for posting here after years but i need some help
This is my arduino code, the raspberry pi code is the same as above.
#include <Wire.h>
#define SLAVE_ADDRESS 0x04
volatile boolean receiveFlag = false;
char temp[32];
String command;
void setup() {
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(receiveEvent);
Serial.begin(1200);
Serial.println("Ready!");
}
void loop() {
if (receiveFlag == true) {
Serial.println(temp);
if (temp == 'test'){
Serial.print("it works");
}
receiveFlag = false;
}
}
void receiveEvent(int howMany) {
for (int i = 0; i < howMany; i++) {
temp[i] = Wire.read();
temp[i + 1] = '\0'; //add null after ea. char
}
//RPi first byte is cmd byte so shift everything to the left 1 pos so temp contains our string
for (int i = 0; i < howMany; ++i)
temp[i] = temp[i + 1];
receiveFlag = true;
}
i want to make it do something like just turning on an led when the received data is test (for example).I do receive the text (test) in the serial monitor but it does nothing when i used this command
if (temp == 'test'){
Serial.print("it works");
}
any help will be appreciated

This doesn't provide an answer to the question. To ask another question, just click Ask Question above. If you wish, include a link to this question to help provide context.

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


text:
Change the sequence of LEDs with button press
I am new to arduino.
I have created a circuit , here is the image:

I want something that as I press the button the sequence of LEDs will change and as I press the button again , the sequence will change again.
I programmed code as following but it don't works correctly:
int led1 = 11;
int led2 = 10;

int output = 2;
int input = 4;
int mode = 0;

void setup() {
  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(output,OUTPUT);
  pinMode(input,INPUT_PULLUP);
  digitalWrite(output,LOW);

}

void loop() {
  while(mode == 0 && digitalRead(input) == 1){
    digitalWrite(led1,HIGH);
    digitalWrite(led2,HIGH);
    delay(100);
    digitalWrite(led1,LOW);
    delay(100);
    digitalWrite(led1,HIGH);
    delay(100);
    digitalWrite(led2,LOW);
    delay(100);
    digitalWrite(led2,HIGH);
  }
  if(digitalRead(output) == 0){
    mode++;
    if(mode >= 2){mode = 0;}
  }
  while(mode == 1 && digitalRead(input) == 1){
    analogWrite(led1,255);
    delay(400);
    analogWrite(led1,150);
    delay(400);
    analogWrite(led2,255);
    delay(400);
    analogWrite(led2,150);
  }

}

According to the above code , two leds led1 and led2 are connected with arduino. When the button is off the both LEDs turns on then led1 turns off then turn on again , next time led2 turns off and turns on again.As the button will be pressed , brightness of led1 will be less than the brightness of led2 and then
will again be equal to the brightness of led2, then brightness of led2 will be less than the brightness of led1 and then will be equal to the brightness of led1. But as I press the button , nothing happens but the led1 and led2 keeps turning on and off . However sometimes when I press the button then it works.
What is the problem with my code and how to solve it?

@jsotola I mean that when the button is not pressed ,  the LEDs will turn off and then turn on again but when I will  press the button , the LEDs will be fading.

That is quite puzzling now.

@jsotola I have edited , have a look now.

Another example :As the button is kept off , the only led will blink and when the button will be pressed , the led will fade , code
Image of the circuit , When I press the button the led keeps blinking , don't fade , why it is so and how to solve this ?

@jsotola I mean there is no change when I press the button.

nothing happens but the led1 and led2 keeps turning on and off .... Since the LEDs are already flashing so when I press the button there is no change in the LEDs flashing i.e. nothing happens.

i think that i understand now. ... you have two display modes. ... clicking the button switches modes.  .... i think that you are not detecting the button press... write some test code that turns on the led when the button is pressed, off when released ..... also, you will need to debounce the switch when you are switching modes (once you get the switch to work)

If you put 9V battery on 5V and GND you gonna burn your arduino. For supply your arduino through GPIO: use max 5.5V on GND and VIN.

@Comeister I have connected 9V battery with my arduino but it don't burns. It is working like charm

Connect the 9 V supply to the “Vin” of the Arduino, not the “5V”. Otherwise the Arduino will “work like a charm” only until it dies. 2) Read the Blink Without Delay Arduino tutorial. You will learn that, if you want to do several things in at the same time (like blinking an LED and being responsive to the button), you have to ban delay() from your code.

I'm voting to close this question as off-topic because it has been abandoned by the asker

There are a few issues with your wiring.

As already stated in comments, you should not connect the battery to
the 5V input of the Arduino. Use the “Vin” input instead.
You should put a current-limiting resistor in series with each of your
LEDs. Any value in the range 330 Ω – 1 kΩ should be fine.
Your Arduino (and your LEDs) will last longer if you stop abusing it!
There is no point in using two digital IO pins to read a button. Just
connect the button between a digital input and GND. Alternatively, you
can wire it like in Holmez's answer, but that requires an extra wire
and a resistor.

And there are two main issues with your code:

You forgot to debounce the button. Mechanical button are bouncy.
The easiest way to debounce them is to use a ready-made library like,
e.g., Bounce2.
You are using delay(), which means you cannot respond to user input
while your Arduino is busy delaying. You should manage your timings
with milis() instead, as explained in the Blink Without Delay
Arduino tutorial.

Here is my take at your problem. This is based on the
finite state machine programming pattern, with a state defined by
two variables. There is a mode variable used to keep track of whether
we are in “digital” or in “analog” mode. And there is a “phase” variable
used to keep track of the phase along the blinking pattern. Phases 0
through 3 correspond to (LED1/LED2) in the states: (HIGH/HIGH),
(LOW/HIGH), (HIGH/HIGH), (HIGH/LOW). Note that, for simplicity, the LEDs
are controlled with analogWrite(), even in “digital” mode.
#include <Bounce2.h>

const uint8_t BUTTON_PIN = 4;
const uint8_t LED1 = 11;
const uint8_t LED2 = 10;

Bounce button;

void setup()
{
    button.attach(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    analogWrite(LED1, 255);
    analogWrite(LED2, 255);
}

/*
 * Vary the LED brightnesses along the following pattern:
 *
 *  phase:   0   1   2   3   0
 *          ___     ___________
 *  LED1:      \___/
 *          ___________     ___
 *  LED2:              \___/
 */
void loop()
{
    static enum { DIGITAL, ANALOG } mode = DIGITAL;
    static uint8_t phase = 0;
    static uint16_t phase_duration = 100;
    static uint8_t low_level = 0;
    static uint16_t last_change = 0;

    // Switch modes on button presses.
    button.update();
    if (button.fell()) {
        switch (mode) {
            case DIGITAL:
                mode = ANALOG;
                low_level = 150;
                phase_duration = 400;
                break;
            case ANALOG:
                mode = DIGITAL;
                low_level = 0;
                phase_duration = 100;
                break;
        }

        // Set initial phase.
        phase = 0;
        last_change = millis();
        analogWrite(LED1, 255);
        analogWrite(LED2, 255);
    }

    // Switch phase after phase_duration elapsed.
    if (millis() - last_change >= phase_duration) {
        last_change += phase_duration;
        phase = (phase + 1) % 4;
        switch (phase) {
            case 0:
                analogWrite(LED2, 255);
                break;
            case 1:
                analogWrite(LED1, low_level);
                break;
            case 2:
                analogWrite(LED1, 255);
                break;
            case 3:
                analogWrite(LED2, low_level);
                break;
        }
    }
}

Use a boolean:
boolean blink = false;
if(digitalRead(output) == 1){
    blink = !blink;
}

if(blink == true){
    digitalWrite(led1,HIGH);
    digitalWrite(led2,HIGH);
    delay(100);
    digitalWrite(led1,LOW);
    delay(100);
    digitalWrite(led1,HIGH);
    delay(100);
    digitalWrite(led2,LOW);
    delay(100);
    digitalWrite(led2,HIGH);
}else{
    analogWrite(led1,255);
    delay(400);
    analogWrite(led1,150);
    delay(400);
    analogWrite(led2,255);
    delay(400);
    analogWrite(led2,150);
}

It is not working.

I think delay command don't let the button being detected when pressed.

There are several issues that I can see.
To start with, you have the button wired to 2 pins, one configured as an input and one as an output. Starting out, you should connect the button as in the example below.

This will read LOW until the button is pressed.
I suspect in your case that because your using in INPUT_PULLUP, your button will read HIGH when the button isn't pressed, but will continue to read HIGH even after the button is pressed - which leads to the second issue of your first while loop - because mode is initialised to 0, and the button is always reading HIGH, the condition for your while loop will always be true, consequently, the loop will never exist.
The next issue (if you change the code so the first while loop does exit) is that you're trying to do a digitalRead on an OUTPUT pin - as an OUTPUT pin, it will never detect the state of the button.
Another issue will be that when you press the button and the if statement is reached (because digitalRead(input) == 0), even if the button is pressed for the shortest time, the loop function will be run several times, and the if statement will be run several times which will effectively result in the mode containing either 0 or 1 almost at random.
While the best way to fix this is with an interrupt (another lesson for another day), a simple way is something like this:
    int buttonPressedProcessed = 0; // an indicator so we know if the button press has been processed.

void setup() {
    ...
}

void loop() {
  while(mode == 0 && digitalRead(input) == 1){
    buttonPressedProcessed = 0; // reset button pressed and processed indicator
    ...
  }
        // check also the button pressed and processed indicator
  if(digitalRead(input) == 0 && buttonPressedProcessed == 0){
    buttonPressedProcessed = 1; // set button pressed and processed indicator
    mode++;
    if(mode >= 2){mode = 0;}
  }
  while(mode == 1 && digitalRead(input) == 1){
    buttonPressedProcessed = 0; // reset button pressed and processed indicator
    ...
  }
}

your using in INPUT_PULLUP, your button will read HIGH when the button isn't pressed, but will continue to read HIGH even after the button is pressed - which leads to the second issue of your first while loop - because mode is initialised to 0, and the button is always reading HIGH, the condition for your while loop will always be true, consequently, the loop will never exist. .... it will read zero after I press the button , looks like you have not tested the code.

@J.Doe I have struck that through, as you were right about that bit. The rest of the answer still stands though, and should provide the solution to your problem.

It is not working as I expected , if I increase the time in delay in the code, the button will not work when it is pressed during delay.

This is a bit misleading. There's nothing wrong with the way the button is wired in the question; it may be unecessary to use an output for the low side of the button, but it is entirely workable, and that output is driven low.


text:
How to call an interrupt when any one of the 12 defined digital inputs go high?
I'm using an Arduino Mega 2560 board. I need to sense 12 digital pins (pins 36-47) coming from another board continuously and display power when they are low.
When any of the 12 pins go HIGH, an interrupt must be created. In the ISR part, I'll be making one new digital pin (PIN 35) go HIGH (this is initialized as low in setup function).
To reset from interrupt, I need to press the "#" key in the keypad. This should make PIN 35 go low again and program should function normally again.
This is my code without using Interrupt.
#include "LiquidCrystal.h"
#include <Keypad.h>

// initialize the library by providing the nuber of pins to it
LiquidCrystal lcd(8,9,4,5,6,7);
 const byte ROWS = 4; // four rows
const byte COLS = 3; // three columns
char keys[ROWS][COLS] = {
 {'1','2','3'},
 {'4','5','6'},
 {'7','8','9'},
 {'*','0','#'}
};
byte rowPins[ROWS] = {22, 24, 26, 28}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {30, 32, 34};     //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
float fwd_voltage = 0.0,rev_voltage = 0.0;
float fpower,rpower;
int sensorValue=0;

void setup() {
  int i;
  for (i=36;i<48;i++) {
    pinMode(i,INPUT);
  }
  pinMode (35, OUTPUT);
  digitalWrite(35,LOW);
}

void reset () {
  while(1) {
    lcd.begin(16,2);
    lcd.setCursor(0,0);
    lcd.print("press # to reset");
    char key = keypad.getKey();
    if (key=='#') {
      digitalWrite(35, LOW);
      break;
    }
  }
}

void process(int pin, char* text) {
  if (digitalRead(pin) == HIGH && digitalRead(35)==LOW) {
    // Use HIGH instead of 1
    lcd.print(text);
    digitalWrite(35, HIGH);
    reset ();
  } else {
    int analog_value = analogRead(A0);//reading forward voltage
    int analog_valuer = analogRead(A1);//reading reverse voltage
    fwd_voltage = (analog_value * 5.0) / 1024.0;
    rev_voltage = (analog_valuer * 5.0) / 1024.0;
    fpower =  ((fwd_voltage)*(fwd_voltage)*10000);
    rpower = ((rev_voltage)*(rev_voltage)*10000);
    lcd.setCursor(0,1);
    lcd.print("REV= ");
    lcd.print(rpower);
    lcd.print("W");
    delay(500);
    lcd.setCursor(0, 0);
    lcd.print("FWD= ");
    lcd.print(fpower);
    lcd.print("W");
    delay(500);
  }
}

void loop() {
  lcd.begin(16,2);
  // set cursor position to start of first line on the LCD
  lcd.setCursor(0,0);
  process(36, "vswr");
  process(37, "thermal");
  process(38, "overdrive");
  process(39, "A1-B1 fault");
  process(40, "A1-B2 fault");
  process(41, "A1-B3 fault");
  process(42, "A1-B4 fault");
  process(43, "A2-B1 fault");
  process(44, "A2-B2 fault");
  process(45, "A2-B3 fault");
  process(46, "A2-B4 fault");
  process(47, "driver fault");
}

How do I modify the program to add an interrupt so that my board works faster and efficiently? BTW I'm new to programming so there might be some mistakes in the program and also I didn't write the program small and efficient.
The interrupt service routine should consist of this part of the above program:
lcd.print(text);
digitalWrite(35, HIGH);
reset ();

My interrupt should detect this part of the program.
if (digitalRead(pin) == HIGH && digitalRead(35)==LOW)

You are kind of unlucky. The ATmega2560 MCU has 32 pins capable of
generating interrupts (counting the INTn and PCINTn, not sure all of
them are routed to board headers), but none of the pins you have chosen
is interrupt-capable.
I suggest you combine your 12 signals, using external logic, into a
single interrupt signal. You would then, in the ISR, sort out which
individual signal triggered the interrupt. A pair of 74HC4075 chips
should be enough to OR together the 12 inputs.

i'll try that. What about PINCHANGEINTERRUPT library? can I use it to use my pin as interrupt pins?

@aparna: You could use pin change interrupts (PCINT) if you can rewire your project and route the 12 relevant signals to PCINT-capable pins. But beware that you get interrupted on both signal edges. If you combine the signals using external logic, a regular interrupt pin would be more convenient, as it allows you to choose either the falling or the rising edge.

Get rid of the 2 delay calls in your process() function. You are just needing to display the error text, so you don’t really need interrupt speed.
You have a 1s delay In total for every time you call the process() function. That doesn’t seem necessary.

i'll get rid of delays but actually I not only need to display error text but also shutdown power of the system i'm controlling. that's why I'm making pin 35 HIGH.

How quickly does your shutdown action need to occur? If it's on the order of tenths or hundredths of a second, you can probably get away with polling. If you require millisecond response time, then you may need to try to solve the interrupt issue.

I think 1/100th second is enough for me. How can I improve the polling speed ? I have already got rid of delays. Moreover removing delay is making the lcd print faster and i'm unable to read. is there any better way?

@aparna: Don't refresh the LCD too often, refresh it only after a certain time has elapsed. Use millis() to know when it's the right time. See the Blink Without Delay Arduino tutorial.


text:
Can we use analog input pins as a parameter of analogWrite() for PWM?
int led = A1;

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

void loop() {
  analogWrite(led, 188.7);
  delay(100);
  analogWrite(led ,0);
  delay(100);
}

Like this and it works! I mean I am getting the exact voltage as calculated while mapping 5V between 0-255

you say it works ... so what is your question?

analogWrite doesn't take float value. the second parameter is int

On the Nano, only the pins D3, D5, D6, D9, D10 and D11 are PWM-capable.
If you try to analogWrite() to any other pin, you will get either
0 V (if you write any value less than 128) or 5 V (for any
other value).
If you get 3.7 V when 5 V is expected, that's because either
your power supply is too weak, or you are putting too a heavy load on
the pin.

How do I use the analog IO pins for giving an analog output on the Nano?

@AaronJohnSabu: You don't. The nano cannot give analog output, only PWM.

PWM output works for my case. But does this mean that the analog pins of an Arduino Nano can only take input and not give an output at all?

@AaronJohnSabu: The analog pins can provide output, but only logic (either LOW or HIGH) output.

Exactly :). How do we do that? Can you point me to an answer that talks of the same?

@AaronJohnSabu: Like any other logical output: pinMode(A0, OUTPUT); digitalWrite(A0, HIGH);


text:
Read analog signal over the SPI bus using MCP3201 ADC and Arduino Uno
It is possible to use the SPI bus when the Vref of MCP3201 ADC is 2.5V?
On the setup i just finished, I used two linear regulators: 5V -> 3.3V to power the MCP602 op-amps and MCP3201 ADC, and another one 5v -> 2.5V for the Vref.
Everyone recommends to connect the Vref from MCP3201 to Arduino's 5V but this does not apply in my case.

The green connector is connected to GND and ADC's Dout where the measured voltage fluctuates from 0.180V when i touch the sensor and his shield, to 0.6V when i'm not touching those parts.
I have no ideea if this is a normal behaviour but everything looks fine to me.
Voltage measured at the output of A4 ( MCP3201 +IN ) is 0.85V and the current Iref is 1mA(through the yellow jumper) as they recommend.
Sorry if these details are a bit off-topic but i think they are relevant to the ADC role in this setup.

It is possible to use the SPI bus when the Vref of MCP3201 ADC is 2.5V?

Of course it is. VREF is purely a reference voltage for taking measurements. It has no other role.
If you look at the functional block diagram from the datasheet:

You can plainly see that VREF is only connected to the DAC that is used as part of the SAR feedback loop. Everything else is fed from VDD

Now it makes sense. So Dout, CLK, CS and GND should be the only pins connected to Arduino for SPI communication. CS->pin9, Dout->pin12, CLK->pin13 and GND->GND.
Is this correct?

That is correct.

Thank you so much for clarifying this aspect. I came from web development so Arduino, C++ and electronics are new and beautiful territories for me.


text:
Need to control 2 DC motors powered using arduino mini and l298n from about range of 100m
I need to control 2 DC motors which are arranged with arduino mini and L298N module from a distance of 100m wirelessly, what is the easiest and cheapest way of doing so?I checked RC controllers and xbee but they are way too expensive!
Any help will be appreciated!

Welcome to Arduino:SE. Please be aware that this is not a free design house or an on-demand online technical encyclopedia. You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

The cheapest way is probably using nRF24L01+, a 2.4 GHz transceiver. It should be possible to communicate over 100 m, using a slow speed and without any obstacles in between. If you need a better/faster communication, either use a version with an external antenna and/or use other frequences (using different transceivers, below 1 GHz). The last options are more expensive.


text:
How to read ASCII values from AT24C32 IC using Arduino? And what is serial.begin(?) in that EEPROM?
#include<Wire.h>
#include<Eeprom24C32_64.h>
#define EEPROM_ADDRESS 0x000

void setup() {
  Serial.begin(9600);
  eeprom.initialize();
  const word address = 0x000;
  const byte count = 94;
  byte inputBytes[count] = { 0 };
  byte outputBytes[count] = { 0 };
  Serial.println("Read bytes from EEPROM memory...");
  eeprom.readBytes(address, count, outputBytes);
  Serial.println("Read bytes:");
  for (byte i = 0; i < count; i++) {
    Serial.write(outputBytes[i]);
    Serial.print(" ");
  }
  Serial.println("");
}

void loop() {
}

Next code... I have tried many sketches.
#include <EEPROM.h>

void setup () {
  Serial.begin (115200);
  Serial.println ();
  for (int addr = 0x0000; addr < 0x0010; addr++) {
    Serial.print ("Address = ");
    Serial.print (addr, HEX);
    Serial.print (", value = ");
    Serial.println (EEPROM.read(addr), HEX);
  }
}  // end of setup

void loop () {
}

And most of the sketches check the internal EEPROM of the Arduino, not the external, stored on address 0x000. I want to read data from external AT24C32.

And what have you tried...?

@IHaveQuestion Please don't post code in the comments. Edit your question and add the code there.

@Majenko done code added plz help to solve this

@sempaiscuba done all codes

You have to know what the I2C address of your EEPROM is. Right now you have
#define EEPROM_ADDRESS 0x000

The example from the library you cite has this:
/**************************************************************************//**
 * \def EEPROM_ADDRESS
 * \brief Address of EEPROM memory on TWI bus.
 ******************************************************************************/
#define EEPROM_ADDRESS 0x50

Then, you have to create an instance of the Eeprom24C32_64 object:
static Eeprom24C32_64 eeprom(EEPROM_ADDRESS);

That sets up the object for the EEPROM on the right I2C address, so you can later use the eeprom object to read and write.

Your picture shows an LCD display. Are you expecting output to that?


text:
How to read Serial data when multiple functions are Running?
I want to halt the execution of that code, when arduino is receiving serial data for the execution. Right now the Serial data runs when the other code has completed its execution. How can I do it ?
void loop() {
    dmd.setBrightness(brighVal); // set the brightness to led matrix
    scroll();  //function to scroll message

}
void serialEvent() {
  while (Serial.available()) {
    Jsondata = Serial.readString(); //reading json data from APP
    DynamicJsonBuffer jsonBuffer;
    Serial.println(Jsondata);
    JsonObject& root = jsonBuffer.parseObject(Jsondata);
    if (root.containsKey("BiM")) {
      brighVal = root["BiM"];
      switch (brighVal) {   // set's the value of brightness according to brighVal
        case 0:
          brighVal = 2;
          break;
        case 1:
          brighVal = 10;
          break;
        case 2 :
          brighVal = 25;
          break;
        case 3 :
          brighVal = 200;
          break;
      }
    }
  }
}
void scroll() {
  dmd.clearScreen( true );
  dmd.selectFont(Arial_Black_16);
  dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
  long start = millis();
  long timer = start;
  boolean ret = false;
  while (!ret) {
    if ((timer + 30) < millis()) {
      ret = dmd.stepMarquee(-1, 0);
      timer = millis();
    }
  }
}

Then let scroll return immediately
void scroll() {
    static long timer = 0;
    static boolean scroll = true;
    if(scroll){
        dmd.clearScreen( true );
        dmd.selectFont(Arial_Black_16);
        dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
        scroll = false;
        timer = millis()
    }else {
        if ((millis() - timer) > 30)  {
            scroll = dmd.stepMarquee(-1, 0);
            timer = millis();
        }
    }
}

The static keyword means that the value of the variable will be kept across calls.
I used the fact that it will be called in a loop to remove the while loop inside. I split the function up into 2 parts: The reset and the update. We first run the reset to init the marquee. After the reset it will set the boolean so the next time it will enter the update part. Then I used the exit condition of the original loop to make it reenter the update part next time.

it worked .Can you please explain the changes? Thank you so much for helping out.

@RaviParmar I added some explanation.

What if i have multiple functions @ratchetfreak. for example

@RaviParmar Do the same for each function, make sure that no function ever blocks for an extended period of time but instead returns instead. Then using saved state in a global or static local resume the correct actions.

thank you @ratchetfrek. it seems that i have used  lot of delay functions in all the functions because of which arduino got halted.

I am facing some weird issue.The second message is displayed first and  first  text in scroll is splitting into two half.void loop(){ scroll(); Split(); }void Split() { static long Splittimer = 0;static boolean SplitState = true; if (SplitState) {dmd.clearScreen(true); dmd.selectFont(SystemFont5x7);dmd.drawString(0, 0, "World", 5, GRAPHICS_NORMAL); dmd.drawMarquee("Scrolling text", 15, 32, 8);  SplitState = false;Splittimer = millis(); }else {  if ((millis() - Splittimer) > 30)  {SplitState = dmd.stepSplitMarquee(8, 15); scrolled  Splittimer = millis(); } }} @ratchetfreak


text:
Fill an Array with Values
I have a function in which I change the pinMode on many of my Arduino's pins based on a passed in mode. I first construct an array of bytes specifying each pin to be an input or an output and then I iterate through the array to set all the pins.
void pinout(byte mode) {
  switch(mode) {
    case 0: char pins[13] = {'O','O','I','I','O','I','I','I','I','O','I','I','O'}; break;
    case 1: char pins[13] = {'O','I','I','O','O','I','O','O','I','O','I','O','I'}; break;
  //etc..
  }
  for(byte i = 0; i <= 13; i++) {
    if(pins[i] == 'I') pinMode(i, INPUT);
    else pinMode(i, OUTPUT);
  }
}

However, since the array is defined inside the switch statement, I loose scope of the pins array when I move onto the for loop. I tried defining the pins[] outside of the switch statement, but then I am confused on how to populate it efficiently. These all threw errors when I tried to populate the variable inside the switch statement:
pins[0,1,2,3,...,12,13] = {...};
pins[13] = {...};
pins[] = {...};
pins = {...};

I know I could go through each entry individually, but this could be rather inefficient use of memory and computational power as I add more cases. Any ideas?

Since your values are all constant you can define them all as constant values and just select between them. The simplest way is to add an extra dimension to your arrays:
const char pins[2][13] =
    {'O','O','I','I','O','I','I','I','I','O','I','I','O'},
    {'O','I','I','O','O','I','O','O','I','O','I','O','I'}
};

for(byte i = 0; i < 13; i++) {
    if(pins[mode][i] == 'I') pinMode(i, INPUT);
    else pinMode(i, OUTPUT);
}

(Note: An array of size 13 has entries 0-12.)
However, that is very inefficient.  Since you only have two states, I and O, and there are only 13 entries, you can store each array as a single 16-bit value:
const uint16_t pins[2] = {
    0b0110111101100,
    0b1010100100110
};

for(byte i = 0; i < 13; i++) {
    if((pins[mode] & (1 << i)) pinMode(i, INPUT);
    else pinMode(i, OUTPUT);
}

(Note: the data is stored backwards - pin 0 is on the right, pin 12 on the left.)

Just out of curiosity, how does marking a variable as const improve performance and/or memory? Is it similar to making a set-byte buffer array in other languages?

On a little 8 bit Arduino it doesn't unless you also start working with PROGMEM. On 32-bit systems though it generally means the array takes no RAM.

I know I could go through each entry individually, but this could be
  rather inefficient use of memory and computational power as I add more
  cases.

The compiler produces assembly/machine code that takes the same effort to load the array, so it's not that inefficient. The bracket arrangement is just a construct for easier to read code.

So, are you saying that filling my array like this: char pins[13]; pins[0] = 'I'; pins[1] = 'O'; ... would be similar in memory footprint to this: char pins[13] = {'I', 'O',...};?

Pretty much, though @Majenko has suggested a very memory efficient solution, using a bit array (i.e, a single 16-bit value) rather than an array of 12 bytes with only two possible values.

@BenjaminBrownlee: char pins[13] = {'I', 'O',...} only works as a global (or static) initialization. It's more efficient than the alternative, as the copying is handled by the __do_copy_data routine of the C run time, which copies the whole program's data section from flash to RAM in one go.


text:
Battery life with Nano v3
Easy secret knock detector to trigger anything with only an Arduino and a few cheap components

First of all I need to state that I'm new to Arduino and electronics in general. My question is about a project where the Nano is being powered up with a 12v rechargeable li-ion 2800 mAh battery on pins VIN and GND.
I'm using the 5v Nano pin to power a SRD-05VDC-SL-C relay along with the ground pin from the Nano. The IN pin on the relay is from the D11 pin on the Nano. So far so good. I'm also using the same 12v battery to power up a solenoid latch, which energizes for just a few seconds.
When I tested this setup (less the relay AND solenoid) for battery life, my volt meter read 9.8v and 1 hour later 2.8v. causing the Nano to go off.
How can I increase battery life?
This is the link to the code I used:

I'm not having an issue with the code or the operation of the setup but the battery life is unacceptable.

please draw a schematic. there is a button for that when you edit your post. ... also, the arduino does not do anything by itself, i am sure there is a program involved. please post that.

I don't quite follow your schematic. What are T1 and T2?

Hi, you just added a link to a YouTube video without any introduction. Could you explain the purpose of the video?

Fritz, you edited my answer to (attempt to) add a link to a YouTube video about a "Easy Secret Knock Detector" and have now edited your question to add the same link. What is your purpose in doing this?

OK, it looks like the YouTube video is what this project is based on. You could edit your question to make all this clearer.

I'm a bit surprised you have the latch connected to what I assume is the NC output of the relay. That means the latch is energised most of the time. Is that right?

Nick T1,T2 are screw terminals on a circuit board to attach the latch and relay switch.

Draining a 12V  batterypack down to 2.8V is very bad for the longevity of li-ion batteries. Please add some kind of battery (undervoltage) protection to your project.

Something is wrong with your setup. I don't have a Nano to hand to test, but it would consume similar current to a Uno (probably less) which is around 50 mA. Thus, using a 2800 mAh battery you should have a life of 2800/50 = 56 hours.
Li-ion batteries come in multiples of cells, where individual cells have a nominal voltage of 3.6V (thus you probably have three cells giving 10.8V). Deeply discharged they will have a voltage of 3.0V per cell (a total of 9V for your three cells). If you started at 9.8V as you stated, then the cells would have been 90% discharged already which probably accounts for the short running time.
Assuming you haven't wired it in a strange way (and it would help to show the wiring and possibly a photo) I suggest you try with a fully-charged battery.

Another helpful thing to do would be to measure the current consumption of the battery using a multimeter. Make sure you read up on how to measure current with a meter or you may damage something (example here).
The basic idea is shown in this photo:

The meter is placed in series with the battery and the Arduino. The negative side of the battery goes to the Arduino in the usual way. The positive side of the battery goes into the "milliamps" input of the meter (which is set to 200 mA range in my case) and then the common (black) lead from the voltmeter goes to the positive (Vin) side of the Arduino.
You can see that in this particular case, with a 9V battery, the Arduino is consuming 57.7 mA.  I don't quite believe that reading as re-measuring with a more expensive meter gave a reading of 51.1 mA. Still, that gives you a ball-park figure. And it shows that spending a bit more on a better meter gives you more accurate results. :)

I have a page about power saving and you can also refer to the Wikipedia page about Li-ion batteries.

my volt meter read 9.8v and 1 hour later 2.8v. causing the Nano to go off.

For a 12V Li-ion battery get down to 2.8V there is something seriously wrong with its protection circuitry. It should cut the battery out at 3V per cell, that is at 9V if you have 3 cells in series.

Nick, I decided the battery needs to be changed out. Waiting for the replacement.


text:
Can we use serial.begin command anywhere in code?
When to use this command? What difference it would create if I add this command in loop function, setup function and declaration section?

You cannot call Serial.begin() in a declaration. Like any program
instruction, you can only use it from within a function. As stated in
Juraj's answer, you can call it as many times as you want. However,
most often it only makes sense to do this in setup(), in order to
initialize the serial link once and for all at the beginning of your
program. Why would you ever want to do this initialization multiple
times?
Thinking about it, I can see two possible scenarios:

Your UART is connected, through a suitable transceiver, to an RS-485
bus. You have several slaves on this bus that require different UART
configurations (different baud rates, or number of data bits, or
parity). Then, each time you want to address one slave, you first
set your UART to the configuration suitable for that particular
slave. In this kind of situation, however, it would be more
convenient to arrange for all the slaves to share the same UART
configuration, if at all possible.
Your UART is connected to a device that continually sends data you
are not interested in. This could be, e.g., a GPS module. Since you
don't want your program to be interrupted every time a character is
received, you keep the UART disabled. Only when you do want the data
you enable it with Serial.begin(), you read as much as you need,
then you disable it again with Serial.end().

There may be other situations, but I bet they are all quite atypical
scenarios. The common practice is to call Serial.begin() once in
setup(), and have the UART enable from there on.

Serial.begin sets the baud rate. And the baud rate is important to the other side of the line. You can use Serial.begin where you need it, only care that the other side of the line has that baud rate too.
I use Serial1.end and Serial1.begin to change the baudrate in a Firmata sketch for Uno WiFi. Some seconds after the start the sketch detects esp flashing sequence on Serial. If detected, the sketch switches the baudrate of Serial1 from Firmata's optimal 57600 to bridge the flashing of esp at 230400 baud.


text:
ATtiny85 and MPU-6050 Gyroscope
I'm doing a project that involves sending MPU-6050 gyroscope data via serial communication to the laptop. Is ATtiny85 micro-controller suitable for this job? Is it powerful enough to do it? I was thinking of using an Arduino nano instead. please give me your opinion.

The attiny85 doesn't (really) support USB. So you'd need to add something like usb-to-serial converter. Just save yourself a lot of headache and just use a Nano.


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:
LSM9DS1: Inconsistent data from an accelerometer
I'm currently getting inconsistent data from the accelerometer of my Adafruit LSM9DS1. To be more precise I either get a value close to the correct gravity (eg. 9.496515) or some reading like it was in space/free fall (eg. -0.023928225).
This seems to happen on all three the axes (I tried rotating the LSM9DS1).
I get the same behavior with FIFO enabled or not and with the Gyro enabled or not.
This is a set of 32 consecutive samples that I read from the FIFO memory:
result = {float[32][]@5092}
 0 = {float[3]@5100}
  0 = -0.41754755
  1 = 0.19501504
  2 = 9.519247
 1 = {float[3]@5112}
  0 = -0.421735
  1 = 0.19980069
  2 = 9.51805
 2 = {float[3]@5120}
  0 = -0.4229314
  1 = 0.20757735
  2 = 9.510274
 3 = {float[3]@5128}
  0 = -0.4127619
  1 = 0.2207379
  2 = 9.502497
 4 = {float[3]@5139}
  0 = -0.39302114
  1 = -0.06580262
  2 = -0.0017946169
 5 = {float[3]@5140}
  0 = -0.06939186
  1 = -0.045463633
  2 = -0.020937197
 6 = {float[3]@5141}
  0 = -0.05742774
  1 = -0.03469593
  2 = -0.0317049
 7 = {float[3]@5142}
  0 = -0.053838514
  1 = -0.039481573
  2 = -0.041874394
 8 = {float[3]@5143}
  0 = -0.054436717
  1 = -0.052642096
  2 = -0.043669015
 9 = {float[3]@5144}
  0 = -0.059820566
  1 = -0.068793654
  2 = -0.03469593
 10 = {float[3]@5145}
  0 = -0.06819545
  1 = 0.22731815
  2 = -0.019142581
 11 = {float[3]@5146}
  0 = -0.38644087
  1 = 0.2225325
  2 = -0.00418744
 12 = {float[3]@5147}
  0 = -0.40079778
  1 = 0.21535406
  2 = 9.505488
 13 = {float[3]@5148}
  0 = -0.40977085
  1 = 0.21355942
  2 = 9.525827
 14 = {float[3]@5149}
  0 = -0.40917268
  1 = 0.21296123
  2 = 9.540783
 15 = {float[3]@5150}
  0 = -0.40558344
  1 = 0.2207379
  2 = 9.5455675
 16 = {float[3]@5151}
  0 = -0.39960137
  1 = 0.22671993
  2 = 9.544371
 17 = {float[3]@5152}
  0 = -0.39302114
  1 = 0.22791636
  2 = 9.534203
 18 = {float[3]@5153}
  0 = -0.3906283
  1 = 0.21535406
  2 = 9.517452
 19 = {float[3]@5154}
  0 = -0.38584265
  1 = 0.19441684
  2 = 9.496515
 20 = {float[3]@5155}
  0 = -0.384048
  1 = 0.17347965
  2 = -0.023928225
 21 = {float[3]@5156}
  0 = -0.38883367
  1 = 0.15553348
  2 = -0.042472597
 22 = {float[3]@5157}
  0 = -0.39541394
  1 = -0.014356935
  2 = -0.05802595
 23 = {float[3]@5158}
  0 = -0.40259242
  1 = -0.026919257
  2 = -0.06580262
 24 = {float[3]@5159}
  0 = -0.40977085
  1 = -0.03589234
  2 = -0.071186475
 25 = {float[3]@5160}
  0 = -0.4151547
  1 = -0.040677987
  2 = -0.062213387
 26 = {float[3]@5161}
  0 = -0.421735
  1 = -0.03888337
  2 = -0.04965107
 27 = {float[3]@5162}
  0 = -0.42831525
  1 = -0.040677987
  2 = -0.032303106
 28 = {float[3]@5163}
  0 = -0.4372883
  1 = -0.04426722
  2 = -0.014356935
 29 = {float[3]@5164}
  0 = -0.445065
  1 = -0.04785645
  2 = 9.496515
 30 = {float[3]@5165}
  0 = -0.44865423
  1 = -0.04666004
  2 = 9.503693
 31 = {float[3]@5166}
  0 = -0.44865423
  1 = -0.04426722
  2 = 9.506086

As you can see 15 times the Z axis shows the correct value and 17 shows -0.
This is how I'm initializing the sensors:
        // soft reset & reboot accel/gyro
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG8, (byte) 0b00000101);
        // soft reset & reboot magnetometer
        writeRegByte(SensorType.MAG, REGISTER_CTRL_REG2_M, (byte) 0b00001100);

        SystemClock.sleep(10);

        byte idXg = readRegByte(SensorType.XG, REGISTER_WHO_AM_I_XG);
        byte idMag = readRegByte(SensorType.MAG, REGISTER_WHO_AM_I_M);
        if (idXg != XG_ID || idMag != MAG_ID) {
            throw new IllegalStateException("Could not find LSM9DS1, check wiring!");
        }

        setFifoMemoryEnabled(false);

        // enable gyro continuous
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG1_G, (byte) 0b11000000); // on XYZ

        // Enable the accelerometer continuous
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG5_XL,
                (byte) (CTRL_REG5_XL_ZEN_XL | CTRL_REG5_XL_YEN_XL | CTRL_REG5_XL_XEN_XL)); // enable X Y and Z axis
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG6_XL, (byte) 0b11000000); // 1 KHz out data rate, BW set by ODR, 408Hz anti-aliasing
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG7_XL, (byte) 0b10000000); // HR - High resolution mode

        // enable mag continuous
        writeRegByte(SensorType.MAG, REGISTER_CTRL_REG3_M, (byte) 0x00); // continuous mode

And this is how I'm reading the accelerometer data:
        byte[] buffer = new byte[6];
        int[] result = new int[3];
        readRegBuffer(SensorType.XG, REGISTER_OUT_X_L_XL, buffer, buffer.length);
        result[0] = (buffer[1] << 8) | buffer[0]; // Store x-axis values
        result[1] = (buffer[3] << 8) | buffer[2]; // Store y-axis values
        result[2] = (buffer[5] << 8) | buffer[4]; // Store z-axis values
        return result;

I'm then converting the raw values with this formula (but this is a constant change so it should not matter):
rawAccelerometerData[i] * mAccelMgLsb / 1000f * mGravity;

I've also tried to disable the gyro and the magnetometer and left only the Z axis enabled and than tried to fetch the data using different output data rate but the result is the same.
The full code of my driver is available here.
I currently have only one LSM9DS1 so I have no clue if this is a defective product or an expected behavior and if this can be fixed with a different configuration.
PS

! as you might have guessed looking at the code I'm not really using an Arduino to access the LSM9DS1 but I still believe that this is still a good place to ask for help since I don't think my issue is platform related but is either some error in my code or a faulty sensor.
  And my code is just a port of this Arduino driver: https://github.com/adafruit/Adafruit_LSM9DS1.

This community will have no way to tell you if your hardware is defective, and since your code isn't for Arduino, it doesn't really fit in this group. The code sample you provided is nice, but can't be verified on Arduino.

I understand this but at least I can have a confirmation that this doesn't happen on Arduino, right? Can someone with a LSM9DS1 tell me if he/she get always consistent data from the accelerometer using this Arduino driver? https://github.com/adafruit/Adafruit_LSM9DS1

the comments in your code shows that you are enabling "everything" .  try enabling only one direction of the accelerometer  and disable the gyro .... also try reading the data at slower rate

Hi @jsotola, thanks for the hint, I tried to disable everything but the accelerometer and there I enabled only the Z axes. I tried with several values of output data rate, from the min to the max, with high resolution enable and disabled but the result is always the same. I've updated the OP including this new info and a link to the full source code of the driver.

The problem is how the accelerometer data is read, to be precise is in these lines:
result[0] = (buffer[1] << 8) | buffer[0]; // Store x-axis values
result[1] = (buffer[3] << 8) | buffer[2]; // Store y-axis values
result[2] = (buffer[5] << 8) | buffer[4]; // Store z-axis values

What I'm getting from the sensor is a 16bit in two’s complement spitted in 2 bytes, for example buffer[4] and buffer[5] where 4 is the low byte and 5 is the high.
In Java the & and | are defined to operate only on int and long values, so what happens is that the byte is always promoted to signed int:
buffer[5] = 00111100
buffer[4] = 11110110
(int)buffer[4] = 11111111111111111111111111110110 = FF FF FF F6
(buffer[5] << 8) | buffer[4] = FF FF FF F6

With the original code both bytes are handled has two’s complement when actually only the high byte is holding the sign.
Long story short, you have to keep the sign for the high byte (cast to int) and threat the low as unsigned (autocast to int using the & and keeping only the original byte with 0xFF):
result[0] = (((int) buffer[1]) << 8) | (buffer[0] & 0xFF); // Store x-axis values
result[1] = (((int) buffer[3]) << 8) | (buffer[2] & 0xFF); // Store y-axis values
result[2] = (((int) buffer[5]) << 8) | (buffer[4] & 0xFF); // Store z-axis values


text:
How to start particular event for particular time using millis()?
In my recent project, I want to run particular event for the particular time. For example, If I want to Turn ON my LED for 20 Second. And rest time LED must be off. I know using delay() it is possible but If we used delay() function then that time we can't do anything. So, I tried out millis() for that. I tried the basic code for this.
The code is below:
const int ledPin =  LED_BUILTIN;

int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 5000;

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

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;

    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    digitalWrite(ledPin, ledState);
  }
}

But the output of this is like LED ON for 5 Second and then LED OFF for 5 Second. And this thing happens continuously.But I don't want this. I just want to turn ON LED for 5 Second when I want and then LED off forever. And I tried out many logics for that somehow can't able to get this thing. Someone suggest me some idea about this.

Use an extra boolean variable. Some use the previousMillis and make it zero to tell that the delay is not active, but please don't do that. Let previousMillis be the value of millis and use an extra boolean variable.
To start the millis delay, three things are needed: enable the delay, set previousMillis, and turn the led on.
To stop the millis delay, two things are needed: disable the delay, turn the led off. There is no need to do something with the previousMillis since the millis delay will be disabled.
const int ledPin =  LED_BUILTIN;

unsigned long previousMillis;
const unsigned long interval = 5000UL;
boolean enableDelay = false;

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

void loop()
{
  unsigned long currentMillis = millis();

  // Trigger the delay, I use analogRead.
  if (analogRead(A0) > 500)
  {
    enableDelay = true;
    previousMillis = currentMillis;
    digitalWrite(ledpin, HIGH);
  }

  // Checking the millis delay should be done in the loop.
  // This code is not inside the code to start the delay, but
  // at the same level as other code in the loop.
  if (enableDelay)
  {
    if (currentMillis - previousMillis >= interval)
    {
      enableDelay = false;
      digitalWrite(ledPin, LOW);
    }
  }
}

There are libraries that can do this. The above code is the basic way to make a millis delay. I have changed the variable "interval" to a unsigned long, because the other two (currentMillis and previousMillis) are also unsigned long. That makes it more straightforward. The currentMillis and previousMillis must be unsigned long, but it is okay if "interval" is a long.
This way of a millis delay can be used with a finite state machine. If your sketch has many states, and one of those states is to keep a fan or a motor on for some time, then you can use it. The variable "enableDelay" is probably not needed in a finite state machine, because the "state" variable tells if that specific state (with the millis delay) is active.

Thank you so much... It is working fine...It is used in many application of mine...


text:
Error while uploading code with Arduino on breadboard using FTDI 232
My circuit is as seen and I hope there is no error with the wiring. I'm using an ATmega328P. The error suggests that the programmer is not responding and ten attempts issuing not in sync code. There isn't any bootloader issue as pin 13 LED flickers as soon as I plug in USB cable. I have selected the following board specification in the Arduino IDE:

Board: Arduino Uno
Programmer: Arduino as ISP

Schematics I followed:

ATmega pinout reference:

Connections:

Pin 1: 10k resistor to 5V, 0.1uF capacitor pin series with DTR of FTDI
Pin 2: Tx of FTDI
Pin 3: Rx of FTDI
Pins 9 & 10: 16 MHz oscillator and 22pf capacitor in series
Pins 7, 20, 21: 5v
Pins 8, 22: ground
Pin 19: status LED (similar to pin 13 LED on standard Arduino Uno)

I used both ways of uploading (directly and upload using programmer) and nothing worked. The bootloader in the chip is that of the Arduino Uno and it was burned using another Uno board. SPI programming using another Uno board works fine. I tried different combination of programmer in IDE but futile. The capacitor for reset is 0.1 µf and it seems that connections are fine as there was no issue with uploading using another Uno board as ISP.I would love if anyone can help me out with this.
Related images are:

PS:
[Post comment changes]
-I added a 47uF and 0.1uF caps for cleaner supply to the chip based on suggestions in comment section.

board with changes[by pass capacitors ,resistor visible on pin 19]
[]5
IDE specifics

Solution-

credits- @Nickgammon
had problem with bootloader which was initially uploaded . later solved it by following instructions from NickGammon Forum -
http://www.gammon.com.au/breadboard

related images-

snap shot from bootloading window in arduino IDE

Comments are not for extended discussion; this conversation has been moved to chat.

Here is a photo of the setup I used on this page about a breadboard Arduino. I can't see any material differences between yours and mine, except that I wouldn't connect Aref (pin 21) to anything.

Close-up of the FTDI connection:

I have 0.1 µF capacitors as decoupling capacitors on both sides of the breadboard.

I used both ways of uploading (directly and upload using programmer) and nothing worked.

Assuming you have the Uno bootloader installed (and that the fuses are still set to what they should be for a Uno) then you want direct uploading (with board type set to Uno), not uploading via a programmer.

I have a 47uF and 0.1 uF as decouplers. I'll see if removing AREF will help. I believe there isn't any issue with bootloader as i could program it using an actual arduino board as ISP and program runs effectively.

If you program using and Arduino as ISP then you are doing SPI programming, so that doesn't prove much. It also will remove any existing bootloader. The flashes you see on the LED might just be the blink sketch.

If you run run my board detector sketch it will confirm whether or not there is a bootloader there.

I realize the flaw in my point regarding bootloader, I'll check through "board detector sketch".By flickering i mean,rapid flashes and also the same when i hit upload button during FTDI serial programming method,but error crops up at the end.It seems like chip is communicating and resetting the board but still cannot upload


text:
HM-10 send and receive data and checking received value
I am wondering what is wrong with my code below. I have 2 issues.
The first issue, I am checking if c equals "hi" and if it does then display said hi. I currently see the output of c when it hits Serial.println(c); but never see the said hi even though Serial.println(c); does say "said hi".
The second issue is that when I start up the Arduino I am sending the AT command using bluetooth.println("AT");, but all it seems to do is display AT on the phone instead of OK as it should.

#include <SoftwareSerial.h>

SoftwareSerial bluetooth(8,9); // RX, TX

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("PC Side Connected");
  bluetooth.begin(9600);
  while (!bluetooth) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  bluetooth.println("Bluetooth Side Connected");
  bluetooth.println("AT"); // just a check
}

void loop() { // run over and over
  String c;
  if (bluetooth.available()) {
    //What is sent back from the BT module
    c = bluetooth.readStringUntil('\n');
    delay(10);
    Serial.println(c);
    if (c.equals('hi')) {
      Serial.println("said hi");
    }
  }
  if (Serial.available()) {
    //Send back data to Bluetooth module
    bluetooth.write(Serial.read());
  }
}

There’s nothing wrong with reading it just checking the value within the if statement.

@AltAir Why? .read() reads a single char not a string.

Could you edit the question and include the exact output please?

@MarkSmith picture added in the OP.

The first issue, I am checking if c equals "hi" and if it does then display said hi.

This is not how you compare:
  if (c.equals('hi')) {

Single quotes indicate a single (or multi-byte) character.  A character string (lower-case) is enclosed by double quotes:
  if (c == "hi") {

But it's better to avoid the String class (more info here).
To eliminate the String class, use char arrays instead (aka "C strings") and accumulate characters until the newline is received.  There are many, many C string functions for manipulating and searching.  In this specific case, you would use strcmp or strstr for comparison:
#include <AltSoftSerial.h>

AltSoftSerial bluetooth; // pin 8 is RX, pin 9 is TX

char btResponse[ 20 ];
uint8_t count;
const uint8_t BT_MAX = sizeof(btResponse);

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

  Serial.println("PC Side Connected");
  bluetooth.begin(9600);

  bluetooth.println("Bluetooth Side Connected");
  bluetooth.println("AT"); // just a check
}

void loop()
{
  if (bluetooth.available()) {
    // Read what is sent back from the BT module
    char c = bluetooth.read();

    if (c == '\n') {
      btResponse[ count ] = '\0'; // NUL-terminate the character array

      // Use C string functions to parse the response

      if (strcmp( btResponse, "hi" ) == 0) {
        Serial.println("only said hi");

      } else if (strstr( btResponse, "hi" ) != nullptr) {
        Serial.println("said hi, among other things...");

      }

      // And if there is a comma in there somewhere, display all comma-separated fields
      if (strchr( btResponse, ',' ) != nullptr) {
        uint8_t fieldNumber = 0;

        char *field = strtok( btResponse, "," );
        while (field != nullptr) {

          Serial.print( "Field " );
          Serial.print( fieldNumber );
          Serial.print( " = " );
          Serial.println( field );

          // Some fields might be numbers.  Parse them into integers.
          if ( isdigit( field[0] ) ) {
            int value = atoi( field );
            Serial.print( "  value = " );
            Serial.println( value );
          }

          // get next field
          field = strtok( nullptr, "," );
          fieldNumber++;
        }
      }

      // Reset the counter to receive another response
      count = 0;

    } else if (c >= ' ') {
      // Accumulate another non-control char, if there's room
      if (count < BT_MAX-1) {
        btResponse[ count++ ] = c;
      }
    }
  }

  if (Serial.available()) {
    // Send data to Bluetooth module
    bluetooth.write( Serial.read() );
  }
}

Notice that it shows how to use strtok to break the response string into individual fields, if a comma character is somewhere in the line.  For example, entering this:
hi,123,456

... produces this output:
said hi, among other things...
Field 0 = hi
Field 1 = 123
  value = 123
Field 2 = 456
  value = 456

It also uses AltSoftSerial for the BT connection.  SoftwareSerial is very inefficient, and it cannot send and receive at the same time.  It will lose received data while it is transmitting to the BT.  This can also interfere with other parts of your sketch or other libraries.
This answer has a good summary of the alternatives and how to select one.  Since you are already using pins 8 & 9, it would be easy to switch to the AltSoftSerial library.  All of the mentioned libraries are available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.