text:
Wiring BMP280 to Arduino Uno
I bought a BMP280 and it looks like this:

How can I connect BMP280 to Arduino Uno?
I tried the following examples on the web, but they didn't work.
I used  this library, connecting the PINS in this way:
VCC  ->  3.3V
GND  ->  GND
SCL  -> 13
SDA  -> 12
SDO  -> 11

But the sensor did not initialize.

Eventually as reported here, it worked using this pinout:
VCC --> 3.3V
GND --> GND
SCK --> A5
SDI --> A4

And this code:
#include <Wire.h>

#define BME280_ADDRESS 0x76
unsigned long int hum_raw,temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;
 int8_t  dig_H1;
 int16_t dig_H2;
 int8_t  dig_H3;
 int16_t dig_H4;
 int16_t dig_H5;
 int8_t  dig_H6;

void setup()
{
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t osrs_h = 1;             //Humidity oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off
    uint8_t spi3w_en = 0;           //3-wire SPI Disable

    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;
    uint8_t ctrl_hum_reg  = osrs_h;

    Serial.begin(9600);
    Wire.begin();

    writeReg(0xF2,ctrl_hum_reg);
    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();                    //
}

void loop()
{
    double temp_act = 0.0, press_act = 0.0,hum_act=0.0;
    signed long int temp_cal;
    unsigned long int press_cal,hum_cal;

    readData();

    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    hum_cal = calibration_H(hum_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    hum_act = (double)hum_cal / 1024.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.print(press_act);
    Serial.print(" hPa  HUM : ");
    Serial.print(hum_act);
    Serial.println(" %");

    delay(1000);
}
void readTrim()
{
    uint8_t data[32],i=0;                      // Fix 2014/04/06
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }

    Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
    Wire.write(0xA1);                          // Add 2014/04/06
    Wire.endTransmission();                    // Add 2014/04/06
    Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
    data[i] = Wire.read();                     // Add 2014/04/06
    i++;                                       // Add 2014/04/06

    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];
    dig_H1 = data[24];
    dig_H2 = (data[26]<< 8) | data[25];
    dig_H3 = data[27];
    dig_H4 = (data[28]<< 4) | (0x0F & data[29]);
    dig_H5 = (data[30] << 4) | ((data[29] >> 4) & 0x0F); // Fix 2014/04/06
    dig_H6 = data[31];                                   // Fix 2014/04/06
}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();
}

void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
    hum_raw  = (data[6] << 8) | data[7];
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}

unsigned long int calibration_H(signed long int adc_H)
{
    signed long int v_x1;

    v_x1 = (t_fine - ((signed long int)76800));
    v_x1 = (((((adc_H << 14) -(((signed long int)dig_H4) << 20) - (((signed long int)dig_H5) * v_x1)) +
              ((signed long int)16384)) >> 15) * (((((((v_x1 * ((signed long int)dig_H6)) >> 10) *
              (((v_x1 * ((signed long int)dig_H3)) >> 11) + ((signed long int) 32768))) >> 10) + (( signed long int)2097152)) *
              ((signed long int) dig_H2) + 8192) >> 14));
   v_x1 = (v_x1 - (((((v_x1 >> 15) * (v_x1 >> 15)) >> 7) * ((signed long int)dig_H1)) >> 4));
   v_x1 = (v_x1 < 0 ? 0 : v_x1);
   v_x1 = (v_x1 > 419430400 ? 419430400 : v_x1);
   return (unsigned long int)(v_x1 >> 12);
}

Actually, BMP280 doesn't monitor relative humidity so you can delete the part related to the humidity control.
#include <Wire.h>

#define BME280_ADDRESS 0x76
unsigned long int temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;

void setup()
{
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off
    uint8_t spi3w_en = 0;           //3-wire SPI Disable

    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;

    Serial.begin(9600);
    Wire.begin();

    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();                    //
}

void loop()
{
    double temp_act = 0.0, press_act = 0.0;
    signed long int temp_cal;
    unsigned long int press_cal;

    readData();

    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.println(press_act);
    delay(1000);
}
void readTrim()
{
    uint8_t data[32],i=0;                      // Fix 2014/04/06
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }

    Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
    Wire.write(0xA1);                          // Add 2014/04/06
    Wire.endTransmission();                    // Add 2014/04/06
    Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
    data[i] = Wire.read();                     // Add 2014/04/06
    i++;                                       // Add 2014/04/06

    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];

}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();
}

void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}

The BMP280 is a sensor that can be used at 3.3V, but not at 5V. The datasheet tells that the interface pins may be maximum 3.6V (when the sensor is powered with 3.3V). That means you may not connect the sensor to an Arduino Uno. Not to the SPI interface and not to the I2C interface. The sensor might already be damaged. This is not a joke. When sensor is still working, the results might be noisy or the values could drift too much.
The easiest solution is a level shifter module for I2C. Another option is to add two extra pullup resistors of 10k from SDA to 3.3V and from SCL to 3.3V and connect the SDA and SCL directly to the Arduino Uno. It will not be reliable, but with some luck it will work. You need some luck, because it will not be okay according to the datasheet of the ATmega328P.
You could also buy a 3.3V Arduino board (Arduino Due, Arduino Zero, Arduino M0, and so on), or buy a BMP280 module that is compatible with 3.3V and 5V signals: Adafruit BMP280

Thanks for the answer, but I am wiring it at 3.3 V so where is the problem?

I was talking about the signals of the SPI bus and I2C bus. Even the I2C bus is not fully compatible with a 3.3V sensor. The internal pullup resistors are enabled and the Arduino Uno requires 3.5V for a reliable high level at SDA and SCL according to the datasheet of the ATmega328P. The internal 50k pullup resistors together with the 10k pullup resistors on the module make a voltage at SDA and SCL of 3.58V. That is enough for a high level of the ATmega328P and it won't damage the sensor. But that is pure luck. It changes if you add something to the I2C bus.


text:
Square wave based on falling edge of alternative pulse of upcoming RPM square wave
In my recent project, I have RPM Square wave from vehicle. Now, based on that I want square wave based on falling edge but only alternative pulse of RPM square wave.
I think below image clear more properly.

Upper yellowish square wave which I need. And below pinkish square wave is RPM square wave.
I made a code for that and it's working fine but when RPM is stable. But when RPM change rapidly then it's not working fine.
const int kPinRPM = 3;        // RPM / Digital Pin 3
const int RPMInterrupt = 1;   // RPM's interrrupt pin
byte engineCylinders = 2;         // Engine cylinders = 4;
byte engineCycles = 4;            // Engine cycle = 2
int refreshInterval = 750;        // Milliseconds between sensor updates
unsigned long previousMillis = 0;
volatile int RPMpulses = 0;
int RPM, Final_RPM;

const int kPinInj = 12;

volatile uint32_t kInjTime = 0;

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

  pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
  attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

  pinMode(kPinInj, OUTPUT);
}

void loop()
{
  if(millis() - previousMillis > refreshInterval)
  {
    previousMillis = millis();
    RPM =  getRPM();
  }

  Serial.println(RPM);

  if((kInjTime > 0) && ((millis() - kInjTime) >= 10))
  {
    kInjTime = 0;
    digitalWrite(kPinInj, LOW);
  }
}

void countRPM()
{
  RPMpulses++;

  if(RPMpulses % 2 == 0)           // Skip alternative pulse
  {
    kInjTime = millis();
    digitalWrite(kPinInj, HIGH);
  }
}

int getRPM()
{
  Final_RPM = int(RPMpulses * (60000.0 / float(refreshInterval)) * engineCycles / engineCylinders / 2.0);
  RPMpulses = 0;
  Final_RPM = min(99999, Final_RPM);
}

After SUGGESTION, updating my codes. But it output waveform has some problem. In white circle, you can see that problem.

Rather than saying
if(RPMpulses % 2 == 0)           // Skip alternative pulse
  {
    kInjTime = millis();
    digitalWrite(kPinInj, HIGH);
  }

and later setting kPinInj in the main loop, you could act as follows:
digitalWrite(kPinInj, RPMpulses & 1); // Set or clear kPinInj
if(RPMpulses & 1)
  kInjTime = millis();  // Store alternate times

This would ensure that your trace 1 toggles properly.  If you want a shorter up-time on that trace, you could treat CHANGE interrupts rather than FALLING, and maintain RPMpulses as a number twice as big as now, ie use 120000 instead of 60000 in the RPM calculation, and could say:
digitalWrite(kPinInj, (RPMpulses & 3)==1); // Set or clear kPinInj
if((RPMpulses & 3)==1)
  kInjTime = millis();  // Store alternate fall times

