text:
Arduino Micro Println prints 0
I am having troubles with my arduino micro.
In my programming, I am using the serial. When I use println, nothing shows up in the serial monitor except for 0. So if I type 1, I get back 0 instead of 1, same goes for 3241234 or any random number.
Here is the code:
void setup() {
  Serial.begin(9600); //Connect to the serial monitor console
}

void loop() {
    while (Serial.available() == 0); //Wait until Serial is available

    //Read val
    int val = Serial.read() - '0'; //Val that represents input
    delay(500);
    Serial.println(val);
}

So I have another problem and people have asked for the code. Basically, printing a string returns 0.
 void setup() {
  Serial.begin(9600); //Connect to the serial monitor console
}

void loop() {
    while (Serial.available() == 0); //Wait until Serial is available

    //Read val
    int val = Serial.read(); //Val that represents input

    delay(1000);
    if (val == 1) {
      Serial.print('Firing the motor');
    } else {
      Serial.print('Please press 1 to fire the motor.');
    }

    delay(4000);
}

Instead of printing Please press 1 to fire the motor, I get 0 in the console.
Thanks for the help!

How are you sending values to arduino device?

@LPs I am using the serial monitor.

Try without
- '0'

You read your data and save into in int. then print that int, when you pass only the int, you get the int as an ASCII-encoded decimal.
Why r u doing
- '0'

?

Hey, I am trying now to use my variable to print something So if I type 1, I want the console to say "Firing function", the problem is that the console prints 0. What is the problem here?

You are going to need to show the code.  Its probably something simple to fix though.

@Matt I have added the code in the question section, thanks.

This time you are comparing an integer 1 with a character '1'.
int val = Serial.read();

Is reading  you pressing the one key and storing it in an integer variable as the number 49 (ASCII '1')
if (val == 1) {

You are now seeing it 49 is the same as 1, which it isn't.
To make your code easier stick to characters.
Change the Serial.Read line to:
const char val = Serial.read(); // Val that represents input
                                // (const because it will not change).

and the if line to:
if (val == '1')  // '1' character 1

By making val const you stop yourself accidentally changing it so if you do
if (val = '4') // Compilation error.

Hope that helps.

Hi Matt, thanks for the help. This is useful. I still cant print the strings I want to: Firing the motor or Please press 1 to fire the motor. I tried replace the ' ' with " " but that doesnt fix it either.

You are right you need double not single quotes so Serial.println("Firing the motor"); is what you need.  println will print a whole line of text.  I am guessing, but it might be something to do with the Serial.Read commands.  Replace you print statements with Serial.write  calls, you will need to look in the manual on www,arduino.cc to get the right parameters.  Make sure you add \n\0 to the end of your strings when you use serial.write.

Hey Matt, using .write returns the amount of characters in a string, so this is not helpful to me. I am going to keep looking, thanks for the help!

@TinoCaer  Serial.write(“hello”);  has the same superficial behaviour as Serial.print("hello");  You can ignore the return value.  Having read the man page I can't see it will help though. :(

To your second question, strings in C are surrounded by the double-quote character: ", not the the single-quote or apostrophe character.


text:
Particle Electron to RS232 Serial gibberish
I've spent all day trying to monitor serial console output of a router. I'm using an "ebay" MAX3232 RS232 to TTL converter connecting only GND, TX and RX to the Electron. Trying to simply monitor the console output during bootup - all I get is gibberish.
Even connected to computer's COM1 port and was unable to echo back and forth. All I get is 0 or weird symbols. (this was tried with more code than below)
Here's my most basic code. I'm about ready to give up. Any ideas?
#include "Particle.h"

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600); // tried with 2400/even 1200 really should be 9600
  Serial.println("Starting up Serial");
  Serial1.println("Starting up Serial1");
}

void loop() {
 while(Serial1.available()>0)
 {
   Serial.write(Serial1.read());
 }
 delay(50);
}

Did you check the power supply voltage on the MAX3232 pins (V+ pin 2 and V- pin 6)? What are the values of the two flying caps (across pins 1-3 and pins 4-5)? And, if you suspect that you were sold a counterfeit part, Maxim customer service would like to know. (Disclaimer: I am a Maxim applications engineer.)

Have you tried both 7-bit and 8-bit data? Are you set to no-parity? (stop bits should not matter).

@MarkU - I didn't check the voltages or the cap values yet. I don't know about counterfeit, or how to determine that - it's a cheap Chinese Serial to TTL adapter board.
Mark - I tried both 7 and 8 bits with no parity and still nothing.

I suspect you have the wrong master serial clock rate.

Loopback test the MAX3232 transceiver by itself (independent of the microcontroller). Connect the loopback on the RS232 side (T1OUT driving R1IN), and then drive logic low on T1IN, expect the RS232 loopback should go to about +5.5V and expect the R1OUT should go logic low. Then drive logic high on T1IN, expect the RS232 loopback should go to about -5.5V and expect R1OUT should go logic high. MAX3232 datasheet

Will definitely try that and get back. Thanks

I didn't see any comments to check other baud rates. How did you determine it should be 9600 baud? What Arduino board are you using? I've not played with the mega board but the examples I saw did not use Serial.begin(). They were all Serial1.begin, Serial2.begin... depending on which serial port you want to use.

If the OP has correctly stated that only three connections to the MAX3232 have been made, power to the device is missing.
Code tested with an RS232 transmitting device (Maxbotix 7092) with Sparkfun MAX3232 breakout and Particle Photon. Serial monitor correctly displays continuous range reading.

You do not need any hardware between the Particle and the router. Both the router and the Particle work at 3.3V logic levels.

Connect the GND of the router the GND of the Particle
Connect the TX of the router to the RX1 of the Particle
Connect the RX of the router to the TX1 of the Particle

You only need the MAX3232 if you want to connect direct to your computer's RS232 port:

Connect the GND of the MAX3232 to the GND of the computer and the GND of the router
Connect the TX of the computer to RIN of the MAX3232
Connect the RX of the computer to DOUT of the MAX3232
Connect the TX of the router to the DIN of the MAX3232
Connect the RX of the router to the ROUT of the MAX3232
Connect the VCC of the MAX3232 to +3.3V from the router.

source: Stack Exchange

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

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

sort: votes


text:
bitClear doesn't work on most significant bit
I'm currently working on a project where I read a 32 bit sequence.
The digitalPin is always HIGH when no sequence is received and starts oscilating with about 1kHz when the sequence starts (RC5).
I am setting and clearing bits of an uint32_t depending on which signal is on the digitalPin.
It seems to work very well with every bit except of the MSB.
Here a short code snippet to show what I mean:
const short irPin = 8;
const short msgDelay = 250;

uint32_t data = 0xFFFFFFFF;
long msgArrived = 0;

void setup(){
  Serial.begin(115200);
  pinMode(irPin, INPUT);
}

void loop(){
  long now = millis();

  if( (!(PINB & 1)) && ((now - msgArrived)> msgDelay)){
    msgArrived = millis();
    bitClear(data, 31);

    Serial.println(data, BIN);
  }
}

This gives me an output of
11111111111111111111111111111111

I have already tried
bitClear(data, 32); -> 11111111111111111111111111111111
bitClear(data, 30); -> 10111111111111111111111111111111

So every output is right, but not the when I try to clear the msb.
Has anyone experienced a similar behaviour?

bitClear(data, 31);  should be the msb of the uint32_t. bitClear() goes from 0 - sizeof(uint32_t)-1. And with bitClear(data, 32); I only tried if the documentation lied to me.

sorry missed a part of code on first comment, does it work if you make it "manually" with data &= ~(0x1 << 31) ?

yes this works, but look at the answer by BrettAM. I missed out, that println() doesn't print leading zeros.

uint32_t data = 0xFFFFFFFF;
Serial.println(data, BIN);
data = 0xFFFFFFFF;
bitClear(data, 30);
Serial.println(data, BIN);
data = 0xFFFFFFFF;
bitClear(data, 31);
Serial.println(data, BIN);

On my mega outputs:
11111111111111111111111111111111
10111111111111111111111111111111
1111111111111111111111111111111

Are you sure you aren't mistaking the fact that println doesn't print leading 0's for the number being nothing but 1's? Try printing as hex, then all the numbers will be the same width:
FFFFFFFF
BFFFFFFF
7FFFFFFF

I fact i actually did miss out the fact, that println doesn't print leading zeros. Thanks. Would +1, but I am missing reputation for that.

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


text:
I2C: What is the difference between A4&A5 and SCL&SDA pins?
On tutorials are most people using the A4&A5 pins with the Wire.h library. But i have an arduino with dedicated I²C pins. How can i use them?

They are the same pins. They are physically connected to each other on the UNO board. (So SDA is connected to A4. SCL is connected to A5)


text:
Why can't I declare variables inside an if statement?
I have a void function that helps me set the time on my arduino clock. I need to use the same function twice - once for the alarm and once for the actual time. The variables I am defining need to equal either alarmHours and alarmMinutes, or hours and minutes. This was my solution:
void setting(int i){
 if(i==0){
  int mi=alarmMinutes;
  int ho=alarmHours;
 }else if(i==1){
  int mi=minutes;
  int ho=hours;
 }
//more code later
}

I got an error saying that ho and mi are undefined.
I fixed this like this:
void setting(int i){

 int mi;
 int ho;

 if(i==0){
  mi=alarmMinutes;
  ho=alarmHours;
 }else if(i==1){
  mi=minutes;
  ho=hours;
 }
}

This solved the problem. Why couldn't I use the first option if I passed in a 0 or a 1 to the parameters of the function?

Declaring a variable inside a block means that they only exist within that block. Once the block is exited, they become inaccessible.

Before, I thought that only applies to functions. I guess it applies to all blocks of code, including the if statements.

Specifically, it applies to the nearest pair of enclosing braces, {}.

The problem with doing it how you originally did is that the variables you initialized inside the if statement do not go onto the else statement.
That is why your solution is correct. You need to declare your variables before going inside of a block in order to use them.
There are uses for declaring a variables inside of a block.. but this is not one of them as you realized and fixed.


text:
How can you check how long a timer interrupt really is?
I'm trying to set a 33 ms interrupt on my Arduino Mega and I'm not sure if I a in fact getting that kind of delay time. Is there a way to check?
I've calculated that that I need 515.6 ticks to achive this kind of delay with a prescaler of 1024 and I've coded it up like so:
void setupInterupt()
{
  noInterrupts();
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = 0;
  OCR2A = PERIOD - 1;
  TIMSK2 = _BV(OCIE2A);
  TCCR2B |= _BV(CS12) | _BV(CS10); // prescale by 1024
  interrupts();
}

I followed the information on the Arduino Playground page and if my math is correct this interrupt should be going off every 33 milliseconds. I tried to test that using the millis(); method but it only returns the time that program was on.

