text:
Transmitting Variables over RF
I'm using the 3715 RF arduino modules and a hc-sr04, and i'm trying to send the distance i get from the ultrasonic over to the arduino with the rf recieving module but i get something like this:
Instead of getting this:
Here are the code snippets for each arduino:
Arduino TX:
#include <VirtualWire.h>

const int led_pin = 11;
const int transmit_pin = 12;
const int receive_pin = 2;
const int transmit_en_pin = 3;
long distance;
long time1;
void setup()
{
   // Initialise the IO and ISR
   Serial.begin(9600);
   pinMode(9, OUTPUT);
   pinMode(8, INPUT);
   vw_set_tx_pin(transmit_pin);
   vw_set_rx_pin(receive_pin);
   vw_set_ptt_pin(transmit_en_pin);
   vw_set_ptt_inverted(true); // Required for DR3100
   vw_setup(2000);   // Bits per sec
}

byte count = 1;

void loop()
{
   digitalWrite(9,LOW);
   delayMicroseconds(5);
   digitalWrite(9, HIGH);
   delayMicroseconds(10);
   time1=pulseIn(8, HIGH);
   distance= int(0.017*time1);
   Serial.println("Distance ");
   Serial.println(distance);
   Serial.println(" cm");
   delay(1000);
   char msg[1] = {distance};

   msg[0] = count;
   digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
   vw_send((uint8_t *)msg, 3);
   vw_wait_tx(); // Wait until the whole message is gone
   digitalWrite(led_pin, LOW);
   delay(1000);

}

Arduino RX:
#include <VirtualWire.h>

const int led_pin = 6;
const int transmit_pin = 12;
const int receive_pin = 11;
const int transmit_en_pin = 3;

void setup()
{
   delay(1000);
   Serial.begin(9600);  // Debugging only
   Serial.println("setup");

   // Initialise the IO and ISR
   vw_set_tx_pin(transmit_pin);
   vw_set_rx_pin(receive_pin);
   vw_set_ptt_pin(transmit_en_pin);
   vw_set_ptt_inverted(true); // Required for DR3100
   vw_setup(2000);  // Bits per sec

   vw_rx_start();       // Start the receiver PLL running
}

void loop()
{
   uint8_t buf[VW_MAX_MESSAGE_LEN];
   uint8_t buflen = VW_MAX_MESSAGE_LEN;

   if (vw_get_message(buf, &buflen)) // Non-blocking
   {
      int i;

      digitalWrite(led_pin, HIGH); // Flash a light to show received good message
      // Message with a good checksum received, print it.
      Serial.print("Got: ");

      for (i = 0; i < buflen; i++)
      {
         Serial.print(buf[i], HEX);
         Serial.print(' ');
      }
      Serial.println();
      digitalWrite(led_pin, LOW);
   }
}

I'm open for pointers as i'm pretty much a noob at this, thank you very much for your help! :)

vw_send() can only send bytes. If you want to send numbers, you have to format them as an array of bytes, either as text or binary, before sending.

@EdgarBonet - or send the raw bytes comprising the existing storage of the number.

If you only need to display the value at the other end rather than do any calculations on it then it's nicer to send it as text rather than a number.
Sending:
   char msg[10]; // bigger than it needs to be to avoid overflow issues

   int length = sprintf(msg,"%ld",distance); // convert value to ascii
   digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
   vw_send((uint8_t *)msg, length + 1); // send value (add 1 to length to include the string terminator)

   vw_wait_tx(); // Wait until the whole message is gone
   digitalWrite(led_pin, LOW);
   delay(1000);

Since the data sent over the radio is now a standard c string complete with null terminator the receiving code becomes:
if (vw_get_message(buf, &buflen)) { // Non-blocking
  int i;

  digitalWrite(led_pin, HIGH); // Flash a light to show received good message
  // Message with a good checksum received, print it.
  Serial.print("Got: ");
  Serial.print(buf);
  Serial.println();
  digitalWrite(led_pin, LOW);
}

This is making the assumption that the whole thing is sent in a single radio packet, if the vw_get_message doesn't return the entire message in one go then nasty things will happen. You could always check for this be ensuring that strlen(buf) returns one less than buflen since buflen should include the null terminator but strlen() won't

"Since the data sent over the radio is now a standard c string complete with null terminator"  You may want to make sure the terminator is there before calling anything, including strlen() which assumes one.

It looks like you're sending only one byte, but expecting to receive three.
In the TX sketch, char msg[1] = {distance}; declares an array of one char, assigns its zero-th element the value of distance. Then msg[0] = count; over-writes it with the value of count. vw_send((uint8_t *)msg, 3); tries to send three bytes but only the first one has been defined. The second and third bytes transmitted are outside of the 1-length array.
You need something more like:
vw_send(distance, sizeof(distance));

on the TX side, and:
long distance;
uint8_t count;

vw_get_message(distance, &count));
Serial.println(distance);

on the RX side. You must receive the count into a variable but can ignore it, on the RX side; you know you'll be receiving a long; though good defensive coding would check the value anyway.


text:
Interrupts not firing sometimes
I am a little new to the arduino space, so forgive me if this question is a bit noobish.
Below I have linked the code. I am using an Arduino Mega and using photosensors, specifically this one EE-SPY415 Reflective Photomicrosensor with a detectable sensing distance of 3- to 19-mm
I am using this with a skeeball type arcade and the Arduino is using usb to communicate with a Pi. I am not sure if this is the best way, so if someone has a better way please let me know. There are 6 sensors now and 2 more that need to be hooked up. I will be using a library that allows for more than 6 interrupts to be used, but wanted to rule out the library as being at fault.
My issue in question is when the game is started, the serial.write isn't always firing when a ball goes through the hole. I am not sure yet if the interrupt fires and not the serial write, so any help there would be good too.
https://pastebin.com/zbVuqec2
Here is the ino file in question.
#include <Wire.h>

String inputString = "";         // a string to hold incoming data
boolean startGame = false;
boolean stopGame = false;
boolean readSensors = false;

boolean sensor_1_tripped = false;
boolean sensor_2_tripped = false;
boolean sensor_3_tripped = false;
boolean sensor_4_tripped = false;
boolean sensor_5_tripped = false;
boolean sensor_6_tripped = false;

#define SENSOR_1 2
#define SENSOR_2 3
#define SENSOR_3 21
#define SENSOR_4 20
#define SENSOR_5 19
#define SENSOR_6 18

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  pinMode(SENSOR_1, INPUT_PULLUP);
  pinMode(SENSOR_2, INPUT_PULLUP);
  pinMode(SENSOR_3, INPUT_PULLUP);
  pinMode(SENSOR_4, INPUT_PULLUP);
  pinMode(SENSOR_5, INPUT_PULLUP);
  pinMode(SENSOR_6, INPUT_PULLUP);

  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inputString == "start") {
      startGame = true;
      stopGame = false;
      readSensors = true;
      Serial.write("STARTED");
      inputString = "";
      return;
    }
    if (inputString == "stop") {
      stopGame = true;
      startGame = false;
      readSensors = false;
      return;
    }
  }

  while (startGame) {
    while(readSensors) {

      attachInterrupt(digitalPinToInterrupt(SENSOR_1), sensor_1_callback, FALLING);
      attachInterrupt(digitalPinToInterrupt(SENSOR_2), sensor_2_callback, FALLING);
      attachInterrupt(digitalPinToInterrupt(SENSOR_3), sensor_3_callback, FALLING);
      attachInterrupt(digitalPinToInterrupt(SENSOR_4), sensor_4_callback, FALLING);
      attachInterrupt(digitalPinToInterrupt(SENSOR_5), sensor_5_callback, FALLING);
      attachInterrupt(digitalPinToInterrupt(SENSOR_6), sensor_6_callback, FALLING);

      if(Serial.available()) {
        char inChar = (char)Serial.read();
        inputString += inChar;
        if (inputString == "stop") {
          stopGame = true;
          startGame = false;
          readSensors = false;
          inputString = "";
          Serial.write("STOPPED");
          break;
        }
      }

      if(sensor_1_tripped == true) {
        sensor_1_tripped = false;
        Serial.write("1");
      }
      if(sensor_2_tripped == true) {
        sensor_2_tripped = false;
        Serial.write("2");
      }
      if(sensor_3_tripped == true) {
        sensor_3_tripped = false;
        Serial.write("3");
      }
      if(sensor_4_tripped == true) {
        sensor_4_tripped = false;
        Serial.write("4");
      }
      if(sensor_5_tripped == true) {
        sensor_5_tripped = false;
        Serial.write("5");
      }
      if(sensor_6_tripped == true) {
        sensor_6_tripped = false;
        Serial.write("6");
      }
    }
  }
}

void sensor_1_callback() {
  sensor_1_tripped = true;
}
void sensor_2_callback() {
  sensor_2_tripped = true;
}
void sensor_3_callback() {
  sensor_3_tripped = true;
}
void sensor_4_callback() {
  sensor_4_tripped = true;
}
void sensor_5_callback() {
  sensor_5_tripped = true;
}
void sensor_6_callback() {
  sensor_6_tripped = true;
}

Why do you use attachInterrupt() every time sensors are read? Is not it enough to do it only at the beginning of the game?

Those booleans that are used in the ISR and are also read from loop need to be volatile.

I added volitile but it didn't help (I did read about how that needed to be done though). As for the attachInterrupt I have it now in the setup() but if its already attached it ignores it. Either way the interrupts still arent working as expected.

Could you try to test with a simpler code without any Serial.read() and also correct your code in the question (volatile and only attach in setup). It is easier to help if the problem is narrowed down as much as possible.

I ended up using Android Things GPIO library and built a custom board that plugs into the Pi via the UART

The best solution I found for communicating interrupts to the Pi3 from Arduino is by using the GPIO. Android Things has a library for this and it all works without any lag!

source: Stack Exchange

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

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

sort: votes


