text:
WeMOS creating soft access point from old code even when new code doesn't have it
In the past I uploaded the code below:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <DHT.h>

#define DHTTYPE DHT22     // DHT 11
#define DHTPIN D5
DHT dht(DHTPIN, DHTTYPE);

const char *ssid = " Hello_IOT";
const char *pass = "12345678";
String command;
ESP8266WebServer server(8080);

void respond(){
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  server.send(200, "text/html", "
Hello from Wemos R1 Mini
");
}

void outputJson(){
  char temp[400];
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  int tf = dht.readTemperature(true);
  snprintf(temp, 400, "{\"wittyCloud\" : [{\"location\" : \"any\" ,\
    \"temperatureInC\" :%d ,\
    \"temperatureInF\" :%d ,\
    \"humidity\":%d,\
    \"ldr\":%d\
    }]}",
  t, tf, h, analogRead(A0));
  server.send(200, "text/json", temp);
}

void setup(){
  Serial.begin(115200);
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.println("Connect to access Point");
  WiFi.softAP(ssid, pass);
  IPAddress IPserver = WiFi.softAPIP();
  Serial.println(" IP address server : ");
  Serial.println(IPserver);
  server.on("/", respond);
  server.on("/json", outputJson);
  server.begin();
  server.onNotFound([](){
    command = server.uri();
    server.send(200, "text/plain", command);
  });
}

void loop(){
  server.handleClient();
  if(command.equals("/mati")){
    digitalWrite(BUILTIN_LED, HIGH); //turn off BUILTIN LED
  }
  if(command.equals("/hidup")){
    digitalWrite(BUILTIN_LED, LOW); //turn on BUILTIN LED
  }
}

For learning purpose it worked, however when I modified it to the code below for WeMOS, to connect to my home wifi router, it creates instead an access point, and on opening the URL after connecting to the WeMOS access point it displays the web page of the updated code.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include "control.h"
#include "webpage.h"
#include <DHT.h>

ESP8266WebServer server(80);
const char* sid = "router+ssid";
const char* passwd = "ssid_password";

#define DHTTYPE DHT22     // DHT 22
#define DHTPIN D5
DHT dht(DHTPIN, DHTTYPE);
const char* host = "nodemcu";

void outputJson(){
  char temp[400];
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  int tf = dht.readTemperature(true);
  snprintf(temp, 400, "{\"wemos\" : [{\"location\" : \"bangalore\" ,\
    \"temperatureInC\" :%2d ,\
    \"temperatureInF\" :%2d ,\
    \"humidity\":%2d\
    }]}",
  t, tf, h);
  server.send(200, "text/json", temp);
}

void handleRoot(){
  const int nsize = 2300;
  char temp[nsize];
  delay(200);
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  snprintf(temp, nsize,
    "%s\n</\div>\n\
    ",webpage::html);
  server.send(200, "text/html", temp);
}

void handleNotFound(){
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message +=(server.method()== HTTP_GET)? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for(uint8_t i = 0; i < server.args(); i++){
    message += " " + server.argName(i)+ ": " + server.arg(i)+ "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void) {
  Serial.begin(9600);
  // config static IP
  IPAddress ip(192, 168, 1, 88);
  IPAddress gateway(192, 168, 1, 1);
  IPAddress subnet(255, 255, 255, 0);
  IPAddress dns(192, 168, 1, 1);
  WiFi.config(ip, dns, gateway, subnet);
  WiFi.begin(sid, passwd);
  Serial.println("");
  EEPROM.begin(512);

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

  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(sid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if(MDNS.begin(host)){
    Serial.println("MDNS responder started");
  }
  MDNS.addService("http", "tcp", 80);
  server.on("/", handleRoot);
  server.on("/json", outputJson);
  server.on("/control", control::toggleRelay);
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println(F("HTTP server started"));
}

void loop(void){
  server.handleClient();
}

I had this issue with one of my chips. I eventually fixed it by using the SPIFFS uploader tool and uploading a blank "data" folder.


text:
How to make a 5-volt relay work with NodeMCU?
I have hooked up 2 channel 5-volt relays with NodeMCU v1.0 as shown in the fritzing below.

Relay are powered with a different power source than NodeMCU.
As of now, I am powering the NodeMCU from my laptop and the relay board from a 5-volt battery.
Below is the code I have written:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "said.";
const char* password = "secret";
ESP8266WebServer server ( 80 );
const int led = 13;
const int outputLed = 12;

void turnOnRelayOne(){
  digitalWrite (outputLed, 1);
  digitalWrite (5, HIGH); //GPIO 5 // Relay 1
  server.send (200, "text/html", "Relay 1 turned on.");
  digitalWrite (outputLed, 0);
}

void turnOnRelayTwo(){
  digitalWrite (outputLed, 1);
  digitalWrite (4, HIGH); //GPIO 4 // Relay 2
  server.send (200, "text/html", "Relay 2 turned on.");
  digitalWrite (outputLed, 0);
}

void handleRoot() {
  digitalWrite ( led, 1 );

  char temp[400];
  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  snprintf ( temp, 400,

             "\
  \
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU hooked to Relay Board</title>\
    \
  \
  \

Hello from NodeMCU!
\

Uptime: %02d:%02d:%02d
\
  \
",

          hr, min % 60, sec % 60
           );
  server.send ( 200, "text/html", temp );
  digitalWrite ( led, 0 );
}

void handleNotFound() {
  digitalWrite ( led, 1 );
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";

  for ( uint8_t i = 0; i < server.args(); i++ ) {
    message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
  }

  server.send ( 404, "text/plain", message );
  digitalWrite ( led, 0 );
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(outputLed, OUTPUT);
  digitalWrite ( led, 0 );
  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );

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

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( "esp8266" ) ) {
    Serial.println ( "MDNS responder started" );
  }

  server.on ( "/", handleRoot );

  server.on ( "/inline", []() {
    server.send ( 200, "text/plain", "this works as well" );
  } );

  server.on("/relay1", turnOnRelayOne);
  server.on("/relay2", turnOnRelayTwo);
  server.onNotFound ( handleNotFound );
  server.begin();
  Serial.println ( "HTTP server started" );
}

void loop (void) {
  server.handleClient();
}

When I execute the URL: 192.168.1.8/relay1 the outputLed blinks as per the logic in turnOnRelayOne.
But neither of the relays turns on. Please help.

Im not sure but it looks like it's not a closed circuit, the 5 volt. I wonder if the ground from the 5volt outlet could be split up, one for NodeMCU and one for the relay. Then you would have a closed cuircuit between the relay and NodeMCU.

all what you need to do is connect the g on the relay to g on the esp8266 and the battary

Simply connect the Vcc of the relay to 3V of NodeMCU.It's working for me.

I have several of these modules. They have an optional opto-isolator built-in, but you have to remove the jumper to use it.

Connect your GPIO trigger as you have it
Run the relay's Vcc and Gnd pins to the MCU, not the power plug.
connect the power plug's +5v to the left-most pin, where the jumper once stood: JDVcc
connect the power plug ground to the MCU or the open common Gnd on the left-group of pins.

Now your relay coil(s) will be powered by the 5v plug, but the relay's logic and control are handled by the MCU.

Can you please elaborate the last connection in your answer, possibly share a fritzing diagram also?

a diagram will take me a while, i'm swamped at work, but it's a common ground on that last connection: as long as the OP's black wire connects to either GND on the relay or a gnd on the MCU it's ok.

Just to confirm, the ground from the 5V supply could either be connected to the second ground (the one beside JD-VCC) on the relay or to a ground pin on the MCU. Correct?

right, the GNDs on the relay module (and MCU) have continuity, so those options behave identically.

The relay has no reference for what the voltage from the NodeMCU is. Since the power supplies of the two devices are isolated (from each other; the laptop may not be isolated itself, but the battery certainly should be) you can (and in fact must) connect the grounds of the relay board and the NodeMCU together. If neither power supply is isolated or if you are unsure if they are isolated then you should use an optoisolator in order to prevent potential power issues.

I believe the problem could be that the relay is 5v but the signal coming from the NodeMCU is 3.3v. You may need do something like boost the signal to 5v or implement a logic level shifter, for example.
Here's a related post:
https://electronics.stackexchange.com/questions/213051/how-do-i-use-a-5v-relay-with-a-3-3v-arduino-pro-mini

That is not the case, IMO. The output of the NodeMcu is not driving the relay but driving a transistor/fet/optocoupler. In all cases, 3.3V is perfectly valid to turn on. @Ingacio is correct, the grounds must be connected. Now only one wire is the connection between the NodeMcu and the relay. "Voltage" is defined as a difference between two potentials, hence one wire is not enough.

How are you powering your ESP-12E?  This is not included in your diagram. I have had success using the VU pin (5V output) when powering from the Micro-USB.  You would then connect VCC to VU, GND to GND, and Signal to your GPIO4.  If you are powering your ESP-12E from a 5v power supply directly into the VIN pin, then I would power the Relay from the same 5V power supply.  you would connect the + from the power supply to VIN (ESP) and VCC (relay) all the grounds tied together then the GPIO4 to Signal.

This relay module works differently.
It is on when the signal is LOW and it turns off when the signal is HIGH (3v3V on the NodeMCU)
So you only need to modify the code in the two functions to be LOW instead of HIGH
Also make sure the NodeMCU and the relay module have a common ground.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "said.";
const char* password = "secret";
ESP8266WebServer server ( 80 );
const int led = 13;
const int outputLed = 12;

void turnOnRelayOne(){
  digitalWrite (outputLed, 1);
  digitalWrite (5, LOW); //GPIO 5 // Relay 1
  server.send (200, "text/html", "Relay 1 turned on.");
  digitalWrite (outputLed, 0);
}

void turnOnRelayTwo(){
  digitalWrite (outputLed, 1);
  digitalWrite (4, LOW); //GPIO 4 // Relay 2
  server.send (200, "text/html", "Relay 2 turned on.");
  digitalWrite (outputLed, 0);
}

void handleRoot() {
  digitalWrite ( led, 1 );

  char temp[400];
  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  snprintf ( temp, 400,

             "\
  \
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU hooked to Relay Board</title>\
    \
  \
  \

Hello from NodeMCU!
\

Uptime: %02d:%02d:%02d
\
  \
",

          hr, min % 60, sec % 60
           );
  server.send ( 200, "text/html", temp );
  digitalWrite ( led, 0 );
}

void handleNotFound() {
  digitalWrite ( led, 1 );
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";

  for ( uint8_t i = 0; i < server.args(); i++ ) {
    message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
  }

  server.send ( 404, "text/plain", message );
  digitalWrite ( led, 0 );
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(outputLed, OUTPUT);
  digitalWrite ( led, 0 );
  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );

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

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( "esp8266" ) ) {
    Serial.println ( "MDNS responder started" );
  }

  server.on ( "/", handleRoot );

  server.on ( "/inline", []() {
    server.send ( 200, "text/plain", "this works as well" );
  } );

  server.on("/relay1", turnOnRelayOne);
  server.on("/relay2", turnOnRelayTwo);
  server.onNotFound ( handleNotFound );
  server.begin();
  Serial.println ( "HTTP server started" );
}