Try counting how many times it fires in a second

Can you expand on that? This is my first Arduino project so I'm not totally sure how to do what you just said.

In your timer ISR add one to a counter. Every second print the counter.

It doesn't fire every 33 milliseconds. First, you missed setting the CSn1 bit necessary for a 1024 prescaler; second, It looks like you want CTC mode (where the timer resets at OCRnA) but you didn't set the WGM21 bit necessary for that mode. After that your problem is that timer2 is an 8 bit timer and so OCR2A cannot store 515, but you math is correct.
You can get the period you want on a 16-bit timer; on the arduino mega thats timers 1,3,4, and 5.
Anyway here is a simple sketch for finding the average interval between interrupts. It just keeps track of the total time elapsed and the number of times the interrupt fired; the ratio of these two is the average time per interrupt.
In this case, with a prescaler of 1024, OCRA = 0xFF, and CTC mode, it runs at an interrupt every 16.384 ms.
volatile uint16_t interruptCount;
volatile uint32_t start;

ISR(TIMER2_COMPA_vect){
    interruptCount++;
}

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

    noInterrupts();
    TCCR2A = _BV(WGM21);
    TCCR2B = _BV(CS22) | _BV(CS21) | _BV(CS20); // prescale by 1024
    OCR2A = 0xFF;
    TIMSK2 = _BV(OCIE2A);
    // start the timer
    interruptCount = 0;
    start = micros();
    interrupts();
}

void loop(){
    // read interrupt count into a local variable atomically
    noInterrupts();
    uint16_t localCount = interruptCount;
    interrupts();
    uint32_t time = micros() - start;

    // time elapsed
    Serial.print(time);
    Serial.print(" ");

    // number of times the interrupt handler fired
    Serial.print(localCount);
    Serial.print(" ");

    // average number of microseconds per interrupt
    Serial.print(time / localCount);
    Serial.println();

    delay(30);
}


text:
How can you count the number of interrupts that have taken place?
I'm trying to program a Timer Interrupt that will go off every 33 ms. I am doing this on the ATtiny85 which has a 20MHz clock. The maximum prescaler I can set is 32 so the longest possible time a single interrupt can be is 408 microseconds.
My plan to reach 33 milliseconds is to just run the interrupt 81 times and that will get me the desired 33 milliseconds. However, I have no clue as to how you can actually count how many time an interrupt has taken place. Anyone on here know how to do that or have any idea as to what would work?

Yes, just add a check inside your ISR statement.
ISR(TIMER0_OVF_vect)
{
  static uint8_t postscale = 0;
  if (++postscale == 81)
  {
    postscale = 0;
    do_stuff();
  }
  else
  {
    go_to_sleep();
  }
}

You always have to enter the ISR method once you're done with the interrupt so just add that if statement and use a static variable (so that it keeps its value) to check if you have made the correct number of loops.

else return; - I suggest. I wouldn't try sleeping inside an ISR.

What would it be returning?

Nothing. return on its own is used with a function returning void (like an ISR). So in fact you could omit the else and the return altogether.


text:
Atmega2560 + weather station freezing
i made a weather station which is build on a ATmega2560 mini pro, Esp8266 module which communicate with atmega on serial1 which sends values to thingspeak, an TSL2561, 2.4 tft lcd, BMP180, DHT22 and a dust sensor module PMS5003 which is set on serial3 on mega2560.
I made the wiring, program etc. the weather station is working fine for some days when it freezes. The problem is that thingspeak reports that it receive some data every 6 mins like i set it but the data received is blank. Not 0, or any other value, just blank data.
I'm thinking it could be a problem with SRAM since it loses the values it reads. But why the loop is still working since it sends blank data to thingspeak ?
Atmega reads all values from sensors, then communicates with esp8266 by serial and using AT commands it sends the values read to thingspeak. So in my opinion it reads the values, but it won't stores them, then it sending blank data to thingspeak.
If i reset the arduino it works fine for some days when suddenly it decides to stop working.
After compiling the program the arduino ide is reporting this:
Sketch uses 28,890 bytes (11%) of program storage space. Maximum is 253,952 bytes.
Global variables use 1,800 bytes (21%) of dynamic memory, leaving 6,392 bytes for local variables. Maximum is 8,192 bytes.
So, my program it's not filling the SRAM.
I'm a beginner in C++ so i tried to do my best with programming.
Link to thingspeak weather station: https://thingspeak.com/channels/116912
The code:
#include <SFE_BMP180.h>
#include <Wire.h>
#include <DHT.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_TSL2561_U.h>
#include <Adafruit_GFX.h>    // Core graphics library
#include "SWTFT.h" // Hardware-specific library

#define DHTPIN 25     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
#define ALTITUDE 320.0 // Altitude in Grasse

// Assign human-readable names to some common 16-bit color values:
#define  BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

SWTFT tft;

DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
SFE_BMP180 pressure;

Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);

//double bmptemp; //temp bmp rectificata cu 1.9 grade -
float hum;  //Stores humidity value
float temp; //Stores temperature value
float lux; //Stores lux luminosity
char status; //used by bmp180
double T,P,p0; //p0 - sea-level compensated pressure in mb, T - temperature, P = absolute pressure in mb

#define IP "184.106.153.149" // thingspeak.com IP address; see their website for more detail
String GET = "GET /update?key=NWHWO6SLWNJP3HGQ"; // you channel will have unique code
int concentration=0;

//cod dust sensor
#define LENG 31   //0x42 + 31 bytes equal to 32 bytes
unsigned char buf[LENG];

int PM01Value=0;          //define PM1.0 value of the air detector module
int PM2_5Value=0;         //define PM2.5 value of the air detector module
int PM10Value=0;         //define PM10 value of the air detector module

void setup() {

  pinMode(17, OUTPUT); //pin pt esp - on /off
  pinMode(16, OUTPUT); //pin buzzer
  pinMode(31, OUTPUT); //pin on/off dust sensor

  Serial.begin(9600); // this is to start serial monitoring with your Arduino IDE Serial monitor.
  Serial1.begin(9600); // this is to start serial communication with the ESP via Software Serial.
  Serial3.begin(9600); //serial dust sensor

  Serial.println("Begin");
  tft.reset();
  uint16_t identifier = tft.readID();
  tft.begin(identifier);

  dht.begin();

  if (!pressure.begin()) {
    Serial.println("BMP180 init fail"); // Oops, something went wrong, this is usually a connection problem,
    while(1); // Pause forever.
    }

  if(!tsl.begin()) {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.print("Ooops, no TSL2561 detected ... Check your wiring or I2C ADDR!");
    while(1);
  }
  //tsl.setGain(TSL2561_GAIN_1X);      /* No gain ... use in bright light to avoid sensor saturation */
  //tsl.setGain(TSL2561_GAIN_16X);     /* 16x gain ... use in low light to boost sensitivity */
  tsl.enableAutoRange(true);            /* Auto-gain ... switches automatically between 1x and 16x */
  tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS);  /* 16-bit data but slowest conversions */

}

void loop() {
  digitalWrite(31, LOW);
  digitalWrite(17, LOW);
  Serial.println("-----------------------");
  dht22 ();
  bmp120 ();
  tsl2561();
  dust();
  Serial.println("-----------------------");

  tft.fillScreen(BLACK);
  tft.setRotation(1);
  tft.setCursor(0, 0);

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("DHT22");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("Temperature = ");
  tft.print(temp);
  tft.println(" C");
  tft.print("Humidite = ");
  tft.print(hum);
  tft.println(" %");
  tft.println();

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("BMP180");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("Temperature = ");
  tft.print(T);
  tft.println(" C");
  tft.print("Pression = ");
  tft.print(p0);
  tft.println(" mb");
  tft.println();

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("TSL2561");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("Luminosite = ");
  tft.print(lux);
  tft.println(" Lux");
  tft.println();

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("Pollution aux particules");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  //tft.println("Concentration - ug/m3");
  tft.print("PM1.0: ");
  tft.print(PM01Value);
  tft.println(" ug/m3");
  tft.print("PM2.5: ");
  tft.print(PM2_5Value);
  tft.println(" ug/m3");
  tft.print("PM10: ");
  tft.print(PM10Value);
  tft.println(" ug/m3");
  //tft.println("Pcs/0.01cf");

  String tempdht22 = String(temp);// turn integer to string
  String humdht22 = String(hum);
  String tempbmp180 = String(T);
  String pressbmp180 = String(p0);
  String lum = String(lux);
  String pol01 = String(PM01Value);
  String pol25 = String(PM2_5Value);
  String pol10 = String(PM10Value);
  esp8266(tempdht22, humdht22, tempbmp180, pressbmp180, lum, pol01, pol25, pol10);
  Serial.println("Waiting..");
  delay(300000);

}

void dht22 () {
//Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.println(" % ");
    Serial.print("Temp: ");
    Serial.print(temp);
    Serial.println(" C");
}

//cod pt dust sensor
void dust () {
  digitalWrite(31, HIGH);
  Serial.println("High Pms5003");
  delay(5000);
  for (int i=0; i <= 60; i++){
  if(Serial3.find(0x42)){    //start to read when detect 0x42
    Serial3.readBytes(buf,LENG);

    if(buf[0] == 0x4d){
      if(checkValue(buf,LENG)){
        PM01Value=transmitPM01(buf); //count PM1.0 value of the air detector module
        PM2_5Value=transmitPM2_5(buf);//count PM2.5 value of the air detector module
        PM10Value=transmitPM10(buf); //count PM10 value of the air detector module
      }
    }
  }

  Serial.print("PM1.0: ");
  Serial.print(PM01Value);
  Serial.println("  ug/m3");

  Serial.print("PM2.5: ");
  Serial.print(PM2_5Value);
  Serial.println("  ug/m3");

  Serial.print("PM10: ");
  Serial.print(PM10Value);
  Serial.println("  ug/m3");
  Serial.println();
  delay(1000);
  }
  delay(1000);
  Serial.println("Low Pms5003");
  digitalWrite(31, LOW);
}

char checkValue(unsigned char *thebuf, char leng)
{
  char receiveflag=0;
  int receiveSum=0;

  for(int i=0; i<(leng-2); i++){
  receiveSum=receiveSum+thebuf[i];
  }
  receiveSum=receiveSum + 0x42;

  if(receiveSum == ((thebuf[leng-2]<<8)+thebuf[leng-1]))  //check the serial data
  {
    receiveSum = 0;
    receiveflag = 1;
  }
  return receiveflag;
}

int transmitPM01(unsigned char *thebuf)
{
  int PM01Val;
  PM01Val=((thebuf[3]<<8) + thebuf[4]); //count PM1.0 value of the air detector module
  return PM01Val;
}

//transmit PM Value to PC
int transmitPM2_5(unsigned char *thebuf)
{
  int PM2_5Val;
  PM2_5Val=((thebuf[5]<<8) + thebuf[6]);//count PM2.5 value of the air detector module
  return PM2_5Val;
  }