text:
Program is working wrong while melody playing
My robot working fine but when I added buzzer and melody into code then is something wrong. Melody is playing when accelerometer is activated but rest of the code need to wait to end of melody. I want to play melody in background when program works. How to do it? There is my code:
#include <RedBot.h>
#include <RedBotSoftwareSerial.h>
RedBotAccel accel;
RedBotMotors motors;
int CM;
long CZAS;
bool started = false;
const int buzzer = A0;

int shortTone = 80;
int longTone = 200;
int standardDelay = 50;
int delayBetweenBars = 50;

void setup()
{
   Serial.begin(9600);
   accel.enableBump();
   accel.setBumpThresh(150);
   pinMode(A2, OUTPUT);  //Trig
   pinMode(A3, INPUT);   //Echo
   pinMode(buzzer, OUTPUT);  //Buzzer
}

void pomiar_odleglosci()
{
   digitalWrite(A2, HIGH);
   delayMicroseconds(10);
   digitalWrite(A2, LOW);
   CZAS = pulseIn(A3, HIGH);
   CM = CZAS / 58;
}

void loop(){

   while (!accel.checkBump() && !started) delay(100);
   started = true;

   if(started = true)
   {   DarudeSandstorm();
   }

   pomiar_odleglosci();
   Serial.print("Odleglosc: ");
   Serial.print(CM);
   Serial.println(" cm");

   if(CM>10)
   {
      motors.drive(100);
   }
   else
   {
      motors.drive(-100);
      delay(400);
      motors.stop();

      delay(400);

      motors.rightMotor(100);
      delay(700);
      motors.stop();

      motors.drive(100);
   }

}
//melody

Define wrong. Also, links to code are not wanted. Post your code in your question and format it correctly. Tell us what you expect to happen, and what actually happens.

Where does the melody play? At the DarudeSandstorm function? Where is it defined? Please provide a link for the red robot includes, so that we can check them.

This is all code: https://pastebin.com/aihBQZT1 , and this is library for redbot.h: https://github.com/sparkfun/SparkFun_RedBot_Arduino_Library/blob/master/src/RedBot.h

You are using delay() in many parts of your code, which makes it very trick. I see a couple of possibilities here:
1 - if you have extra time and patience, get rid of all delays and find your around it counting millis() or some similar technique.
2 - if you have some extra bucks, get another controller just to play the melody, an ATtiny85 should be cheap and practical for this.
There is also the super-lazy, almost-no-work-at-all, relatively cheap solution: use a small media/MP3 player module, which also would allow you to have more than one melody and eventually adtiional noises.

So for example how to change delay(1000); to millis?

look at the BlinkWithoutDelay example code in the Arduino IDE

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


text:
GSM arduino to webservice not working
I have setup a arduino with a SIM300 based GSM board. I have

Tx of Arduino connected to the Rx of GSM board
Rx of Arduino connected to the Tx of GSM board
Gn of Arduino connected to the Gd of GSM board