Note, the floating point arithmetic in getRPM() is slow.  At a 750 ms refresh interval, that may not matter much.  But you probably can get good enough results rather more quickly using just integer arithmetic, if you parenthesize the expression somewhat as follows:
Final_RPM = ((RPMpulses * (60000UL / 2) * (engineCycles/engineCylinders)) / refreshInterval;

That is, do any remainderless divisions early; multiply all the remaining numerator terms together into a large number; then divide by the comparatively small refreshInterval, ending up with numerous significant digits without the use of floating point arithmetic, which takes many milliseconds on typical Arduino systems.
Edit 2: If your modified code still says RPMpulses = 0; within getRPM(), you may get a glitch at the end or beginning of each   refresh interval.  You may instead need to say RPMpulses = 1;, or RPMpulses &= 1;, or some such.  Also, to avoid an extra count when the latter expression is 1 instead of 0, say RPM0 = RPMpulses &= 1; and use (RPMpulses-RPM0) instead of RPMpulses in calculating Final_RPM.

Thank you. I tried out this code. But I faced some problem in Output waveform. I just posted out photo. Please see it.

@Hasan see edit 2

Ok, thank you. It is working fine now after your second suggestion. Of course, I do. Don't worry.

There are some things you shouldn't be doing within an interrupt service routine (ISR) like countRPM():

Don't call the millis() function. It depends on other interrupts which will be disabled during the execution of your ISR.
Don't call digitalWrite or any other functions
Don't use execution cycles hungry operators like % (modulo). To obtain modulo 2, just use a bit mask for the LSB.

What you should actually be doing within the ISR is just setting/resetting a flag or variable. Then, do all your stuff in the loop() function according the value of the flag or variable.

Calling millis() is OK. It won't increment inside the IRS, but it works fine in an use case like this.

As E.B. notes, calling millis() is ok – it doesn't need interrupts to report a result.   2. Although digitalWrite() is slow  – a couple of microseconds – it's ok to call it.  It's true that calling non-reentrant functions should be avoided.  3. Typically, compiler implements div or mod by any power of 2 by shifting or via bitwise AND with a mask; ie, while % may in general be "execution cycle hungry", %2 isn't.  That said, I'd use a mask as you suggest.

Hey, @jwpat7, I'm also E.B.! :)

source: Stack Exchange

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

sort: votes


text:
Arduino to read from RS232 converter to TTL serial module (updated)
Here's the system I want to work on:

The weight controller device detects weight which can transfer data via RS232 serial connection
I used RS232 converter to TTL serial module to connect the weight controller device to Arduino
The TTL connections were made to respective pins of Arduino UNO Board (GND-GND, VCC-5V, RX-0, TX-1)

The serial print from serial connection should produce 17 character length string : ST,GS    1.58,kg
Why am I getting strange results at times?
// Read Serial (RS232) data from Weight Controller Device via RS232 to TTL Converter Module

// Ignore the include statement, the editor does not allow pasting certain characters

include SoftwareSerial.h

int RX_PIN = 2;
int TX_PIN = 3;
int BAUD_IDE = 9600;
int BAUD_WEIGHT_SENSOR = 9600;

// serial port from weight controller
SoftwareSerial mySerial = SoftwareSerial(RX_PIN, TX_PIN);

void setup() {
  mySerial.begin(BAUD_WEIGHT_SENSOR);
  Serial.begin(BAUD_IDE);
}

void loop() {
  while (mySerial.available()) {
    int inChar = mySerial.read();
    if (inChar != '\n') {
      serialData += (char)inChar;
    }
    else {
      int dataSize = serialData.length();
      Serial.print(serialData);
      Serial.print(" length:  ");
      Serial.print(dataSize);
      Serial.print("\n");
      delay(3000);
      serialData = "";
    }
  }
  serialData = "";

}

// this one works perfectly but i want to store as string to
process
// information and use for other functions
/*void loop() {
if (mySerial.available()){
  Serial.print((char)mySerial.read());

I have got the same problem, if you have already had the answer please help me.
Thanks in advance

You need to disconnect the Arduino`s RX and TX pins from any device before trying to upload a sketch via USB, because the Serial data is directly wired from the USB chip to these pins. It's as if you're trying to flash the thing behind your RS232 adapter.

Yes, if they were trying to use the hardware UART, but they are not - the root problem is that they placed the peripheral and their software UART on the hardware UART pins rather than on distinct pins, creating an unnecessary conflict with operation as well as flashing.  Your suggestion will get the code uploaded, but not make it work (if they  do see output, it would be output directly from the converter, not through the sketch).

that worked, atleast i m getting some data now but it's not what i expected

You are attempting to talk to your peripheral via a second serial UART implemented in software on arbitrary pins, which should leave the hardware UART free for uploading and debug or other runtime communication between the Arduino and a PC.
However, the "arbitrary pins" you choose to use to connect the peripheral are the same pins as used by the hardware UART.
Move your peripheral to two other pins, for example
int RX_PIN = 2;
int TX_PIN = 3;

and move the connections accordingly
Also consider if you really want Serial.println() which will add a line break after every character in the output, and will also print the received characters as their numeric ASCII codes, one per line, rather than printing the characters themselves.  You probably want Serial.write().

I did as you said. However, the output is not what was desired.please see my latest comment

As I already said, serial.println() is not what you want.  However it looks like the problem is more than just line breaks.  As Serial.read() returns an integer, you are printing the ascii codes of your data rather than the data itself.  Apparently to fix that you want Serial.write()

fixed it, still have minor bugs, please check my revised post. is the current bug related to baud rate?

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

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


text:
Void value not ignored
Why does this throw the error: "void value not ignored as it ought to be
returning = printTemperature(returnLine);"
void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC == -127.00) {
    Serial.print("Error getting temperature");
     return 0;
  } else {
    return tempC;
  }
}

void loop(){

   delay(2000);
   feeding = printTemperature(feedLine);
   returning = printTemperature(returnLine);
    mySql;
    feeding = 0;
    returning = 0;
}

Both 'feeding' and 'returning' are declared as a float too.

Something about "void"

printTemperature() is declared void (i.e., nothing returned) but it contains a return statement, and you've attempted to assign the (void) value. You probably meant to declare the function as 'float'.

Ah yeah. I hacked this sketch together and was meant to change it but forgot. Sometimes you spent ages looking for you error but just don't see it while it was staring you in the eyes... Tanks!

First of all: In C/C++ world void means "empty" as in "no value".
As the method is declared void it is saying that it does not return a value.
But the code sets the value and also assigns the return value to a variable.
Logically that does not make sense.
In the old days a void method returned an int (I'm not sure whether that is still the case) but it has never been a good idea to make a value returning method a void returning method.
So technically in the old days it made sense but it still was "not a good idea"
Nowadays compilers will return an error when you return a value in a void method. This can be turned off by using the -fpermissive compiler directive.
This directive might be useful in some template cases. I advice not to use it.


text:
analogRead returning 0 constantly when connected to joystick
What reasons could there be for a joystick to return 0 when using analogRead?
X-pin is connected to AO and y-pin is connected to A1.
VCC is connected to 5V and GRND is connected to GRND.
By default (as in when not using the joystick) the value should be approximately 500, right? Well why is the value then 0? Can this only be a wiring issue?

What value do you get when you move the stick? Maybe 0 just means centre and then when the stick is moved you get -90 and +90 (or something like that)?

It doesn't go below 0 at any point, however it does increase by 2 or so when moved up/right

Moving just 2 sounds like electrical static and that the joystick is not working or not powered correctly. Have you set your arduino analog pins as INPUT?

thank you... I changed the wiring a bit and it worked :)

For a question like this you need to a) check your joystick out of circuit with an ohm meter and confirm the values that the pots are producing, and b) describe (ideally with a schematic) the exact circuit you're using. Note that as it stands this isn't a very good StackExchange question because it's unlikely to help anybody else. Going back and filling in the details might get you some upvotes.

Follow these steps to identify the problem.

Disconnect A0/A1 from Arduino and use a multimeter to check the voltage coming from the joystick X and Y. If it swings from 0 to 5V....the problem is in the Arduino. Check your code and connections. Maybe your wires are damaged?
If the voltage is not changing at X and Y pins, disconnect power from the joystick and use a multimeter to check the joystick potentiometer. Check all three terminals in each axis of the joystick. If R is the measured resistance between the two outer pins, then the resistance between the central pin and each of the outer pins should vary from 0 to R depending on the position of the joystick.
If there is no problem at all with the joystick readings by potentiometer then the problem has to be on the Arduino side.

Adding an answer after clarification:-
Moving the joystick also failed to produce a valid reading which indicated a wiring issue or incorrect configuration of the Analog pin in the Arduino code.
Proven to be a wiring problem


text:
How can I alter my program to read PWM signals from Arduino Mega?
I am new to programming and Arduinos but I've decided to give a go for a project. I'm after a code that will read PWM signals from a RC receiver (Specifically aileron and throttle) and output this as 4 PWM signals to drive two H Bridges (Right motor forward/reverse and left motor forward/reverse).
This is my code that isn't working.
unsigned long timer[3];
byte last_channel[2];
int throttle;
int aileron;

void setup() {
pinMode(8, OUTPUT);//Right motor fowards
pinMode(9, OUTPUT);//Right motor reverse
pinMode(10, OUTPUT);//left motor fowards
pinMode(11, OUTPUT);//left motor reverse

PCICR |= (1 << PCIE0);  //This enables pin change intterupt enabler

PCMSK0 |= (1 << PCINT0); // This tells the mask register
which pins will cause an intterupt (Pin 2)

PCMSK0 |= (1 << PCINT1); // (Pin 3)

Serial.begin(9600); //Sets the data rate in bits per second
}

void loop() {

}
ISR(PCINT0_vect) {

timer[0] = micros(); // registers intterupt time

//Throttle_Channel----------------------------------------------------------

if(last_channel[0] == 0 && PINB & B00000001 ) { // This checks if pin has
changed from low to high

last_channel[0] = 1;

timer[1] = timer[0];
}

else if(last_channel[0] == 1 && !(PINB & B00000001)){

last_channel[0] = 0;

throttle = timer[0] - timer[1]; //calculates the change in time and sets to

input[0]
//--------------------------------------------------------------------------
}
//Aileron_Channel-----------------------------------------------------------

if(last_channel[1] == 0 && PINB & B00000010 ) { // This checks if pin has

changed from low to high

last_channel[1] = 1;

timer[2] = timer[0];
}

else if(last_channel[0] == 1 && !(PINB & B00000010)){ //This checks if pin  has

changed from high to low

last_channel[1] = 0;

aileron = timer[0] - timer[2]; //calculates the change in time and sets to i

input[0]
//--------------------------------------------------------------------------
}

//Calculations to put output in correct form--------------------------------
int throttle_pwm = (throttle - 1500) / 1000;

int aileron_pwm = (aileron - 1500) / 1000;

int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;

int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;

int lm = v + (w/2) * 255;

int rm = v - (w/2) * 255;
//--------------------------------------------------------------------------

if (lm > 0 && rm > 0){

analogWrite(8,rm);

analogWrite(9,0);

analogWrite(10,lm);

analogWrite(11,0);
}

else if (lm > 0 && rm <= 0){

analogWrite(8,0);

analogWrite(9,abs(rm));

analogWrite(10,lm);

analogWrite(11,0);
}

else if (lm <= 0 && rm > 0){

analogWrite(8,rm);

analogWrite(9,0);

analogWrite(10,0);

analogWrite(11,abs(lm));

}

else if (lm <= 0 && rm <= 0){

analogWrite(8,0);

analogWrite(9,abs(rm));

analogWrite(10,0);

analogWrite(11,abs(lm));

//--------------------------------------------------------------------------
}
}

It compiles fine but I've tried measure PWM at the four output and it doesn't work. If anyone could offer advice or guidance it would be greatly appreciated.

It'd be really helpful if you could reformat your title ("What's wrong with my code" doesn't really tell us anything about the problem) and reformat the post so the code is easier to read. I believe four spaces on each line will format it in the "coding" format.

Thanks for the advice I've made the suggested layout edit. :)

If this is an RC controller, have you considered using a serial data protocol, like SPI over ZigBee? PWM signals are great for power control to analog devices, but when you have two microcontrollers communicating, a serial protocol would probably be better.

It looks like the code in the ISR is slow and it may compute incorrect results.
It is slow because of using floating point arithmetic in throttle_pwm and aileron_pwm calculations.  It may be so slow that the trailing edge of a PWM pulse occurs while the leading edge still is being processed.  This will delay trailing edge processing, and mis-measurement of pulse lengths.
The main thing to do to reduce the amount of code executed in the ISR is separate the input measuring phase from the output actuating phase.  You could compute pulse widths and store them in volatile variables for a loop in main to pick up and use in analogWrite() statements there.

Note, in 16-bit int arithmetic, the value of expression (t-1500)/1000 is 0 for 500 < t < 2500.   Because throttle and aileron are supposed to be RC pulse lengths in the range 1000 to 2000 μs, your  throttle_pwm and aileron_pwm will be zero.  That means you can replace the following code,
int throttle_pwm = (throttle - 1500) / 1000;
int aileron_pwm = (aileron - 1500) / 1000;
int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;
int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;
int lm = v + (w/2) * 255;
int rm = v - (w/2) * 255;

with this code:
int throttle_pwm=0, aileron_pwm=0, v=0, w=0, lm=0, rm=0;

which should save you several milliseconds of computation!  Also, having lm and rm as constant zeroes means that you don't need all those lengthy and laborious if and else blocks.   You can replace those 24 lines of stuff with just the following:
analogWrite(8,0);
analogWrite(9,0);
analogWrite(10,0);
analogWrite(11,0);

Slightly more seriously, it looks like you intended for your arithmetic like (throttle - 1500) / 1000, etc. to determine whether to raise or lower the throttle, etc.   Instead of doing that time-consuming division, just say:
int throttle_pwm = throttle > 1500 ? 1 : -1;  // or whatever values you meant to have
int aileron_pwm = aileron > 1500 ? 1 : -1;    // ditto

Instead of all those 24 lines of stuff, just say:
analogWrite(8,  (rm>0) * Level);
analogWrite(9,  (rm<=0)* Level);
analogWrite(10, (lm>0) * Level);
analogWrite(11, (lm<=0)* Level);

where Level is some level you want to set the control to.  Note, an expression like (rm>0) has a value 1 when it is true and and 0 when it is false.  So when rm>0, you have, in effect, analogWrite(8,Level); and analogWrite(9,0);.
If instead you end up with a calculation where lm and rm are actually usable PWM levels, ie numbers from 0 to 255, you could instead say:
analogWrite(8,   (rm>0) * rm);
analogWrite(9,  -(rm<=0)* rm);
analogWrite(10,  (lm>0) * lm);
analogWrite(11, -(lm<=0)* lm);

or could say:
analogWrite(8,  rm>0  ?  rm : 0);
analogWrite(9,  rm<=0 ? -rm : 0);
analogWrite(10, lm>0  ?  lm : 0);
analogWrite(11, lm<=0 ? -lm : 0);

Also see my answer to the question  Read RC receiver channels using Interrupt instead of PulseIn and see my answer to the question  Arduino read PWM duty cycle value with input (analog / digital).

See my page about interrupts. Data to be shared between an ISR and the main code should be declared volatile which yours isn't.

Also see:
https://www.arduino.cc/en/Reference/softwareSerial

Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

It's not really clear from your post which pins you are using for the encoder, but you mention pins 2 and 3:

PCMSK0 |= (1 << PCINT0); // (Pin 2)
PCMSK0 |= (1 << PCINT1); // (Pin 3)

Pins 2 and 3 on the board are not PCINT0 and PCINT1. Also they are not in the list of supported pin-change interrupt pins.
You might be better off using external interrupts (see my page above). External interrupts are supported on pin 2 and 3. However your code needs to change a bit.

If you are trying to read a PWM signal, you should try using the pulseIn function, which reads the length of a pulse signal.


text:
Connect Arduino Uno to video camera's web Server via Ethernet (not working)
I work with cameras in the film and TV industry. A project I have just started tinkering around with is building an Arduino Uno-based box that would automatically collect the metadata (settings, etc.) via the camera's built-in web server (over Ethernet, at least at the moment). Specifically the Arri Alexa camera.
Like I said, this camera already has a web server and the functionality built in for somebody to hook their computer directly up to the camera with an Ethernet cord (it actually uses an RJ45 - Lemo proprietary cable system in order to support some accessories that draw more power than RJ45 is capable of). Then when you navigate to the camera's IP address in a web browser it serves up a web page to you with all the camera settings and other things displayed.
I found that my test computer connected perfectly to the camera without fiddling with any network settings as the manufacturer's documentation seemed to indicate. Here are the basic network settings my computer had when connected directly to the camera over ethernet (no Arduino yet):

Notice the IP Address and subnet mask: 169.254.106.46 and 255.255.0.0 respectively.
Just to note, these are the manufacturer recommended settings I found in some literature:

Since that was working I tested the Arduino using the same settings. I am using an Arduino Uno combined with a Seeed Ethernet Shield (v2.0) which utilizes a Wiznet 5200 processor (not the 5100 normally used). Because of this you have to use the Ethernetv2_0 library that Seeed provides rather than the normal Ethernet library.
Here is my code, basically an adapted version of the WebClientRepeating example. I got this code working when I was just connecting to say arduino.cc and was going through the hub of my router (auto-assigned IP address). However when I attempt to connect to the camera with the Arduino sans Hub / Switch with a manually assigned IP address and subnet mask and all that I can never make the client (object) to connect. Basically this code is printing out "connection failed" to the serial monitor indicating and connection was never established.
#include <SPI.h>
#include <EthernetV2_0.h>

// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

// fill in an available IP address on your network here,
// for manual configuration:
//IPAddress ip(169, 254, 106, 46); //Address that worked on my computer
IPAddress ip(169, 254, 1, 2); //Manufacturer recommended address

// fill in your Domain Name Server address here:
IPAddress myDns(1, 1, 1, 1); //Random, not sure if I need to do anything specific here

// subnet mask that manufacturer recommends and what worked on my computer
IPAddress subnet(255, 255, 0, 0);

// initialize the library instance:
EthernetClient client;

//IPAddress server(64,131,82,241); //arduino.cc IPAddress
IPAddress server(169, 254, 184, 143); //Arri Alexa (Camera) IPAddress

unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

#define W5200_CS  10
#define SDCARD_CS 4

void setup() {
  // start serial port:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  pinMode(SDCARD_CS,OUTPUT);
  digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns, subnet);
  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
  // if ten seconds have passed since your last connection,
  // then connect again and send data:
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();
  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP GET request:
    client.println("GET /webremote/index.html HTTP/1.1");
    client.println("Host: 169.254.184.143");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();
    // note the time that the connection was made:
    lastConnectionTime = millis();
  } else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

I guess my question is, if I'm using the exact same network settings that worked for my computer connecting to the camera, why aren't they working for the Arduino? I know this is somewhat of an obscure situation but I'll appreciate any ideas you can give me. Thanks!

The code looks reasonable to me - no obvious goofs that I can spot. If you're at a loss, I'd suggest stripping out the SD card stuff and disconnecting the reader, just in case it's interfering, and also testing against a PC rather than the camera - you'll be able to see if the connection comes in at all, for example. If you use Linux, or possibly Mac, then nc or netcat is a really useful tool for debugging this sort of thing.

Please link to the specifications or at least product pages for the particular hardware you're using; having to search for that themselves can discourage people from answering your question.

For what it's worth, I did check the datasheet and confirmed that the chip supports Auto MDI-X, so it's not a case that you need a crossover cable. However, I'd suggest trying your connection through a switch anyway as at least you'll have some lights to see if one end or the other is not making an Ethernet-level connection.

I agree with Mark that your code all looks sensible, apart from the line defining myDNS. I have no experience of the board/library you are using, but recently I saw an industrial board suffer from a similar problem that turned out to be it was trying to resolve an IP address to a name using reverse DNS and because the DNS server wasn't set properly it failed to connect. So it might be that by setting the address in the myDNS line to a valid DNS server (the one your test PC uses?) then the problem will go away.
If that doesn't work then can you read the manual and see if the Client object can be persuaded to give you an error code or message that would give you a hint as to why it isn't working?
I understand that 169.254.1.2 is the manufacturer recommended address, but why did you use 169.254.106.49 for the test PC? It's very unlikely to be anything, but...
Also (I'm sure this was your first check), is the connection between the Arduino and the camera a straight connection, there are no firewall, routers, switches or bridges in the way doing NAT or PAT or blocking certain connections etc?
(DNS = Domain Name Service, converts names like google.com into meaningful addresses like 1.2.3.4)

In the spirit of "Use the Source, Luke," I've had a look at the code on GitHub, which is I hope the same code that you're using or very similar to it.
There the four-parameter version of Ethernet.begin() takes the gateway, not the subnet mask, as the fourth parameter. The subnet mask, when passed in explicitly, is the fifth parameter of the five-parameter version.
This shouldn't actually make any difference since the gateway ought not be used for anything on the same subnet, and the default subnet for class B addresses  (from 128.0.0.0 through 191.255.255.255), in which range your address falls, is 16 bits, 255.255.0.0.
The problem is, the code linked has what I would argue is a bug:
void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway)
{
  IPAddress subnet(255, 255, 255, 0);
  begin(mac_address, local_ip, dns_server, gateway, subnet);
}

The subnet mask is always set to 24 bits (255.255.255.0), in this call that you're using.
169.254.1.2 and 16.254.184.143 don't have the same 24-bit prefix, so the software (I assume, I've not followed it through) will try to contact the gateway you inadvertently supplied, which isn't even on the same network (not to mention nonexistent), and so fail.
Try calling the 5-argument Ethernet.begin() (passing in 0.0.0.0 for the gateway should be fine) and see if that fixes your problem.
I checked the WebClientRepeating example in that repo and they use the three-parameter version. Perhaps you switched to the four-parameter version, or perhaps you got your example from another library. (This example hasn't been modified since the start of the repo in April 2014.)


text:
DS18B20 - Temperature a bit off?
I'm trying to measure the temperature using a DS18B20 sensor. I'm using the DallasTemperature and OneWire Libraries. The sensor is connect in Pin 10 with a 4k7 resistor between VDD and DQ (actually I'm using 4x 1k and 2x 330 ohms) as so:

Here's the code I'm using:
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 10

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

float celsius;

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

  sensors.setResolution(12);

  sensors.begin();
}

void loop(void) {
  sensors.requestTemperatures();
  celsius = sensors.getTempCByIndex(0);

  Serial.println(celsius);
}

The sensor is outputing values close to the actual temperature (measure with a mercury thermometer), but a bit off.
Example:
Sensor Temperaute: 34.44°C
Thermometer Temperature: ~32°C

Why is that? And how can I fix it?

if the error is consistent (stable) you can just correct it in software, but it should be within 1/2 deg C; is your thermometer calibrated?

When the wires to the DS18B20 are short, you can use a 10k resistor as well.
The DS18B20 is accurate. If you have connected it wrong and it became very hot, then it might be damaged. But normally it is always accurate.
Many report that the DS18B20 returns a high temperature, and the cause is often something nearby that makes the DS18B20 warmer. For example an Arduino board (with a hot voltage regulator) or a computer screen or a certain air flow of warm air or even very dim sunlight. A normal thermometer does not do that, but the DS18B20 is highly influenced by warm things nearby.
Some temperature sensors have a problem with self-heating. You could add a delay of 5 seconds in the loop function, to see if that makes a difference.
To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water).
The picture uses pin 2 and the sketch uses pin 10. I assume that is a mistake.

Oh I see, maybe that's why, The sensor is in a protoboard in my desk, it has a bit of sunlight shining on it, should I cover the sensor? Doesn't it create the problem of airflow trapping hot air inside? I'll try the delay maybe that's why, I'm using no delay whatsoever.

Get it away from the sunlight, and, as mentioned, anything else that might be warm.

As long as the thermometer is measuring the same exact conditions as the sensor, you should be OK.  Put the bulb right against the sensor and wrap it in a rag or something.  Both would be measuring the temperature in the center of the rag.


text:
Serial LCD has like a "rolling shutter"
I've attached my LCD Display (AV1624YRB-SJ) to my Arduino Nano on the following pins:
#define LCD_RS 7
#define LCD_ENABLE 8
#define LCD_D4 9
#define LCD_D5 10
#define LCD_D6 11
#define LCD_D7 12
#define LCD_CONTRAST 6 //PWM Wave with capacitor for contrast

and im initializing it this way:
LiquidCrystal lcd(LCD_RS, LCD_ENABLE, LCD_D4, LCD_D5, LCD_D6, LCD_D7);

byte arrow[8] = {
    B00000, B00100, B00010, B11111, B00010, B00100, B00000,
};

void setup() {
  pinMode(LCD_CONTRAST, OUTPUT);
  pinMode(LCD_D4, OUTPUT);
  pinMode(LCD_D5, OUTPUT);
  pinMode(LCD_D6, OUTPUT);
  pinMode(LCD_D7, OUTPUT);
  analogWrite(LCD_CONTRAST, STARTCONTRAST); // Set LCD Contrast

  lcd.begin(16, 2);
  lcd.createChar(CHAR_ARROW, arrow);
  lcd.setCursor(3, 0);
  lcd.print("Welcome To");
  lcd.setCursor(1, 1);
  lcd.print("My Test");
  delay(2000);
}

The Problem is, that there is nothing to see on the display.
If i crank up the contrast slightly you can see something like a rolling shutter effect.
http://i.imgur.com/FOIEwVj.gif
The display worked just fine 3 days ago.
Where could be a mistake. I don't remember changing something, but i tried rewiring.

Your method of handling the contrast is unusual. Normal is a potentiometer as in this diagram http://codb.coocox.org/component/doc/coocox-master/1602IIC/bef8ac476249c994b8ac544091c7f424a33c0796/index.html

The Potentiometer just produces a given voltage. PWM plus Lowpassfilter equals a voltage too. This way i can adjust the contrast digitally.

I'd temporarily replace it with a pot to rule out that this is the problem. Also, try pressing down on the black border of the LCD. It could be a connection problem between the glass and the pcb of the display.

As I noted in a comment to the question  Arduino LCD is displaying gibberish, sometimes,  a PWM's sharp-cornered waveform might introduce a lot of noise into the LCD.  If you have to use PWM, you probably should put a good low-pass filter between PWM and LCD pin 3.
Check whether using a fixed voltage (from a voltage divider or pot) fixes the problem.  That fixed the problem in the case of the linked question.
If you need programmable control of contrast, and can't get PWM to work without heroic measures involving op-amp based filters, you could use a digital pot or a DAC.

The contrast works pretty fine. As stated my Display used to work and with an Encoder i could set the contrast digitally.
PS: I've added some imformation

If this is set up on a breadboard, maybe one of the wires is loose; try reinserting them.


text:
Photoresistor value drops when board stacked on Arduino Uno
I have a simple photoresistor displaying values on a serial monitor every second so I can establish a value that I want to use to have it activate a relay.
It has worked fine for a few weeks, with bright sunlight values about 1000, total dark is 0. I soldered only the headers on a protoshield, and stacked it on the Arduino. I have nothing else on the protoshield and I am still using jumper wires to a breadboard, which I have not changed.
Why would the photoresistor values drop to approximately 40 (from 900's) when I stack the second board on the Arduino?

It should not happen.
I have changed this answer, because at first I read that the resulting value was changed by -40, but I think it drops from 900 to 40.
The shield is doing something, so it is not empty. Perhaps it shortcuts the AREF to GND. Perhaps you are reading an open input, and the sensor is at another analog pin. Perhaps the shield does something to the voltage pins.
A breadboard can have bad contacts. The shield can have bad contacts.
Be sure that the sensor is connected to the channel that you are reading. Measure the voltage at that analog input with a multimeter with and without the shield. Check the 5V, 3.3V and AREF pins with and without the shield.

thanks.  i took off the shield and found out the readings did not change.  i completely redid the breadboard and fixed the issue.  what is weird, I even used a diagram from the sparkfun sik guide ( circuit 6) and ended up getting the inverse values (as it gets darker , the value goes up)   I reversed pos and negative leads from what the diagram shows and  got the right readings.  I put the shield back on hooked it up and the values are correct, so it was both on the breadboard, and following the diagram on that "how to do it" guide.

Does the proto-shield have any LEDs on it?
You were probably connected to a pin unknowingly.
How is resistance being measured? A voltage divider with an analogRead()?
Using a cheapo multimeter can cause problems.
Possibly, his proto-shield has some trace "wires" etched into it that were unseen, and he was connected to a floating pin or ground.
Or maybe the shield was shifted over one pin, and he wasn't connected to the pins he thought.

It says it only has headers on it, so it looks like the answer is no

Can you provide more information to your answer? How can the OP test your theory. How do you suggest it should be fixed?

How is resistance being measured? A voltage divider with an analogRead? Using a cheapo multimeter can cause problems. Possibly his proto-shield has some traces that were unseen, and was connected to a floating pin. Or maybe the shield was shifted over one pin, and he wasn't connected to the pins he thought. Gotta love troubleshooting :)

@Chris - you need to address your comment to someone, probably the OP, as otherwise no one will ever get notification that you are asking for clarification (and it may not be read by whoever you except to read it). In fact, it is better to post your comment under the original question, rather than your answer, as it looks as if you are asking yourself for this additional information, rather than asking the OP.

Also, if you are adding more information to your answer, then it is preferable to edit your answer and add the information there, as comments can be deleted at any time. Plus, it consolidates the information, and saves other people from having to wade through comments in order to get the full picture.

@Greenonline Thanks, I didn't realize I needed to notify. I was providing more information and giving possible things to test at the request of sa_leinad.  My rep is not high enough to post on the OP, or I would have commented there in the first place.


text:
unexpected change of ADC value with multiple voltage dividers (thermistors and pot)
So this is my basic circuit. Three voltage dividers: one 10k pot, 2 thermistors. Fan driver circuit using TIP120 (currently just driving an LED from the 3.3v source). Board is a Leonardo clone, circuits.io only had the Uno in their library. Edit: circuit is now more simplified.
Schematic:

reality:

When I adjust the pot, the ADC value of airPinValue changes, regardless of which analog input it is connected to. meatPinValue does not change. Swapping the inputs that airTempPin and meatTempPin are assigned to has no effect, airTempPin changes the same. Physically swapping the thermistors has no effect, nor does switching which input they connect to.
Code:
#define potPin A0
#define airTempPin A5

int potValue = 0;
int airPinValue = 0;
int i = 0;

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

void loop() {
  i++;
  potValue = analogRead(potPin);
  airPinValue = analogRead(airTempPin);
  if (i == 2000) {
    Serial.print(potValue);
    Serial.print(",");
    Serial.println(airPinValue);
    i = 0;
  }
}

EDIT: much simplified code
EDIT v2.0 : I have now swapped out the board for an official Uno, as well as swapped everything to a different breadboard and a different Leonardo, with no change in behavior.
EDIT v3 : Corrected code sample. I have also dropped my DMM onto this, reading from the 5v rail to the voltage going to A2. With the pot set to 0 I see 2.401v from the divider, pot to max, same voltage, 2.401v.
EDIT v4: with only the pot and airTemp hooked up, still happens. Further DMM probing actually shows that this only happens when the pot and thermistor are both hooked up to the arduino. If either one is disconnected, the voltage being read by airTempPin is stable/correct. Once both are hooked up to the analog pins on the arduino, that's when the voltage at airTempPin goes off...
Also update diagram, pic, and code to match what I'm currently testing with.
EDIT v5 : This is some sort of analog bleed between the analog input ports. Not really sure how I can combat this :\

if pin A1 is left floating like the schematic and used like in the code, any noise will alter it's value. Use A2 in code and it should work.

sorry, that was a copy/pasta problem. As stated in in the question, I've tried using different analog pins to see if the behavior was the same, and it doesn't change when reading from A0 or A2 (and move the physical connection to that pin too)

What do they change to?  Can you swap a pot for airPinThermistor?  maybe simplify the println(String()+String()+...) into separate lines without the string concatenation magic?

Also, did you try swapping the order of analogRead()s? If it is a sample-hold problem from the prior read, this might help identify it.  You could jumper A5 to GND or +5, and intersperse a analogRead(A5) too.

0,459,484
457,482,484
1023,515,484``` - oh, apparently can't have linebreaks in comments. This is a small sample showing the values of the pins

oh, that sample was without the String conversion and concatenation, I'll update the code sample

take a look at Edit v4

Moral of the story, the multiplexer was not switching between inputs quickly enough causing the odd reading, looking very much like bleed between the pins. By simply reading each analog input twice and only storing the value of the second reading, I was able to get a valid, stable, reading as expected.
#define potPin A4
#define airTempPin A0

int potValue = 0;
int airPinValue = 0;
int i = 0;

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

void loop() {
  i++;
  analogRead(potPin);
  potValue = analogRead(potPin);
  analogRead(airTempPin);
  airPinValue = analogRead(airTempPin);
  delay(10);
  if (i == 50) {
    Serial.print(potValue);
    Serial.print(",");
    Serial.println(airPinValue);
    i = 0;
  }
}

How resistive are your thermistors?  I think I saw if they were on the order of 10K, they can switch pretty fast, but if lots higher, it takes more time to slew.  Maybe adding a cap to buffer/hold the thermistor signal would be good too.

They're 220k-ish, and pretty slow to change (might update to RTDs in the future, but these work for now). My supply of caps is a bit low right now, got an order of a bunch from China arriving next week.

5V/220k=22uA, which isn't a lot to fill up the sampling capacitor (14pF on the ATMega32u4 I'm used to).  The https://www.embeddedrelated.com/showarticle/110.php recommends a cap of about 1000x the sampling capacitor, or 14nF or so.

Good to know. Would I just drop that between the return leg from my thermistor and the analog pin, or parallel with the 220k resistor to ground?

R1 is a 220K? Put the hold cap between the R1 +Rtherm junction and GND.   It will charge all the time, and only discharge into the ADC sampling cap when sampled.

#define meatTempPin A0
#define airTempPin A1

Your code says A0,A1 but the circuit and picture of the wires say A0,A2.
Since A1 doesn't appear to be connected, as you scan things, the ADC could be sampling and holding some voltage from the prior conversion of potPin.
Try this instead:
#define meatTempPin A0
#define airTempPin A2

beat me by 5 secs, good work!

sorry, that was a copy/pasta problem. As stated in in the question, I've tried using different analog pins to see if the behavior was the same, and it doesn't change when reading from A0 or A2 (and move the physical connection to that pin too)

This is sort of a common problem with open-circuited analog inputs.  When you are doing your swapping of wires and pins, could one of the jumpers or one of the breadboard connections be open-circuit?

https://www.arduino.cc/en/main/arduinoBoardUno

Vin. The input voltage to the Arduino/Genuino board when it's using an
  external power source (as opposed to 5 volts from the USB connection
  or other regulated power source). You can supply voltage through this
  pin, or, if supplying voltage via the power jack, access it through
  this pin.

Thisi not to be used as powersource for motor/LED whatever, this is input.
Use 5V instead, maybe this would solve the problem.

or, if supplying voltage via the power jack, access it through this pin.

Aside from that, even with it disconnected, the behavior is the same.

You need to have a reference voltage for ADC the problem is that you are not setting the reference voltage for ADC.Change the code in setup where you add a analog reference voltage as internal or default according to your requirement.

This is kind of a vague answer. Please consider editing it to add some example code to demonstrate exactly what you're talking about.


text:
Calculate the time since arduino started working for a year
I want Calculate the time since arduino started working for a period of one year using arduino uno and when the period is over flip a light on

I'd use an RTC, as you only need one power outage for the system to fail (without an RTC).

Simplest solution would be to use millis(), but you will need to
somehow take care of the periodic rollover. Creating a lower frequency
software timer, as explained by Jot, is one solution. Another option is
to extend millis() to 64 bits:
uint64_t millis64()
{
    static uint32_t low32, high32;
    uint32_t new_low32 = millis();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

You must call this function at least once every 49.7 days, otherwise it
will loose time. I would just call it on every loop iteration, like
this:
const uint64_t ONE_YEAR = 365.25 * 86.4e6;  // Julian year

void loop()
{
    if (millis64() >= ONE_YEAR) {
        // do some stuff...
    }
}

Besides the issue of a possible power failure, there is another caveat:
the Arduino Uno is clocked off a ceramic resonator. These are not very
accurate, and are typically specified to be within 0.5% of their nominal
frequency. This means that your “year” can be off by as much as
1.8 days. RTCs are clocked off a quartz crystal and are then far
more accurate. Ultimate accuracy could be achieved with a GPS receiver.

The function millis counts up to about 50 days. However, you can make a software timer with millis of, for example, 1Hz. With a unsigned long that counts the seconds, it is easy to count a year.
It will not be reliable. When the power is off, it starts again. A RTC (Real Time Clock) with its own battery is better.
Are you a good software engineer ? How can you be sure that it will work ?

I would use a network card to talk to an NTP server. In setup(), fetch the time and save it to EEPROM if there's not one already saved. You can then ping the NTP server every day or every boot, comparing the saved date and responding as appropriate. This strategy avoids MCU timer slew, power-out milis() resets, and extra hardware (other than networking, which more and more projects have already anyway).


text:
Motor running during Motor Shield R3 reset
I have a problem with the Arduino Motor Shield R3 on an Arduino Uno. I Have a DC Motor on the A Channel and the Shield is connected to an external power source. When I reset the Arduino card the motor starts running by default until the pins are initialized.
This is really problematic for me because the motor is on a rail delimited by 2 switches, when a switch is reached the motor stops. When the motor moves during reset the value of the switches are not read yet, which causes the motor to go beyond the switch and be blocked afterwards.
When I reset the card I read the value of the 3 digital pins used to drive the motor :

pin 12 : Direction (DirA), HIGH motor foward, LOW motor running backward
pin 3 : Power (PwmA), HIGH motor running, LOW motor not running
pin 9 : Brake (BrakeA), HIGH brake is on, motor can't run, LOW brake is off, motor can run

Before reseting I put the 3 pins at HIGH, At reset, pin 12 == HIGH, pin 9 == LOW, pin 3 == HIGH
which means that the brake is disengaged but the Power is still here, so the motor starts running again until the pinMode function is reached. During that reset time of approximately 2 seconds, the motor has the time to go beyond the switches which causes the system to break.
Is this normal ? Is there a way to force the pin 3 to be at LOW when the Arduino resets ? I put my code at the bottom.
Naïve solution : is to put PwmA at LOW when a switch is reached, so I'm sure it will stay that way until the next reset. But if the arduino is reseted while the motor is running I still have the problem.
int closeSwitch = A3;
int openSwitch = A2;
int DirA = 12;
int PwmA = 3;
int BrakeA = 9;

int OpeningDirection = LOW;
int ClosingDirection = HIGH;

bool motorRunning = false;
bool motorOpening = false;
bool openSwitchReached = false;
bool closeSwitchReached = false;

void setup() {

  Serial.begin(9600);

  sendToPC("Init\n"); //This is just to read the init state of the pins
  Serial.print(digitalRead(DirA));
  Serial.print(digitalRead(BrakeA));
  Serial.print(digitalRead(PwmA));

  pinMode(openSwitch, INPUT);//is High when Hublot opened
  pinMode(closeSwitch, INPUT); //is HIGH when hublot closed
  pinMode(DirA, OUTPUT); //Initiates Motor Channel A pin
  pinMode(BrakeA, OUTPUT); //Initiates Brake Channel A pin
  pinMode(PwmA, OUTPUT); //Initiates Brake Channel A pin

  sendToPC("\nAfter\nA:"); //After init all is LOW
  Serial.print(digitalRead(DirA));
  Serial.print(digitalRead(BrakeA));
  Serial.print(digitalRead(PwmA));

  //Stopping the motor
  setMotorSpeed(0);
  if (digitalRead(BrakeA) == LOW) {
    brakeMotor();
  }

  //Is the first switch on
  openSwitchReached = (digitalRead(openSwitch) == HIGH);
  //Second switch state
  closeSwitchReached = (digitalRead(closeSwitch) == HIGH);

  handleSerialInput(-3); //Send ping return
  handleSerialInput(-2); //Send status
}

void sendToPC(const char * str) {
  Serial.write(str);
  delay(215); //Delay to avoid answers being read as one
}

void setMotorSpeed(int speed) {
  if (speed > 0)
    digitalWrite(BrakeA, LOW);   //Disengage the Brake for Channel A
  digitalWrite(PwmA, HIGH);   //Spins the motor on Channel A at full speed
}

void setMotorDirection(int direction) {
  digitalWrite(DirA, direction); //Establishes direction of Channel A
}

void brakeMotor() {
  digitalWrite(BrakeA, HIGH);
  //digitalWrite(PwmA, LOW); -> this is my naïve solution
}

void handleSerialInput(int input) {
  Serial.print(input);
  if (input == 1 && !openSwitchReached) { //open
    brakeMotor(); // stop motor
    delay(100);
    setMotorDirection(OpeningDirection);
    setMotorSpeed(255); // set motor max speed
    motorRunning = true;
    motorOpening = true;
    sendToPC("HublotOpening");
  }
  else if (input == 2 && !closeSwitchReached) { //close
    brakeMotor(); // stop motor
    delay(100);
    setMotorDirection(ClosingDirection);
    setMotorSpeed(255); // set motor max speed
    motorRunning = true;
    motorOpening = false;
    sendToPC("HublotClosing");
  }
  else if (input == -2) { //get status
    if (openSwitchReached)
      sendToPC("HublotOpened");
    else if (closeSwitchReached)
      sendToPC("HublotClosed");
    else if (motorRunning && motorOpening)
      sendToPC("HublotOpening");
    else if (motorRunning && !motorOpening)
      sendToPC("HublotClosing");
    else if (!motorRunning)
      sendToPC("HublotNotMoving");
  }
  else if (input == -3) //Ping
    sendToPC("ArduinoHublot");
  else if (input == 0) { //Stop
    brakeMotor(); // set motor max speed
    motorRunning = false;
  }
  else {
    sendToPC("WTF");
    Serial.print(input);
  }
}

void loop() {

  openSwitchReached = (digitalRead(openSwitch) == HIGH);
  closeSwitchReached = (digitalRead(closeSwitch) == HIGH);

  if (openSwitchReached && motorRunning && motorOpening) {
    sendToPC("HublotOpened");
    brakeMotor();
    motorRunning = false;
    delay(200);
  }
  else if (closeSwitchReached && motorRunning && !motorOpening) {
    sendToPC("HublotClosed");
    brakeMotor();
    motorRunning = false;
  }

  if (Serial.available()) {
    int read = (Serial.readStringUntil(':')).toInt();
    handleSerialInput(read);
  }

}

Add pulldown resistors (10KΩ) to any pins you want to force to be low at reset.
(Quite frankly I'm amazed they don't exist on all inputs to the board by default - it seems a bit of a fatal omission).

According to this that's what they done for BrakeA, I will try it. Thanks for the answer.


text:
How do I make specific tones with a piezo buzzer?
I am using a piezo buzzer and fiddling around with it a little bit. I currently have different tones with delays in between and I have to do a lot of trial and error for the piezo buzzer to play sounds like I want it to. Is there a better way to do this? because at this rate I will be stuck for a while.
I am trying to get the piezo buzzer to make the sound of an alarm. Any suggestion on how I can get it to sound exactly like an alarm or is trial and error the only way?

Posting your current code, might help us to better understand what it is you want to achieve (better).

are you using an active or passive buzzer? (they need different code)

It's very hard to know from your question what you are having trouble with.  I have a piano and I can hit the keys, but it takes me a long time to hit them in the right order and with the right timings to create a new symphony.
Anyway, if creating the sounds is the problem, have you looked at the Tone library?
Different alarms have different sounds.  I once heard an alarm which sounded like the start of Fuer Elise, so probably the notes were E and D#.  That would make their frequencies about 330Hz and 311Hz:
void loop()
{
    tone(pin, 330, 250);
    delay(300);
    tone(pin, 311, 250);
    delay(300);
}

The sound you linked to sounds to me like it starts on a C, and slides up gradually one octave.  One octave higher is double the frequency, so this code should do that:
void loop()
{
    const int startFreq = 523;  // C5 is 523Hz

    // Start at the given freqency, and increase gradually by
    // one octave (double the frequency)
    for (int freq=startFreq ; freq<= (startFreq*2) ; ++freq)
    {
        tone(pin, freq, 10);
        delay(3);
    }
}

Like I said I want to make the piezo buzzer implement an alarm. However, I need to have right tones. I have to find this right tone, and its hard for me to get there. maybe there is an easier way to implement the type of sound you are wanting to produce. Does this make it more clear?

What is the pin? because its not declared in the scope?

It's the pin number that you have the buzzer on. You could find that out by reading the links in my post, and you would learn much more than by copying and pasting code you don't understand.

A specific alarm I was looking for was like a fire alarm

https://www.youtube.com/watch?v=lo4yJbjkMWA like this one

That sounds to me like it's starting on a C and sliding up one octave. See if you can write code to do that. If you can't, I'll do it tomorrow when I'm on a proper computer. Do you have the tone library working and generating sounds?

Yes I do have the tone library. Thank you very much I'll let you know if I get it done

Nah mate, tried to get there today (was close) but I was still doing the same trial and error. If you can help me out, that'd be great thanks.

hmm..I don't know why but the piezo makes no sound. Maybe if I put the code and the circuir in the post, you might see why?

You can see for yourself https://circuits.io/circuits/4202932-the-unnamed-circuit/edit

Does it make no sound ever, or only with my code?  Please include in your question example code, using the tone library, with which it makes some sound, because I don't know what I'm debugging here.

Well for my particular code (which I have provided you the circuit and the code) I have not used the tone libraby. Why is it that the library must be included. I have used the piezo before with other projects which made sound just fine... I think its the problem with the for loop, because I removed it and kept the other lines and it produced sound, still not the way I wanted it to sound like :/.

It's alright. I don't want to be nagging. This is not a homework site so i'll just let it pass. Thanks for all that you could offer.


text:
door protector using arduino uno and GSM sim800 module
Please check the arduino program given below and help me to find out error. The program is for following hardware. GSM 800 module Arduino Uno board Limit switch(2)
We place two limit switch at main door & back door as main door is open the message will be send that is Main door is open & when it closed it will send message Main door is closed. This is same for Back door also.
We run this program & it run but it sends the massage repeatedly after some time. Please help me to find out error..
    const int Main = 7;
    const int Store = 8;
    const int Main_led =  13;
    const int Store_led =  14;
    bool i = false;
    bool j = false;
    bool k = false;
    bool l = false;
    int buttonState1 = 0;
    int buttonState2 = 0;
    void setup() {

      Serial.begin(9600);
      pinMode(Main_led, OUTPUT);
      pinMode(Store_led, OUTPUT);
      pinMode(Main, INPUT);
      pinMode(Store, INPUT);
    }

    void loop() {
      buttonState1 = digitalRead(Main);
      if (buttonState1 == HIGH && i == false ) {
        digitalWrite(Main_led, HIGH);
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print("Main Door is closed");
        Serial.write(0x1A);
        delay(5000);
        i = true;
        j = false;
      }
      else
      { if (buttonState1 == LOW && j == false )

        { digitalWrite(Main_led, LOW);
          Serial.println("OK");
          delay(1000);
          Serial.print("AT+CMGF=1\r\n");
          delay(500);
          Serial.print("AT+CMGS=\"");
          Serial.print("+91---------------");
          Serial.print("\"\r\n");
          delay(5000);
          Serial.print("Main Door is open");
          Serial.write(0x1A);
          delay(5000);
          i = false;
          j = true;
        }
      }

      buttonState2 = digitalRead(Store);
      if (buttonState2 == HIGH && k == false) {

        digitalWrite(Store_led, HIGH);
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print("Store room is Closed");
        Serial.write(0x1A);
        delay(5000);
        k = true;
        l = false;
      }
      else
      { if (buttonState2 == LOW && l == false)
        {
          digitalWrite(Store_led, LOW);
          Serial.println("OK");
          delay(1000);
          Serial.print("AT+CMGF=1\r\n");
          delay(500);
          Serial.print("AT+CMGS=\"");
          Serial.print("+91------------------");
          Serial.print("\"\r\n");
          delay(5000);
          Serial.print("Store room is Open");
          Serial.write(0x1A);
          delay(5000);
          k = false;
          l = true;
        }
      }
    }

To avoid duplication of effort here's a link the exact same question posted on the electronics site: http://electronics.stackexchange.com/questions/290062/door-protector-arduino-program

what if the door is open less than 11.5 seconds?

@dandavis  message does not repeated .


text:
How to use a 4-pin ultrasonic sensor as a 3-pin ping sensor?
const int pingPin = A0;

void loop() {
  long duration, inches, cm;
  pinMode(pingpin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}

How to change this code for a 4-pin ultrasonic sensor?

Its not possible to answer this question.  What sensors have you got (model numbers and names)?

Also why are you setting up the pin assignments in the loop() normally they would go in the setup function.

@Matt: the pin mode is dynamic to recycle the same pin for pinging and listening.

if you want to use that code, short the 2 pins in question.

The four pin Echo))) module is basically the same as three pin ones, except for triggering is done by another pin. So you don't have to care about setting pin to the output mode and switching it back to the input mode after the trigger pulse. You can read about it for example here.
const int8_t pingPin = A0;
const int8_t trigPin = A1;

void setup()
{
  pinMode(pingPin, INPUT);
  pinMode(trigPin, OUTPUT);
}

void loop()
{
  // pulse on trigger pin:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // 10us is minimum trigger pulse duration
  digitalWrite(trigPin, LOW);

  // measure HIGH pulse duration:
  long duration = pulseIn(pingPin, HIGH);

  // and rest of the code:
  long   inches = microsecondsToInches(duration);
  long       cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}


text:
Arduino Mega external interrupts fire randomly
I'm trying to solve a nagging issue with external interrupts - this is for a slot car track lap count controller. It uses the Mega's 6 external interrupt lines connected to photo diodes. The HW itself works fine - yes, trust me, it's fantastic.
I have observed the following. The code in the loop() is surrounded with:
detachAllInterrupts();
delay(10);
...
... process any interrupts and/or button presses
...
delay(10);
attachAllInterrupts();

If I omit or reduce the delay amount the random firing gets worse.
The ISR is lean and mean:
void lapDetected1() {
  lane1.lapDetected();
}

calling the method of class Lane:
    void lapDetected() { // called by ISR, short and sweet
      now = millis();
      if ((now - finish) < laneProtectionTime) {
        return;
      }
      start = finish;
      finish = now;
      count++;
      reported = false;
    }

all the variables used are declared volatile.
I don't like to use delay and I'm seeking advice on how to correctly implement ISRs and their handling.
here's the link to the entire code on GitHub: https://github.com/gabe2001/PCLapCounterWithArduino/
Thanks for any advice I can get here!
-gabe

Not related with your problem - but it'd be way shorter with arrays and for each loops. Like for (auto & lane : lanes) lane.reset(); and so on...

Wow. You will need to provide something more. When I opened the github space, I only found some hardware diagram of the wiring. Therefore. Please provide the full code here in Stacktrace, or, in a form where I would not have to sit and guess where you have stuffed the code :-)... I am very experienced in interrupt softwares and such stuff, so I guess that I can help you if you provide me with the complete code you have and explain why it is like it is. FIRST of all, I would guess that you have hardware noise. You could decouple that one nicely, however, you would then first have to provide a d

Continuing David's comment: `iagram for me, not a hardwire-picture like the one on GITHUB. We electronic engineers use diagrams and then I can tell you what you may have to do, to avoid hardware noise.
Untied inputs can produce noise in certain environments. If that is not the case, we will look into other possibilities - but then you will have to provide the entire code block.`

If you are IN DOUBT of if the input produces noise, then again - give me the diagram, then I will go through your wiring to reveal if there are places which are actually prone to making noise. IF we are in doubt then we can actually probe into it, but that would require that we build some more electronics on to the construction.

first - many many thanks for your reactions!
second - apologies for the delay (and counting...) - I will provide more details the coming months.
What I can say now is this: it's most likely an environmental issue. After the guys grounded most of the track the stray interrupts have become less. The more people are in the room, the more likely we see stray interrupts. The track is surrounded by a synthetic curtain to hide the posts and other stuff under the track. The floor is covered with carpet tiles. The combination is a perfect source for static charges all around.
more to come...

Now, you write the following:
detachAllInterrupts();
delay(10);
...
... process any interrupts and/or button presses
...
delay(10);
attachAllInterrupts();

I understand that you put this stuff into the loop, such that the loop in effect looks like this:
void loop() {
    detachAllInterrupts();
    delay(10);
    ...
    ... process any interrupts and/or button presses
    ...
    delay(10);
    attachAllInterrupts();
}

Assuming that the above is correct, then you will be enabling and disabling your interrupts in one long stream. You would often NOT disable your interrupts, because you don't know when the are available or not, then.
You should typically ENABLE the interrupts in the startup code, and then in the loop() you can have any Other processing you want, but not any processing referring to the interrupt processing.
The interrupt processing would take care of the button pressed etc. So - in the lane.lapdetected1() algorithm, you would take care of reading buttons pressed etc., and, you would have to attach the interrupt itself directly to your algorithm. I cannot see that you have told that when an interrupt has been happening, then the code execution goes to the ISR lane.lapdetected1() algorithm?
What you would want to do, is to setup an interrupt in the setup(), which is run once upon start of the program in the arduino, and then, providing that you want the interrupt on pin 2 (external pin), and the algorithm to run while you receive falling signals on the pin 2 is lapdetected1, then you could use the following:
void setup() {
  attachInterrupt(digitalPinToInterrupt(2), lapdetected1, FALLING);
}

Thereby you would remove the detachAllInterrupts(), and all the way down to attachAllInterrupts() from the loop construction and thereby you would be able now to process interrupts within the lapdetected1-algorithm and run what ever you would want to run, normally, from within the loop-construction.

The code in the loop() is surrounded with:

it doesn't make much sense for you to "process the interrupts" in the loop(). Use ISR instead.


text:
I have a diagram of my Arduino circuit. How do get it ready for PCB manufacture?
For my engineering class, I am building a digital scale. My team has assembled the prototype out of:

Arduino Uno
Hx711 amplifier module
1 kg load cell
2 push buttons
A 4 digit 7-segment display module we found online, but we don't know its specific name
HC-05 Bluetooth module, no specific manufacturer
Lilypad switch CR2032 battery module
DC-DC step up to 5V boost converter module

Our prototype works. Well, sort of (we're still trying to work out the boost converter and c2032 to work). We have diagrammed how each module connects to each other on a piece of paper. However, we want to properly diagram this in a way so we can create a PCB for it.
I have tried the Eagle and Fritzing programs. I am very inexperienced with them. I am not able to find the HC-05 and LED display .sch or .fzz files online for this, so I have came to a halt. I am not sure how each of these modules are actually wired together either.
What can I do next?

I'm a bit unclear what your question is. If your prototype works, can you not look at it to find how it's wired together?  There are many good tutorials on Eagle.  Don't bother with Fritzing - it seems easy at first, but you'll hit its limitations very quickly.

Thank you.  I'm lost as to what to do next, as no one in my school knows about PCB manufacture.

As I wrote there ^^, I don't understand what you're asking for help with. Could you clarify please?  Removing all information from your question which is not directly relevant to the question would be a good way to start.

You're enrolled in engineering at a school where nobody (not even the teachers?) know about PCB design? I found Fritzing to be very useful for new users, you should check out some youtube tutorials on how to import components you find off the web. Also, probably running the whole thing of a CR2032 won't last long with the 4 digit 7 segment display, afaik. Have you calculated the power usage? Engineering isn't just flicking some parts together ;D

You can just place a pin header on your diagram, where you'll want to solder (or mount) the HC-05 module. Or check the internet for existing HC-05 fritzing files. For the 4digit7segment I think you'd be able to find a genereic one. Mind the difference between common anode/cathode and you'll be fine.

You can find the parts on fritzing.org. Anyway. You can get rid of some parts and save money if you pick the right ones. Instead of an Arduino Uno take an Arduino Pro Mini with 3.3V and HC-05 without a breakout for 5V Arduinos.
Doing that everything will smaller and running on 3.3V thus getting rid of the DC-DC converter.

Sorry, I am very inexperienced.  Would I be able to run everything at 3.3 volts with a CR2032 coin cell battery?  That is why I have the DC-DC converter.
I am not able to use AAs as I am trying to use as minimal space as possible

Possibly. But you have to take tight control over everything. I assume your Scale will be off most of the time. If you turn everything off and put the Arduino Pro Mini into sleep you can get as low as 1µA. A coin cell battery like CR2032 has something about 200mAh capacity. So it can stay in sleep mode for 200'000 hours or 22 years. Of course the battery will self-discharge much faster. While active your components will draw much more power. You need to examine how much power all your components draw and if you can turn them off. This can be a long path of trial and error.

I am trying to use as minimal space as possible - there are quite a few Arduinos that are much smaller than the Uno, for example an Arduino Micro.

You can try to implement the circuit without an Arduino board on a breadboard. So you can get more information about what works and what not. From there after making necessary changes (if there is any), you can draw the schematics and create a PCB layout using Orcad, Eagle etc.There are a lot of tutorials out there about PCB designing.


text:
Using rotary encoders with pin change interrupts
I'm using an Arduino Uno and two (3-pin) rotary encoders for a project. Since the loop takes a bit long and accuracy is important, I'd like to use interrupts to read the values from the rotary encoders. Also, pins 2 and 3 are occupied so I can't use hardware interrupts.
I'm using the Rotary library (github link) for the rotary encoders and the EnableInterrupt library (github link) for external interrupts. The Rotary library includes an interrupt example, but I couldn't manage to modify it to work with pin change interrupts. This is my current state (test code):
#include <EnableInterrupt.h>
#include <Rotary.h>

Rotary r = Rotary(2, 3);

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

  /* Original interrupt setup:
  PCICR |= (1 << PCIE2);
  PCMSK2 |= (1 << PCINT18) | (1 << PCINT19);
  sei();
  */

  enableInterrupt(2, interruptFunction, CHANGE);
  enableInterrupt(3, interruptFunction, CHANGE);
}