//transmit PM Value to PC
int transmitPM10(unsigned char *thebuf)
{
  int PM10Val;
  PM10Val=((thebuf[7]<<8) + thebuf[8]); //count PM10 value of the air detector module
  return PM10Val;
} //cod dust sensor

void bmp120 () {
  status = pressure.startTemperature();
  if (status != 0)
  {
    // Wait for the measurement to complete:
    delay(status);

    // Retrieve the completed temperature measurement:
    // Note that the measurement is stored in the variable T.
    // Function returns 1 if successful, 0 if failure.

    status = pressure.getTemperature(T);
    if (status != 0)
    {
      // Print out the measurement:
      Serial.print("Temp2: ");
      Serial.print(T);
      Serial.println(" C ");

      // Start a pressure measurement:
      // The parameter is the oversampling setting, from 0 to 3 (highest res, longest wait).
      // If request is successful, the number of ms to wait is returned.
      // If request is unsuccessful, 0 is returned.

      status = pressure.startPressure(3);
      if (status != 0)
      {
        // Wait for the measurement to complete:
        delay(status);

        // Retrieve the completed pressure measurement:
        // Note that the measurement is stored in the variable P.
        // Note also that the function requires the previous temperature measurement (T).
        // (If temperature is stable, you can do one temperature measurement for a number of pressure measurements.)
        // Function returns 1 if successful, 0 if failure.

        status = pressure.getPressure(P,T);
        if (status != 0)
        {

          // The pressure sensor returns abolute pressure, which varies with altitude.
          // To remove the effects of altitude, use the sealevel function and your current altitude.
          // This number is commonly used in weather reports.
          // Parameters: P = absolute pressure in mb, ALTITUDE = current altitude in m.
          // Result: p0 = sea-level compensated pressure in mb

          p0 = pressure.sealevel(P,ALTITUDE); // we're at 1655 meters (Boulder, CO)
          Serial.print("Pressure: ");
          Serial.print(p0);
          Serial.println(" mb");
        }
        else Serial.println("error retrieving pressure measurement\n");
      }
      else Serial.println("error starting pressure measurement\n");
    }
    else Serial.println("error retrieving temperature measurement\n");
  }
  else Serial.println("error starting temperature measurement\n");
}

void tsl2561 () {
  /* Get a new sensor event */
  sensors_event_t event;
  tsl.getEvent(&event);

  /* Display the results (light is measured in lux) */
  if (event.light)
  {
    Serial.print(event.light); Serial.println(" lux"); lux = event.light;
  }
  else
  {
    /* If event.light = 0 lux the sensor is probably saturated
       and no reliable data could be generated! */
    Serial.println("0 lux");
  }
}

void esp8266( String temp1, String humm, String temp2, String pression, String luminosite, String pol001, String pol025, String pol010) {
  //update value on thingspeak
  digitalWrite(17, HIGH);
  Serial.println("High ESP8266");
  delay(4000);
  Serial1.println("AT+RST"); // this resets the ESP8266.
  Serial.println("AT+RST"); // this is just echoing the command to your serial monitor so you can follow what is going on
  delay(2000);
  Serial1.println("AT");
  Serial.println("AT");
  delay(5000);
  if(Serial1.find("OK")){
      Serial.println("OK");
      Serial.println("Connected");
  }

  Serial.println("in the update loop");
  //ESP8266.println("AT+RST"); // it seems that mine works better if I reset it everytime before I do CIPSTART
  //Serial.println("AT+RST");
  //delay(5000);
  String cmd = "AT+CIPSTART=\"TCP\",\""; //standard code. see https://github.com/espressif/esp8266_at/wiki //
  cmd += IP; // += is concatenating the previous cmd string with the content of IP
  cmd += "\",80"; // same thing here it just keep adding stuff to the cmd string content
  Serial1.println(cmd);//type in the string in cmd into the ESP8266
  Serial.println(cmd);
  delay(1000);

  if(Serial1.find("Error")){
    Serial.println("AT+CIPSTART Error");
    digitalWrite(16, HIGH);
    delay(250);
    digitalWrite(16, LOW);
    return;
  }
  cmd = GET + "&field1=" + temp1 + "&field2=" + humm + "&field3=" + temp2 + "&field4=" + pression + "&field5=" + luminosite + "&field6=" + pol001 + "&field7=" + pol025 + "&field8=" + pol010 + "\r\n\r\n";
  Serial1.print("AT+CIPSEND=");
  Serial1.println(cmd.length());
  Serial.print("AT+CIPSEND=");
  Serial.println(cmd.length());
  delay(1000);
  if(Serial1.find(">")){ // if ESP8266 return the > prompt back from the CIPSEND command, you are set, if not something is wrong
    Serial1.print(cmd); //type in the GET command string and done
    Serial.print(">");
    Serial.println(cmd);
    Serial.println("OK Sent");
  }
  else
  {
   Serial.println("AT+CIPSEND error");
    digitalWrite(16, HIGH);
    delay(250);
    digitalWrite(16, LOW);
  }
  delay(1000);
  digitalWrite(17, LOW);
  Serial.println("Low ESP8266");
}

Here i uploaded the data file from thingspeak. You can see that until 2016-06-17 14:58:00 UTC it was working fine then thingspeak started receiving blank data. It received something but only blank data.
The weather station is in another location so i don't have acces all time to reset it.
http://www.filedropper.com/feeds8
[Shown below are some lines from the front, the transition point, and the end of the feeds (8).csv file at Andrei's filedropper link. – jw]
created_at,entry_id,field1,field2,field3,field4,field5,field6,field7,field8
2016-06-16 05:50:45 UTC,1,19.10,92.70,20.80,1003.02,1512.00,8,15,15
2016-06-16 05:55:07 UTC,2,19.00,94.00,20.91,1003.09,1659.00,41,54,61
2016-06-16 06:01:32 UTC,3,19.10,92.70,20.98,1003.11,2233.00,6,7,12
2016-06-16 06:07:57 UTC,4,19.00,92.90,21.16,1003.11,2620.00,6,7,11
2016-06-16 06:14:22 UTC,5,19.10,92.70,21.19,1002.97,2701.00,6,6,12
2016-06-16 06:20:48 UTC,6,19.10,92.20,21.44,1002.97,2973.00,220,291,327
2016-06-16 06:27:13 UTC,7,19.30,92.20,21.47,1002.99,3197.00,5,6,7
...
2016-06-17 14:19:30 UTC,305,22.70,50.50,23.43,1013.88,1956.00,1,1,1
2016-06-17 14:25:55 UTC,306,22.60,51.20,23.27,1013.88,1979.00,1,1,1
2016-06-17 14:32:20 UTC,307,22.70,50.10,23.18,1014.00,1962.00,1,1,1
2016-06-17 14:38:45 UTC,308,22.70,49.50,23.17,1014.03,1967.00,1,1,1
2016-06-17 14:45:10 UTC,309,22.50,50.90,23.55,1014.01,1856.00,2,2,2
2016-06-17 14:51:35 UTC,310,22.60,51.80,23.62,1013.99,1870.00,1,1,1
2016-06-17 14:58:00 UTC,311,22.60,50.80,23.21,1013.94,1987.00,1,2,2
2016-06-17 15:04:26 UTC,312,"",,,,,,,
2016-06-17 15:10:51 UTC,313,"",,,,,,,
2016-06-17 15:17:16 UTC,314,"",,,,,,,
2016-06-17 15:23:41 UTC,315,"",,,,,,,
2016-06-17 15:30:06 UTC,316,"",,,,,,,
2016-06-17 15:36:31 UTC,317,"",,,,,,,
2016-06-17 15:42:56 UTC,318,"",,,,,,,
...
2016-06-17 22:59:18 UTC,386,"",,,,,,,
2016-06-17 23:05:43 UTC,387,"",,,,,,,
2016-06-17 23:12:08 UTC,388,"",,,,,,,
2016-06-17 23:18:33 UTC,389,"",,,,,,,
2016-06-17 23:24:58 UTC,390,"",,,,,,,
2016-06-17 23:31:23 UTC,391,"",,,,,,,
2016-06-17 23:37:48 UTC,392,"",,,,,,,
2016-06-17 23:44:13 UTC,393,"",,,,,,,

I went and saw the station, it's more like an electrical problem imo because if i reset arduino nothing happens. The data readed by arduino on dht22 is nan and the rest of the sensors is working fine. The only way i could make dht22 reading again is to unplug the power and plug it back. So that's why i think it's more an electrical problem but can't figure why dht22 stops responding and need to switch off all power to bring it back to life. I will try putting an capacitor on wires to dht22 to see if it's better.

Please edit your question and add examples of output from when it is working, and from when it isn't.   Your statement that “the data received is blank” is ambiguous.  Do you mean the whole transmission, or just the data fields; and by blank, do you mean "not there" or "blank characters"?  To avoid that ambiguity, please edit your question and add examples of output from when it is working, and from when it isn't.

I edited some of those lines into the question.  The link to filedropper seems cumbersome to use.  ¶  What I'd like to see, instead of data as processed by  thingspeak, is what was sent to thingspeak.  Ie, what the Arduino is sending, not what thingspeak extracted from that input.  I imagine field names are missing (in the http GET request) as well as data

You may have a power problem, but with all those libraries, I would also suspect memory issues with String.  The percentages reported by the IDE do not show actual String memory usage, just the declared variables and double-quoted string constants, like "BMP180 init fail".
I think those humidity sensors have a heating cycle, so maybe they're causing a power sag, or maybe the sketch has run amok and is constantly requesting conversions.
Regardless, instead of building a String to be printed all at once, just print the pieces.  That is, instead of this:
String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  Serial1.println(cmd);

...do this:
Serial1.println( F("AT+CIPSTART=\"TCP\",\"") );
Serial1.print( IP );
Serial1.print( F("\",80") );

This saves copying bytes into buffers, reallocating Strings, copying them to the output buffer... yuck.
The F("x bytes") macro also saves x bytes of RAM each time you use it on a double-quoted string constant!
And this:
cmd = GET + "&field1=" + temp1 + "&field2=" + humm + "&field3=" + temp2 + "&field4=" + pression + "&field5=" + luminosite + "&field6=" + pol001 + "&field7=" + pol025 + "&field8=" + pol010 + "\r\n\r\n";

OMG.  Use separate Serial1.print statements and F() macros.  However, because you have to send the command length first to the ESP8266, don't pass them in as Strings, pass them as ints or floats, and add up the individual string lengths.
There are several ways to do this, depending on the old RAM-vs-speed tradeoff.  Here's a minimal RAM approach:
  //  Pass in values, not Strings
  esp8266( temp, hum, T, p0, lux, PM01Value, PM2_5Value, PM10Value );
}
    ...