The GSM has a Vodafone 3g sim, activated with 3g. The GSM board has 2 LED's, one remains ON and the other blinks ever 4-5 seconds. Which I guess means that its configured to work with the SIM.
I then run the following code.
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  mySerial.begin(9600);

  Serial.println("Serial ports initialized");

   delay(500);
   Serial.println("AT+CGATT=1");
   delay(500);
   Serial.println("AT+CGDCONT=1,\"IP\",\"TATA.DOCOMO.INTERNET\",\"0.0.0.0\",0,0");
   delay(500);
   Serial.println("AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"");
   delay(1000);
   Serial.println("AT+CSTT=\"TATA.DOCOMO.INTERNET\",\"\",\"\"");
   delay(2000);
   Serial.println("AT+CIICR");
   delay(5000);
   Serial.println("AT+CIFSR");
   delay(500);
   Serial.println("AT+CIPSTATUS");
   delay(500);
   Serial.println("AT+CDNSORIP=1");
   delay(500);
   Serial.println("AT+CIPSTART=\"TCP\",\"http://myec2DNS-us-west-2.compute.amazonaws.com:myportnumber/mywebservice/myreques/Authentication/Request?identity=somecode&identityType=sometype\",\"myportnumber\"");
   delay(500);
   Serial.println("AT+CIPSEND");
   delay(500);
   Serial.println("AT");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

On cutecom I get te following
Serial ports initialized
AT+CGATT=1
AT+CGDCONT=1,"IP","TATA.DOCOMO.INTERNET","0.0.0.0",0,0
AT+CDNSCFG="8.8.8.8","8.8.4.4"
AT+CSTT="TATA.DOCOMO.INTERNET","",""
AT+CIICR
AT+CIFSR
AT+CIPSTATUS
AT+CDNSORIP=1
AT+CIPSTART="TCP","http://myec2DNS-us-compute.amazonaws.com:8080/myservice/mycommand/Authentication/Request?identity=%somecode&identityType=1","8080"
AT+CIPSEND
AT

When I run `tail -f  /var/lib/tomcat7/logs/localhost_access_log.2014-09-20.txt' on my webserver, I get nothing from the arduino.
What am I missing here ?

it seems like you are using the wrong serial interface. I see Serial and mySerial.
After mySerial.begin() you write to Serial, not to mySerial which runs on pins 10 and 11.
What's when you send the AT Commands from your Serial connection to the Arduino? It Should redirect them to the GSM board.

I welcome your answer. Shouldn't the loop method take care of that ? I did also get OK's for all AT commands.

The loop() redirects incoming commands from Serial to mySerial and vice versa.  If i'm not mistaken the AT Commands in setup() are sent to your computer and not to the GSM module. Where does the OK's come to?

The OK's come on the cutecom ttyUSB0. I think its working that way.

You might want to implement error handling for the AT commands.
Though if you believe this answer has fixed your question press the ✔ below the ⇩ on the left side of the question.

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


text:
Sensor for underground water tank level
In a similar way to the question  "best way to determine if a 5 gallon water jug is getting empty", I'm looking for a way to measure water in a container. This is so it can be connected to an Arduino for logging and reporting.  But it's a very different container.
I have a home with the household water supplied from an underground concrete tank (around 3000 US gallons, 11000 litres).  Although there is a float switch cutout when it gets empty (to protect the pump), I'd like to know it's gettting low long before that (as it takes a while before a tanker delivers a fresh load).  Ideally something that measures exactly or in steps (at least in eights of a load), so software can predict when it'll run out based on average usage, and it can be monitored online when away.
The tank has a heavy concrete hatch, and a small hole that has an existing primitive dipstick, so access is limited.  It's in a harsh desert environment, but the pump room and power are only a few feet away.
Some ideas I had:

suspend an array of float switches with strings of different lengths from a bar inside the tank, and wire them all back to a controller.  Hard to install, ugly, low tech. Or something similar on a vertical pole.
contacts (like a US 2 pin plug) on a vertical pole that again are connected back to a controller (probably using a ribbon cable).  Corrosion/anodes might be a problem, although power could just be a short pulse at times.  Condensation, spiders webs and dead bugs may give false readings.
run a fully insulated cable vertically down it, and use as an antenna to send a pulse through, and use the difference between how it works as an antenna in air, and in water, (like an SWR meter) to calculate how far down the water is.
ultrasonic (or light?) distance finder mounted under the hatch.  Range needs to be up to 2 metres (6 feet).
depth finder (sonar) on a float.  Biggest challenge here is getting the signal out (long cable might get tangled when the tank fills).

The last two would be even better if they were wireless (to save running a cable that might get damaged) but I don't think I'd get the battery life I'd like (1 year or more).
Any other ideas?  Has anybody ever done this?

I have a background working on ships where robust and workable tank level gauges are  a huge part of instrumentation available to you. Water is the most forgiving and easiest liquid to measure - it's cool, not too viscous, not corrosive in itself, and easy to clean off. There are a lot of options available to you.
Personally I would avoid any system which involves immersing anything in liquid if at all possible. Waterproofing isn't easy. I would also try to stay with a tried and tested system.
So to run through your solutions:

Multiple float switches - has poor resolution. Would be reliable. You can buy assemblies with LowLow, LowHigh, HighLow, HighHigh float limit switches already on them for maintaining tanks levels, but these are industrial quality with industrial prices.
This would work, but corrosion is going to be an issue. Resolution limited by how many contacts you have.
Interesting idea, but would likely require a lot of DSP work. Not a tried and tested method.
An ultrasonic sensor would be my preferred method. Non-contact, high resolution, range of 2m is easy. Tried and tested system.
Interesting idea, would require a lot of work. Easier to measure depth of air as per 4 and do the simple maths.

A few other methods come to mind:

A pressure sensor at the bottom of the tank. This is often used on ships, works well but needs immersion which can be avoided.
Inflow/outflow monitoring. A flow meter on the output can tell you how much you have used. Inferring level like this is prone to errors though.

There are a million other methods, but they get more and more complex.
The ultrasound would be a great way to do this. The commonly available Parallax Ping sensor would do the job. Realistically, you would only need to make measurements at most once every hour, so you could achieve great battery life. The concrete is likely to present a wireless range challenge. Most RF transceivers will get through concrete though, so place the receiver nearby.
If you want ideas on how it is done, google for ultrasonic oil level monitoring - there are loads of wireless commercial solutions.

I would concur with the ultrasonic sensor.  Stick a length of PVC down the dipstick hole into the tank so the pipe fills from the bottom.  Drop a ping pong ball or a float down the pipe so it rides up and down inside the pipe.  Aim an ultrasonic sensor down the pipe and read the distance to the ball/float.

I've had no issues using the bare sensor onto water with a 5cm length of pipe over the end to reduce spurious reflections, but I do like the ping pong ball idea.

@Mike Good idea but I don't know if most ultrasonic sensors would reach deep enough for a 3,000 gallon tank. Also, a sensor might be too wide to fit in a pipe that holds a ping-pong ball...

Question states range would need to be about 2m, Parallax Ping does 3m.

cybergibbons - nice list of for/against reasons, I agree with you that ultrasonic looks the simplest and most standard.  I'll leave the question open for a few more days for other suggestions before accepting an answer.  @mikeY - nice idea, simpler to mount, but the existing hole (through concrete) that the dipstick uses is (as Annonomus Person suggests) too narrow for a sensor (it's about 1/2", 12mm diameter).  Looking at the dipstick, the depth might be nearer to 3m than 2m, but that's still enough (as it's never empty).

http://playground.arduino.cc/Main/Waterlevel
The above link had a nice approach.

The principle is the same as traditional pneumatic level gauge, excepted that the dial indicator is replaced by a pressure transducer, and the manually-operated pump is replaced by an aquarium air pump.
When the pump is on, air flows through the weighted PVC pipe to the bottom of the tank, where bubbles appear. At this moment, the air pressure in the PVC pipe is equal to the hydrostatic pressure at the bottom of the tank. As the water pressure at the bottom of the tank is directly proportional to the water level, the same goes for the air pressure in the PVC tube. The air pressure is then converted to an analog voltage by the pressure transducer. This voltage can be read easily by the arduino.
A big advantage of this method with regards to other existing techniques is that no electronic or metallic parts needs to be placed in the tank, where the environmental conditions (mainly humidity) are not favorable. This avoids any risk of corrosion.

Please update your answer with some detail in case the link gets changed or removed.

It's tricky when you only have a small hole to work with, so trying to get inside to install a series of floats or contact pins on the side is not ideal. The ultrasonic is a good idea, but I don't know how that would be achieved. Personally, I would try the cable, as it is simple enough to drop it in the hole, and wait for your results.
If you wanted to try running a cable through it, you might want to use this Water Level Sensor, or at least base your own project on it.
It is non-corrosive, and has no moving parts, which is supposed to lead to a heightened accuracy, and less chance of it failing or breaking down. The enclosure is water-proof, and you can buy one with a relay attached to fit your monitoring needs. The only issue that I see is that it isn't wireless, but other than that, it seems to be pretty functional.

I know you asked this a few months ago .. but sometimes with something technical the project never gets completed, or at least not in short order.
So while you're building your new-world-order with an Arduino, can I suggest you put a pipe down the dip hole and insert a floating dip stick? 1.5" pipe. 1/4" dowel glued to a ping-pong ball. Flag on top of the dowel. Now you'll see the level any time you walk past.

I've been using the Ultrasonic method for close to a year and the biggest problem is the sensor failing due to water infiltration(condensation). My latest attempt lasted for about two weeks. I used plastic spray like the stuff you use on tool handles. I also used the wireless shield to make a website that displayed the level on any device connected to my router. I would like to get it to email me when the level is below 10% but can't get it to work....It's not bad but still needs work for stability...

The bubble tube method (http://dexautomation.com/?p=9) springs to mind.
Also capacitive measurement is doable (http://olimex.wordpress.com/2012/02/02/duinomite-project-tank-fluids-level-metering-by-capacitance-measurement/) but more tricky. If you can use the steel inside the concrete it can be made completely contactless.
Please note, that if the water is meant for consumption without filtering or purification you may want to refrain from direct-contact methods.
Googling for "tank level measurement arduino" yields lots of potentially useful results.
Also, is consumption so erratic that you can't predict when the tank needs filling?

Id go with an ultrasonic detector as Cybergibbons suggests together with a usage/flow monitor (http://www.ebay.com/bhp/water-flow-sensor) so as to understand if there are any losses through leaks etc. I'd use a YUN or Ethernet or shield to call or email you a monthly report / fill a datbase as well as place the order directly to the water supplier as well as cc'ing you.

You could take a piece of 2 conductor wire in a U shape that is weighted at the bottom of the "U" to rest at the bottom of the tank.  (The reason to use a U shaped wire instead of a straight wire is to prevent having to insulate one end from the water).  You would then measure the capacitance of the wire, where some baseline capacitance is the wire when dry and any wire that is wet would increase the capacitance proportional to the length that is wet.  Any wire that is rated for outdoor operation, i.e. does not absorb water would do and actually the thicker the jacket the better as the baseline capacitance would be lower.
The capacitance could be measured in the same way as a capacitive touch sensor or a capacitance to frequency converter (Sometimes called an "Oscillator").

The limited access issue is tough... If you were going to use the float idea, it would be hard to difficult to actually install the thing. The other issue is waterproofing components and making sure that they won't corrode and cause false readings, which defeats the purpose of installing the system. Although it is a different scenario, i use this Water Level Sensor to moniter my home aquarium. the sensor is totally insulated, and is thus waterproof. also the sensor itself is aproximately 1 mm in width,so it probably fit into your reservoir. From what i've seen so far from my use is that it is pretty accurate, and it works in both my salt water and fresh water tanks. Hope this helps!

I have used FM antenna cable successfully as soil moisture sensor and as fluid level sensor. Dip the bottom end into melted glue stick to insulate.
For permanent installation in a water tank I would also dip the cable into a paint tin and hang it up to dry for extra insulation. Antenna cable without any extra waterproofing was used for soil moisture measuring for 3 years with no problems.
The top end is connected to two parts of a LM393. The first one is a Schmitt trigger with 470K feeback and 1M series. The neg side is fed back with 220K. The second one is simply an inverter, and the output feeds back through a 220K. The two 220ks get connected to the sensor cable, and a parallel 100pf cap.The cable is thus excited differentially.
The ciruit oscillates according to the capacitance of the sensor cable. The frequency is measured by your favourite micro. The extra 100pf is only there to keep the frequency in a range where the oscillations can be fed over a line.
A bucket of water is enough to calibrate the setup.


text:
ATSAMD21 sleep + watchdog?
Has anyone got sleep/standby + watchdog to work together on their Arduino Zero or Sparkfun SAMD mini?
I am able to get the WDT to reset the device, and am able to put it to sleep - but can't get the WDT to bring it out of sleep.  Every time I try, it pops right back out of sleep mode again as if SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk was never even called

use this:
attachInterrupt(wakeUpPin, wakeupFunction, HIGH);
    USBDevice.detach();
    SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
    __DSB();
    __WFI();

void wakeupFunction(){
  NVIC_SystemReset();
}


text:
can homemade arduino be powered up with battery?
I am new to arduino. It is costly for me to buy an arduino uno board. Therefore I am going to make a Arduino with breadboard at my home. I also want to make my Arduino portable. Arduino Uno boards can be powered up with battery. But can I do so with my homemade Arduino? If it is possible, what things need to be included in my homemade Arduino?

A modern irony is that it can by hard to buy a single processor for less than the cost of a clone board - especially if you want one with the bootloader pre-programmed.  And while the USB-serial chips used on some of the clones can be problematic (as much with the Windows drivers as the hardware), you will need to supply similar functionality when breadboarding, which tends to cost as much as or more than MCU itself.

A breadboard and all components needed will often actually cost more as one of the boards from e-bay.
It should also be very easy to find millions of tutorials on how to make your own Arduino.
For the battery part you will need some kind of regulator. And to be honest, this is also one of the basic "electronic engineering" projects of which millions of articles and blogs can be found. Circuitry and everything can be found most regulators' datasheet.

But can I do so with my homemade arduino? - of course. Why on earth wouldn't you?

First, of course, you'll need a battery with enough capacity, and voltage enough greater than 5v (assuming you want to run your home-built at 5v - typical, but you could run it lower, say 3.3v) to give enough run-time before the battery discharges to where it can no longer supply the system. Note that the 9v, so-called "Transistor battery" is not capable of supplying much current. A battery pack of off-the-shelf alkaline batteries or rechargables, or a Lithium Polymer rechargable battery will do much better.
You'll need a low dropout voltage regulator to reduce the battery voltage to your chosen Arduino supply voltage. National Semiconductor's LM1117 would be a good choice. The diagram below from NS's datasheet shows a simple-to-make voltage regulator. Its input is your battery; its output will be the supply voltage to the chip and any accessory circuitry.

Linear regulators mean wasted battery capacity.  Unless something in the system needs a consistent voltage, one may not be needed.

That never occurred to me but of course! The programmer, FTDI cable in my case, would have to guarantee clean power during programming (or one could regulate its output). But once built & programmed, it could run off of 4.5v from 3 Alkalines until it fails or until it detects the voltage is too low for the clock frequency. Thanks for the idea!

Yes you can power it from a battery, as long as you add a 5V regulator to your board.  You might get strange behaviour when the battery is running low.
These links all tell you what you need to build the board, good luck.
https://www.arduino.cc/en/Main/Standalone
http://www.instructables.com/id/How-to-make-your-own-Arduino-board/
http://www.instructables.com/id/DIY-Arduino-or-The-DIY-Duino/

You won't get strange behavior if brownout detecting is enabled (which it is by default in Arduino's).

You can use 9 Volt batteries to power most Arduino Boards.  For instance the Mega 2560 has a rated Vin range of 7 to 12 Volts.  A car battery can be used for longer life, although not nearly as portable as a 9 Volt one with a clip.  I'd recommend a common 7809 Positive Voltage Regulator TO-220 between a car battery charged using a car alternator and an Arduino board though, because the Voltage may vary quite a bit above the 12 V maximum.
I've used batteries with microprocessors for years for various embedded applications where access to AC is inconvenient, impractical, or nearly impossible.
The Mega page on the Arduino site explicitly permits battery power 1.
Helpful Guidelines
Here are some important criteria to meet.

The Voltage is within the published range for the Arduino model you are using
The positive of the battery supply connected to Vin (NOT any of the other power pins)
The negative of the battery supply is connected to Gnd
Critical applications don't run under the assumption that the battery will never drop below the minimum of the published supply range
The header is never plugged in backwards or in the wrong location, which would likely damage the Arduino circuitry

Connection Safety Using Plug and Jack
If you are connecting and disconnecting the Arduino from your battery frequently or you just want .
See the Power section of the pageto make sure you never plug in the header wrong, you can connect your battery supply to the Arduino board's existing power jack 2.  When connecting a battery supply to an Arduino compatible plug, you can ensure that the plug's inner conductor is positive in Voltage relative to the outer sheath using a Voltmeter.
Battery Use in Robotics and Flight Control
A 9V battery will eventually drop in Voltage below the rated minimum, upon which the operation of the board may fail at any time, so you may want to add more 9V batteries in parallel to extend your battery supply's life 3.
Another approach common in robotics or flight control applications, to preemptively avoid erratic behavior as the battery drains below operational thresholds, is to use the low voltage detection features of the CPU.  The Atmel CPU used by the Arduino Mega 2560 4 has a Brown-Out Detection feature 5.
A simpler approach for critical applications is a resistor divider on an analog input is another related approach.
.....
[1] See the Power section of this page https://www.arduino.cc/en/Main/ArduinoBoardMega
[2] Information about compatible plugs is at http://forum.arduino.cc/index.php?topic=4892.0.
[3] Batteries may vary in Voltage when purchased, but some small variance above or below 9V hurts neither the batteries nor the Arduino.  They will equalize themselves without dissipating (wasting) much energy, so you will get close to N times the battery life, where N is the number of 9V batteries in parallel (See https://electronics.stackexchange.com/questions/177204/will-connecting-two-batteries-in-parallel-increase-current-drawn-in-simple-led-c and http://www.zbattery.com/Connecting-Batteries-in-Series-or-Parallel).
[4] http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf
[5] The Atmel CPU for the Due and other boards have under-voltage detection too.

I mostly use two AA batteries to power my 'standalone' ATMega328s. One of the downsides of this, is that you can't run the ATMega at 16Mhz, but only at 8Mhz. I don't mind that, as running at a slower speed reduces the current usage.
You could use 3 AA batteries, or 4 rechargeable AA batteries, instead to get a voltage that is closer to 5V
To get your circuit to run for more than a couple of days, you have to implement ways of reducing the current consumption. One of the first things would be to put the processor into sleep mode.

Indeed, one of the few remaining advantages of the ATmega processor is it's relatively wide voltage range.  As long as you don't exceed the maximum when alkaline cells are new, or drop below the minimum for the chosen clock when NiMH or NiCd are nearing time for recharge, running directly off of them is a possibility with this processor not shared to the same degree by many newer alternatives.

You can also use two 18650 batteries as they have a higher charge capacity
Each battery is about 3.7-4.2 V
That would be perfect for arduino....

Could you please edit your post and remove the "shouting" of all capitals? Also, do you mean 2 x 3.7V (7.4V)? For a homemade Arduino which may not have a voltage regulator that would be too high a voltage.

depends, if you are trying to make a big project

meaning like if you want the Arduino to power up all the components connected

I'm  not sure about homemade arduino

ill check and let u know

https://www.google.com.kw/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=2ahUKEwiW_YvDw9PeAhWuyYUKHTouCmMQwqsBMAF6BAgAEAc&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDMb9Gv8ko6g&usg=AOvVaw2qx2un9CudtgOjJ2pRSDq3

check out this one

https://www.youtube.com/watch?v=DMb9Gv8ko6g


text:
Attiny cores with SPI support?
It's been done, but the the tutorials I find seems incomplete. What I'm trying to do is make the ATTiny84 talk to the 2.4 GHz NRF24L01+ radio. I understand that in order to do that I need the MCU to talk to the radio by serial. Attiny84 (and 85) does not have serial, hardware any ways.
But as I understand it you can do software serial by USI, but in order to do so the core for the board has to have this modification?
I've searched far and wide. I bump into the cores on Google Code (https://code.google.com/archive/p/arduino-tiny/downloads). I've installed them but SPI is not listed in the list of libraries.
I've got another tinycore (from where I dont know), when I use this one SPI is a library I can reference, but compiling causes
error: 'SPIE' was not declared in this scope

So, could anyone point me to a known good source of cores to Attiny85 and 84 so I can enable SPI?

This has been discussed on Github. https://github.com/TMRh20/RF24/issues/236

The NRF24L01+ does not use "serial" in the usual meaning of asynchronous serial or "software serial" soft UART libraries.  Instead it uses the synchronous serial SPI interface, which the ATtiny series is intended to handle with a hardware/software hybrid approach.  Doing so in bare AVR code is fairly straightforward.


text:
Conflicts with USB and external power supply
I want to power an Arduino Leonardo with an external power supply and simultanously communicate via USB. I have read some other threads on this topic, therefore, I know that if one supplies more than 7V over the power jack, the board will use the external power supply in this case.
My suspicion is rather concerning the ground connection. From the schematic, I can tell that the USB ground is connected via a tiny coil to the board ground, so with DC it is shorted. Wouldn't that cause problems if the computer's USB ground is at a different potential than the external power supply of the board, resulting in a voltage between the two grounds? What if this voltage is up to several Volts?
Thanks a lot!

USB is mains earth references (except for laptops). You other power supply is either also main-earth references, or floating. In either case no current will flow. That's the way I understand it. Either way, everybody does it this way, so it's not a problem..

I am going to clear one thing, many students and hobbyists are still confused and think that their Arduino board will blow away if they use the External power supply at the same time when Arduino board is connected to the pc through USB cable. This statement is totally wrong, you can give power to the Arduino board by using both sources at the same time and Arduino board is intelligent device it will choose the best input power having more current as compared to the other one.

It's actually a choice of whether or not the voltage from the power jack exceeds 7.3V. This is because there is a MOSFET on the board that chooses USB input if Vin exceeds 6.6V (a voltage divider lets it compare the output of the 3.3V voltage regulator to that). Since Vin is on the other side of a protection diode which drops 0.7V, then you need to put 7.3V or more into the input jack for it to switch to using that.

When you connect the USB, you also connect the ground of the computer to he arduino board. And then when the external power supply is connected to the arduino board the negative pin or the ground pin coming from the external power supply is connected to the ground pin of the USB. Thus the external power supply and the PC share the same ground.

Why do you suspect a potential difference? Where is th 7V coming from? If the 7V power supply is free floating and used for nothing else, there is no source for potential difference.
A typical wall wart will have a free floating output.

I intend to use the power supply of another PC. Are these ground potentials always guaranteed to be connected to Earth?

Connect the grounds of the two PC together, then they will be.

@Dawamaha or, if you want to be 100% sure, use a multimeter...

To answer your question:  I have never seen a conflict like that.
I power my Unos with CCTV-style power supplies (12V) when I am using the HC-11 Wireless module which requires 100 mA or more in order to communicate.
When powered on just USB they can't talk at all.  I mean, not at all - like you simply can't make them work until you plug in the second power supply to get more current.
Everything in the board is grounded together, and that it 99% of the battle when using two power supplies.  Whether I am programming from a Raspberry Pi or a laptop, it all works the same.


text:
Uploading to a CH340 "Nano" board using a Mac with Osx High Sierra
I recently purchased some inexpensive Nano boards, but they give an error signal and won't upload from my Mac with OSX High Sierra...  I am able to upload to Unos and Megas without issues.  I am selecting the correct board and the Atmega 328P and the dev/cu.bluetooth-incoming-port.I have also installed the CH341SER_MAC drivers using the H34X_INSTALL_V1.3 pkg. The error msg is as follows:  Can you help???
/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc" -Wall -Wextra -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/sketch/Blink.ino.cpp.o" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/core/core.a" "-L/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522" -lm
"/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.eep"
"/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.hex"
Sketch uses 948 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.Bluetooth-Incoming-Port -b57600 -D -Uflash:w:/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/daniellecomte/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.Bluetooth-Incoming-Port
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
Invalid library found in /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC: /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC
Invalid library found in /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC: /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC

"Bluetooth-Incoming-Port" is not a valid port selection for an Arduino.  If you think your board has a CH341, then it is not an Arduino Nano and you should not use that tag, but rather the clones one. Conversely, if it is an Arduino, you don't want to install the notorious CH341 drivers on your system since they have no relevance to an actual Arduino. Even if needed and you decide you are willing to allow it on your system, the CH341 driver must not be in your Arduino libraries folder - it is (or at least purports to be) a system driver, it is not in any way shape or form an Arduino library.

Chris...  I don't decide how the WCH  Ch 340G drivers install themselves...  I simply click to install and follow through...  I restart my computer as they say..  but that doesn't work???

Sorry, but no.  The only way the CH340G drivers got in your Arduino folder is if you put them there (for example when you downloaded them) or if you followed some horribly mistaken unofficial instruction or used some mysterious unofficial driver package put together by someone with no idea at all what they are doing.  As yet it's unclear if the CH340 drivers are even appropriate for your board - if they are, you must remove the improper arduino-nano tag.

Hello Chris...  I gather that you prefer Arduino brand Nanos...  I'm just trying to use a half dozen Nanos that I bought on line...  they use a WCH CH340G chip, and I have run an install app to download and install the drivers...  but it's not working...  I might have the wrong type of cable which looks much thinner than the Arduino Uno cable...   Doesn't the install app know where to install the drivers???  Should I delete drivers that already exist in my Arduino library files...  I'm not sure exactly what you are suggesting that I do?   What are the exact steps to take to make this work???

The problem is that when you FALSELY state a problem as pertaining to an Arduino Nano by mis-tagging, that in fact only happens with a board using DIFFERENT PARTS NOT PRESENT IN ANY ARDUINO PRODUCT you merely confuse the issue and lessen the chance both that you will find a solution for your board, and that those who actually have Arduino products will find a solution for theirs.

As already explained, the Blueooth port is not a valid port selection.  You need to select a valid port entry.  If one is not present, you need to figure out why.

Chis... get ahold of yourself...  I'm not falsely stating anything...  Arduino itself allows other companies to make Nanos, Unos and Megas, and gives them the use of the code and the IDE...   most people use less expensive boards...

Arduino very specifically and emphatically does not allow unauthorized parties to label their products Arduino.  When your problem stems from the difference between your board and an actual Arduino, falsely labelling it an Arduino Nano by misusing that tag is indeed making a counterproductively false statement.  There is help for CH340 boards available here - in fact there are many topics on that subject.  But to get help, you have to ask about what you have, and not the board that you do not have.

And for the third time, "Bluetooth incoming port" is not a valid selection - you will get absolutely nowhere until you choose a valid port.

If your clones come with a CH340G-chip you might proceed as follows:
Download the latest driver with Hi Sierra compatibility here: Select Driver version 1.4 !!
Install the driver by double clicking the downloaded file - the installation will stop, issuing an error message as it is an unsigned driver - but if you downloaded the driver via the GitHub link, it is ok. So open Tools, Security and you will be asked by OS X's security system if you want to install the driver anyway - YES!
After restarting your Mac connect your Nano clone and start a copy of the Arduino IDE. Assuming you got version 1.8.5: under Tools/Port you should see something like /dev/cu.wchusbserialXXX - select this port. Now update your board manager, close and restart the IDE again. Under Tools select  "Board: Arduino Nano" and "Processor: ATmega 328P (Old Bootloader)".
Now you should be ready to upload your sketch.
Background information:
Since January 2018 all original Nanos come with the Optiplex bootloader (which is also incorporated in other Arduinos like the Uno. Clones will most likely have the old bootloader pre-loaded, that's why the Processor selection must be set to ".... (Old Bootloader)".
Hope that helps to get along.

Wow, THANKYOU. This completely resolved my uploading problems with: OS X Mojave; clone Nano; CH340/341 drivers installed via https://learn.sparkfun.com/tutorials/how-to-install-ch340-drivers/all - until I switched to OLD BOOTLOADER, my uploads would fail with "not in sync" because avrdude was apparently getting confused by the startup serial messages from my running code.


text:
Lifecycle hook in Arduino to know if Arduino is reset or powered down
I am new to Arduino programming and I'm really fascinated with its working. Is there a way to know if an Arduino is getting switched off or being reset? Like a function would be called before the Arduino gets switched off.
I want to detect this event to preserve a value, where a user resets his Arduino, or switches it off. Is it possible?

The simplest thing to do is to turn the problem around, if possible - Instead of doing something when the arduino is switched off, do it when it is switched on again.

If i want to preserve a value, then i have to know when its switched off

In this case, it's simply not possible without some external circuitry that (1) realises the switchoff and (2) keeps the arduino alive for some last gasp actions. Try to save your value in EEPROM if it doesn't update too often. Maybe you can give some more detail what you actually want to do.

EEPROM has a limit of 100,000 write/erase cycles, so we cant do more than that

Shutting off an Arduino is as simple as cutting off the power supply. As the voltage declines the Browout Detection could notice it but there won't be enough time to write any value into the EEPROM or write something out via serial. There simply is no such thing in the Arduino lifecycle. But you can use a pin and a button to externally trigger a write to EEPROM and then cut off the power.

@bukkehariprasad That's why I wrote "if it doesn't update too often" - Then accept it's not possible.

What value do you want to preserve? How often does it change? How big is it?

EEPROM has a limit of 100,000 write/erase cycles, so we cant do more than that

You have 1k bytes of EEPROM and they survive a minimum of 100,000 writes. So that's 102,400,000 writes you could potentially do, if you are saving one byte. Even at one write a second that would be around 3 years.
However the EEPROM page size is 4 bytes, so that is actually 25,600,000 writes you could get away with (of 4 bytes at a time). Still, that is quite a lot of writes.
A while back I tested one of my chip's EEPROM and found that it greatly exceeded the 100,000 writes specified before it starting misreading the data back.
Also, if you refrain from writing if the value hasn't changed (hopefully that's a lot of the time?) then you could probably extend the life to 100 years.

Like a function would be called before the Arduino gets switched off.

No, that's impossible. How would it possibly know it is about to be switched off? Once it is switched off, functions are hardly going to be able to run.

Is there a way to know if an Arduino is getting switched off or being reset?

Once you hit Reset the processor starts again. It doesn't run any functions "just before" or "just after" being reset (using the original variables). That would mean that the reset doesn't actually reset it.

If you are designing some gadget that lets you configure it (eg. with a volume control) then simply save the new setting to EEPROM when it is changed. This is hardly going to happen 24 hours a day.

Reset does not actually clear memory variables; instead default startup code added by the compiler does.  So in fact, code can run "just after reset" and before this happens in the case of a warm reset.

I understand that, however programming in C++ you would have difficulty in retrieving those variables. In any case, I don't see how you would recover variables after the power had been removed.

For a self-confessed novice to retrieve variables after a reset (and be able to tell the difference between valid variables and random data after being powered up) would not be easy.

Many things are difficult, but used.  Passing RAM variable in fixed locations across reboot is one of them.  Writing to persistent memory on loss of input power, before the capacitor your are running off of has drained is another.  Together, they can solve the problem.  But no, it won't be easy.

Writing to persistent memory on loss of input power, before the capacitor your are running off of has drained is another. Together, they can solve the problem. - well, Chris, the "Answer" button is there for you to explain how to achieve this. I'm sure the OP will appreciate your advice.

@NickGammon thanks a lot for the detailed explanation. I am using file system now instead of eeprom to save data. I think its lifetime is more than the default storage provided by arduino.

@bukkehariprasad - actually the eeprom has a longer cycle life that whatever is hosting your file system.  Though a well designed flash translation layer could walk the data through more cells, limiting the wear on each one.  So each individual cell on an SDcard has shorter life, but you can write a given small chunk of data more times to a well engineered sd card system than you can to a small eeprom, since you can write it in different places.  The critical question then becomes if all the pieces of the sd  card system are well engineered: often at least some are not.

@ChrisStratton I am not using an SD card, but using internal memory to store the file. I have changed the process, and this time I am not writing to the memory often. I might read/write to the file once a month or something like that. Hope the file has enough life cycle to handle so many writes.

What "internal memory" ?  The ATmega328 tagged in your question only has eeprom, and program flash, but you can't really put a "file system" in either of those.

Maybe he means RAM.

You can read the MCUSR status register to determine the source of the reset.
Sources can be the Watchdog timer, brownout (too low a voltage), reset (button), or power-cycle.

Can you explain more? Or point to a tutorial about using MCUSR? Thanks

try https://arduino.stackexchange.com/questions/34331/run-different-code-on-different-type-of-reset-in-arduino-nano/34332#34332 .

Also https://arduino.stackexchange.com/search?q=MCUSR

This isn't really an answer to the question asked, so much as a strategy for different goals.  The comments clarify that the desire is for saving state, so this won't help.


text:
How can I use a 'Global' class object?
I created a class inside the sketch file(not in another file) and init it as object before setup() and loop() as a global object, after I change some parameters inside the object in setup() , I found in loop() the parameters in the global object remain unchanged.
Here is the pseudocode code to describe my question:
//all of the code below are in the same ino file.
class Animal{
public:
  bool alive = false;
  Animal (bool liveStatus){
    alive = liveStatus;
  }
}

Animal dog(false);
Animal cat(false);
Animal lion(false);
Animal animalArray(dog,cat,lion);

void setup(){

  for (int i=0;i<3;i++){
    Animal current_animal = animalArray[i];
    current_animal.alive = true;
  }
  //here when I print each animal's alive flag is 'true'
}

void loop(){
  for (int i=0;i<3;i++){
         // here the alive flag of each animal is still false  , they should be all true!!
  }

}

It looks like after I quit setup() somehow every change of the global object inside the setup are all gone .
Thanks for helping me ..

I can't replicate this error. Can you post the whole code you were uploading before with the print statements and everything?

Hi BreetAm , the original code is relative complex and long(about 600 lines ) ,post to here won't be a good idea .. is that kind of codes works for you ?

Its great that you've tried to keep the example minimal, but in this case you also seem to have removed the source of your problem. Maybe you can pair down you code while constantly testing for the error and seeing how small you can make it without causing dog's value to reset?

Thanks BrettAM, I am currently doing more test on it , I will push a better example tomorrow and notify you :)

Hi BrettAM, sorry I didn't mentioned that I use array in my code . I've edited the example could you check it out please? :) Thanks...

I still don't have any problems, but this code is pretty far from compiling and the minimal changes I made to get it to compile could be different from your implementation. You should test these on your own first.

Hi BrettAM thanks for your kind help! I've reedited the example could you post your answer down then I could approve it for you and helping more people ,thanks! :DD

Your problem here is that Animal current_animal = animalArray[i]; is making a whole new Animal object that starts as a copy of animalArray[i];, but after that the two are no longer associated. Then when you call current_animal.alive = true;, you are not actually changing the animal in animalArray[i] anymore.
The simplest way to fix this is to make current_animal a reference to the object you pick out of the array, although a pointer would work the same way. With this code:
Animal& current_animal = animalArray[i];
current_animal.alive = true;

current_animal becomes a reference to animalArray[i], instead of a copy. Then operating on current_animal changes the same data that is stored in animalArray[i] like you intend.

Thanks BrettAM for your kindness help , this solution saved my day .This problem should be very common on C or C++ languages which involve with pointer stuff  , such a shame I just forgot it even I was a computer science student ..  Thank you!


text:
Lighting up long led strip no longer works when my code grows
I have a 144 LED strip - Adafruit NeoPixel Digital RGB LED Strip 144 LED, link here:  https://www.adafruit.com/product/1507
If I create a simple project, eg turning pixels on off from the serial connection, then everything works fine.  But when I build a solution with an ethernet jack and acting as a http server and lots more code, as soon as I try to show the strip then random pixels light up in random colours.
I know the code is logically ok because if I run it to eg print a string to the serial port, "Turning pixels 0-71 green" the code works.
There are 762 lines of code and quite a few global variables defined.
When I compile I see:
Sketch uses 19180 bytes (59%) of program storage space. Maximum is 32256 bytes.
Global variables use 1462 bytes (71%) of dynamic memory, leaving 586 bytes for local variables. Maximum is 2048 bytes.

I did previously see build messages warning of instability due to size of global variables which I cut down and at least don't see the instability warning now.  Could it be that the code is using too many resources?  Any tips of reducing the code and / or use of global variables?
I am powering via the USB cable.  The unit is an Arduino Uno -the Arduino starter kit.  Could it be a power issue?
I have a 470ohm resistor on the data line into pin 6.  And a 1000uF capacitor between 5V+ and ground.  Anything else that could help?
I am using the Neopixel library to control the led strip: https://github.com/adafruit/Adafruit_NeoPixel

Chances are the Neopixel library can't allocate the memory it needs (432 bytes) for the RGB buffer for the LEDs. I don't know what library you're using though.

762 lines seems a lot for switching on a few lights.  Are there any strings that you can move with the PROGMEM macro, (or whatever it’s called)

Maybe some interrupts are interfering with the data transmission to the strip and are destroying the timing of the pulses. The strips can be very sensitive. Maybe you can try to turn of interrupts for the execution oft strip.show().

@chrisl How would I turn the interrupts off?

There are builtin functions for that: noInterrupts() and interrupts() (hope I have correct spelling). You should only do this to ensure that short timing sensitive code is executing without interruption. Functions like millis() and it`s siblings will not work correctly in this time, because they rely in Interrupts. Shifting the data out to the strip should be short enough to not disturb most other code.

@chrisl by using F() for static strings and reducing the code size I am now able to light the pixels ok.  I guess it must have been low static memory being the problem.  But all the comments are useful if I see problems again.


text:
Turn on led by phone and phone contacts
I would like ask for help. Can you give me an advice how to create (contacts) nubers who can turn on led.
#include <GSM.h>
#define PINNUMBER ""
GSM gsmAccess;
GSMVoiceCall vcs;
char numtel[20];

void setup()
{
 pinMode(13, OUTPUT);

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

Serial.println("Receive Voice Call");

boolean notConnected = true;

while (notConnected)
{
if (gsmAccess.begin(PINNUMBER) == GSM_READY)
  notConnected = false;
else
{
  Serial.println("Not connected");
  delay(1000);
}
}

vcs.hangCall();

Serial.println("Waiting for a call");
}

void loop()
{

switch (vcs.getvoiceCallStatus())
{
case IDLE_CALL:

  break;

case RECEIVINGCALL:

  Serial.println("RECEIVING CALL");

  vcs.retrieveCallingNumber(numtel, 20);

  digitalWrite(13, HIGH);

  vcs.answerCall();
  vcs.hangCall();
  digitalWrite(13, LOW);

  break;

  }
  delay(1000);
  }

Can you elaborate a bit on what you are trying to achieve?

Now when i call to my number arduino do   digitalWrite(13, HIGH); and low after. But i need something as adress book with numbers who when call arduino do  digitalWrite(13, HIGH); afer low and hangcall, but when call something who not is on the list of my contact arduino only hang call. Sorry for my english. And thanks for answer

I do not know the GSMVoiceCall library, but I assume retrieveCallingNumber may return the number of the caller in the string (character array) numtel. So you need to compare that against your list of predefined numbers that are allowed to switch the LED. Have a look at http://www.arduino.cc/en/Tutorial/StringComparisonOperators

So, retrieveCallingNumber is documented in here. It "retrieves the calling number, and stores it" in a character array passed as second argument.
The simplest solution to check if this number is among the allowed ones is to construct a string from this and compare it against a predefined string for equality. (If you have more than one allowed number, repeat for all.)
Something like this:
vcs.retrieveCallingNumber(numtel, 20);
String s = String(numtel);
if (s == "allowed number goes here") {
    // toggle LED etc.
}


text:
How I can populate a buffer from data read from SPI?
I have wired a Macronix MX35LF1GE4AB Flash memory into an arduino Uno using Logic Level Shifters. What I try to do with it is to dump its contents.
In order to do so, I am implementing the following sketch:
#include <SPI.h>

#define LASTBLOCK 1023
#define LASTPAGE 63
#define LASTBYTE 2111

#define PAGE_READ 13h
#define PAGE_READ_CACHE_SEQUENCIAL 03h
#define READ_FROM_CACHE 3Bh
#define PAGE_READ_CACHE_END 3Fh

#define BUFFER_LEN 2111

int page_to_read = 1;
int block_to_read = 1;

// We store each page to Microcontroiller's ram
byte buffer[BUFFER_LEN];

void setup() {
 SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));