void loop() {

}

void interruptFunction() {

  Serial.println("Int. called");

  unsigned char result = r.process();
  if (result == DIR_NONE) {
    // do nothing
  }
  else if (result == DIR_CW) {
    Serial.println("ClockWise");
  }
  else if (result == DIR_CCW) {
    Serial.println("CounterClockWise");
  }
}

Everytime I turn the encoder for one step, the interruptFunction gets called a bunch of times (about 2~4) but the r.process() call never returns a value.
My current guess is that this has something to do with the rotary encoder outputting gray code, but I'm not quite sure how my approach differs from the Rotary interrupt example using hardware interrupts.
Hope you can help!

Avoid Serial in an ISR. Check the online documentation.

I'm aware of that, i just used the provided (and working) example as a base to eliminate possible sources of failure. I will of course change it for my production code.

The function process() of the Rotary Library is not a blocking function and only read the state of the 2 pins and compute an output. How you can say "but the r.process() call never returns a value." ?

The best strategy for ISR is do the least possible. You don't need to Serial.print inside the ISR. All you need to do is store result and do the print inside loop. In the ISR change a global variable to signal that you have a new value; reset it in the loop after you do your thing.

I too had this problem. I chased my tail in SW for hours. I was making the ISRs non-reentrant (assumed they accidentally were), I was doing SW debouncing etc. I even looked at the signal on a scope but did not see any significant bounces.
I eventually added 0.1uF capacitors to the inputs and that solved all my problems with the ISR.
So don't trust the encoder manufacturers, there WILL be signal bounce and your Arduino WILL detect it and throw multiple interrupts.
Good luck with your project!
LDP