void esp8266( float temp1, float humm, float temp2, float pression, float luminosite, int pol001, int pol025, int pol010 )
{
    ...

  //  Start with the fixed-length string constants:
  //     GET + 8 * "&field#" + line termination
  size_t cmdLength = strlen(GET) + 8 * 8 + 4;

  //  Convert each value to a char array to see how big each one is...
  char buf[16]; // to hold temporary "char strings"

  unsigned char decimalPlaces = 2;
  dtostrf( temp1, (decimalPlaces + 2), decimalPlaces, buf);
  cmdLength += strlen(buf);

  dtostrf( humm, (decimalPlaces + 2), decimalPlaces, buf);
  cmdLength += strlen(buf);

  dtostrf( temp2, (decimalPlaces + 2), decimalPlaces, buf);
  cmdLength += strlen(buf);
     ...
  itoa( pol10, buf, 10 );  // value, char *, base
  cmdLength += strlen(buf);

  //  Now we know the total length
  Serial1.print("AT+CIPSEND=");
  Serial1.println( cmdLength ); //  <-- calculated!
  delay(1000);

  if (Serial1.find(">")) {

    // send all the same pieces of the GET command
    Serial1.print( GET );

    Serial1.print( F("&field1=") );
    dtostrf( temp1, (decimalPlaces + 2), decimalPlaces, buf);
    Serial1.print( buf );

    Serial1.print( F("&field2=") );
    dtostrf( humm, (decimalPlaces + 2), decimalPlaces, buf);
    Serial1.print( buf );

    Serial1.print( F("&field3=") );
    dtostrf( temp2, (decimalPlaces + 2), decimalPlaces, buf);
    Serial1.print( buf );
        ...
    itoa( pol010, buf, 10 );  // value, char *, base
    Serial1.print( buf );

    Serial1.print( F("\r\n\r\n") );

NOTE: It is important that you use the same technique to calculate the length of one piece and to print that piece.  Here, the same dtostrf call with the same decimalPlaces is used for each piece.  Ditto for itoa.
The speed penalty is that you convert each parameter twice, but this is probably still quicker than all the alloc/realloc/delete/copy that String was doing.
The RAM advantage is that you are using only 16 bytes for buf instead of hundreds of bytes on the heap (that's where String actually stores its characters).
The program space advantage is about 1600 bytes for not using the String library.
I hope you now see that the apparent "convenience" of using the String class has real costs in speed, RAM and program size.  String also affects the long-term stability of your program: you get weird crashes, hangs or string values.

Thank you very much for your reply. I am a beginner in C programming, i started learning C about some months ago, so i will try to understand what you told me about optimising the program and then applying to my project, because honestly now i don't understand them :) I did a research on google and saw that others are having problems with DHT22 sensor that stops working and need to replug it on power to works.
When i saw the weather station today like i told all the sensors was running except the dht22 which replied as nan.Since nan is not an int value thingspeak is not accepting transmission

The dht22 is doesn't have a heating time so i could attach the vcc pin of dht22 to an arduino pin and activate it when i need to read the temperature.
The library is made like this when dht22 is not responding it give a value of nan. I could modify the library to give a value of 50 degrees for example but this is not a solution to my problem.
If you have any other comments regarding my program feel free to help me :) Thank you !


text:
Renaming pins in sketch
I'm trying to rename pins so that they post as some kind of alpha-numeric combination in a database.  For example, if I define the following....
#define APLHA 0
#define BRAVO 2
#define CHARLIE 5
#define DELTA 6

...I would like to rename the output of the pins, as recorded in the db, as something other than 0, 2, 5, and 6 (or whatever pin is used). Let's say A, B,C, and D for the purposes of this exercise.
Is this just as simple as creating if() function that is called upon prior to posting to the db (ex. if 0 then A, if 2, then B, etc)?  I feel like there must be a better, dare I say more elegant(?), way of doing this?
Current output:
PIN | VALUE
0  |   1
 2  |   1
 5  |   0
 6  |   0
Desired:
PIN | VALUE
 A  |   1
 B  |   1
 C  |   0
 D  |   0

I would like to rename the output of the pins, as recorded in the db - I don't understand this, sorry. You can give pins names, as in your list of defines. What is the issue here?

Why not record the names in the database and let the database do the databasing instead.

Sounds like I'm overcomplicating this.

If I understood your question correctly, you're looking for something like this:
static const byte PIN_NUMBER[4] = { 0, 2, 5, 6 };
static const char *PIN_NAME[4] = { "A", "B", "C", "D" };

// and use them like this:

void Log(byte index)
{
  byte val = digitalRead(PIN_NUMBER[index]);
  Serial.print(PIN_NAME[index]);
  Serial.print('|');
  Serial.println(val);
}

void setup()
{
  for (byte i = 0; i < 4; ++i) pinMode(PIN_NUMBER[i], INPUT);
}

void loop()
{
  Serial.println("PIN|VALUE");
  for (byte i = 0; i < 4; ++i) Log(i);
  delay(1000);
}

Also, in the special case of "A", "B", "C", "D" as pin names, you don't really need the PIN_NAME array, instead of
Serial.print(PIN_NAME[index]);

you can use:
Serial.print('A' + index);

This is exactly what I was looking for!  Thank you.  I'll try it and report back but this looks to be the solution.

authors: Виктор Дерий


text:
MFRC522 Module Won't Read Multiple PICCs Consecutively
I recently bought an MFRC522 RFID module to use with my Arduino Uno, which came as a kit with a couple of MiFare 1K cards.
The issue I've been having is that, I cannot scan cards consecutively (the same card or two different ones) without resetting the Sketch.  I hold a card in front of the reader and it is scanned, but when I hold another card in front of the reader it just doesn't recognize it as being there in the mfrc522.PICC_IsNewCardPresent() function.  It does however work when using the example sketch "DumpInfo".
Here is the code I've written (please excuse any of my bad practices/untidiness).
/* Include Required Libraries */
#include <MFRC522.h>
#include <SPI.h>

/* Define Values for MFRC522 */
#define RST_PIN 9
#define SS_PIN 10

/* Instantiate the MFRC522 Object */
MFRC522 mfrc522(SS_PIN, RST_PIN);

/* Initialize Variables */
byte resultBuffer[18];
MFRC522::MIFARE_Key key;
unsigned int integerValue = 0;
char incomingByte;

void setup()
{
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
  Serial.println(F("Ready to scan card..."));

  for (byte i = 0; i < 6; i++)
  {
    key.keyByte[i] = 0xFF;
  }
}

void loop()
{
  if (!mfrc522.PICC_IsNewCardPresent())
  {
    if (Serial.available() <= 0)
    {
      return;
    }

    integerValue = 0;
    while(true)
    {
      incomingByte = Serial.read();
      if (incomingByte == '\n') break;
      if (incomingByte == -1) continue;
      integerValue *= 10;
      integerValue = ((incomingByte - 48) + integerValue);
    }

    printHeader();
    Serial.println("NEW BLOCK READ VALUE :");
    Serial.println(integerValue);
  }

  if (!mfrc522.PICC_ReadCardSerial())
  {
    return;
  }

  readAndPrint(integerValue);
}

void printHeader()
{
  Serial.println(" ");
  Serial.println("----------------------------------------");
}

int authenticateKeyA(int blockNumber)
{
  printHeader();
  Serial.println("Authenticating with key A...");

  int largestModulo4Number = blockNumber / 4 * 4;
  int trailerBlock = largestModulo4Number + 3;

  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));

  if (status != MFRC522::STATUS_OK)
  {
    Serial.println("ERROR : Authentication was unsuccessful.");
    return 0;
  }
  else
  {
    Serial.println("SUCCESS : Authentication was successful.");
    return 1;
  }
}

int authenticateKeyB(int blockNumber)
{
  printHeader();
  Serial.println("Authenticating with key B...");

  int largestModulo4Number = blockNumber / 4 * 4;
  int trailerBlock = largestModulo4Number + 3;

  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, trailerBlock, &key, &(mfrc522.uid));

  if (status != MFRC522::STATUS_OK)
  {
    Serial.println("ERROR : Authentication was unsuccessful.");
    return 0;
  }
  else
  {
    Serial.println("SUCCESS : Authentication was successful.");
    return 1;
  }
}

int readBlock(int blockNumber, byte *resultBuffer)
{
  printHeader();
  Serial.println("Starting read block function...");

  int authSuccess = authenticateKeyA(blockNumber);
  Serial.println(" ");

  if (!authSuccess)
  {
    Serial.println("ERROR : Terminating function.");
    return 0;
  }

  byte bufferSize = 18;

  byte status = mfrc522.MIFARE_Read(blockNumber, resultBuffer, &bufferSize);

  if (status != MFRC522::STATUS_OK)
  {
    Serial.println("ERROR : Read failed.");
    return 0;
  }
  else
  {
    Serial.print("SUCCESS : Block ");
    Serial.print(blockNumber);
    Serial.print(" was read successfully.");
    return 1;
  }

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}

void readAndPrint(int blockNumber)
{
  readBlock(blockNumber, resultBuffer);

  printHeader();
  Serial.println("RESULT :");
  for (int j=0 ; j<16 ; j++)
  {
   Serial.print(resultBuffer[j], HEX);
   Serial.print(" ");
  }
  Serial.println(" ");

  delay(2000);
  printHeader();
  Serial.println("Ready to scan card...");
}

Before scanning the card for the first time, the serial output looks like this :

After scanning the card for the first time, the serial output looks like this :

After scanning the card for the second time, the serial output doesn't change from image 2.  I tried running Serial.println("no card detected"); when the code inside if (!mfrc522.PICC_IsNewCardPresent()) is ran, just to check if the program was frozen (I'd heard someone else had an issue where the program froze after scanning the first card) - it wasn't frozen, both before and after scanning the first card, it printed out 'no card detected' repeatedly.
I would greatly appreciate any help as I have no clue as to how I should proceed.
Cheers,

What is printed in the serial monitor? Post the image in your question.

@TisteAndii Images have been added to the question.  Cheers

Do not return from 'loop()', it should loop forever.

If you return it still loops.