// Serial.begin(9600);
}

void loop() {

  // I need to reset the counts before reading any block
  if(page_to_read > LASTPAGE){
    page_to_read = 1;
    block_to_read ++;

  }

  if(block_to_read > LASTBLOCK){
    return ;
  }

  if(page_to_read == LASTPAGE){
     SPI.transfer(PAGE_READ_CACHE_END);
  } else if (page_to_read == 1) {
     SPI.transfer(PAGE_READ);
     SPI.transfer(PAGE_READ_CACHE_SEQUENCIAL);
  }

  SPI.transfer(READ_FROM_CACHE);

  page_to_read++;
}

Now what I want is to populate the buffer byte buffer[BUFFER_LEN] with data, so I can send them over a serial port.
How I can achieve that?

SPI.transfer(buffer, BUFFER_LEN); -- https://www.arduino.cc/en/Reference/SPITransfer

Other than what Nick and Majenko point out, for proper use of SPI library, you should always call SPI.begin() in your setup (unless you are running it as a slave) because it help to setup the proper IO states of MOSI, MISO and SS, etc.. SPI.beginTransaction() should be called before the SPI.transfer(), and SPI.endTransaction() to be called after you done with the data transfer. This allows other tasks to be able to use the SPI bus.

#define BUFFER_LEN 2111
byte buffer[BUFFER_LEN];