void loop (void) {
  server.handleClient();
}

Hm, can you infer from that drawing the actual type of the relay module? Many modules wok using positive logic, i.e. setting input high turns the relay on.

source: Stack Exchange

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

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

sort: votes


text:
Can't upload sketch - avrdude: butterfly_recv(): programmer is not responding
I'm trying to upload a Blink example to run on a pro-micro (leonardo) but it is not working anymore (it was just working yesterday).
Steps to reproduce:

Plug the device in USB port
Open Blink example in Arduino IDE (version 1.8.8)
Select the port and board accordingly to Arduino Leonardo
Compile and try to upload it.

The code compile successfully but when uploading it just halts. The ide console displays:

avrdude: error: programmer did not respond to command: exit bootloader
Forcing reset using 1200bps open/close on port /dev/ttyACM0 PORTS
  {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
  {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
  PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
  / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
  {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS
  {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
  {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
  PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
  / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
  {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS
  {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
  {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
  PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
  / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
  {} Uploading using selected port: /dev/ttyACM0
  /home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/bin/avrdude
  -C/home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf
  -v -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/tmp/arduino_build_350609/Blink.ino.hex:i
avrdude: Version 6.3-20171130
           Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
           Copyright (c) 2007-2014 Joerg Wunsch
     System wide configuration file is "/home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf"
     User configuration file is "/home/fabio/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/ttyACM0
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : butterfly
     Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is
  not responding
avrdude: butterfly_recv(): programmer is not responding

A strange behavior I noticed is each time I plug the device again in the usb port different leds are light up, some times only RX, sometimes only TX and sometimes none (the power led is always on)
What could be happening here? Can it be the problem on the hardware?

I experienced the same frustrating issue for days. It was Ubuntu.
The fix was also so easy: sudo apt purge modemmanager
Until I discovered it, I suffered headache for days.
The auto upgrader may cause issues with this command. It can be solved
with the following command:
sudo dpkg-reconfigure -plow unattended-upgrades
At the first prompt, choose not to download and install updates.
Then reboot.

Holy crap, this actually worked for me. I couldn't program a "SMAKN Beetle USB ATMEGA32U4 board" Leonardo clone, and this fixed it. Thank you so much.

On fedora and using a Pro Micro, I did systemctl restart ModemManager and upload using micro board on Arduino IDE.

Purging modemmanager worked for me too! It is important to reboot after removing the package. Thanks so much!

I have successfully solved this a year ago and I am trying to remember how I did it. So while it's fresh in my head this thing has to do with the bootloder.
The first and most obvious thing you can do is try to doubletap the reset and ground contact. Double tapping it will force the Arduino to reset and start in the bootloader for 8 seconds.
This is how I managed to install the driver for my pro-micro, it wouldn't install unless you did it when Arduino was in bootloader mode. But this strategy doesn't work for the code upload for some reason although many people claim it was the only thing that helped.
Another thing that could maybe help is clearing the Arduino's cache. When I was trying to compile a year ago, after many attempts I had to clear the pro-micro with another Arduino once in a while (you may need this later on). [thebusybee's note: I never heard about a cache in AVR micros. If a sketch is uploaded it will be flashed into the non-volatile memory overwriting all that was at its place before.]
Something else I remembered (if this is the case it would make things very problematic for me) is the USB cable. Again before my 1 year break I remembered that uploading the sketch for me only worked with 1 out of like 15 micro-USB cables I had (the one that's the shortest and thickest). That cable is broken now so I can't really check this unless I start researching microUSB cables right this instant.
Finally it may be the system. If nothing works try uploading the sketch from another preferably clean system.
Anyway, I hope you solve this because I am trying to solve the same issue.
Good luck

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


text:
Keyboard.h: No such file or directory - Arduino pro micro (leonardo)
I've just bought a new pro-micro and I want to simulate some keyboard inputs with it, the thing is the Arduino IDE (version 2:1.0.5) can't seem to find neither HID.h or Keyboard.h libraries. The steps to reproduce the problem are:

plug the device using usb cable on the pc
Open arduino ide
try to compile my code
it fails with the error

test_keyboard.ino:27:22: fatal error: Keyboard.h: No such file or directory
  compilation terminated.

The code is:
#include <Keyboard.h>

void typeKey(int key)
{
  Keyboard.press(key);
  delay(50);
  Keyboard.release(key);
}

/* Init function */
void setup()
{
  // Begining the Keyboard stream
  Keyboard.begin();

  delay(400);

  //Keyboard.press(KEY_LEFT_GUI);

  Keyboard.press(KEY_CTRL);
  Keyboard.press(KEY_ALT);
  Keyboard.press(KEY_T);

  Keyboard.releaseAll();

  delay(100);

  Keyboard.print("echo 'hello world'");

  typeKey(KEY_RETURN);

  delay(100);

  // Ending stream
  Keyboard.end();
}

/* Unused endless loop */
void loop() {}

By the way, I'm running this on linux, after pluging it and running lsusb on terminal I got:
  Bus 002 Device 071: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)

The Keyboard functions were moved into their own library in Arduino IDE 1.6.6/Arduino AVR Boards 1.6.9. In previous Arduino AVR Boards versions, those functions were part of the core library and there was no Keyboard library or Keyboard.h. Since you're using a very outdated version of the Arduino IDE, you don't have a Keyboard library, thus the error. There are two options to solve this problem:

Remove the line #include <Keyboard.h> from your sketch.
Update to a modern version of the Arduino IDE. Note that when you install the Arduino IDE via sudo apt-get install arduino, you end up with the very outdated IDE version you're using. I recommend always installing the official Arduino IDE downloaded from https://www.arduino.cc/en/Main/Software.

For anyone wanting to write code that's backwards compatible with old IDE versions, you can do this:
#if ARDUINO > 10605
#include <Keyboard.h>
#endif

Reference: https://github.com/arduino/Arduino/pull/3304

Don't hang around in the stone age, step forward to 2019 and join us with the newest Arduino IDE.
Do you use the newest linux version, for example Ubuntu 18.10?
Remove all arduino related packages from the repositories.
Be sure to remove the package librxtx-java.
You don't need to install Java, jdk, openjdk, jre or any of those.
If you use snap, remove the Java and Arduino from the snap as well.
When you have used such an old version, I suggest to delete the hidden .arduino15 folder from your HOME folder.
Perhaps you have downloaded libraries that are now included with the Arduino IDE. You could check the "libraries" folder (in the same folder as the folders of your projects) and delete unused libraries.
Download the Arduino IDE from the arduino.cc website.
The 32-bit version for a 32-bit linux system, and the 64-bit version for a 64-bit linux system.
Unpack it somewhere in under your HOME folder. You can make a shortcut to the file "arduino" and run the shortcut.
Don't make changes to the stardard Arduino system files (the Arduino IDE that you have downloaded and unpacked). Sometimes it is needed to make changes to the files in the hidden .arduino15 folder.


text:
Radio tx/rx makes my oled screen not work
I've been struggeling with this assignment for school for a couple of days. I have finally figured out where the problem lies.
I have an oled screen that is supposed to print out the temperature of a DHT11, at the same time a RF sender should transmit the temperature to another microcontroller. The first microcontroller should also be able to recieve messages via RF and display them on the screen.
I've been having trouble with the oled screen. When i include my RF communication .head file, the oled wont work!!! I Cant understand why and it's really bugging me, I'm thinking it might be a memory problem, but the arduino IDE tells me it is only using 61% of the storage space. I'm using a arduino nano but i also have an Uno and a Mega laying around.
Do you think i should try the Uno or is there a problem in the code somehow?
Thank you so much!
main.ino:
#include "display.h";
//#include "DHT.h";
#include "Radiocom.h";

//long temperature;
String message = "abc123";

void setup()
{
  Serial.begin(115200);
  //initDHT();
  initDisplay();
  //initRF();
}

void loop()
{
  //temperature = readTemp();
  //delay(1000);
  //printTemp(temperature);
  printMessage(message);
  //sendMsg();
  //RFlisten();
  delay(1000);
}

radiocom.h:
#include <RH_ASK.h>
//for feather huzzah ESP:
//RH_ASK rf_driver(2000,13, 12, 14);
RH_ASK rf_driver;

void initRF(){
  rf_driver.init();
  Serial.println("Radio transmitter initiated..");
}

void sendMsg(){
  const char *msg = "testing testing, one two";
  rf_driver.send((uint8_t *)msg, 24);
  rf_driver.waitPacketSent();
  delay(1000);

}

void RFlisten(){
  uint8_t buf[24];
  uint8_t buflen = sizeof(buf);
  if(rf_driver.recv(buf, &buflen)){
    Serial.print("Message received: ");
    Serial.println((char*)buf);

  }

}

display.h:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>  // Include core graphics library for the display
#include <Adafruit_SSD1306.h>  // Include Adafruit_SSD1306 library to drive the display

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Define SPI pins:

#define OLED_MOSI   9
#define OLED_CLK   6
#define OLED_DC    7
#define OLED_CS    8
#define OLED_RESET 13

// Create display
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
  OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

void initDisplay(){

  delay(100);

  display.begin(SSD1306_SWITCHCAPVCC);

  display.clearDisplay();  // Clear the buffer

  display.setTextColor(WHITE);  // Set color of the text

  display.setRotation(0);  // Set orientation. Goes from 0, 1, 2 or 3

  display.setTextWrap(false);  // By default, long lines of text are set to automatically “wrap” back to the leftmost column.
                               // To override this behavior (so text will run off the right side of the display - useful for
                               // scrolling marquee effects), use setTextWrap(false). The normal wrapping behavior is restored
                               // with setTextWrap(true).

  display.dim(0);  //Set brightness (0 is maximun and 1 is a little dim)

  Serial.println("Display initiated..");

}

void printMessage(String message){
  display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0
  display.setTextColor(WHITE);
  display.setCursor(0,50);
  display.clearDisplay();
  display.print(message);
  display.display();
  Serial.println("printing message on display");
  delay(1000);

}
void printTemp(long temp){

  display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0

  display.clearDisplay();  // Clear the display so we can refresh
  // Print text:
  display.setCursor(25, 15);  // (x,y)
  display.println("temp:");  // Text or value to print
  // Draw rectangle:
  display.drawRect(79, 0, 35, 27, WHITE);  // Draw rectangle (x,y,width,height,color)
                                           // It draws from the location to down-right

  // Print variable with left alignment:
  display.setCursor(83, 20);  // (x,y)
  display.println(temp);  // Text or value to print

  display.display();  // Print everything we set previously
  Serial.println("Printing temp..");

}

I thought I rad somewhere that SPI on the nano uses 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK) - though, if that were a hard and fast rule, I guess your code wouldn't work with the OLED either way .. edit: oh, I see, you're using using software (bitbang) SPI

It could be memory, yes. What many people don't realise is that using the SSD1306 display normally eats up a quarter of their RAM with a dynamic allocation of a display buffer. This does not show in the "used memory" in the IDE.

Make sure that when talking to your display it's chip select is asserted and your RF radio's chip select is de-asserted .   Reverse this when talking to the radio.  One of the drivers is likely leaving one of the chip selects in the wrong state.


text:
How do I make a Servo Stop if it Hits Resistance?
I am trying to make a device which will turn a turn key with a servo.
However, I want it to stop turning the turn key if the resistance is too great (meaning it is locked and will not ever turn).
How do I do this? Would I just tell it to turn and then have it turn back after a time (because if it is locked or not it should be done within that time)?
I do not want to damage my servo by having it try to turn something that it can't turn.
I am using an Arduino Uno and the library "Servo.h". The servo being used is a Batan S1123.

It depends on what kind of failure you expect. If you're afraid the motor may break your linkage (the gears, cranks, belts, whatever you have in place), you have to react very fast, and it's only feasible with a current measurement. That would require sensing the current and reacting very quickly on over-current to be effective.
If you know for a fact that your linkage can withstand the stall torque of the motor, you just have to worry about overheating the motor. Such a protection can be done with a position sensor or a limit switch if you happen to have one. You could even implement a protection with no sensors at all: drive the motor for just long enough to do its job and then stop: either it will turn the key or it won't, but it won't overheat if stalled for a second or two.

You could either:

Use a limit-switch to sense that the servo has completed it move. If it doesn't complete it a reasonable time, return it to its original position. Or,
Measure the motor current by putting a low value resistor inline with the ground side of the motor's power supply. With one of the A/D pins, measure the voltage on the motor side of the resistor, which increases with motor current. You'll need to have figured out how much current the motor draws when operating normally. If the motor stalls, your controller could sense that by seeing that current increase. Pick a value (try 150%, for example) of over-current as an indicator that the motor is stalled, and return it to its original position.

The first way is easier to implement but possibly lets the motor stall while you wait for the expected move time to expire. The second way lets you detect stalling and take action immediately.

I don't think the limit switch solution would prevent the servo from stripping its gears if it binds before you check the switch. Option 2 would be the better avenue to explore.

You should understand that you control the servo with PWM pulses. The servo translates the width of the pulse to an amount of rotation. A standard servo has no means of indicating its current position. You can only tell it where you want it to be.

If it could strip gears, it's under-built; it shouldn't be able to damage itself under forseeable circumstances (stalling). But even then, current-sensing should give you sufficient opportunity to protect it.

"If it could strip gears, it's under-built" - this is usually true for toys and small applications (so it's likely the OP's case as well), but not true in general. Most products where a motor is not designed to work at 0RPM (mixers, etc.) will happily strip gears when stalled, unless they have protection implemented in software.

I suggest detecting the current flowing through the servo or using a potentiometer to detect whether the servo is moving. You could also put a clutch between the servo and the key, but then you wouldn't know the angle of the key at any given time.

The best way is use external feedback. Hall sensor for example.
200-250ms after using servo check status of hall sensor

Or a current sensor on the Servo power line, back off the position when you detect the current rising from the motor being stalled.

Yes, that's possible. Hall seems easier

Could you expand on how you would use a hall sensor to complete this task?

Put little magnet on key and hall sensor near end point of key.

Ah. So if sensor fails to detect magnet x moments after servo push has started, resistance has been encountered, stop pushing.


text:
ESP-13 WiFi shield - "error: espcomm_upload_mem failed"
I am creating a web server with Arduino and a ESP-13 WiFi shield. The wiring is as following:
Arduino UNO || ESP-13 WiFi shield
5V          || .5V
GND         || GND
TX          || RX
RX          || TX
            || GPIO 0 to GND

When I run my code, I get an error. The error is
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I have tried many videos, tests and rewiring but nothing is working. If this would help, before I upload my code, the led on the wifi shield is red. When I am uploading my code, the Arduino Uno flashes between the RX and TX leds. The code:
#include <ESP8266WiFi.h>

/*==========================================================================
 * Project: ArduinoBasics WiFi Scanner
 * Author:  Scott C
 * Date created: 16 September 2018
 * Arduino IDE version: 1.8.5
 * Operating System: Windows 10 Pro
 *
 * Description:
 * The ESP-13 WiFi shield will create an Access Point that you can connect to
 * using your phone/tablet/PC. Once connected via WiFi, navigate your browser
 * to the IP address displayed in the Serial monitor to see the list of Access Points in your area.
 *
 * Acknowledgements:
 * Some of the code used within this sketch was inspired by or adapted from other notable sources.
 *    Webserver code: adapted from https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/server-examples.html
 *    WiFi scanner code adapted from tablatronix : https://gist.github.com/tablatronix/497f3b299e0f212fc171ac5662fa7b42
 *    HTTP/1.1 protocols: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
 *
 * -------------------------------------------------------------------------
 * LIBRARIES:
 * Libraries used: ESP8266WiFi.h  - installed with Boards Manager : https://github.com/esp8266/Arduino
 * More information about ESP8266WiFi.h library :
 * https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html
 * https://arduino-esp8266.readthedocs.io/en/2.4.2/libraries.html#wifi-esp8266wifi-library
 *
 *
 * GLOBAL VARIABLES:
 * The SSID and Password for the Access point (AP) that will be created by the ESP-13 WiFi shield
 * The WiFi server which will listen for Clients on Port 80 (eg. Web Browsers)
 ============================================================================ */

const char* ssid = "PinkFluffyUnicorn";
const char* password = "12345678";
WiFiServer server(80);

/* ==========================================================================
 * SETUP:
 * Begin Serial Communication using a Baud Rate of 115200
 * Configure the ESP-13 WiFi shield into Access Point Mode
 * Create an Access Point for devices to connect to.
 * Display the Access Point (AP) IP address in the Serial monitor.
 * Start the server if the Access Point has been created successfully
 ============================================================================ */
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.mode(WIFI_AP);
  boolean r = WiFi.softAP(ssid, password);

  if (r) {
    server.begin();
    Serial.println("");
    Serial.print("Please connect to the Access Point: ");
    Serial.println(ssid);
    Serial.printf("then open %s in a web browser\n", WiFi.softAPIP().toString().c_str());
    Serial.println("");
  } else {
    Serial.println("FAILED to create Access Point");
    while(1){}
  }
}

/* ==========================================================================
 * LOOP:
 * Start listening for Clients
 * Notify when a Client connects to the server using the Serial Monitor
 * Then write any request messages from the client to the Serial Monitor
 * Wait for the client to send through an empty line, then
 * Serve the constructed HTML page to the client
 * The delay gives the browser some time to receive the HTML page, before
 * the server dicsonnects from the client.
 * Notify when the client has been disconnected.
 ============================================================================ */
void loop() {
  WiFiClient client = server.available();
  if(client){
    Serial.println("\n A Client just connected to the server");
    while(client.connected()) {
      if(client.available()){
        String clientMessage = client.readStringUntil('\r');
        Serial.print(clientMessage);
        if(clientMessage.length() == 1 && clientMessage[0] =='\n') {
          client.println(constructHTMLpage());
          break;
        }
      }
    }
    delay(1000);
    client.stop();
    Serial.println("\n The server has disconnected the Client");
  }
}

/* ==========================================================================
 *constructHTMLpage:
 *SCAN for available WiFi networks within range of the ESP-13 WiFi Shield
 *Construct the necessary HTTP response and HTML to
 *  - display the SCAN results within a web browser (client).
 *  - automatically refresh the HTML page every 5 seconds.
 *
 *The HTML page will display the following information in a table:
 *  - SSID,
 *  - Signal Strength and
 *  - Encryption type.
 ============================================================================ */
String constructHTMLpage(){
  int numSSID = WiFi.scanNetworks();
  String HTMLpage = String("HTTP/1.1 200 OK\r\n") +
                            "Content-Type: text/html\r\n" +
                            "Connection: close\r\n" +
                            "Refresh: 5\r\n" +
                            "\r\n" +
                            "<!DOCTYPE HTML>" +
                            "\r\n" +
                            "
WIFI NETWORKS
\r\n" +
                            "

SSID	Signal Strength	Encryption type
\r\n";

  for(int i=0; i<numSSID; i++){
    HTMLpage = HTMLpage + String("
");
    HTMLpage = HTMLpage + String(WiFi.SSID(i));
    HTMLpage = HTMLpage + String("	");
    HTMLpage = HTMLpage + String(WiFi.RSSI(i));
    HTMLpage = HTMLpage + String("	");
    HTMLpage = HTMLpage + String(encryptionTypeStr(WiFi.encryptionType(i)));
    HTMLpage = HTMLpage + String(" [");
    HTMLpage = HTMLpage + String(WiFi.encryptionType(i));
    HTMLpage = HTMLpage + String("]");
    HTMLpage = HTMLpage + String("
");
  }
  HTMLpage = HTMLpage + String("
\r\n");
  return HTMLpage;
}

/* ==========================================================================
 *encryptionTypeStr:
 *Will accept a WiFi.encryptionType() integer and convert it into a more
 *meaningful string.
 ============================================================================ */
String encryptionTypeStr(uint8_t authmode) {
    switch(authmode) {
        case ENC_TYPE_NONE:
            return "OPEN";
        case ENC_TYPE_WEP:
            return "WEP";
        case ENC_TYPE_TKIP:
            return "WPA_PSK";
        case ENC_TYPE_CCMP:
            return "WPA2_PSK";
        case ENC_TYPE_AUTO:
            return "WPA_WPA2_PSK";
        default:
            return "UNKOWN";
    }
}

Thank you in advance.

Don't cross post. You already asked this on SO.

GPIO 0 to GND - doesn't that put the ESP into flash mode?

before you run the code you must upload it. why do you have the module wired to Uno, if you have a sketch for esp8266? I know why. You abuse the Uno as USB adapter. But then wire TX to TX, RX to RX. (and make sure the ATmega sketch doesn't have Serial.begin())

I deleted the Serial.begin(), but I am still getting the same error.

Also, I've changed my wiring. I'm using a serial to usb adaptor:

Adaptor | ESP-13 WiFi


text:
Can you current-limit Arduino 101 GPIO pins?
A number of questions ask about max possible in/out current on a GPIO pin, that's not my question here. I'm asking if it's possible to set a maximum current limit on a GPIO pin, such that any attempts to draw more than that current would result in the Arduino entering a constant current mode e.g. reducing the pin voltage?
I've read this, this, this, and skimmed the Curie datasheet, but I don't see a feature like this mentioned anywhere.
The only half-answer I have seen is on the Ruggeduino website, which explains that they have added a fuse to each GPIO pin to avoid overcurrent draws due to short circuits.
For context - I have an external sensor that claims to be more reliable with a small amount of constant current. I didn't know if I could easily add that limitation (e.g. max 15mA at 3.3V) into the GPIO pin as a safety measure, so I went on a search to find out which has eventually led me here

you could add an external circuit that accomplishes the current limiting that you need

Which sensor is it and who claims that? I have not heard of something like that for a sensor.

INPUT_PULLUP should be fairly current-limited, but might not help...

No. I have never heard of a microcontroller with constant current or current limiting on the GPIO pins.
You may get a drive strength on the pins of an FPGA, but I have never seen such a thing on a microcontroller.
In general, if you have a need to reduce the voltage as the current increases you would just slip a resistor in the circuit. Or for more precise control using the GPIO pin to control a constant current source or constant current sink is the normal way of doing it.
GPIO pins are generally designed for communicating with other logic level devices. They require minimal current. Some microcontrollers provide a higher drive strength to work with larger fanouts (lots of devices connected to one pin, such as in SPI buses), but they are not intended for providing power to a device or giving control over their current.

Ok, that makes sense. Kind of what I expected, and I am happy to have someone other than myself confirm. (I can only accept the answer in 7 more minutes as I'm new to this SE site...)

Point of clarification: CMOS needs minimal input current for logic signals. (they have nearly infinite input impedance.) TTL is another story

@DuncanC CMOS has a relatively high capacitance on the gates though, and that means a higher drive strength for a high fanout count to get them thar capacitors charged fast enough.

Typically port pins do have some current limiting inherent in the design of the chip. But it isn't something that should be used as protection. More line a fact that should be taken into account when implementing a design.
Say a 3.3 volt processor has a maximum rating of 12mA. With a 5 mA draw from the pin the high output voltage might be 3.0 volts. When 12mA is drawn from the chip the output voltage might only be 2.5 volts. It is important to check the data sheet to determine what you will get under the expected conditions.
A port with an internal pull up option may be considered more like (but not like) a constant current source. But that's stretching things a bit.

Really? At ≈1/3 of its rated max power, its voltage would droop by almost 10%? I would have expectred the output to be "stiff" enough to keep the voltage at the spec'ed voltage up to nearly the max current draw. Are there readily available current;/voltage graphs for the various models of Arduinos? And are they consumable by mere mortals? I'm pretty comfortable with most spec sheets, but I'm a CS guy, not an EE.

"I would have expectred the output to be "stiff" enough to keep the voltage at the spec'ed voltage up to nearly the max current draw." My example did not use a specific processor. This is a problem I see often, assumptions. What I am saying is that the specs need to be read. Because the capability is specified, and not all chips will have "stiff" outputs. And also the specification over the temperature range must be considered if that would be a condition that it will operate. The 12mA I was thinking of was maximum output of the ESP8266. Yes it can put out 12mA but with quite a voltage drop.

And the Intel Curie (used in the Arduino 101, that the question was about) is specified with a maximum current of 20mA.


text:
How to slow ADC clock speed to 1MHz on Arduino Due?
I know that the ADC on the Arduino Due has a clock speed from 1 MHz to 20 MHz. I have two questions: 1. What is the default clock speed when I run a sketch, and 2. How can I change it? (I am using Arduino 1.6.4.)
The reason why I want to slow down the ADC as much as possible is to obtain the maximum source impedance. Is this logic correct? (i.e., if I slow down the ADC in the arduino code to kHz values, then the source impedance will reach MΩ values?)

You can change the prescaler (ADCSR register). Lowest scaler is 2, so it can never run at 20mHz. Also Atmel recommends a max ADC clock of 1MHz.
Arduino sets the ADC clock to 125 KHz (prescaler of 128)
So to match Arduino, you should select a prescaler of 8 ( set bits ADPS1 and ADPS0)

Interesting. Where may I find the ADCSR register? Also, what's the highest prescaler possible? The reason why I want to slow down the ADC as much as possible is to obtain the maximum source impedance. Is this logic correct? (i.e., if I slow down the ADC in the arduino code to kHz values, then the source impedance will reach MΩ values?)

@Gerben Are you sure that holds true for the Due (ARM) or just for an Uno/Mega/Leonardo (AVR) as ADCSR sounds suspiciously like an AVR register name and not like an ARM one.

@David Look for system\libsam\include\adc.h, system\libsam\include\adc.c, and variants\arduino_due_x\variant.cpp in the IDE directory. I am not sure of the exact paths as I have 1.5.1, not 1.6.1 and they've probably changed since then. But the first two have all the access routines for the ARM ADCs. The final one shows how they have initialised it. You will notice they initialise it to ADC_FREQ_MAX which is defined in adc.h to be 20MHz.

@TomCarpenter you are right. This doesn't work on the Due. ATMega only.

The atod clock is set in the mode register. The clock is 42MHz/(PRESCAL#+1). One way of setting it is the use ADC->ADCMR = ADC_MR_PRESCAL(PRESCAL#), where PRESCAL# is some integer.  These symbols are defined in component_adc.h in the Arduino source code.
 In the AVR data sheet, the recommended clock is MIN=1MHz, MAX=20 MHZ, corresponding to numbers between 41 and 1. Look in the data sheet, section 43.

I cannot find where the PRESCAL value is defined by the Arduino framework, do you have the link somewhere? :)

Sorry,  think I found it: #define ADC_MR_PRESCAL(value) ((ADC_MR_PRESCAL_Msk & ((value) << ADC_MR_PRESCAL_Pos))) available here: https://android.googlesource.com/platform/external/arduino-ide/+/f876b2abdebd02acfa4ba21e607327be4f9668d4/hardware/arduino/sam/system/CMSIS/Device/ATMEL/sam3n/include/component/component_adc.h#102 . But not very sure how this should be understood.

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


text:
SSH and web interface broken on Yun
I have two Arduino Yuns that are not accessible at all on the network. I can't go to the arduinoname.local, ssh arduinoname.local, as I previously could. I know at least one it working because it sends emails as I programmed it, yet it seems there is no longer a way to ssh into it. Any ideas?
Yes, I have unplugged, plugged in the router,  and the yuns.

It turns out the problem is a fairly common one - Actiontec wireless access points break this way when set to Both, not AES - see https://superuser.com/questions/522781/unable-to-ssh-from-any-wireless-ip-to-another-wireless-ip-on-home-network
Apparently on other routers this bug is marked as a feature, "Wireless Isolation" or something.


text:
Arduino code cannot continute process
Two days ago, my code is working fine on the arduino board. But yesterday, and today I tried so many time to upload the arduino code, which contains 1000 lines of code. It was successfully uploaded the code into arduino. But it only upload half code into arduino when I saw the serial monitor results (I use serial println(); test where the code is located. ) I am so confusing, why the code is working fine two days ago. but later, only half code being used. Please help.
Here is the memory I left when I uploaded it.
Sketch uses 48,314 bytes (19%) of program storage space. Maximum is 253,952 bytes.
Global variables use 2,603 bytes (31%) of dynamic memory, leaving 5,589 bytes for local variables. Maximum is 8,192 bytes.
Here is the code it stuck :
   Get Parameters
//
//  This function reads the information from the SD card for a given monitoring
//  site.
//

//
int getParameters(){
  String lowerLimit, upperLimit;

   char buffer[36];
  char newChar;
  int index, index1, index2, index3, line, theLength, numSensors;
  myFile.setTimeout(2000);
  line = 0;
  while (myFile.available()) {
    index = 0;
    do{
      newChar = myFile.read();
      buffer[index] = newChar;
      index += 1;
    }
    while(newChar != 10);
    buffer[index] = 0;
    theLines[line] = buffer;
    Serial.print(theLines[line]);
    //here the result is something like this
    //theLines[0] , class 111
    //theLines[1] , 192.168.1.10
    //theLines[2] , Mac Address

    line += 1;
  }

//so it is working fine above the code. But here is the problem stuck.
//the code cannot go through the rest of the code below. Nothing happened!!!
  for (int line = 0; line < 10; line++){
    Serial.print(theLines[line]);

  }

Please edit question and say how much program memory is in use, how much RAM is being used, and perhaps provide a diff between current code and the code that worked a few days ago

I have posted it.

A portion of your code is shown below.
  myFile.setTimeout(2000);
  ....
  while (myFile.available()) {
    index = 0;
    do {
      newChar = myFile.read();
      buffer[index] = newChar;
      index += 1;
    } while(newChar != 10);
   ....
  }

Apparently your code is accepting and printing several lines of option setting text and then hangs up in the code extract shown above.
Suppose, for example, one extra character appears after the supposedly-last linefeed character.  Your while (myFile.available()) loop will run again.  It will store the extra character, then try to read another character.  If another character isn't available, newChar = myFile.read(); will return a -1 that your code will store.  That will happen repeatedly,  clobbering RAM.
To see if this is what's happening, you could change while(newChar != 10); to (eg) while(newChar != 10 && index<36);.  If the code then stops hanging up, look into where the extra character is coming from.

I think this may well be correct, however also, how big is this array theLines? How many lines are in the file you are reading? Possibly you have exceeded the size of the array. Or possibly you have run out of RAM.

In addition change while(newChar != 10) to while(newChar != 10 && myFile.available()) to allow for running out of file data.


text:
Why do I get avrdude: stk500v2_ReceiveMessage(): timeout error when uploading to Arduino Mega?
I have an Arduino Mega clone and I haven't used it for a while. I remember it not working so when I plugged it in and tried uploading the code to it and sure enough it didn't work. So I plugged in an Uno and it worked. The Mega is a 2560 Atmel. Here's my code:

#define distanceForward A0
#define distanceLeft A1
#define distanceRight A2
#define distanceRightAngle A3
#define distanceLeftAngle A4
#define distanceBack A5
int talk = 2;

void setup() {
  Serial.begin(9600);
  pinMode(talk, OUTPUT);
  pinMode(distanceForward, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Front Facing
  pinMode(distanceLeftAngle, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Left Angle
  pinMode(distanceRightAngle, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Right Angle
  pinMode(distanceLeft, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Left
  pinMode(distanceRight, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Right
  pinMode(distanceBack, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, back
}

void hall_roam() {
  Serial.write("forward");
  if (analogRead(distanceLeftAngle) < 30) {
    Serial.write("right");
    if (analogRead(distanceLeftAngle) > 30) {
      Serial.write("forward");
    }
    if (analogRead(distanceRightAngle) < 30) {
      Serial.write("left");
      if (analogRead(distanceRightAngle) < 30) {
        Serial.write("forward");
      }
      if (analogRead(distanceForward) < 60) {
        Serial.write("stop");
        if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
          Serial.write("left");
          if (analogRead(distanceForward) > 60) {
            Serial.write("stop");
          }
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("right");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      } else {
        Serial.write("forward");
      }
    }
  }
}

void roam() {
  Serial.write("forward");
  if (analogRead(distanceForward) < 60) {
    Serial.write("stop");
    Serial.write("left");
    if (analogRead(distanceForward) > 60) {
      Serial.write("stop");
      Serial.write("forward");
    }
  }
}

void talkbb8() {
  pinMode(talk, HIGH);
  pinMode(talk, LOW);
}

void chill() {
  Serial.write("stop");
  talkbb8();
}

void loop() {
  if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
    hall_roam();
  } else if ((analogRead(distanceForward) < 60) && (analogRead(distanceBack) < 60)) {
    Serial.write("left");
    if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
      Serial.write("stop");
      hall_roam();
    }
  } else {
    roam();
  }
}

If there's a bracket out of place or something it's probably nothing. I'm talking about the characters. Is there anything in the characters that would screw up the upload like the three "!!!" problem I heard about or something like that. It's possible that the USB chip in it isn't recognized by my iMac. If so how do I fix that?

The error message basically means that the programmer is unable to contact the boot-loader on the device. The code you're trying to upload has no bearing on the problem.
There could be one of the four possible reason behind it. They are:

Wrong Port Selected:
If TX/RX led is not blinking, then you may have selected wrong port. If one of both of them are blinking then, you aren't using the wrong port. It might be worth checking again though, sometimes USB COM devices install on strange port numbers.
Board is not in Bootloader Mode:
The Arduino Mega is not executing the bootloader for some reason. If the programmer is not resetting the micro before attempting to connect, this might be the reason. Try to reset the board (press and release the button) while the programmer is attempting to connect. Sometimes software that runs in a tight loop will prevent the bootloader from connecting.
Barring that, the fuses might have gotten messed up or the code erased. You would need to reflash the bootloader and proper fuses, again, see the appropriate info page for your device.
Arduino Mega 2560 only: ATmega8U/16U software
Might not be working and would need reprogramming. See the Programming section on the info page, you will need the firmware and Atmel-compatible DFU (device firmware update) software on your computer toreflash the target.
Hardware damage:
There could be hardware damage to the board, AVR(s), or FTDI chip. Time to buy another board.

You can check this answer.

there are only two ports but when i plug in the one that works a third one comes up when with the mega it doesn't. could it be the usb chip

Non of these seem to be the problem or you didn't give the solution to them i don't know.

If you have a timeout issue please ensure the crystal used on board is 16 Mhz.
change
mega.menu.cpu.atmega2560.upload.protocol=wiring
To:
mega.menu.cpu.atmega2560.upload.protocol=stk500v2
Thank you!
Solved my problem!

I tried all the solutions listed on this page:

changed ports,
checked correct port on Arduino IDE,
restarted,
reconnected,
bought a new arduino mega,
etc.

Nothing worked.
Finally gave up and used the web version of the Arduino IDE and it worked just fine.

I had the same issues on MAC OSX El Capitan (older iMAC) using IDE 1.8.x and of course JAVA performed an update.  I regressed the Arduino AVR drivers to 1.6.21 (as instructed online) and this did not resolve the Timeout errors.
I gave up and used IDE 1.8.9 on my OSX MB Pro, and it worked flawlessly.
I think that Java versions and IDE drivers were the issue.

If you have a timeout issue please ensure the crystal used on board is 16 Mhz.
change
mega.menu.cpu.atmega2560.upload.protocol=wiring

To:
mega.menu.cpu.atmega2560.upload.protocol=stk500v2

I had this problem after changing crystal value and changing parameters solved the above problem.


text:
save bytes from Serial into ROM (EEPROM)
I am trying to save an incoming text from serial into the ROM of the Arduino using EEPROM. I found out that you can only save a byte at once. So I thought I could do it like that:

#include <EEPROM.h>

byte c;
int i; // counter for addressing EEPROM

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

void loop(){
  if(Serial.available()){ // check if there is some input form Serial
    while(Serial.available()){ // loops through every character of the Serial input
      c = Serial.read(); // saves current character into variable c in byte form
      EEPROM.write(i, c); // saves c into rom with the address i (counts up after each character)
      i++; // counts c up
    }

    // after all characters are looped through and saved into EEPROM
    Serial.println(i); // print the amount loop runs / amount of characters that are saved
    Serial.println(EEPROM.read(0)); // prints the first character of the input that got saved into EEPROM
    Serial.println("--"); // print cut for overview
    i = 0; // resets counter to 0. That way all values are goint to be overwritten if you type something new into the serial monitor
  }
}

Unfortunately that is not working at all. So what did I do wrong?

Are you sure that you don't want to read back and print the byte you wrote with EEPROM.read(i); and not always read from address 0 with  EEPROM.read(0); as you have implemented the code?

Your code makes no sense whatsoever. You should start by learning how to read serial into an array (https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/) and then copy that resultant array byte-by-byte into the EEPROM.

it does make sense. I will command it. One moment

i is used prior to being initialized.2) It assumes that all the data to be written has arrived and is sitting in the serial buffer already. Serial is slow so the chances are that it'll only get 1 byte each time it runs through that while(serial.avalible()) loop. You're only ever going to write to address 0 (other than the first byte which will go to an undefined random location)

so how would you do something like this?

How about using the EEPROMex library. I find it very useful. Can even save a whole class/struct which can be easier to expand http://playground.arduino.cc/Code/EEPROMex. Your serial should read into a large enough array or struct member, such as char[20]. Then use EEPROMex to get or save the whole thing for you.

Thank you Visual Micro. That tip helps me a lot. I guess that is the solution :)


text:
Help to delimit and read specific contents of incoming HTTP string
I am sending strings to an Esp8266 via web browser.
The below code returns the following in serial monitor if I send in browser:
Send from browser to esp8266 - http://192.168.1.220/s1s2s3s4s5d1
Receive in Arduino Serial monitor - GET /s1s2s3s4s5d2 HTTP/1.1
How do i read only the contents s1s2s3s4s5d1  ? This content can vary in length, numbers could be double digits but alphabets will remain in between.
Please note I am still a novice.

// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

google arduino parsing strings

Thanks, i have tried to implement some methods unsuccessfully. i simply do not have the experience especially since the content required varies in length. i was hoping to get an example if possible.

do you have any control over the URL format ....maybe you need to use something like http://192.168.1.220?s=1&s2=4&s3=8&d=1&abcd=1234

will this method retain the letters or does it strip to numbers?

I have this
if (client.connected()) {
  if (client.available() && client.find(' ')) { // GET /fn HTTP/1.1
    char fn[20];
    int l = client.readBytesUntil(' ', fn, sizeof(fn));
    fn[l] = 0;
    while (client.read() != -1);
    Serial.println(fn);
    client.stop();
  }
}

Thank you, will apply solution and revert.

@s-b, did it help?

you can try something like this
int first_space = request.indexOf(' '); // location of the first space
int second_space = request.indexOf(' ', first_space); // the next space after first

String query_arg = request.substring(first_space,second_space);


text:
analogRead always returns 1023 - Arduino Mega 2560
I have connected an FSR (Force Sensitive Resistor) to  as per image(edited name for avoiding mismatch). When I measure the voltage b/w two pins of fsr, voltage changing as per pressure applied. But analogRead always returns 1023. But my another Mega works good with same code and configurations. Can someone guide me to correct it. Thanks in advance.

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

void loop() {
  int num1 = analogRead(A15);
  Serial.println(num1);
  delay(1500);
}

Your code doesn't check the same pin that your schematic shows being connected.   2.  That LED with no current limiting resistor can cause bad things to happen to your board.  That may have something to do with it.

image is just for reference. In our scenario we connected to A15  and used Mega. Please ignore the LED part and UNO

So basically the picture is just a total lie that has nothing to do with the question?  Why post it then?  Why not post the actual circuit you used?

You can't ignore the LED.  It may be the thing causing your problem.

I dont't know how to make the circuit diagram like the above one.

Really?  Get a pencil and a piece of paper and draw a schematic.  take a picture and upload.  What's hard about that?  It might not be so pretty but at least it will be right.  And what do you think is more important, that it be pretty or that it be accurate?

basic debugging includes switching components around ... have you done that? (switch the +5V and the GND connections)

do some research about voltage dividers

If mega a works and mega b doesn't with the same circuit then mega b must be broken.

I had a similar problem when I ported my code from an Arduino Due to an Arduino Mega. I was able to solve this problem by adding the following call in the setup function.
analogReference(DEFAULT);

It seems that in some other Arduinos, the analog reference will be selected automatically, but at least the Arduino Mega needs it.

I had the same problem when simulating a similar circuit in proteus software. I was able to solve it by supplying power with an external dc input terminal to the arduino board 5v pin.

It sounds like your Arduino Mega 2560 is broken.

If mega a works and mega b doesn't with the same circuit then mega b must be broken. – Majenko

You can confirm this theory by creating a voltage divider circuit (or use a potentiometer as a voltage divider) and get your Arduino Mega to read that in. It is good practice to measure the voltage using a multi-meter as well. This will help you verify that the voltage read in correspond with the voltage measured and will also help so you do not go over-voltage.
If you are constantly getting 1023 then change it to another analog input. If that still does not work, then try the other Arduino Mega.


text:
AVRdude does not read the FUSE byte values correctly
I am exploring the ATmega328p MCU via a standard Arduino UNO, with the help of avr-gcc toolchain and AVRdude (All in the WINAVR package). I have successfully programmed the board a few times with it. However, when I try to read the fuse values via AVRdude, I get 0x0 for lfuse, hfuse and efuse.
I am using the following command (or its variants) to read:
avrdude -c arduino -p ATMEGA328p -P com3 -b 115200 -v -F -U hfuse:r:hi_fuse_val.hex:h
Following is the output I get:
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0

The file hi_fuse_val.hex also has 0 written to it.What am I doing wrong?

A couple of things.  That you can't change fuses from the bootloader and that optiboot can't report fuse values correctly, even if you change them.
No self-programming of fuses
A bootloader can't write fuses, at all.  The chip just doesn't allow self-programming of fuses.  If you want to change fuses, you'd need to resort to external programming (usually using the ISP protocol) with an AVR programmer (or another Arduino set up to behave as one).
Optiboot and reading fuses
Optiboot doesn't report fuses, at least not as compiled for UNO.
The "arduino" bootloader protocol used by the avrdude -c arduino option is a modified version of the STK500(v1) protocol.  The are two commands there that would need to be implemented to read fuses, Cmnd_STK_READ_FUSE and Cmnd_STK_READ_FUSE_EXT.  They have corresponding definitions in the AVR Arduino core's copy of optiboot source.  But the places where they would be implemented in the series of if-elses are absent.  Unlike writing fuses, reading fuses is possible from AVR code.  So it's not a limitation of the chip, the code to do it just isn't there.
Sidenote: You may notice that there are also definitions for commands that write FUSES.  These exist for STK500v1 programmers rather than bootloaders, which can implement these to support writing fuses.
For what it's worth optiboot doesn't actually read the signature of the chip either.  It just reports whatever values have been baked in at compile time.  Both this and the not-reading-fuses above are probably done to keep optiboot as small as possible, which is its goal.
In any case, if you do change your fuses using a programmer, expect optiboot to continue reporting them as zero.
Current fuse values
If you're curious about your actual fuses values, you run sketch that reads them and prints them over serial by using #include <avr/boot.h> and
Serial.print('E');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS), HEX);

Serial.print('H');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS), HEX);

Serial.print('L');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS), HEX);

Thanks a lot for the detailed response. Much appreciated.


text:
Problems connecting Adafruit Feather M0 to network
I'm trying to connect my Adafruit Feather M0 board to an existing WiFi network. Whenever I use the "ConnectWithWPA" example sketch, I receive "Attempting to connect to WPA SSID: "MyNetwork" " in the serial window, where "MyNetwork" is the SSID for the WiFi I wish to connect to. The network never gets connected. The WiFi I want to connect is WPA, password protected. When I connect the feather to an open network (one without a password) it does in fact get connected. The problem only occurs when I try to connect to a network with SSID and password.
Does anyone know what the problem may be?
#include <SPI.h>
#include <WiFi101.h>

#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the WiFi radio's status

void setup() {
  //Configure pins for Adafruit ATWINC1500 Feather
  WiFi.setPins(8,7,4,2);
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  // attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid, pass);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid); //, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");

 }

void loop() {
  // check the network connection once every 10 seconds:
  delay(10000);
  }

I was able to get the Feather board communicating with my WiFi network after I updated my Arduino IDE and firmware. Hope this helps anyone else facing this problem.


text:
How to programmatically choose "board model" and "port number" in Arduino IDE?
I'm testing three different Arduino (nano, Uno and Mega) each of them having a nRF module. The codes (sketches) are different for each module.
I've connected the arduinos to my single laptop via 3 USB ports.
Problem is, whenever I want to re-upload a sketch and fix a bug, I have to choose board model and port number of that sketch by using the menus. It has become frustrating using mouse each time I need to change something.
How can I set these parameters in code so each sketch knows which port and model it is related to?

I don't think you will be able to do that with the Arduino IDE. You may have more luck with a Makefile-based workflow.

You can do it in UECIDE...

You can't in the Arduino IDE, it's not designed that way (you can't even have different board/port settings in different windows - it's stored in the Java equivalent of a single global).
Instead you will have to switch to a different programming environment.
Personally (since I am the author) I would suggest switching to UECIDE. That has far more advanced facilities than the Arduino IDE, yet still retains most of the simplicity of use.
In UECIDE you can not only have different ports and boards selected in different windows, you can also configure individual sketches to automatically select their board and port.

Sketch -> Sketch Properties... -> Objects tab

You have to install "majenko-keyring" first from the same repository. It adds the public key for you.

Or you can manually download the public key and add it with apt-key add: http://majenko.co.uk/debian/key.asc

Darn, looks like I only had that package in unstable. Just backported it to stable.

NodeMCU support is sometimes a little shaky. The development tools provided by the ESP crowd aren't always the most stable of beasts. If you have any troubles with it head over to the UECIDE forums and I'll adjust whatever needs adjusting.

Take a look at the (similar) question and answer in https://arduino.stackexchange.com/a/9182/22924
It talks about multiple UNOs, but the solution should help here.


text:
Why is the T2 transistor used in Arduino Micro?
I was about to design a small custom board using ATmega32U4, replicating the Arduino Micro. I know that T1 is used to block VUSB when VIN is connected.
But why T2? The gate is 5V, so it will be always OFF! Or does it act as a diode?
Schemtic https://www.arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf

T1 and T2 implement a power supply ORing of the VUSB and VIN voltages. Read this for extended information.
The body diode of each MOSFET performs the basic ORing function. When the MOSFET is turned OFF it just behaves as a diode. But when the MOSFET is turned ON, the diode is shorted by the conduction channel, thus avoiding its voltage drop (and achieving a behaviour closer to an ideal diode).
So:

When VUSB is present and VIN is not connected (but pulled down to ground by R9), T1 turns ON and the +5V rail is connected to VUSB. Also, T2 turns OFF and the regulator input is isolated from VIN and the regulator simply doesn't operate (thus, avoiding a potential conflict because its output +5V is being forced to VUSB).
When VUSB is not connected and VIN is present, T1 turns OFF and VUSB is isolated from the +5V rail. Also T2 turns ON and VIN is connected to the regulator input, which then regulates the voltage down into the +5V rail.
When both VUSB and VIN are connected, the behaviour is the same as in case 2 above. Because VIN is supposed to be >7V and VUSB approx 5V, T1 will isolate VUSB and avoid a conflict with the regulator output. Also, a VIN >7V will allow T2 to turn on hard enough to bypass the body diode and avoid its voltage drop.

i got it. Could you please tell why "7V" in 3rd case?

The input voltage VIN for the Arduino Micro is specified in the 7-12 V range.

So it could be any volt that can be handled by voltage regulator?

The input capacitor probably can't withstand as much voltage as the regulator itself. I wouldn't operate the Micro outside its recommended voltage range.

It's known as a "zero drop-out diode". When the power is first applied the body diode of the MOSFET conducts and powers the system. That imposes a (roughly) 0.7V drop on the input voltage.
Once the power gets through the regulator and is regulated to 5V that is then fed back into the gate of the MOSFET, which turns it on (as long as -5V is above the source voltage less the diode drop, so -5.7V minimum [it's a P channel so thresholds etc are negative]). That then bypasses the internal body diode getting rid of the 0.7V drop.
If the input voltage is too low the 5V gate no longer turns the MOSFET on and the body diode blocks any reverse current.


text:
Unable to interface AD7705 (SPI) with Arduino
Code as shown below. I am unable to get the 16-bit data. Can someone help me identify my mistake?
byte spiTransfer(volatile byte data) {
  SPDR = data;
  while (!(SPSR & _BV(SPIF)));
  return SPDR;
}
#define DOUT      (50)
#define DIN       (51)
#define SCLK      (52)
#define CS_AD7705 (53)
#define DRDY (4)

void setup() {
  Serial.begin(9600);
  pinMode(DOUT, OUTPUT);
  pinM ode(DIN, INPUT);
  pinMode(SCLK,OUTPUT);
  pinMode(CS_AD7705,OUTPUT);
  pinMode(DRDY,INPUT);
  SPCR = _BV(SPE) | _BV(MSTR) | _BV(CPOL) | _BV(CPHA) | _BV(SPI2X) | _BV(SPR1) | _BV(SPR0);
  delay(10);
  digitalWrite(CS_AD7705, LOW);
  spiTransfer(00010000); //setup register
  spiTransfer(01100110);
  spiTransfer(00100000); //clock register
  spiTransfer(00001000);
  digitalWrite(CS_AD7705, HIGH);
}

void loop() {
  unsigned int data=0;
  digitalWrite(CS_AD7705,LOW); // enable device
  while(!digitalRead(DRDY));
  data = spiTransfer(00111000);  // select ch1 and setup read 16-bit data register
  data = spiTransfer(0)<<8;
  // Get the most significant 8 bits
  Serial.println("data : "+data);
  data |= spiTransfer(0); // Get the least significant 8 bits
  digitalWrite(CS_AD7705, HIGH); // release device
  delay(1000);
  Serial.println(data, HEX);
}

Why mess around with registers like that? Why not just use the SPI library - that's what it's there for.

I think the main problem is the values you are passing to spiTransfer().  By the way they are written I think you think you are passing binary values, you aren't you are passing decimal values.  So
data = spiTransfer(00111000);  // select ch1 and setup read 16bit data

should be
data = spiTransfer(B00111000);  // select ch1 and setup read 16bit data

The number needs prefixing with a B
Also passing a volatile parameter to this function looks wrong to me, especially when you only pass in constants.

Actually, numbers starting with 0 are octal, not decimal. And you should avoid "B" since they are Arduino-specific macros. Instead you should use the (standard these days) 0b format.

Personally I'd write it in hex, but ... :)

Binary is better when you're working with registers - you can visualise the bits in the register easier.

even though using B as prefix the AD7705 is not taking inputs from potentiometer. can some one help me .i has  left vref(+) and vref(-) open

I've been trying to get one of these working too. I think before you can read the data register, you have to tell the COMMs register your intention to do so.
// Select channel to read:
// write to comm reg selecting channel and
// setting up next op to be a read from data reg
SPI.transfer( DRDY_DONT_CARE | REG_DATA | STDBY_OFF | COMMS_READ | CHAN_AIN1 );
//  Do two 8-bit reads, MSByte first
highByte = SPI.transfer(0xff);
lowByte  = SPI.transfer(0xff);

adcValue0 = highByte << 8;
adcValue0 = adcValue0 | lowByte;

Still, I've had sketchy and intermittent success reading the ADC. The looping code seems to lose sync with the ADC; I've been speculating that reading ASAP following DRDY going True is important.
Have you verified that your SPI interface is working? You can read the 24-bit calibration data, which should match the documented values. Doing so verifies that the SPI reads and writes properly, unless the SPI interface behaves differently for different functions. Are you using genuine Analog Devices silicon, or one of the widely available knock-offs (TM7705, like mine)?


text:
Problem with simple sound detection circuit using a microphone
I am very new to this community. My first project with Arduino was using a LDR (light dependent resistor) in a circuit like this:

The input I got was as expected between 0 - 1023.
I then tried a similar project this time using a sound sensor like this:

My circuit is as follows:

A0 on mic to A0 on Arduino
GND to GND
+ve to 5V
LED along with resistor to digital pin 9 on Arduino

My program is as follows:
const int analogInPin = A0;
int sensorValue = 0;

void setup() {
  pinMode(analogInPin, INPUT);
  pinMode(9, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  sensorValue = analogRead(analogInPin);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\n");
  if(sensorValue > 900)
    digitalWrite(9,HIGH);
  else
  digitalWrite(9,LOW);
}

The problem is the serial monitor gives a weird reading, randomly giving 1023 and 0 after regular intervals.
sensor = 124
sensor = 0
sensor = 1023
sensor = 39
sensor = 352
sensor = 1023
sensor = 142
sensor = 0
sensor = 1023
sensor = 44
sensor = 338
sensor = 1023
sensor = 163
sensor = 0
...
...

I can't figure out the problem myself so I came here.

Do you know what a sound wave looks like?

i understand it is made up of rarefactions and compressions . what i was expecting this device to do was show approx loudness though(intensity if i am correct) .

I mean electrically. When you view it on an oscilloscope, or as a WAV or MP3 file in, say, audacity. It's a long sequence of discrete voltages at different points in time. That is what you are seeing. Discrete voltages at different points in time. That "module" is a microphone and amplifier. Nothing more. It is up to you to process those values to do something meaningful with them.

could you recommend something to read . i was expecting to light the led above a certain loudness. i can see though the similarities between this and a wave ( periodical 1023 and 0s ).Also what am i getting as the input then ??

The one thing you are missing in your thinking is time. During what period must the volume rise above a certain loudness to be counted? Also, you should know that the opposite must be true - not only rising above a certain value but falling below a certain value is just as loud.

Another thing: you can't print to serial whilst at the same time monitor the audio. You are only seeing very short snatches of sound in between your serial prints. Like if you stick your fingers in your ears, then pull them out and put them back in again very quickly. You just get short snatches of sound that make no sense.

The presence of 0 or 1023 in the data indicates clipping, which is to say that signal (or noise or interference) has hit the limit of and probably exceeded the voltage range which the ADC can handle, so the gain needs to be reduced so that "normal" inputs only produce unclipped samples.  But as already pointed out, the sampling rate is really too low and inconsistent.

I plotted the values you got in a spreadsheet:

You must admit that looks a bit like a sound wave! If you want to know if it is a soft sound or a loud sound you really need to see the maximum values (1023 in your case). If the maximum was 512 then clearly the incoming sound isn't as loud.
An alternative, if you just want loudness would be to filter the incoming signal, eg.

simulate this circuit – Schematic created using CircuitLab
This would smooth the incoming voltage so that consecutive readings would be in a narrower range.

Warning: Judging by the graph, you may be getting negative input into A0. The Arduino pins are not designed for negative voltage. You may want to use a diode to eliminate the negative component.

Thanks for the analysis...it felt like a wave to me too. I am afraid though that the maximum is always 1023 and lowest 0 no matter how loud or soft the sound is ,therefore I can't really check the loudness by measuring the peak. Reading through other answers and comments it feels like I should have been expecting a wave like input (am I right in saying it?) .Does that mean the microphone atm is too sensitive(therefore I am always getting a peak of 1023).

Possibly there is a connection problem and you are getting random values. Or you might be right about it being sensitive. I would be measuring with an oscilloscope to see what is really happening.

This is severely mistaken.  First, the data you plot is probably severely undersampled, given the serial printing at 9600 baud in the sampling loop.  Next, it is as likely AC power line hum as intended audio.  Your comment on maximum values is quite mistaken as it ignores that the data is an AC signal centered at some intermediate value, to measure a meaningful maximum the DC component must be removed and the absolute value taken.  Your lowpass filter proposal is the opposite of what would be useful - it removes the AC that should be analyzed, and provides the DC part that should be ignored.

Chris is right about the sampling rate. A higher baud rate may help a bit (and remove the string "sensor = "). He may also be right about the hum - you would need to know when the samples were taken to know what frequency that signal is.

This is severely mistaken. - no doubt the OP would be grateful if you would post an answer showing how to go about solving his problem.

Based on your code, it looks like you are trying to use the analog signal to obtain a digital output (turn an LED on or off). The sound sensor board does this for you and has a digital output pin called "D0".
Heres a simple sketch using the serial monitor to show you what the sensor "D0" pin is putting out. Connect ground and 5 volts as you did before, and connect sensor D0 to Arduino pin 3.
const byte DigitalInputPin = 3;

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

void loop(){
  Serial.print("Digital Pin = " );
  Serial.println(digitalRead(DigitalInputPin));
  delay(50);
}

You don't have to connect the sensor to an Arduino to adjust it or test it. There are 2 LEDs on the sensor circuit board. The one closest to the potentiometer will turn on when the D0 pin is high and off when it's low. You use the potentiometer to set the "trigger point" based on the level of sound you want to make the output go high.


text:
Multiple If Conditions Arduino
I have a project which requires me to read if the input is "HIGH".
I have 15 inputs (switches), and each input has its own output (LED). I am using a Shift Register to control its inputs and outputs.
My current code looks like this (4 inputs and 4 outputs, it works though...):
#include "SPI.h"
#include "MFRC522.h"
#include "rgb_lcd.h"
#include <Wire.h>

#define SS_PIN 17
#define RST_PIN 7

int counter = 0;
int lock = 100;

MFRC522 rfid(SS_PIN, RST_PIN);
rgb_lcd lcd;
MFRC522::MIFARE_Key key;

// Define Pins
int SHIFTIN_LATCH = 22;
int SHIFTIN_DATA = 23;
int SHIFTIN_CLOCK = 21;
int numberToDisplay = 0;

#define SHIFTOUT_DATA  18
#define SHIFTOUT_LATCH  19
#define SHIFTOUT_CLOCK  20

//Define variables to hold the data
//for each shift register.
//starting with non-zero numbers can help
//troubleshoot
byte keySlotID[15] = {
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
byte keyInsert[15] = {
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
byte keyReg[10] = {
  0,0,0,0,0,0,0,0,0,0}; // amt of reg.

void setup() {
  //start serial
  Serial.begin(9600);

  //define pin modes
  pinMode(SHIFTIN_LATCH, OUTPUT);
  pinMode(SHIFTIN_CLOCK, OUTPUT);
  pinMode(SHIFTIN_DATA, INPUT);

  pinMode(SHIFTOUT_DATA, OUTPUT);
  pinMode(SHIFTOUT_LATCH, OUTPUT);
  pinMode(SHIFTOUT_CLOCK, OUTPUT);
  Serial.begin(9600);
  SPI.begin();
  rfid.PCD_Init();
  lcd.begin(16, 2);
}

void KeyID(){
  // Key slot indicator.
  keySlotID[0] = (keyReg[0] & 0x1E) >> 1;
  keySlotID[1] = (((keyReg[1] & 0x03) << 3) | ((keyReg[0] & 0xE0) >> 5)) >> 1;
  keySlotID[2] = (keyReg[1] & 0x78) >> 3;
  keySlotID[3] = (keyReg[2] & 0x0F);
  // Key inserted indicator.
  keyInsert[0] = (keyReg[0] & 0x01);
  keyInsert[1] = (keyReg[0] & 0x20) >> 5;
  keyInsert[2] = (keyReg[1] & 0x04) >> 2; // X
  keyInsert[3] = (keyReg[1] & 0x80) >> 7; // X
}

void registerWrite(byte data1, byte data2) {
  digitalWrite(SHIFTOUT_LATCH, LOW);
  delay(10);
  shiftOut(SHIFTOUT_DATA, SHIFTOUT_CLOCK, MSBFIRST, data2);
  shiftOut(SHIFTOUT_DATA, SHIFTOUT_CLOCK, MSBFIRST, data1);
  digitalWrite(SHIFTOUT_LATCH, HIGH);
  delay(10);
}

void LedIFs() {

  if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 0) {
    registerWrite(0xFF,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 1) {
    registerWrite(0x40,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 0) {
    registerWrite(0x10,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 1) {
    registerWrite(0x50,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 0) {
    registerWrite(0x04,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 1) {
    registerWrite(0x44,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 0) {
    registerWrite(0x14,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 1) {
    registerWrite(0x54,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 0) {
    registerWrite(0x01,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 1) {
    registerWrite(0x41,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 0) {
    registerWrite(0x11,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 1) {
    registerWrite(0x51,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 0) {
    registerWrite(0x05,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 1) {
    registerWrite(0x45,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 0) {
    registerWrite(0x15,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 1) {
    registerWrite(0x55,0);
  }
}

void loop() {

  //Pulse the latch pin:
  //set it to 1 to collect parallel data
  digitalWrite(SHIFTIN_LATCH,1);
  //set it to 1 to collect parallel data, wait
  delay(1);
  //set it to 0 to transmit data serially
  digitalWrite(SHIFTIN_LATCH,0);

  //while the shift register is in serial mode
  //collect each shift register into a byte
  //the register attached to the chip comes in first
  keyReg[0] = ~shiftIn(SHIFTIN_DATA, SHIFTIN_CLOCK);
  keyReg[1] = ~shiftIn(SHIFTIN_DATA, SHIFTIN_CLOCK);
  keyReg[2] = ~shiftIn(SHIFTIN_DATA, SHIFTIN_CLOCK);

  LedIFs();
  KeyID();
}

The problem I'm facing is that it would be too long for me to write down 15 KeyInserts. That would mean I have to write about or close to 200,000 lines of code...

some code wasn't added as it is of no relations to this part of the code.

What are you trying to do EXACTLY?

Just Read the Inputs and if the input is high, output is high. It would've been easier if i don't need to use a shift register but i have to , to save pins. Im currently doing a project, a 15 lock project.

Can you please add your circuit diagram.

Could you please describe KeyInsert, KeyReg and KeySlotID.

Key insert is the switch. KeyReg is thE SHIFTIN register. Key Slot ID is smtg unrelated, you can just ignore that.

May I respectfully suggest you read up on how to write loops? This should be achievable in a dozen lines of code.

If each input represents a single bit in the output then it's about 3 lines: uint16 output=0; for (int i=0;i<16;i++) output |= keyInsert[i]<<i;

Let's assume value that will be stored into "keyInsert" are either "1" or "0". Therefore, its a waste to declare them as an array byte
byte keyInsert[15] = {
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

It means that you will have 15 * 8 bytes variable, and its overkill.
it will be much simpler if you declare it as
uint16_t keyInsert;

Which have 16 bits data (2 bytes).
in your code, you can implement it by doing
void LedIFs() {
if (keyInsert == 0x0001) registerWrite(0xFF,0); else
if (keyInsert == 0x0002) registerWrite(......)......
......
}

I can't quite get the logic of your keyInsert[] array. Why don't you
use a binary number (e.g. uint16_t, which is 16 bits) instead of an
array of zeros and ones? Also, half of the lines of the output shift
register seem essentially unused.
If I understand correctly, you want to simplify LedIFs() in order to
handle many bits with few lines of code. Examining your current
implementation, it appears that you are writing to the output register
the very same bits you have in keyInsert[], only in different
positions. Instead of testing every possible combination, it would be
much simpler to just move the bits into their appropriate positions:

keyInsert[0] becomes bit 0 (i.e. least significant) of the first
argument of registerWrite()
keyInsert[1] becomes bit 2 (it's weight is 22 = 0x04)
keyInsert[2] is bit 4 (weight: 24 = 0x10)
keyInsert[3] is bit 6 (weight: 26 = 0x40)

This is done using bit shifts, and joining the bits with the |
bitwise-or operator:
void LedIFs() {
    byte val = keyInsert[0] << 0
             | keyInsert[1] << 2
             | keyInsert[2] << 4
             | keyInsert[3] << 6;
    if (val == 0) val = 0xff;
    registerWrite(val, 0);
}

Notice that << 0 has no effect: it is here only because it looks nicer
(more symmetric, easier to read) this way. The compiler will optimize
out this operation anyway. Also, the case when all the bits are zero is
special, since you are writing 0xff instead of zero.
If I were you, what I would do is store the information in keyInsert[]
as a single number with the bits already at their correct position. Then
I would write
uint16_t keyInsert;

//...

static inline void LedIFs() {
    registerWrite(keyInsert ? keyInsert : 0xff, 0);
}

I will be using digitalReads and digitalWrites but just follow this logic:
int state[num_of_switch_that_you_have];

for(int i=0; i<num_of_switch_that_you_have; i++)
{
  //buttonPins is the pin to which all your buttons are connected to in an array
  state[i] = digitalRead(buttonPins[i]);

  //leds is the pin to which all your leds are connected to in an array
  digitalWrite(leds[i], state[i]);
}

Try to follow this logic while using your shift registers. Sorry if I don't have a full code with shift registers for you, I'm not really good with them!
If you need any more details, please comment, I'll be happy to help!


text:
SPI communication Problem Arduino
I'm trying to set up SPI communication between two Arduinos (UNO and Mega),
I want to read the status of the slave output pin from the master.
I connected a diode to pin 9 of Mega and I wanted to display its state on the virtual terminal of the master (Uno). The problem is that when the LED flashes I do not receive values just at the terminal level but when I hold it to zero or 1 the display is correct.
I used another code I found online.
MASTER code

#include <SPI.h>
const byte btn =8;

void setup(void) {

Serial.begin (9600);
pinMode (btn, INPUT_PULLUP);
digitalWrite (SS, HIGH);
SPI.begin ();
SPI.setClockDivider (SPI_CLOCK_DIV8);

}

void loop(void) {

byte Mvalsent,Mvalreceived;
digitalWrite (SS, LOW);
for (int jj=0; jj<255; jj++)
  {
      Mvalsent =jj;
      Mvalreceived =SPI.transfer (Mvalsent);
      Serial.print ("Retou d'etat ");
      Serial.print (Mvalsent);
      Serial.print ("\t ,l'etat de la diode est ");
      Serial.println (Mvalreceived);
      delay (400);
  }

  digitalWrite (SS,HIGH);

}

SLAVE Code
#include <SPI.h>
byte state;
const byte led =9;
volatile boolean process_it;
volatile byte Svalreceived, Svalsent;
int jj=0;
void setup (void)
{
  Serial.begin (9600);
pinMode (led,OUTPUT);
//set MISO pin as output
pinMode (MISO, OUTPUT);
//turn on SPI in slave mode
SPCR |= _BV (SPE);
//get ready for an interrupt
process_it = false;
//now turn on interrupts
SPI.attachInterrupt ();
}
ISR (SPI_STC_vect)
{
  Svalreceived = SPDR;
  process_it =true;
}
void loop (void)
{
 if (process_it)
 {

   digitalWrite (led, LOW);
   state =digitalRead(led);
   SPDR = state;
   Serial.print("l'etat de la diode est: ");
    Serial.println (state);
    delay (400);

    process_it =false;
  }
}

Why not use I2C slave-master between arduinos?  You can hook up other arduinos or devices on I2C simultaneously (as long as each uses a distinct address).
And you still keep the SPI for a microsd card adapter, for example.
Follow this official tutorial:

MASTER ARDUINO 1
// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}

SLAVE ARDUINO 2
// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

This is an alternative example of a setup using a nodemcu (which doesnt function in slave mode, btw).