I too had this problem. it isn't fair to blame a coding issue on this topology. But your point about the beauty of hardware debouncing is still valid, and often ignored by newbies wanting to bet their lives on software debouncing.

Everytime I turn the encoder for one step, the interruptFunction gets
  called a bunch of times (about 2~4)

This is due to contact bounces. You should either implement a hardware debouncing circuit (a simple R-C filter could be enough. Do not connect instead large capacitors directly in parallel to your contacts, as when the contact closes, the energy stored on the capacitor will damage over time the contacts. Using large capacitances on an input can also lead to problems when power is removed), or better a good software debouncing strategy.
For instance, when the interrupt is called the first time, disable the pin-change interrupts. Then set up a timer, which will trigger an interrupt when it expires (the time should be larger than the bounce time, usually several ms or more). Then in the timer interrupt, first put your code:
  unsigned char result = r.process();
  if (result == DIR_NONE) {
    // do nothing
  }
  else if (result == DIR_CW) {
    Serial.println("ClockWise");
  }
  else if (result == DIR_CCW) {
    Serial.println("CounterClockWise");
  }

end re-enable the pin-change interrupts.
  enableInterrupt(2, interruptFunction, CHANGE);
  enableInterrupt(3, interruptFunction, CHANGE);

but the r.process() call never returns a value.