That will definitely not work because the Uno has 2048 bytes of RAM, some of which are needed by the system. The serial buffers, for example, are 64 bytes each.

So I'll need a 32byte buffer?

Yes, a smaller buffer will help.

Why do you think you need a buffer at all when you're just outputting through serial?

In order to fan the data read from spi though USB serial, though I can just read them byte by byte. Also I'll need to transcode them as well in hex. Futhermore I'll need to send the page and the block id's in order to recontruct the data into a file in my computer.


text:
Arduino motor shield
I'm making a soccer car with arduino. And I have this undocumented motor control shield. So I don't know how to program it. I've tried to code it as if it be an H bridge, but is not working. Someone know which are the pins that I have to use?
The plate is from DK Electronics, and says motor control shield for arduino.
Don't know why but the image can't be upload from my phone.
As I can't show more this way I have published on my Twitter account the image, if you can I'll be grateful.
Link: https://twitter.com/ricardovaras_99/status/789249497322889216
This is the code I used guided by some internet articles about the Arduino's original motors control shield.
 pinMode(8,OUTPUT);       //Channel A Brake Pin Initialize
 pinMode(9,OUTPUT);       //Channel B Brake Pin Initialize
 pinMode(12,OUTPUT);      //Channel A Direction Pin Initialize
 pinMode(13,OUTPUT);      //Channel B Direction Pin Initialize