The correct condition, for what you intend, should be if (mfrc522.PICC_IsNewCardPresent()), so that the code in the IF block is run when a card is present, though this isn't the best structure. Like you discovered, your program isn't frozen. One of the 2 return statements (I'm not sure which) is causing it to abort loop() before calling readAndPrint(). With your current code:

the first return will always be executed whenever no card is detected. Since you don't seem to be sending anything with the Serial monitor,  Serial.available() will return 0 and so loop() returns.
The second return will be executed if the reader fails to obtain the UID of the card with a SELECT. The SELECT will fail only if you don't first call PICC_RequestA() for 'new' cards (just coming within range), or PICC_WakeupA() for HALTed cards (cards already within range but sleeping).

I don't know if you're trying different cards or just one. If its just one card, you may have to take it out of range and then bring it within range again for the reader to detect it a second time. But, if you want to read the card's data more than once, without taking it out of range, you have to call PICC_WakeupA() instead of PICC_IsNewCardPresent() since, as the names indicate, you're waking a sleeping card, not detecting a new card entirely. Also structure your loop() like this:
void loop(){
  if (!mfrc522.PICC_IsNewCardPresent()) {  // replace the condition with PICC_WakeupA()
    return;  // if you dont want the card to leave the reader's range
  }

  if (!mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  // all the code that should be executed if a card has been detected and its UID read

}

However, there's usually little sense in HALTing a card and then waking it in the very next iteration, so you might want to do all the sector reading and writing at once, HALT the card, and then wait for a new card to enter the field; at least that's what's desired in most applications.


text:
Arduino, 74HC595N, magic
Good day
I'm playing with Arduino and shift register chip 74HC595N and already tried many different ways to solve my problem, but still to luck :(
So that is my current simple scheme:

Arduino 2,3,4 ports connected to data, clock and latch pins of 74HC595N. I've connected only first two output pins of chip to make minimum power consumption and to simplify this example as much as possible.
That is my sketch:
const int latchPin = 4; //Pin connected to ST_CP of 74HC595
const int clockPin = 3; //Pin connected to SH_CP of 74HC595
const int dataPin = 2;  //Pin connected to DS of 74HC595

void setup()
{
  Serial.begin(9600);
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  Serial.println("ON");
  digitalWrite(13, HIGH);
  send(B10000001);
  Serial.println("OFF");
  digitalWrite(13, LOW);
  send(B01000010);
}

void send(byte d) {
  Serial.println(d);
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, d);
  delay(1000);
  digitalWrite(latchPin, HIGH);
}

And the problem is: sometimes leds are blinking but very unstable. Sometimes it's not working at all, sometimes only first led is blinking, but second one is not. Sometimes opposite - second led is blinking, first one is not. Sometimes one of led is blink very fast (just flash instead of 1 second delay).
If I touch wires and elements on breadboard - something changing. Even without touching anything - situation changing. It seems like problem is somewhere in connection or power supply and I've already tried to except it: tried few different breadboard, two different 595 chips, different wires and resistors, tried Arduino Uno, Mega and nano. Even tried atmega328p standalone, tried power it from USB, from 9v battery, old mobile charger (5.4V, 650 mA), tried to power arduino with external source (12V, 1A). In all cases the problem still exists.
I've already read a lot about power supply for Arduino, but I think at least few of the ways I've already tried to supply power is good enough for 595 chip and two LEDs - isn't it?
Please, advice me what else can I try?

Try moving the "delay(1000)" in send() to the loop() instead.

You haven't tied the OE pin (13) to ground.

@MikaelPatel: I've tried many different variants and nothing helped except Gerben's advice :)

@Gerben, Thanks a lot - seems like OE and MR pins was the reason. I'm still experimenting, but seems like that it helps!

Even this is quite old, to help others as well:
As you already did, pin 13 (output enable, active low) to ground and pin 10 (master reset, active LOW) to HIGH, to disable reset.


text:
Arduino crashing and rebooting
I have recently written a program which is supposed to change the duty-cycle to keep the feedback voltage measured on A0, A1 constant. The problem is that the Arduino will start crashing at pretty constant intervals if it approaches it's target current. Once it crashes I have confirmed that it restarts the program (but crashes again in a moment).
Here's a sample of the serial output during the crash:
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 236.00
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 235.96
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 235.92
Current A: 64   Current B: 67   PWM A: 175.00   PWM B: 235.88
Current A: 64   Current B: 66   PWM A: 250.00   PWM B: 285114740000000000000000000.00
Current A: 0    Current B: 0    PWM A: 1.30     PWM B: 0.00
Current A: 0    Current B: 0    PWM A: 2.60     PWM B: 1.30
Current A: 0    Current B: 0    PWM A: 3.90     PWM B: 2.60
Current A: 0    Current B: 0    PWM A: 5.20     PWM B: 3.90

And here is all of my code:
#include <MemoryFree.h>

//Program to run on the Vegetarium
//Written by Leon Teichroeb on 12/6/2016

//Hardware description:
//-Oscillator 2A and 2B for the two onboard driver circuits
//-Pin 13 is attached to the "heartbeat" LED
//-Channel A (3) and B (11) current measurements on A0 and A1

//Functionality:
//-Drive Channels at set current

float PWMA = 0;
float PWMB = 0;

int TARGETA = 65;
int TARGETB = 65;

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

  pinMode(3, OUTPUT);
  pinMode(11, OUTPUT);
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(CS20);
  OCR2A = (int)PWMA;
  OCR2B = (int)PWMB;
  digitalWrite(3, LOW);
  digitalWrite(11, LOW);

  delay(5000);
}

void loop() {
  int CURRENTA = analogRead(A0) / 4;

  if(CURRENTA < TARGETA) {
    PWMA += (TARGETA - CURRENTA) * 0.020f;
    if(PWMA > 250) {
      PWMA = 250;
    }
  }
  if(CURRENTA > TARGETA) {
    PWMA += (TARGETA - CURRENTA) * 0.020f;
    if(PWMA < 5) {
      PWMA = 5;
    }
  }

  int CURRENTB = analogRead(A1) / 4;

  Serial.println("Current A: " + (String)CURRENTA + "\t" + "Current B: " + (String)CURRENTB + "\t" + "PWM A: " + (String)PWMA + "\t" + "PWM B: " + (String)PWMB);
  //Serial.println("PWM A: " + (String)PWMA + "\t" + "PWM B: " + (String)PWMB);
  //Serial.print("freeMemory()=");
  //Serial.println(freeMemory());

  if(CURRENTB < TARGETB) {
    PWMB += (TARGETB - CURRENTB) * 0.020f;
    if(PWMB > 250) {
      PWMB = 250;
    }
  }
  if(CURRENTB > TARGETB) {
    PWMB += (TARGETB - CURRENTB) * 0.020f;
    if(PWMB < 5) {
      PWMB = 5;
    }
  }

  if(PWMA < 10) {
    digitalWrite(3, LOW);
  } else {
    analogWrite(3, (int)PWMA);
  }
  if(PWMB < 10) {
    digitalWrite(11, LOW);
  } else {
    analogWrite(11, (int)PWMB);
  }

  delay(40);
}

My circuit also provides power for the Arduino through a simple 7815 voltage regulator. The analog input does not exceed a few volts, and the PWM outputs are driving two logic level MOSFETs. If more information on the circuit is necessary please let me know!
EDIT: I have found out that it isn't a bug in the two feedback loops, because both work on their own. It crashes as soon as I use both feedback loops together. As far as I'm aware, there are no shared variables or data between them

I can't see anything horribly wrong with your code. Maybe a memory issue. Did you try printing without Strings? Like: Serial.print("Current A: "); Serial.print(CURRENTA); .... It's cumbersome but memory friendly.

I can definitely give it a try, but I actually wrote the serial code to debug this problem specifically. I also suspected memory issues, but with MemoryFree.h I found that I still have >1500 bytes free and no leaks

The 285114740000000000000000000 is kind of odd.  Also, PWM B: 0.00 seems to be impossible with the code above. Very odd. (Did you add some capacitors to the output of the 7805?)

The 0.0 PWM signal is possible because it is only limited to 5.0 if it is lowering the duty-cycle. Also, I have a 0.1uF capacitor on the output of the 7805 even though it's powered with a lab bench power supply

Target current or target voltage?

I finally figured it out, the Arduino was entering a current protection mode causing it to reset. The pins driving the MOSFETs were pulling too much current once the regulation started because of the BUZ11's input capacitance.
To fix the problem I just had to add 120 ohm resistors in series with the gate. This made the activation and deactation slower resulting in less current flow.

are u telling u have added 120 ohm resistor in series with ic 7815 i am having same prob. please tell is this sol. will work

What's a BUZ11, a MOSFET? So the gate input capacitance on the MOSFET was exceeding the current limits on the logic lines? Or are you talking about the power draw of the MOSFET? Can you provide a wiring diagram? It's hard to understand what you're saying.


text:
expected class-name before '{' token
I am getting the following error when attempting to compile my sketch:

In file included from sketch.ino:24:0: SerialRenderer.h:7: error:
  expected class-name before '{' token

SerialRenderer.h
#ifndef SERIALRENDERER_H_
#define SERIALRENDERER_H_

#include <MenuSystem.h>

class SerialRenderer : public MenuComponentRenderer
{
public:
    SerialRenderer();
    virtual ~SerialRenderer();

public: // methods from MenuComponentRenderer
    virtual void render(Menu const& menu) const;
    virtual void render_menu_item(MenuItem const& menu_item) const;
    virtual void render_back_menu_item(BackMenuItem const& menu_item) const;
    virtual void render_numeric_menu_item(NumericMenuItem const& menu_item) const;
    virtual void render_menu(Menu const& menu) const;
};

#endif // SERIALRENDERER_H_

The contents of MenuSystem.h can be found at https://github.com/jonblack/arduino-menusystem/blob/master/MenuSystem.h.
It seems like the include of MenuSystem.h does not happen when SerialRenderer.h is included from my main sketch file. I get the same error if the include in SerialRenderer.h is removed.
Is there something simple I am missing for the compiler to be able to "see" MenuSystem.h?
EDIT:
Turns out I was looking at a newer version of the arduino-menusystem library than I had installed (version 2.1.1). That version did not have a class called MenuComponentRenderer.
I pulled the latest version from https://github.com/jonblack/arduino-menusystem/tree/master and it compiles fine.

It is most likely caused by the fact that a correct version of MenuSystem library is not properly installed.
Check whether you can add the library to your sketch.
EDIT: added that also the version should be correct

I can include the library in my sketch via Sketch > Include Library. Also Library Manager shows that version 2.1.1 is installed.

Rembember to add the include to the sketch. The build will look at the sketch includes to add the necessary paths.

@MikaelPatel My main sketch is including both SerialRenderer.h and MenuSystem.h, but I get the same error whether or not MenuSystem.h is included.

Indeed the version is also important.


text:
What is the maximum prescaler you can set for an ATtiny85 Timer Interrupt?
I'm having trouble understanding the datasheets for the ATtiny and I need to know what is the largest prescaler that can be set for an ATtiny Timer Interupt? I'm new to hardware so can someone tell me if this is correct:
void setupInterupt()
{
  noInterrupts();
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = 0;
  OCR2A = PERIOD - 1;
  TIMSK2 = _BV(OCIE2A);
  TCCR2B |= _BV(CS13) | _BV(CS12) | _BV(CS12) | _BV(CS10);
  interrupts();
}