r.process() will ALWAYS returns a value. Maybe you did mean that it returns DIR_NONE ?

check the library to see if it debounces the input.
if not, write your own code. usually state machine-based approaches are very resistant to switch bounces.

Code Correction 7th October - Tidy code as per comments
Code Correction 7th October - proper reading of rotary encoder
Uses the Pin Change interrupts to allow increment and decrement of the 2 rotary encoders within an interrupt service routine using arduino (in my case nano) with ATMEGA328P chip. Need to add 2 x 104 (0.1uF caps) at the rotary encoder between each pin and the centre ground pin to stop the debounce, doesnt work without the capacitors added. Does not need any library. Watched the Tutorial: Pin Change Interrupts on the Arduino by makecourse which helped understand the Pin change interrupts, will help to watch this if have a different version of arduino so know what digital pins relate to what interrupts.
          //*******************************************  rotary encoder ************************************************************
          #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))    //shortcut way to clear a bit in a register
          #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))     //shortcut way to set a bit in a register

          #define Encoder1pin 3 //corresponds to PCINT19
          #define Encoder2pin 4 //corresponds to PCINT20
          #define Encoder3pin 5 //corresponds to PCINT21
          #define Encoder4pin 6 //corresponds to PCINT22
          #define Encoder5pin 7 //corresponds to PCINT23

          unsigned long encoderPos1 = 100;
          unsigned long oldEncPos1 = 0;
          unsigned long encoderPos2 = 100; //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
          unsigned long oldEncPos2 = 0; //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)

          volatile byte portDstatus;

          volatile bool readingEncoder1pin = 0;
          volatile bool readingEncoder2pin = 0;
          volatile bool readingEncoder3pin = 0;
          volatile bool readingEncoder4pin = 0;
          volatile bool lastreadingEncoder1pin = 0;
          volatile bool lastreadingEncoder2pin = 0;
          volatile bool lastreadingEncoder3pin = 0;
          volatile bool lastreadingEncoder4pin = 0;

          void setup() {

            Serial.begin(9600);

          //*************************************************** rotary encoder ******************************************************************************
            pinMode(Encoder1pin, INPUT);//define pin as INPUT
            digitalWrite(Encoder1pin, HIGH);//connect the internal pull-up resistor - this will yield a HIGH readout if the switch is open.
            pinMode(Encoder2pin, INPUT);
            digitalWrite(Encoder2pin, HIGH);
            pinMode(Encoder3pin, INPUT);
            digitalWrite(Encoder3pin, HIGH);
            pinMode(Encoder4pin, INPUT);
            digitalWrite(Encoder4pin, HIGH);
            pinMode(Encoder5pin, INPUT);
            digitalWrite(Encoder5pin, HIGH);

            //setting up the interrupt pins:   //I needed to set all of these otherwise the serial monitor does not read the byte correctly -
                                               // and it doesnt work.

            sbi (PCICR, PCIE2); // enable interrupt PCI2);
            sbi (PCMSK2,PCINT23); // set the interrupt control bits for pins 7-3. These bits control whether the pins can trigger the interrupt or not.
            sbi (PCMSK2, PCINT22);
            sbi (PCMSK2, PCINT21);
            sbi (PCMSK2, PCINT20);
            sbi (PCMSK2, PCINT19); // we do not want to set interrupt control for pins 0 or 1 since this is serial reading .

          //******************************************************************* LED *********************************************************************
          }

          void loop()

              {
               }

          ISR(PCINT2_vect) // Interrupt Service Routine. This code is executed when a state change occurs on a pin
          {

                portDstatus=PIND;
               readingEncoder1pin = bitRead(portDstatus,3);
               readingEncoder2pin = bitRead(portDstatus,4);
             if(lastreadingEncoder1pin == 1 && lastreadingEncoder2pin == 0 && readingEncoder1pin == 1 && readingEncoder2pin == 1)
              {
                  encoderPos1 ++;
                   lastreadingEncoder1pin = readingEncoder1pin;
                   lastreadingEncoder2pin = readingEncoder2pin;
              }

              else if(lastreadingEncoder1pin == 0 && lastreadingEncoder2pin == 1 && readingEncoder1pin == 1 && readingEncoder2pin == 1)
              {
                encoderPos1 --;
                  lastreadingEncoder1pin = readingEncoder1pin;
                  lastreadingEncoder2pin = readingEncoder2pin;;
              }
              else
                {
                   lastreadingEncoder1pin = readingEncoder1pin;
                   lastreadingEncoder2pin = readingEncoder2pin;
                }

    //  reading the second encoder:

               readingEncoder3pin = bitRead(portDstatus,5);
               readingEncoder4pin = bitRead(portDstatus,6);

             if(lastreadingEncoder3pin == 1 && lastreadingEncoder4pin == 0 && readingEncoder3pin == 1 && readingEncoder4pin == 1)
              {

                  encoderPos2 ++;
                   lastreadingEncoder3pin = readingEncoder3pin;
                   lastreadingEncoder4pin = readingEncoder4pin;
              }

              else if(lastreadingEncoder3pin == 0 && lastreadingEncoder4pin == 1  && readingEncoder3pin == 1 && readingEncoder4pin == 1)
              {
                encoderPos2 --;
                  lastreadingEncoder3pin = readingEncoder3pin;
                  lastreadingEncoder4pin = readingEncoder4pin;;
              }
              else
                {

                   lastreadingEncoder3pin = readingEncoder3pin;
                   lastreadingEncoder4pin = readingEncoder4pin;
                }
             // serial print for testing only then remove from ISR
          Serial.print(encoderPos1);
          Serial.println(encoderPos2);

             }