No one will be able to assist you until we have more information. The photo may help, but more importantly is the documentation which begs the question:why did you buy a product with no documentation?

would it be this in any case?? http://www.oddwires.com/motor-shield-for-arduino/

You are going to have to try harder. A shield which you don't have a photo of, combined with code you haven't posted, and you are asking for help?

@canadiancyborg yes is exactly that one

@NickGammon Done, please, help me :'D

@ambitiose_sed_ineptum Done, the code is there, and an image I've posted on twitter because my phone, or my internet are sad or something.

That link doesn't lead me to an image. Get to a PC or something and get the image into this post. I have long since cancelled my Twitter account because they were driving me mad with spam. Even afterwards, so I had to make an automatic email rule to send all their stuff directly to the spam folder.

Judging by the fact that you agree it looks like this, a search reveals it is a knock-off of the Adafruit V1 motor shield.
Their page shows how to connect to it, and has example code and a library.
I don't really want to post a link-only answer, but the alternative would be to parrot the Adafruit page, which isn't really fair to them because this board wasn't even purchased from them.


text:
Pulse counter to measure flow-rate: 0 Pulse issues
I am using a Netafim M-Series flow meter interfaced with a UC-32 Arduino. The goal of this is to create a pulse counter than in turn will allow us to determine flow rate in the meter. (1 US gallon per pulse for this model.)
I am using a relatively simple program to test my wiring and the flow meter's connection to the UC-32. I will include it here:
int pin = 30;
volatile unsigned int pulse;
const int pulses_per_litre = 450;

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

  pinMode(pin, INPUT);
  attachInterrupt(0, count_pulse, RISING);
}

void loop()
{
  pulse = 0;
  interrupts();
  delay(1000);
  noInterrupts();

  Serial.print("Pulses per second: ");
  Serial.println(pulse);
}

void count_pulse()
{
  pulse++;
}

Code was obtained by a source online, since I will make my own to match my specific needs later on. The problem is, no matter how much I modify this code, I receive 0 pulses (even when blowing air into the meter). I have therefore narrowed down the problem to wiring.
I am using a small breadboard with a 1 kOhm Resistor. The flow meter requires 12v input that is supplied by a barrel jack power supply into the UC-32. I will show an image of my circuit. From what I can see, this should be working, but I feel like I'm sort of going insane looking over and over this circuit so I wanted to get an outside opinion.

Sorry about the large sizes images, but to me, it is a simple circuit that should work. I could be very wrong. Does anyone with perhaps experience with this sort of flow meter see any problems with my code/circuit?

Fixed, wow. Sometimes typing out your problem helps answer the question. Resistor position was wrong, and adjusting the Vin wire.