Will this set a prescaler of 16384? Am I understanding the chart on page 89 correctly and is my syntax okay? This is my first Arduino Project.

You're using the registers for timer 2, which that chip doesn't have. Also, you're using CS12 twice.

So I only have Timer 1? I guest that limits the kind of sleep mode I can use since the power saver mode turns Timer 1 off.

Please clarify what you are trying to do with the timer. Short answer, looking, yes it does set a prescaler of 16384, that stuff is for the PWM stuff. Please clarify the your clock frequency and what you plan to do with the timer? Thanks

The ATtiny85 doesn't have Power-save mode, only Idle, ADCNR, and Power-down.

I'm trying to put my ATtiny to sleep after the program has run and then wake it up every 33 milliseconds. I need a large prescaler value because the ATtiny85 has a speed of 20MHz. I'm using the Power-down mode to maximize the amount of power saved.

@IsabelAlphonse  moving down to a smaller clock speed will start saving you power to begin with, is there any specific reason you have a 20MHz crystal?

TCCR2B should be TCCR1. I'm pretty sure the above code doesn't even compile.

Isn't 20MHz the speed of the ATtiny processor?

Why not just use the watchdog to wake?

I don't know the objectives of your project, or its constraints and requirements.  Thus, portions of the following might not apply.
If I were using an ATtiny85 in an application that needed to “maximize the amount of power saved” and also needed to wake up about every 33 ms, I'd use the factory-calibrated 8 MHz clock (rather than attaching a 20 MHz external crystal), and use system clock prescaling [see §6.3, System Clock Prescaler, on page 31 of the ATtiny85 specs, and Table 6-15. Clock Prescaler Select, p. 33] to scale that 8 MHz down to 250 KHz.  As implied by Table 21-1, DC Characteristics, page 162 of specs, this will drop CPU current draw down to under 0.1 mA if powered by 2 V, or under 0.35 mA if powered by 3 V.
With the system clock running at 250 KHz, you can use timer 0 prescaled by a factor of 1024 [see §11.3.1, Internal Clock Source with Prescaler, p. 166 of specs] to get an interrupt every 33 ms or so.
If 250 KHz is too slow to get done with whatever computation needs to be done every 33 ms, upon waking I would change the system clock prescale factor per §6.3.1, Switching Time, to 8 MHz or 4 MHz or whatever it needs to be to get the computation done at lowest power cost.  That might or might not be the same as getting the computation done most quickly.
Then, after the periodic computation is done, I'd revert the system clock to 250 KHz, and go to sleep in Idle mode (Ref §7.1.1, Idle Mode) with almost everything except timer 0 shut down via the PRR. (Ref §7.3, Power Reduction Register.)


text:
nRF24L01+ module fried?
I have 2 nRF24L01+ modules that were working fine then...stopped. I'm wondering if I accidentally fried one of the modules.
When I run the RF24 library GettingStarted example, this is the output of the module I believe may be fried:
RF24/examples/GettingStarted/
ROLE: Pong back
*** PRESS 'T' to begin transmitting to the other node
STATUS        = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1  = 0x0000000000 0x0000000000
RX_ADDR_P2-5  = 0x00 0x00 0x00 0x00
TX_ADDR       = 0x0000000000
RX_PW_P0-6    = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA         = 0x00
EN_RXADDR     = 0x00
RF_CH         = 0x00
RF_SETUP      = 0x00
CONFIG        = 0x00
DYNPD/FEATURE = 0x00 0x00
Data Rate     = 1MBPS
Model         = nRF24L01
CRC Length    = Disabled
PA Power      = PA_MIN

I've changed out cables and connections all the way through. I also replaced this module with the other one directly and the other worked fine.
So, my question: Is this output showing definitively that I've killed the module and just need to buy a new one? Or is there some way to "flash" or reset the module?

If one works, and the other (in the same circuit) doesn't, then it does indeed look like it's fried. There is no way of resetting these devices.

First, you should check continuity of your wiring (wire connections may become loose after some time, in particular if you move your circuits around). Then, if you have access to a digital analyzer you could check levels of all connections between Arduino and NRF (MISO, MOSI, SCK, CS, CE) and see if something is wrong.

Output says no connection with the chip, if you have not messed with it, if it has not been shorted or in any other way mishandled, I'd suspect wiring. Because I have never heard of anyone frying the neat chips neither somehow damaging. But if you give it 5V instead of 3.3V or short the board itself somehow everything is possible or just ESD above the rating killed it.

Also these devices lack any permanent configuration, power is cycled means settings are lost. It also lacks any reflashable firmware.

Assuming you have triple checked all your wiring before posting this question you should add a small capacitor between Vcc and GND near the nRF24: anything between 10uF and 100uF will do.
Rationale: these devices draw quite a decent amount of current when bootstrapping and transmitting and if they don't receive enough juice they just reset themselves showing those all zeroes settings.
They are pretty robust devices, not that easy to fry.

The nRF24L01 modules are very sensitive to electrostatic damage, I have killed three. By bit-banging the SPI lines it appears that the SCK line dies as I can detect MISO change on activating CSN (since status information should be returned whatever command is sent). I surmise the zeros you see in the status report are the first pre-clock bit repeated when there is no clock signal received. I put a 33k pull-down resistor on SCK.


text:
Duplicate a garage door key
I am trying to copy my garage door key. I opened it and found out it has dip switches which you can flip so you can send different codes. It uses 12 bits and operates at 315Mhz. I bought a 315Mhz transmitter for arduino and i am trying to send that 12 bit code. I used an RTL-SDR and found out that the key uses AM modulation. Now, the problem is i dont know how to send bits (1,0 or high and low). I connected vcc of the transmitter to arduino 5V and gnd to gnd. Data pin is connected to pin 9. I tried setting pin 9 high or low coresponding to the code with 2ms pause in beetwen but RTL-SDR showed that nothing was transmitted. I tried using rc_switch and virtual_wire libary and using diffferent transmitters in case this one was damaged but no success. So how do i actually send high and low signals with these transmitters?
PS: I know i can buy those garage key copiers but this is more fun and i learn more.

Not the issue you asked about, but note that most remote garage door openers send a different code at each activation.  The DIP switches are like a password, and what is sent is like an encrypted password with a different salt each time.


text:
How to send AT command to sim800l with SoftwareSerial
I have SIM800l module connected to Arduino and I'm trying to initialize it in my setup function with this code:
#include <SoftwareSerial.h>

//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 6
//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup()
{
  Serial.begin(38400);
  while(!Serial);
  serialSIM800.begin(38400);
  Serial.println("wait for .... it");
  delay(10000);

  // comments added just for example, both commands return junk
  //serialSIM800.write("AT\r\n");
  //serialSIM800.write("AT+SAPBR=3,1,\"Contype\",\"GPRS\"\r\n");

  Serial.println("command sent");
  delay(2500);

  Serial.write(serialSIM800.read());
}

But Serial.write returns junk.
When I use this code in loop:
  //Read SIM800 output (if available) and print it in Arduino IDE Serial Monitor
  if(serialSIM800.available()){
    Serial.write(serialSIM800.read());
  }
  //Read Arduino IDE Serial Monitor inputs (if available) and send them to SIM800
  if(Serial.available()){
    serialSIM800.write(Serial.read());
  }

and send AT+SAPBR=3,1,"Contype","GPRS" or just AT command with serial monitor, everything works fine.
Can someone help with this?

Can you place your schematic? Are you using the 4V regulation and transistor on RST pin? Maybe this library might help

What sort of junk? Copy and paste please. Also writing the output from a read, without testing for available is likely to return "junk" or at least ÿ.

You're reading only a byte like others have noted. Also, you seem to be sending 2 commands, one immediately after the other. This could result in gibberish. Though it would be nice to see exactly what your 'junk' results are.

I'm a bit surprised you have put a bounty of +100 rep on this question, but are not answering queries like the comments above, that might help resolve it.

You can try to use serialSIM800.println("AT") instead of write. Here some examples https://github.com/stanleyhuangyc/Freematics/issues/17

NeoSWSerial would be better for this.  It can read and write at the same time, unlike SoftwareSerial, and it doesn't disable interrupts for the entire character receive time (~1ms!).  AltSoftSerial would be even better, but you can only use it on pins 8 & 9 (on an UNO, different pins on other Arduinos).

Somewhere you said that ...but Serial.write return's junk....
Make sure that serial print is Both NL & CR

You are getting junk because of baud rate, set as 9600.
Serial.begin(9600);
  while(!Serial);
  serialSIM800.begin(9600);
  Serial.println("wait for .... it");
  delay(10000);

IIRC, SIM800 modems are very 1990s, they default to 9600 baud. You will get garbage at 38400.
I successfully used a SIM800 at 9600.

My SIM808 returns a bit of junk right from the get-go, so that might be influencing things.
Also, it's conceivable you are retrieving a -1 from your initial serialSIM800.read() call - it's a nonblocking call and returns -1 when no data is available.  That would almost definitely appear as junk.

Sim800 series free Atcommander software.
http://bayanbox.ir/info/3493267131357723232/ATcenter


text:
What's up with my code?
Sorry if my code isn't well written or anything because I'm new to Arduino and coding in C, but what is wrong with my code?
int sidepin = 2;
int LED = 5;
int val;
void setup() {
  pinMode(sidepin, INPUT);
  pinMode(LED, OUTPUT);
}

void loop() {
  val = digitalRead(sidepin);
  if(val = 0)
  {
    pinMode(LED, HIGH);
  }
  else(val > 0)
  {
    pinMode(LED, LOW);
  }
}

Please help the helpers help you by asking a more specific question than "what's up..." If you need help with compiler errors, say so, and report at least some of the message and the location of it. If you're asking about run-time behavior, please state what you expected it to do and what it actually did. You can get lots of good help here but please try to direct your readers to the specific problem. The guide to asking good questions has a lot of good suggestions.

else(){} looks like bad syntax.

Your IF statement, you're using: (val = 0), and I believe you meant (val == 0).
Also, you're using else(val > 0) and else doesn't need any argument. So the fixed code should look like:
int sidepin = 2;
int LED = 5;
int val;
void setup() {
  pinMode(sidepin, INPUT);
  pinMode(LED, OUTPUT);
}

void loop() {
  val = digitalRead(sidepin);
  if(val == LOW)
  {
    pinMode(LED, HIGH);
  }
  else
  {
    pinMode(LED, LOW);
  }
}


text:
Arduino as switch for external circuit
I am trying to use the Arduino as a switch for an external circuit.
I first thought about using a shift register, but this wont allow me to switch the external circuit. Here is a little sketch of what I want to do :
So basically I got this external circuit with a 3 position switch. And I want to replace this manual switch with an Arduino so it can be controlled by a PC, without influencing the other circuits Voltage or Amps...
Any suggestions ?