This code has a few issues: 1. portDstatus is set but never used. For consistency, it would be better to read PIND only once, then get the individual pin readings out of portDstatus. 2. lastportDstatus is never set nor used. 3. encoderPos and oldEncPos may overflow, they should thus be unsigned in order to avoid undefined behavior. 4. (last)readingEncoder[12]pin need not be long, byte should suffice. 5. Only encoderPos needs to be volatile, assuming it is going to be used in loop().

(continued...) 6. The pull-ups can be enabled with pinMode(pin, INPUT_PULLUP);, which is clearer that using digitalWrite(). 7. There is no point in enabling PCINT on pins 5, 6 and 7 if the encoder is only connected to pins 3 and 4. 8. The decoding logic looks flawed, e.g. lastreadingEncoder1pin should not be set to zero unless the last reading of the encoder 1 pin was indeed zero. 9. Using Serial.println() within an ISR is asking for trouble.

You have fixed issues 1–4. Great! Still a small issue with the encoder logic: 8′. If the encoder oscillates between readingEncoder(1,2)pin = (1,0) and (1,1), the position will continually increment. And it will decrement if it oscillates as (0,1) ↔ (1,1). This can be fixed by decrementing on (1,1) → (1,0) instead of (0,1) → (1,1). And then: 7′. Only PCINT{20,22} need to be enabled, which would avoid superfluous interrupts.

The correct solution is to use a debouncing circuit. The MC14490 is a hex debouncing circuit and is perfect for this type of application. No need to block interrupts or set timers. It's available as either SMD or thru hole.

That's not a bad device... except that the SMD version is expensive (~US$11) and the through-hole version is no longer manufactured. There are other, cheaper, smaller, simpler, practical ways of debouncing contacts.

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