text:
Esp 8266 doesn't reply to AT commands
I am working on esp8266 module with arduino uno board.  This is my program.
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different
   Serial.print("START");
  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.find("pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
     pinNumber += (esp8266.read()-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,1000,DEBUG); // close connection
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    Serial.println(esp8266.print(command)); // send the read character to the esp8266

    long int time = millis();
    while( (time+timeout) > millis())
    {

      while(esp8266.available())
      {
        Serial.print("Coming");

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

the problem is  i am not getting any output from esp module but arduino is transmitting the data.  power supply for esp is given by 3.3v regulator (LD3.3)feeding 12v from arduino power supply adapter  to regulator input .
TX esp to rx arduino
arduino tx to esp rx by voltage divider (R1=1k and R2=1.8k)
esp gnd  to arduino gnd
chpd and esp vin are 3.3v from regulator
Can anyone tell me where the problem is ?

I see you have plenty of debug traces sent to Serial, could you copy what you get on the serial console and paste it in your question? That could help checking out your issue.

I don't get any data from the esp device ,If esp data available from the device i am printing the response from serial terminal.. But No data coming

This is not actually what I asked: there are lots of Serial.print() in your code, it would be interesting to show exactly what gets printed to the serial console right from the start of the program.

Also, I am surprised by the baud rate used to talk with the ESP. In newer versions, the default rate should be 115200, not 9600.

Try powering the ESP from an external 3.3V power supply if possible - some people say the Arduino 3.3V regulator may not provide enough power for it (it is quite power hungry at startup).
Another option worth trying is to put a 100uF capacitor between ESP VCC and GND. Put some small delay at the beginning of your setup() function if you do that just in case.
Also, there are several pins you need to pull UP: CH_PD, RESET, GPIO0. If you have GPIO15 broken out (depends on the board), pull it to ground. I have also noticed the ESP won't boot properly if GPIO2 is LOW - either leave it floating or pull it up.
Here is a picture you can use as a guide
Of course, you should make sure the ESP is flashed with the AT commands firmware (they usually are) and your baud rate is correct. If you don't know - try 9600, 57600, 115200.
If you have a USB to TTL converter, it might be better (easier) to test your setup using it, without Arduino. Any serial terminal program (including Arduino IDE Serial Monitor) will be fine. Just make sure you send both CR and LF for new lines. If you send "AT" and receive "OK" your wiring is correct, if you don't - it is not.


text:
ATMega328 + Bluefruit LE stops working soon after power on (not consistently)
Now I am Running Arduino code for Bluefruit LE on bare ATMega328 with 8MHz internal clock, with Bluefruit connected, pin 0 and 1 RX/TX unused, and AT42QT1011-based capsense circuits (logical input to pins 1, 2, 3).
There appeared one problem: when I try to switch the device ON (with 4.5 V batteries, but the same with 5 V USB power), it happens only after three or more attempts. Each time "loop" stops after a second of what appears to be correct operation. For example, if I touch one of the capsensors on the first second of operation, and LED is on, it stays ON, which means, the "loop" is not run.
I have tried to put back the Serial (it was in use in the original echoDemo example), tried to put pollACI after digitalWrite to LED pins. See pin assignments defined in the sketch, those were re-checked with actual circuit.
Measured power supply current and voltage - there were no significant changes in it, even if both LEDs were on. BLE module at startup or while transmitting, was not causing any brownouts. In addition, checked input current and voltage with oscilloscope, and there were no anomalies as well.
NB, this is atmega328, without "p", so for the record I am using 0x07 efuse, 0xE2 lfuse and 0xD9 hfuse.
Also, if the device starts up, it will work fine for at least an hour.
What could be other reasons for such random early failure? (in average, about four attempts to switch on, sometimes starts even on first, second time)
The sketch in question:
/*********************************************************************
This is an example for our nRF8001 Bluetooth Low Energy Breakout

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/products/1697

Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!

Written by Kevin Townsend/KTOWN  for Adafruit Industries.
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in any redistribution
*********************************************************************/

//#define F_CPU 8000000

#include <SPI.h>
#include "Adafruit_BLE_UART.h"

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2     // This should be an interrupt pin, on Uno thats #2 or #3
#define ADAFRUITBLE_RST 7

#define REDLED 8
#define BLUELED 9
#define LEFTPAD A2
#define RIGHTPAD A3
#define BADPAD A1

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

unsigned int leftcnt, rightcnt;

void setup(void)
{
  pinMode(REDLED, OUTPUT);
  pinMode(BLUELED, OUTPUT);
  pinMode(LEFTPAD, INPUT_PULLUP);
  pinMode(RIGHTPAD, INPUT_PULLUP);
  pinMode(BADPAD, INPUT_PULLUP);
  digitalWrite(BLUELED, LOW);
  digitalWrite(REDLED, LOW);
  delay(300);
  BTLEserial.setDeviceName("MYUART"); /* 7 characters max! */
  BTLEserial.begin();
  digitalWrite(REDLED, HIGH);
  delay(300);
  digitalWrite(BLUELED, HIGH);
  leftcnt = 0;
  rightcnt = 0;
}

aci_evt_opcode_t laststatus = ACI_EVT_DISCONNECTED;

void loop()
{
  BTLEserial.pollACI();

  if (digitalRead(LEFTPAD)) {
    leftcnt++;
    digitalWrite(BLUELED, LOW);
  } else {
    leftcnt = 0;
    digitalWrite(BLUELED, HIGH);
  }
  if (digitalRead(RIGHTPAD)) {
    rightcnt++;
    digitalWrite(REDLED, LOW);
  } else {
    rightcnt = 0;
    digitalWrite(REDLED, HIGH);
  }

  aci_evt_opcode_t status = BTLEserial.getState();

  if (status == ACI_EVT_CONNECTED) {
    boolean inp = false;
    while (BTLEserial.available()) {
      char c = BTLEserial.read();
      inp = true;
    }
    if (inp) {
      if (leftcnt > 5) {
        BTLEserial.print("LEFT");
      }
      if (rightcnt > 5) {
        BTLEserial.print("RIGHT");
      }
      if (digitalRead(BADPAD)) {
        BTLEserial.print("CENTRAL");
      }
    }
  }
}

UPDATE: MCU's reset pin is pulled-up by a resistor. Bluefruit's RST connected to PD7 on atmega328 (also known as arduino digital pin 7). Also, 3.3 uF capacitor on the power lines near MCU's IC. (there are more near capsense circuits).
When I disconnect Bluefruit's power, the rest of the circuit (LEDs showing cap sensors state) works without failures after startup. So it looks like under some circumstances, control never leaves BLE code to return to the loop?
UPDATE 2: Found long list of reset causes (not sure yet whether relevant here): Arduino/AVR ATmega microcontroller, random resets, jumps or variable/data corruption ...
UPDATE 3: Added two 100nF bypass capacitors near GND / VCC pins on both sides. The problem is still there.
UPDATE 4: Performed all kinds of experiments, placing BLE module's power lines in different places, with different capacitors. Only in the case of separate power (common ground) the problems were different (but may be due to different times of turning module and MCU on).
UPDATE 5: May be relevant or not, but when I run MCU on 1MHz (8 MHz internal clock, divided by 8 - lfuse 0x62), success rate is better than 70%. The speed seem to be enough for my application, but of course near 100% turn-on success should be achieved.
MAY BE IMPORTANT: I have added watchdog to sketch (thanks to the "Make: Sensors" book by Karvinen & Karvinen, Valtokari):
  WDTCSR |= (1<<WDCE) | (1<<WDE);
  WDTCSR = 1<<WDP0 | 1<<WDP3;
  WDTCSR |= _BV(WDIE);
  MCUSR &= ~( 1 << WDRF);

And in the respective ISR red led is turned on or off once in about 8 seconds or so. And ISR code works (thus, MCU works all the time too, right?), even though the "loop" runs no longer.
Can this still be attributed to trouble with power or is it more likely control flow is stuck somewhere in the BLE library?
UPDATE: Well... As advised here, while trying out Serial (via microbot USB adapter), I understood, that it does not work reliably (if at all, sometimes eats characters, prints garbage, ...). Not sure whether SPI is sensitive to clock accuracy, but if it is, it may be the problem. Also, the circuit turns on always when powered from USB3 port 5V.

What is the wiring of your reset pin?  Do you have bypass caps on the power pins?   Write a sketch which outputs a running count on the serial port, temporarily connect a logic level serial port (USB converter cable or whatever) to the transmit pin, and monitor that to see if it keeps running or also experiences unexplained failure.

Updated. Do you mean a sketch, where I do not do any Bluetooth? As for connecting serial port, I will try.

Yes, one with no bluetooth only to test the hardware of the MCU portion of your board.  The capacitor you have described is more of a filter than a bypass.  Don't remove it, but you should also have a smaller (and hence lower inductance) capacitor connected as directly across the power pins as you can manage.

Updated: the rest of circuit works without failures, when power disconnected from Bluefruit (or if all control wires disconnected - I have two separate cables).

You should still try it connected, but with a program that doesn't use it, and only outputs on the serial.  One thing to keep in mind is that BLE chips, especially first generation ones, can draw a lot of pulse current when transmitting.

Tried. The device works fine when I remove BTLEserial.pollACI(). Otherwise the same behaviour: more often than not cease to operate after approx. a second. I have not seen any pulses of current on the scope, but will do more checking tomorrow. Also, when I disconnect/reconnect Bluefruit's power, MCU sometimes resets - this might indeed indicate power problem (unless the Adafruit's library is doing this reset).

Does the bare ATMega328 have some decoupling capacitors near it?

The main problem cause was inaccurate internal clock. As soon, as external 8MHz crystal has been attached to XTAL pins (with a pair of 22pF capacitors to GND), problems with turning the board on disappeared.
Also, I found
while(1);

loop in the Adafruit's nRF8001 library, which runs whenever problems with the Bluefruit LE board are encountered. That is possibly why interrupts worked fine, but the whole MCU never returned to the main loop.


text:
mcufriend 2.4 tft mega 2560
Please help me w/ my 2.4 mcufriend TFT on my Mega2560.
I've followed any instructions I can find, including:
2.4" TFT LCD Shield isn't working on Arduino Mega
I still get a show white screen. I wonder if my TFT is different or is it broken? Mine looks like this:

I did run the example code from SWtft. I got this output on serial:
TFT LCD test

LCD driver chip: 6TFT LCD test
LCD driver chip: 6767
Benchmark                Time (microseconds)
Screen fill              1786024
Text                     413024
Lines                    2569212
Horiz/Vert Lines         226196
Rectangles (outline)     176972
Rectangles (filled)      4682244
Circles (filled)         2703104
Circles (outline)        1119540
Triangles (outline)      815028
Triangles (filled)       2867288
Rounded rects (outline)  469268
Rounded rects (filled)   5733992
Done!

What TFT is on the carrier board? What chip does it use?

That is the problem.. the shield came without any document.. i tried to read the chip but it is also unclear.

You won't read the chip I am on about - the "Chip On Glass" that is embedded in the TFT screen. You need to know what that is so you can get the right driver. The seller should know. If they don't then they're no good.

According to the seller the the driver is HX8347G LCD n they have managed to run it on uno while i git no luck on mega 2560.

@rudirahmadi check for differences in pin-compatibility between the UNO and MEGA. Make sure that every pin that needs PWM has PWM.

I have one of these TFT LCD shields, but mine is a ILI9335. It has taken me nearly 2 weeks to find a working Library and code for my 9335 driver and I am now setting about creating sketches based around my working Library.
  Library - TFTLCD using st7783 controller
Unfortunately most sellers of these shields (excluding good reputable companies) do not adivise of which Driver is onboard the shield and it becomes difficult to locate a working Library for the driver of the purchased shield.
ALSO, check that the Libraries you have are working for your version of Arduino IDE. Some of my libraries would not compile in v1.0.5 but will in v1.6.3 (and vice versa)
If there is no Library specific to your 6767 Driver (and I must say I have not seen one in my searches for the 9335 Driver) then you may have to download as many different Libraries to locate a sketch that works for yours.
Once you have a working Library then it is just a matter of modifying it for your purposes.
Good luck in finding a working solution for your shield.
Lance..

Thx for your share lance, i wonder if it looks like mine n did you manage to run it on mega2560?

Hello, I also have the 9335 but I have't been able to make it work. Could you share with me the libraries and examples you are using? Thanks

You need to modify these #define parameters of TouchScreen() from
#define YP A3
#define XM A2
#define YM 9
#define XP 8

to
#define YP A2
#define XM A1
#define YM 6
#define XP 7

Only insert the 4th line if (identifier == 0x6767) identifier = 0x7575;
into setup() as below

............
  tft.reset();

  uint16_t identifier = tft.readID();

  if(identifier==0x0101)
      identifier=0x9341;

  if (identifier == 0x6767)
      identifier = 0x7575;

  if(identifier == 0x9325) {

    Serial.println("Found ILI9325 LCD driver");

  } else if(identifier == 0x4535) {

    Serial.println("Found LGDP4535 LCD driver");

  }else if(identifier == 0x9328) {

    Serial.println("Found ILI9328 LCD driver");

  } else if(identifier == 0x7575) {

    Serial.println("Found HX8347G LCD driver");

  } else if(identifier == 0x9341) {

    Serial.println("Found ILI9341 LCD driver");

  } else if(identifier == 0x8357) {

    Serial.println("Found HX8357D LCD driver");

  } else {

    Serial.print("Unknown LCD driver chip: ");

    Serial.println(identifier, HEX);

    Serial.println("If using the Adafruit 2.4\" TFT Arduino shield, the line:");

    Serial.println("  #define USE_ADAFRUIT_SHIELD_PINOUT");

    Serial.println("should appear in the library header (Adafruit_TFT.h).");

    Serial.println("If using the breakout board, it should NOT be #defined!");

    Serial.println("Also if using the breakout, double-check that all wiring");

    Serial.println("matches the tutorial.");

    return;

  }

Try it.

Most likely not supported controller or disabled in .cpp file. Firstly find out your ID like for example ID=0x6767. Then look in the MCUFRIEND_kvb library folder "extras" to enable support for example in our case 0x6767 is 8347D. Lastly go to library root and edit MCUFRIEND_kvd.cpp and uncomment asin ou example: #define SUPPORT_8347D. Save the modified .cpp file then upload example graphic test.

Hi and welcome. uncomment asin ou example - do you mean uncomment as in your example? Please [edit] and fix any typos. Thanks.

There are several of these boards on sale (mostly from China).
The following IDs of the different chips are taken from a file named mcufriend_kbv_2_8.txt from an archive named Mcufriend_kbv_2.8.zip which provides a whole library(supposely an UTFT fork) supporting these PCBs. Here in the Arduino.cc forum is one of the download links.
----- HX8347-A 240x320  ID=0x8347 new Untested
ILI9320  240x320  ID=0x9320
ILI9325  240x320  ID=0x9325
ILI9327  240x400  ID=0x9327
ILI9329  240x320  ID=0x9329
ILI9335  240x320  ID=0x9335
ILI9341  240x320  ID=0x9341
ILI9481  320x480  ID=0x9481
ILI9486  320x480  ID=0x9486
ILI9488  320x480  ID=0x9488
LGDP4535 240x320  ID=0x4535
RM68090  240x320  ID=0x6809
R61505V  240x320  ID=0xB505
R61505W  240x320  ID=0xC505 new Untested
R61509V  240x400  ID=0xB509
----- S6D0139  240x320  ID=0x0139 removed due to lack of tester
S6D0154  240x320  ID=0x0154
SPFD5408 240x320  ID=0x5408
----- SSD1963  800x480  ID=0x1963 new Untested
SSD1289  240x320  ID=0x1289
ST7781   240x320  ID=0x7783
ST7789V  240x320  ID=0x7789

A white screen is the result of choosing the wrong chip. Choose the right one (by ID) and it will work.

authors: احسان روحانی اصفهانی


text:
Modified Mesh networking using nrf24l01
I am trying to make a mesh network of three nrf24l01 nodes in which all three are transceivers, such that all three are in a line. The modification I want to make is that if two end nodes are not able to communicate with each other as they fall short of range the signal must be sent via the middle node. How should I approach?

You can do it this way

Or just use a library that does it for you?

To be honest, I still have to receive my RF's... But I have a similar problem, meaning I also need to have them all to both receive and transmit.
I thought it was not possible, since in a 6-1 network, one is receiver, 6 are transmitting. With auto-ack messages can be returned.
Depending on the amount of messages being sent and latency you can let them talk when needed and hope there is not too much sending simultaneously (causing resends).
One solution you could use, is to put in the message a receiver ID. Suppose the 'geographic location' of your objects are
A   <---->   B  <----> C
Assume A wants to send to C, but it will not be received by C, C does not auto-ack, and A knows this. Know A can send the message to B, which can auto-ack, and B has to send it to C. Possibly the original source (A) has to be added to the message as well, if this is important for C to know.
Update: (in steps)
Suppose A wants to send a message m to C

A sends message m to C
C does not receive it, thus is does not send an ACK-message back to A
A gets a timeout
A knows that message m has not been sent to C (so it is out of range)
A sends the message m to B (adding 'A' as sender of the message if not already done)
B receives message m
B sends an ACK back to A
A knows message m has been sent to B
B sends message m (with A as sender) to C
C receives the package
C sends back a message to B
B needs to send a message to A that m has been sent successfully

Some generic remarks:
- This scheme is maybe not full-proof or can be optimized (like that A knows from now on it needs to send to B first to reach C).
- Also both B and C can be out of range, you want to resend it (later)?

Sorry Michel but I could not understand your logic clearly. Can you explain it to me as if i am a layman.

I updated my answer with some possible steps


text:
Arduino an sparkfun microled problem
In on of my projects i am using sparkfuns MicrOLED library. Downloaded it from github, installed as usual but no code calling that library compiles. Error is SPF_MicrOLED.h no such file or directory.
It is strange as the library is installed, example sketches are in the examples menu but they don`t want to compile ether, same error. Not sure what to do. Tried also to rename microled library folder but same error.

First, like most all of us, I started with the Blink program.  It is the first way I could see how the IDE worked.  Compile, upload, observe.  It would be very helpful if you could let us know how that acts.

The question is fine and perfectly clear as it encapsulates the obvious problem of mistyping the name of the library which has been identified below.  That might not be the only problem, but it is a problem that makes a perfectly valid question.

Error is SPF_MicrOLED.h no such file or directory.

That is to be expected because the library doesn't contain a file named SPF_MicrOLED.h.
It does contain a file named SFE_MicroOLED.h. Use the correct filename in your #include and the problem will be solved.


text:
Arduino port grayed out for Fake Board with CH340
I have downloaded and used Arduino IDE v1.8.4 from official site (needs no install) for windows10, and connected my random board with a ch340, but it's LED is only blinking and I can't select the port (ie. it's grayed).
I did test all USB ports and restarted my laptop but that didn't work!
I tried to install 1.6.9 IDE that I had before, but again the port option is unselectable!
This is my board:
http://uupload.ir/files/xgv_uno.jpg

What OS are you on? Is it a Genuine Arduino board?

Which LED is blinking? Any chance of a screenshot?

Have you tried a new cable? or a different laptop? If you have is its possible you have the wrong board selected?

What OS are you using?

@Majenko: windows10, I don't know is this genuine or not? how can I find this? (I only see the microcontroller is SMD)

@sa_leinad: i have edited my question

@CodeGorilla: Cable is OK, and I have no computer at know to test it

Simplest possible thing would be that you do not have CH340g driver installed and you should try installing it first; These boards use CH340 for usb to serial and they need the driver to be installed; Please give it a try by getting the driver from the following link http://www.wch.cn/download/CH341SER_EXE.html or any other reliable source if there is any problem with the link;
If the board is not recognized even after that, it could be a bad USB port or a bad USB cable or even a board with the CH340 chip dead;