Is it important for the switch to have 3 positions? Would it matter if two contacts can be on at the same time? Why use a shift register if you only need 3 positions, you could use 3 I/O pins? What voltage/current will go through?

I will start off with three but it should be expandable to lets say 32 or more later on. Temporarily it wouldnt matter if two were on at the same time, but after some time only one has to be on. What do you mean with 3 I/O Pins ? Voltage will be max 1V at 100mA max.

Since you are only switching low voltage, you could probably use a transistor instead of a more expensive relay.

Yeah but transistors would influence the currents and th voltage in case of not being opened

Three-position makes it a little more tricky than normal.
The simplest option, though depending on what the circuit is, maybe not the safest option, is to use three relays.

Switch only one relay on and it is the same as having the three-position switch in that same state. Switch that relay off and switch another on and you have changed the switch position.
The danger is that this arrangement can have two or even three relays on at once, something that can't happen with a switch.  Also how you do the switching could be critical. Switch one relay off, then add a delay before switching the next one on, so that the previous one has a chance to switch off properly first. That way you avoid having two on at once. Of course, depending on what it is you're switching, that may or may not be an issue.
The safest option, though the hardest to create, would be to physically move the existing switch with, say, a servo motor. Without knowing a little more about the mechanics of your switch I can't really advise more on this option.

Hello, yes it needs to be at least 3... It should even be expandable to 32 later on. I tought about relays but it seems to be a hassle to get them powered and controlled by the arduino? We cant have anpther power source....

The use 5V relays and use the Arduino as the power source. Tip: buy pre-built relay modules with the driver circuit built in. They are cheap enough, and you can get them in up to 8 relays to a board.

Also about the relays being on at once isnt too bad temporarily. Te mechanical switch has to go away so no way to use a servo. This sounds like a good way to go. Do you know any prebuilt modules easily available in europe / germany?

There are plenty made in china on eBay. Cheap, easy to get, etc. SainSmart are a common maker of them. They have a good selection.

Ok perfect thanks, one more question, will the relay have an influence on the current and voltage tat flows trough my external circuit ?

No they are just the same as a switch.

Thanks ! I went for a sainsmart 8 channel relay module. It says 5V , can this be powered soley by the arduino ? There is always only one switch open at the time

Yep, that's the ideal choice.


text:
Standalone Arduino with ATMEGA328P / Serial working, but serial programming not (only once after buning bootloader)
For my master thesis I've designed a board with an ATMEGA328P-AU as micro controller.

As I want to use some libraries and I like the simplicity, I want to use "Arduino" to program it.
Everything works fine to a point:
I took an Arduino Uno and uploaded the "ArduinoISP" sketch.
I connected the ISP pins and burned the bootloader with board set to "Arduino Duemilanove / Diecimila" - got the message, bootloader burned.
I disconnected the ISP pins, took the ATMEGA out of its socket on the UNO board and connected the serial pins.
Here comes the problem I cant figure out:
Once I have done a above procedure I can upload a sketch and Serial communication is working. But I can only upload it once! The second time (no matter if during the same power-up or at another time) I push the upload sketch button, I get no response for several minutes (I once waited up to 10min to confirm there is nothing coming anymore :)). If I unplug either USB or the TX/RX cables I get the error (or for the USB cable something similar):

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

When I upload the bootloader again I can once again upload a sketch same as before. Then the same problem happens again.
I checked several question on Stackexchange already (specially all points in this one here) and googled the problem, but until now I am not able to find a solution.
As you can imagine it is quite annoying to always unplug the RX/TX cable and hook up the ISP cable again and burn the bootloader.
So my question: What could cause this problem and how can I solve it?
Btw. I am using the Arduino software version I'm using is 1.6.9

Did you change the fuses? What bootloader did you use?

I didn't change any of the fuses. What do you mean, with "what" bootloader? Are there different ones? I burned the bootloader with the board set to "Arduino Duemilanove / Diecimila" in the Arduino 1.6.8 environment.

How is your serial connection wired up? It's missing from that schematic.

The 2 lines RX and TX just go to a 4pin pin header (for a cable with 4 wires, 5V, TX, RX, Gnd)

There is a problem with your circuit and the way you have it wired when programming. You have failed to use the RTS line for Serial programming. You need to have that line connected to the RESET of the ATMega328, this is as the bootloader for programming ove rserial will not start if the IC is not reset. Also you should burn the Arduino UNO bootloader rather than the one you chosen.
Seems you clarified you were using the diode as ESD protection, thank you. It is the recommended arrangement if you have a capacitor attached to the reset line in noisy environments.
The circuit between the RTS signal and the Arduino RESET pin needs to be this:
            C
 RTS >>----||------->> RESET(PIN1)
           0.1µF

From the same "Have I bricked my Arduino" that you linked, about 3/4 down Nicks post he mentions the use of serial programming of an Arduino
FTDI    Arduino Uno

GND       GND  (black wire on FTDI cable, blue jumper wire)
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
RTS       To RESET with a 0.1 µF capacitor in series with it (green wire)

What you can do if you don't have the proper serial programmer with an RTS output, you will have to manually reset the microcontroller to enter the bootloader just as the IDE says "Uploading...".

Doh, how did I miss this... Let me give it a try.

The diode is correct.
Please see this application note, its for ESD protection. http://www.atmel.com/Images/Atmel-2521-AVR-Hardware-Design-Considerations_ApplicationNote_AVR042.pdf
Also the Arduino boards are using it.
http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

@KarlKarlsom    I know its ESD protection but why. Have you got it in a ESD prone environment. I would possibly choose a diode then with a larger pulse current for the ESD protection.

sorry for the late reply and acceptance of your answer. I just now had the chance to test it! The missing reset connection solved the problem! However your suggestion using the UNO bootloader is not working. It says it burned the bootloader. But then I get a timeout when uploading a sketch. With Duemilanove selected as bootloader it is working!

Replying to an old post:  The Reset diode is not really ESD protection, it is there to shunt any high voltage spikes to Vcc to keep the chip from reacting to a high voltage and going into High Voltage programming mode, and then acting hung when there are further control signals to complete the sequence.


text:
Water measuring
After recent flooding of my apartment (pipe burst) I got an idea of automatic water flow watch. I would like to measure or just watch if water flows on main water intake. Arduino will know at what time of day (during nights and when nobody is home) the water flow is a problem and will send me an sms or whatever alarm. Measurement will be better to enable you to go to the bathroom, so the alarm will be raised only after certain amount of water.
The main problem is how to measure the water, are there any water-meter that can communicate with arduino?

Yes. Places like Seeed, Adafruit, etc all sell water flow meters.

This even tells you how: http://www.seeedstudio.com/wiki/G1/2_Water_Flow_sensor

I have an electronic water flow meter which uses a turbine wheel inside the pipe. Ostensibly there is a magnet on one or two or all four of the blades, which is read by a hall-effect sensor inside the meter. The specifications require 3 gallons per minute, which may be lower than you wish.
http://catalog.gpi.net/item/chemical-and-water-meters/01-series-electronic-digital-meters/01n31gm-nylon-water-meter?plpver=1001
If the flow rate is acceptable, you could add your own hall-effect sensor outside the pipe and connect an appropriately programmed Arduino to perform the tasks you require.
Alternatively, one could create via 3d modeling software an equivalent design to be printed by an online service or a friend with a printer. For balance purposes, a magnet in each vane would be advised.
Years ago, I had a speedometer for a kayak, about the size of one's thumb. It used the same technology, although the sensor was about two inches away on the upper side of the hull, while the tiny propeller was on the bottom. Apparently small magnets spinning create sufficient disturbances in the force to be read by mass produced sensors, even more than a decade ago.

The utility company probably already placed a meter at your apartment.
Mine has a spinning dial, that's half metal, half plastic. I've had a photo-reflective sensor attached to it that so I could detect the change in amount of light being reflected (metal vs plastic). Every peak meant one liter.
Mine also has a rotating magnet, but I wasn't able to read that using a hal-effect sensor, or the magnetometer on my phone.

Your post brings up an interesting thought. If the magnet in the utility meter could be read from "outside" the casing, it could also be slowed or otherwise affected, changing the rates charged for water use. I suspect the flow meter I posted is not authorized for utility use and less likely to be shielded.

@fred_dot_u There is probably some geared reductions going on. Also the water pressing against the turbine inside has quite some force. You have to apply a lot of force to slow it down. Doing so will probably not even have any effect, other than a reduced water pressure in the house, resulting in less water flowing out of the faucets. If you want free water, have look at the datasheet of your meter. Most meters have a reduced accuracy low flowrates. So having a dripping faucet fill a bucket, will probably not be measured by the meter.So at the end of the day, you'll have a bucket of free water

Other than the aforementioned end user type meter, I don't have a utility based one. I'm inclined to agree with your assessment.


text:
serial.write() five sensors and Processing
To all of this, hope to formulate the question right.
In my project I have 5 sensors connected to Arduino, which I want to interpret via Seria.write() --> Processing.
Arduino:
firstSens = 100 + (155 * digitalRead(8));
secondSens = analogRead(A1)/4;
thirdSens = analogRead(A2)/4;
fourthSens = humData;
fifthSens = tempData;
int sensData[6] = {firstSens, secondSens, thirdSens, fourthSens, fifthSens};

int i;
for (i = 0; i < 5; i = i + 1) {
  Serial.write(sensData[i]);
}

Processing:
serialInArray[serialCount] = inByte;
    serialCount++;

if (serialCount > 4 ) {
  firstSens = serialInArray[0];
  secondSens = serialInArray[1];
  thirdSens = serialInArray[2];
  fourthSens = serialInArray[3];
  fifthSens = serialInArray[4];

  // print the values (for debugging purposes only):
  println(firstSens + "\t" + secondSens + "\t" + thirdSens + "\t" + fourthSens + "\t" + fifthSens);

  // Send a capital A to request new sensor readings:
  myPort.write('A');
  // Reset serialCount:
  serialCount = 0;

My problem is that sensors find their place in Processing's array randomly, so for example arduino's firstSens could be Processing's secondSens or fifthSens
Why is this happening and how can I control it?

What is happening is you are just spewing out a list of numbers:
4132
132
1928
3240
1239
238
3048
391
... etc ...

There is nothing anywhere to say what anything is.
You need to add that kind of information. Either as a "start of data" tag before each block, or with each line.  For instance:
---START OF DATA---
4132
132
1928
3240
1239
---START OF DATA---
238
3048
391
... etc ...

Or:
0:4132
1:132
2:1928
3:3240
4:1239
0:238
1:3048
2:391

It is then up to your processing application to interpret the data and work out what is what.
Personally I like using the second method since it means you don't have to send all the data every time - you can send different values at different speeds of update and maintain a "current value" at the Processing end. For instance if you have one value that updates frequently and others that don't:
3:4132
1:132
3:1928
3:3240
3:1239
2:238
3:3048
0:391

You don't even have to use numbers, you could use words:
pressure:4132
temperature:132
pressure:1928
pressure:3240
pressure:1239
humidity:238
pressure:3048
rainfall:391

I have done similar code for our car project dash display
you're looking for something like this on your Arduino side:
  Serial.print("U*"); //A header
  Serial.print("A");  //a token to indicate the message payload
  Serial.print(avgRPM);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("B");  //a token to indicate the message payload
  Serial.print(avgVoltage);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("C");  //a token to indicate the message payload
  Serial.print(avgCurrent);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("D");  //a token to indicate the message payload
  Serial.print(avgThrottle);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("E");  //a token to indicate the message payload
  Serial.print(avgBrake);
  Serial.println("");

and something like this on processing side:
 if (port.available() > 0) {
    data = port.readStringUntil('\n');
  }
  String payload = "";
  if (data != ""){
    int offset = data.indexOf("U*"); //this is our Header (0x552A)
    if(offset>=0){
      payload = data.substring(offset+3, data.indexOf('\n'));
      switch(data.substring(offset+2, offset+3)){
        case "A":
          RPM = payload;
          break;
        case "B":
          voltage = payload;
          break;
        case "C":
          current = payload;
          break;
        case "D":
          throttle = payload;
          break;
        case "E":
          brake = payload;
          break;
        case "F":
          telemBits = payload;
          break;
        default:
          //packet not recognised
      }
    }
}


text:
I/O expander with i2c interface vs Multiplexer
I am wondering where are the difference in between using something like:
CD4067, which selects which pins to read/write from by "selecting" an address with 4 pins by writing to it. Versus the MCP23017 which uses the i2c interface.
I am trying to learn and build a simple application with lots of digital inputs and outputs, and need something that is fast at switching the pins and reading/writing to it.

The MCP23017 gives you 16 extra real IO pins. Each one has facilities such as pull-up resistors, change notification interrupts, etc - the kind of things that you expect from real IO pins. You can read and write to all of the pins.
A multiplexer though just feeds signals through to the existing pins. They're pretty dumb. Only the signal that is currently fed through can have anything done to it. So only one signal can have a value written on it or read from, and pullup resistors and interrupts are non-existent.
However the CD4067 can be used with signals other than digital - as such they are good at being a multiplexer to the analog inputs, something an IO expander can never do. You could, though, use an I2C ADC chip for that.
For high speed IO control you really want to be using the MCP23S17 instead of the MCP23017. It uses SPI instead of I2C and thus is much faster to control.


text:
Inheritance not working as expected
Short version: This is a lighting control project.  Some of the clases are Pin and  Channel. Channel contains a Pin.  Pin is a base class for DigitalOutPin and will be the base class for AnalogOutPin, and I want Channel to be able to use any child of Pin.
Pin has an abstract method setPinValue(), but when I create a DigitalOutPin object and call setPinValue(), Pin.setPinValue() gets called, not DigitalOutPin.setPinValue() and my program doesn't work because Pin.setPinValue() is empty as it's supposed to be overwritten.
Long version:
If I leave out the definition of Pin.setPinValue(), I get that most idiotic of error gcc messages, "undefined reference to `vtable for Pin'".  If I make it pure virtual I get several errors in the form of
In file included from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:9:0:
/devel/arduino/libraries/LightBrightLib/Channel.h:21:20: error: cannot declare parameter 'pin' to be of abstract type 'Pin'
     void begin(Pin pin, int channelNumber);
                ^
In file included from /devel/arduino/libraries/LightBrightLib/DigitalOutPin.h:10:0,
             from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:8:
/devel/arduino/libraries/LightBrightLib/Pin.h:16:7: note:   because the following virtual functions are pure within 'Pin':
 class Pin
   ^
/devel/arduino/libraries/LightBrightLib/Pin.h:33:18: note:  virtual void Pin::setPinValue(int)
     virtual void setPinValue(int value)=0;
              ^
In file included from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:9:0:
/devel/arduino/libraries/LightBrightLib/Channel.h:23:9: error: invalid abstract return type for member function 'Pin Channel::getPin()'
 Pin getPin();
     ^
In file included from /devel/arduino/libraries/LightBrightLib/DigitalOutPin.h:10:0,
             from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:8:
/devel/arduino/libraries/LightBrightLib/Pin.h:16:7: note:   since type 'Pin' has pure virtual functions
 class Pin
   ^

Full code is at GitHub but here are the relevant parts:
Pin is declared like this right now as pure virtual, but I've tried with and without =0
class Pin
{
  public:
   ...
  protected:
   ...
  // This method is child-specific. It's empty in this base class
  virtual void setPinValue(int value)=0;
};

DigitalOutPin is declared as
class DigitalOutPin : public Pin
{
  public:
    void on();
    void off();
  protected:
    void setPinValue(int value);
};

and defined as
void DigitalOutPin::setPinValue(int value) {
....
}

Disclaimer: I'm primarily a Java developer so C++ OO is very different for me, but as far as I can tell this should work as designed.
Thanks for any advice you can offer.

Your DigitalOutPin is protected - it should be public to match the base class definition and allow access outside the class.

Especially in embedded context, you might want to take advantage of final, which can enable the compiler to produce more efficient binary code: http://en.cppreference.com/w/cpp/language/final

From the same POV, if you can avoid having VMT and runtime lookup, it's definitely more efficient. One way to do that could be to turn is_a relationships into has_a ones.

@Majenko Sounds like that could be it! Originally I had another public method that called that one, and likely it broke then. I will try that tonight.

@IgorStoppa Very good suggestion. Thanks. Will chec out that link tonight.

@IgorStoppa WRT inheritance vs composition, I specifically want a Channel to hold any child of Pin, so that wouldn't work here, but good to know in other circumstances.  Thanks again.

@Majenko Actually rereading the code, I elided the protected: line when shortening the code above.  I just fixed that in the question.  It's protected in Pin and DigitalOutPin.  Sorry for leading you astray, but that's not the problem here.

I have taken your code from above and compiled it for a PC in Visual Studio.
When I create an object of type DigitalOutPin and call setPinValue() it calls the function I expect.  So this means either you have managed to find a bug in the gcc compiler, or there is something else in your code that is coming into play.  Can you try writing a VERY simple minimal test program that defines the Pin class and DigitalOutPin class (with just the setPinValue functions that print a string) and the setup and loop functions.  Just to see if you have found a gcc bug.
Even if this fixes the inheritance problem, you have other issues with you code because C++ is weird.  In Channel.h your Pin variables will need to be pointers, this will allow them to call the functions in the derived classes, not the base class functions.
I think you may get a performance improvement by using "const int& foo" for you parameters.  The const means the function can't change it, this allows the compiler to treat it differently and the "&" means use a reference to the variable rather than make a new copy of it.
Functions that don't change member variables within the code should also be declared constant.  "int FooBar(const int& value) const;"  It makes it clearer to the reader and the compiler probably does some funky stuff to improve performance.  (You might want to investigate "inline" if you are writing one line functions.)
Finally I'd recommend using constructors and destructors.  In release builds variables are not assigned a value.  If these variables are class members this means you don't know what they are to start with.  Also derived classes should initialise the base class, so:
// Class constructor for DigitalOutPin
DigitalOutPin::DigitalOutPin(const int& pinNumber)
  : Pin(pinNumber)  // Initialise the base class
  , m_State(false)  // Initialise all the class members (in order declared in .h file)
{
  // Lots of lovely code
}
// Class destructor for DigitalOutPin (Declared as virtual)
DigitalOutPin::~DigitalOutPin()
{}

Thank you Matt.  In doing more research I started to think the problem was that it wanted to instantiate Pin somewhere, and I came to the same conclusion that that Channel needed a *Pin not a Pin, and changed all the uses of it to dereference the pointer.  At that point it worked as expected.  I still need to make most of the parameters const references, but it's working now.  Thank you .

With respect to constructors and destructors, it's my understanding that constructors have very limited value in the Arduino world, and it's best to have a begin() method to initialize the object, because of the order things are initialized, what can happen in loop(), what can happen in setup(),...


text:
Bootloader sequence
If I got the picture right(correct me if I'm wrong) the standard bootloader senses the serial comm, and if nothing is read it passes control to the core program, which roughly corresponds to
int main(void) {
    init();
    setup();
    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
    return 0;
}

I wish to understand what happens when  (while the core program is running) I upload a new sketch (using the IDE or avrdude). I guess that the bootloader regains control when something is read in the serial comm, and this happens via a board reset (triggered somewhere inside serialEventRun).
If so, how does this flow interplay with the usage of the serial port? Assume I want to use avrdude to upload the sketch via USB, and also use the serial comm during the program execution.

Opening a serial connection will reset the board, and thus load the bootloader. Which board are we talking about?

Most computers begin execution at (or jump indirect through) location zero on startup. There may be variations, but this is the general idea. Whatever is put at location zero when the bootloader is installed causes the bootloader to gain control on a power-up or a reset. After that, it is up to the bootloader what happens next.
What usually happens is that the bootloader watches the serial port for the start of a "handshake" sequence; when (if) it sees what it is looking for, it replies in a manner that lets the loader program, e.g., avrdude, know that this is the bootloader replying and not some random text that was being sent just at that moment. (If the bootloader doesn't see the the handshake sequence begin within a short period, or it sees something other than the handshake, it starts the existing user program).
From there, the loader program and the bootloader cooperate to transfer the user program to the Arduino and load it into Flash memory at specified locations. Also transferred along with the user program is its starting address. When the upload is finished and verified, the bootloader transfers to the user program's starting address.
At this point, the user program owns the machine, including the serial port(s), and will continue to do so until another power-cycle or a reset. There is no need for the user program and the bootloader to negotiate use of the port; the bootloader owns it from reset to end-of-upload, and the user program owns it thereafter.
Update:

However at that point (while the user program is running) I can start
  an upload (from the IDE or avrdude).

This is possible only because avrdude can send a hardware signal (not contained in the data stream) that the Arduino board uses to cause the chip to reset. It is still the reset process that transfers control from the running program to the bootloader. As an example, on a number of my hand-built boards I did not include that auto-reset circuit. On those boards, avrdude cannot begin a new upload autonomously; I have to manually reset them when I start avrdude.

"At this point, the user program owns the machine, including the serial port(s), and will continue to do so until another power-cycle or a reset." However at that point (while the user program is running) I can start an upload (from the IDE or avrdude).

@leonbloy - only by doing something that resets the chip or convinces part of the running sketch to return control to the bootloader.  An example of the first would be toggling an flow control signal connected via a capacitor to the target MCU's reset.

It sounds like you're missing the fact that the Arduino IDE resets the Arduino board by toggling one of the comm port flow control signals. This causes a hardware reset on the Arduino board and then things happen as you've explained.