text:
Arduino toggles on multiplexer not working
I am currently working on an Arduino project that needs alot of on/off toggles. Because my Arduino Mega does not have enough pins I connected 5 multiplexers to it (the MuxShield 2's). The problem is that only one of them functions correctly at any given moment.
Each multiplexer has 3 rows and they each have their _shiftReg1, _shiftReg2 and _shiftReg3 array in the library. I think there's something up with this, when I loop over the rows of each multiplexers only the first first, second and third row of any given multiplexer work as expected. The outputs on each row light up one by one as they should. But when I loop over a row number which is already looped over all the outputs turn on at once. I have no idea why this is happening and really need some help figuring this out.
This is my main project file, I commented which loops work and which ones don't:
#include <Arduino.h>

#include <MuxShield.h>
#include <ToggleMux.h>

// Initialize the Mux Shields
MuxShield muxShield1 = MuxShield(31, 29, 27, 25, 23, 10, 11, 12, A0, A1, A2);
MuxShield muxShield2 = MuxShield(41, 39, 37, 35, 33, 10, 11, 12, A3, A4, A5);
MuxShield muxShield3 = MuxShield(2, 4, 6, 7, 8, 10, 11, 12, A6, A7, A8);
MuxShield muxShield4 = MuxShield(51, 49, 47, 45, 43, 10, 11, 12, A9, A10, A11);
MuxShield muxShield5 = MuxShield(22, 24, 26, 28, 30, 10, 11, 12, A12, A13, A14);
// ToggleMux
ToggleMux t1 = ToggleMux(muxShield1, 1, 0, muxShield3, 3, 0);
ToggleMux t2 = ToggleMux(muxShield1, 1, 1, muxShield3, 3, 1);
ToggleMux t3 = ToggleMux(muxShield1, 1, 2, muxShield3, 3, 2);
ToggleMux t4 = ToggleMux(muxShield1, 1, 3, muxShield3, 3, 3);
...

void setup()
{
    muxShield1.setMode(1, DIGITAL_IN);
    muxShield1.setMode(2, DIGITAL_IN);
    muxShield1.setMode(3, DIGITAL_IN);

    muxShield2.setMode(1, DIGITAL_IN);
    muxShield2.setMode(2, DIGITAL_IN);
    muxShield2.setMode(3, DIGITAL_IN);

    muxShield3.setMode(1, DIGITAL_IN);
    muxShield3.setMode(2, ANALOG_IN);
    muxShield3.setMode(3, DIGITAL_OUT);

    muxShield4.setMode(1, DIGITAL_OUT);
    muxShield4.setMode(2, DIGITAL_OUT);
    muxShield4.setMode(3, DIGITAL_OUT);

    muxShield5.setMode(1, DIGITAL_OUT);
    muxShield5.setMode(2, DIGITAL_OUT);
    muxShield5.setMode(3, DIGITAL_OUT);
}

boolean hilo = true;

void loop()
{
    for (int i = 0; i < 16; i++) {     // works as expected
      muxShield3.digitalWriteMS(3, i, hilo ? 1 : 0);
      delay(10);
    }

    for (int i = 0; i < 16; i++) {     // turns them all on at once because row 3 has already been looped over
      muxShield4.digitalWriteMS(3, i, hilo ? 1 : 0);
      delay(10);
    }

    for (int i = 0; i < 16; i++) {     // works as expected
      muxShield4.digitalWriteMS(1, i, hilo ? 1 : 0);
      delay(10);
    }

    for (int i = 0; i < 16; i++) {     // works as expected
      muxShield4.digitalWriteMS(2, i, hilo ? 1 : 0);
      delay(10);
    }

    // for (int i = 0; i < 16; i++) {
    //   muxShield4.digitalWriteMS(3, i, hilo ? 1 : 0);
    //   delay(10);
    // }

    for (int i = 0; i < 16; i++) {    // turns them all on at once because row 1 has already been looped over
       muxShield5.digitalWriteMS(1, i, hilo ? 1 : 0);
       delay(10);
     }

     for (int i = 0; i < 16; i++) {    // turns them all on at once because row 2 has already been looped over
       muxShield5.digitalWriteMS(2, i, hilo ? 1 : 0);
       delay(10);
     }

     for (int i = 0; i < 16; i++) {    // turns them all on at once because row 3 has already been looped over
       muxShield5.digitalWriteMS(3, i, hilo ? 1 : 0);
       delay(10);
     }
     hilo = !hilo;

  // t1.listen();
  // t2.listen();
  // t3.listen();
  // t4.listen();
    ...
}

This is my toggle library:
#include "Arduino.h"
#include "ToggleMux.h"
#include "MuxShield.h"

ToggleMux::ToggleMux(MuxShield muxShieldIn, int inRow, int inBit, MuxShield muxShieldOut, int outRow, int outBit) :
_muxShieldIn(muxShieldIn),
_muxShieldOut(muxShieldOut),
_inRow(inRow),
_inBit(inBit),
_outRow(outRow),
_outBit(outBit)
{
    _state = 0;
    _previous = 0;
    _reading;

    _time = 0;
    _debounce = 100;
}

void ToggleMux::listen() {
    _reading = _muxShieldIn.digitalReadMS(_inRow, _inBit);
    _state = _muxShieldOut.digitalReadMS(_outRow, _outBit);

    if (_reading == 1 && _previous == 0 && millis() - _time > _debounce) {
        if (_state == 1) {
            _state = 0;
        } else {
            _state = 1;
        }

        _muxShieldOut.digitalWriteMS(_outRow, _outBit, _state);
        _time = millis();
    }

    _previous = _reading;
}

void ToggleMux::on() {
  _state = 1;
  _muxShieldOut.digitalWriteMS(_outRow, _outBit, 1);
}

void ToggleMux::off() {
  _state = 0;
  _muxShieldOut.digitalWriteMS(_outRow, _outBit, 0);
}

And this is the MuxShield 2 library:
/*
 MuxShield.cpp - Library for using Mayhew Labs' Mux Shield.
 Created by Mark Mayhew, December 29, 2012.
 Released into the public domain.
 */

#include "Arduino.h"
#include "MuxShield.h"
#include "BitBool.h"

int _shiftReg1[16] = {0};
int _shiftReg2[16] = {0};
int _shiftReg3[16] = {0};

MuxShield::MuxShield(int S0, int S1, int S2, int S3, int OUTMD,int IOS1, int IOS2, int IOS3, int IO1, int IO2, int IO3)
{
    _S0 = S0;
    _S1 = S1;
    _S2 = S2;
    _S3 = S3;
    _OUTMD = OUTMD;
    _IOS1 = IOS1;
    _IOS2 = IOS2;
    _IOS3 = IOS3;
    _IO1 = IO1;
    _IO2 = IO2;
    _IO3 = IO3;

    pinMode(_S0,OUTPUT);
    pinMode(_S1,OUTPUT);
    pinMode(_S2,OUTPUT);
    pinMode(_S3,OUTPUT);
    pinMode(_OUTMD,OUTPUT);
    digitalWrite(_OUTMD,LOW);
    pinMode(_IOS1,OUTPUT);
    pinMode(_IOS2,OUTPUT);
    pinMode(_IOS3,OUTPUT);
}

MuxShield::MuxShield()
{
    _S0 = 2;
    _S1 = 4;
    _S2 = 6;
    _S3 = 7;
    _OUTMD = 8;
    _IOS1 = 10;
    _IOS2 = 11;
    _IOS3 = 12;
    _IO1 = A0;
    _IO2 = A1;
    _IO3 = A2;

    pinMode(_S0,OUTPUT);
    pinMode(_S1,OUTPUT);
    pinMode(_S2,OUTPUT);
    pinMode(_S3,OUTPUT);
    pinMode(_OUTMD,OUTPUT);
    digitalWrite(_OUTMD,LOW);
    pinMode(_IOS1,OUTPUT);
    pinMode(_IOS2,OUTPUT);
    pinMode(_IOS3,OUTPUT);
}

void MuxShield::setMode(int mux, int mode)
{
    switch (mux) {
        case 1:
            switch (mode) {
                case DIGITAL_IN:
                    pinMode(_IO1,INPUT);
                    digitalWrite(_IOS1,LOW);
                    break;
                case DIGITAL_IN_PULLUP:
                    pinMode(_IO1,INPUT_PULLUP);
                    digitalWrite(_IOS1,LOW);
                    break;
                case DIGITAL_OUT:
                    pinMode(_IO1,OUTPUT);
                    digitalWrite(_IOS1,HIGH);
                    break;
                case ANALOG_IN:
                    digitalWrite(_IOS1,LOW);
                    break;
                default:
                    break;
            }
            break;
        case 2:
            switch (mode) {
                case DIGITAL_IN:
                    pinMode(_IO2,INPUT);
                    digitalWrite(_IOS2,LOW);
                    break;
                case DIGITAL_IN_PULLUP:
                    pinMode(_IO2,INPUT_PULLUP);
                    digitalWrite(_IOS2,LOW);
                    break;
                case DIGITAL_OUT:
                    pinMode(_IO2,OUTPUT);
                    digitalWrite(_IOS2,HIGH);
                    break;
                case ANALOG_IN:
                    digitalWrite(_IOS2,LOW);
                    break;
                default:
                    break;
            }
            break;
        case 3:
            switch (mode) {
                case DIGITAL_IN:
                    pinMode(_IO3,INPUT);
                    digitalWrite(_IOS3,LOW);
                    break;
                case DIGITAL_IN_PULLUP:
                    pinMode(_IO3,INPUT_PULLUP);
                    digitalWrite(_IOS3,LOW);
                    break;
                case DIGITAL_OUT:
                    pinMode(_IO3,OUTPUT);
                    digitalWrite(_IOS3,HIGH);
                    break;
                case ANALOG_IN:
                    digitalWrite(_IOS3,LOW);
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }

}

void MuxShield::digitalWriteMS(int mux, int chan, int val)
{
    int i;

    digitalWrite(_S3,LOW);                              //S3 here is LCLK
    digitalWrite(_OUTMD,HIGH);                          //set to output mode
    switch (mux) {
        case 1:
            _shiftReg1[chan] = val;                     //store value until updated again

            for (i=15; i>=0; i--) {
                digitalWrite(_S0,LOW);                  //S0 here is i/o1 _sclk
                digitalWrite(_IO1,_shiftReg1[i]);       //put value
                digitalWrite(_S0,HIGH);                 //lactch in value
            }
            break;
        case 2:
            _shiftReg2[chan] = val;                     //store value until updated again

            for (i=15; i>=0; i--) {
                digitalWrite(_S1,LOW);                  //S1 here is i/o2 _sclk
                digitalWrite(_IO2,_shiftReg2[i]);       //put value
                digitalWrite(_S1,HIGH);                 //lactch in value
            }
            break;
        case 3:
            _shiftReg3[chan] = val;                     //store value until updated again

            for (i=15; i>=0; i--) {
                digitalWrite(_S2,LOW);                  //S2 here is i/o3 _sclk
                digitalWrite(_IO3,_shiftReg3[i]);       //put value
                digitalWrite(_S2,HIGH);                 //lactch in value
            }
            break;
        default:
            break;
    }
    digitalWrite(_S3,HIGH);                     //latch in ALL values
    digitalWrite(_OUTMD,LOW);                   //Exit output mode

}

int MuxShield::digitalReadMS(int mux, int chan)
{
    digitalWrite(_OUTMD,LOW);   //Set outmode off (i.e. set as input mode)
    int val;
    switch (mux) {
        case 1:
            digitalWrite(_S0, (chan&1));
            digitalWrite(_S1, (chan&3)>>1);
            digitalWrite(_S2, (chan&7)>>2);
            digitalWrite(_S3, (chan&15)>>3);

            val = digitalRead(_IO1);
            break;
        case 2:
            digitalWrite(_S0, (chan&1));
            digitalWrite(_S1, (chan&3)>>1);
            digitalWrite(_S2, (chan&7)>>2);
            digitalWrite(_S3, (chan&15)>>3);

            val = digitalRead(_IO2);
            break;
        case 3:
            digitalWrite(_S0, (chan&1));
            digitalWrite(_S1, (chan&3)>>1);
            digitalWrite(_S2, (chan&7)>>2);
            digitalWrite(_S3, (chan&15)>>3);

            val = digitalRead(_IO3);
            break;
        default:
            break;
    }
    return val;
}

int MuxShield::analogReadMS(int mux, int chan)
{
    digitalWrite(_OUTMD,LOW);
    int val;

    digitalWrite(_S0, (chan&1));
    digitalWrite(_S1, (chan&3)>>1);
    digitalWrite(_S2, (chan&7)>>2);
    digitalWrite(_S3, (chan&15)>>3);

    switch (mux) {
        case 1:
            val = analogRead(_IO1);
            break;
        case 2:
            val = analogRead(_IO2);
            break;
        case 3:
            val = analogRead(_IO3);
            break;
        default:
            break;
    }
    return val;
}


text:
Sum values, store them and print the last value
I have a mass flow meter connected to an Arduino Uno board. I have managed to read the volume flow in L/hour, but now I'm struggling to implement a code that stores the values so that I see the number of Liters used.
For instance, I can see on my monitor this:
0 L/hour
0 L/hour
And if I have some water running through,
10 L/hour
20 L/hour
20 L/hour
Then when I stop the flow it goes back to 0.
0 L/hour
Is there any ways to sum up time instances, get the total number of liters and keep it printed during every instance?
Mathematically is not that difficult (Volume = Volume Flow in L/hour * time), but I don't know how to implement this. Can anyone help with this? It can be in seconds or ms or whatever.
Paul

What you want to do is integrate the flow rate vs time curve. You have to keep track of the current flow rate. You also need to choose some unit of time measurement; this depends on how often you're sampling the flow rate. For instance, if you sample it every second, then you should convert your L/hr flow rate to L/s. This means a flow rate of 10L/hr is equivalent to 10L/3600s = 0.002778 L/s. So, if you get a reading of 10 L/hr for 10 seconds, 0.002778 L/s * 10 s = 0.02778 L of water flowed through your valve or whatever. An accumulating sum is what you need. You can try something like this:
#define INTERVAL 1000  // sampling interval in millisec
#define HR_TO_SEC 2.778E-4  // number of hours in a second

int curr_rate = 0;  // current flow rate in L/hr
unsigned long lastRead = 0;  // the last time the rate was sampled
float totalVolume = 0;

void loop(){
  if (millis() - lastRead >= INTERVAL){
    lastRead += INTERVAL;
    curr_rate = getFlowRate();   // or whatever function you call; should take << 1 sec
    totalVolume += curr_rate * HR_TO_SEC;  // update the volume
    Serial.println(totalVolume, 4);
  }
}

This rectangular method is reasonably accurate, depending on your application. If you want a better approximation, google "trapezoidal numerical integration" or "Simpson's method" if you want even better approximation.

The higher order integration methods achieve better accuracy by leveraging the smoothness of the integrand. Here, since there is a valve, the flow is unlikely to be smooth. If you want better accuracy, you only have to sample at shorter intervals.

Also, I replaced lastRead = millis(); by lastRead += INTERVAL;. Otherwise you have a systematic bias, as the average sampling interval would be larger than INTERVAL.

Thank you both for the help. I have managed to implement this code and it does indeed store the data. I have poured 1 L of water through the meter and the monitor reads 1.2 L. Not a huge difference, but  I will change the method of integration and we will see if I can correct that. Also, I had to remove "unsigned" for "float totalVolume = 0;". The code would give an error otherwise.

@Paul You can do as Edgar Bonet says and reduce the interval to 200 ms maybe. Also take care to change HR_TO_SEC to reflect that: convert your interval to hours. If this solves your problem, consider accepting it.

Okay. I will do some experiments these days and see how it goes. I will write back! Thank you

This  will be helpful.
reading is your flow meter value in L/Hour
float reading;//value of the flow meter
long startTime;
float total=0;

void setup() {
  Serial.begin(9600);
  startTime=millis();

}

void loop() {
//read your flow meter to reading variable.
 total+=reading*float((millis()-startTime))/3600000.0;
 Serial.println(total);

}

Thank you very much! I have tried with this code and it keeps giving me 0. Also, I needed to add long startTime=millis(); instead of simply declaring long startTime and then calling it. Is the "reading" function responsible for me getting 0? Does it have to be related to the signal or the pinmode?

reading is the variable..You must pass your flow meter reading to that variable as a float type.
you must enter it before Serial.println() function as I commented.
if you can give previous code,I will be  able to give full code.

The code can be found here: http://forum.arduino.cc/index.php?topic=8548.0 (It is too long to post it here). Thank you!

In a recent comment, you posted a link to a forum thread with the
code for reading the sensor. You should have provided this information
up front, because it completely changes the problem. It appears that the
flow meter sends pulses at a frequency proportional to the volume flow,
and the code uses an interrupt to count the pulses over a specified
time.
TisteAndii's answer suggests you integrate the flow readings to get a
volume. And that suggestion makes perfect sense given the limited
information he had available at the time. Now that we know how the flow
meter is read, it makes no sense anymore:

the interrupt service routine counts a number of pulses that is
proportional to the total volume that has gone through the meter
the linked code differentiates that reading in order to get the flow
you are now integrating that flow in order to get the total volume.

Instead of doing an integration on top of a differentiation, you could
just convert the raw reading into a volume. Then you do not have to
worry about any approximations done while differentiating or
integrating.
In the forum thread it is stated:

Pulse frequency (Hz) in Horizontal Test= 7.5Q, Q is flow rate in L/min.

Writing this in a more mathematically accurate form (i.e. with
unit-correctness) gives:

f/Hz = 7.5 Q/(L/min)

where f is the frequency and Q the volume flow.
Given that 7.5 Hz⋅min = 450 pulses, the above equation can be rewritten as

f = 450 pulses/L × Q

or, in terms of integrated quantities:

volume = (pulse count) / (450 pulses/L)

Here is an example code that just convert the pulse count to a volume:
// Calibration constant of the flow meter.
const float calibration = 1/450.0;  // 450 pulses per liter

// How often to print the measured volume.
const uint32_t print_interval = 1000;  // once per second

// Number of pulses counted so far.
volatile uint32_t pulse_count;

// Count the pulses inside an ISR.
void count_pulse() { pulse_count++; }

// Return volume reading, optinally resetting the count to zero.
float totalVolume(bool reset = false)
{
    noInterrupts();
    uint32_t pulse_count_copy = pulse_count;
    if (reset) pulse_count = 0;
    interrupts();
    return pulse_count_copy * calibration;
}

void setup()
{
    pinMode(2, INPUT_PULLUP);
    attachInterrupt(0, count_pulse, RISING);
    Serial.begin(9600);
}

void loop()
{
    static uint32_t last_print;
    if (millis() - last_print >= print_interval) {
        last_print += print_interval;
        Serial.println(totalVolume());
    }
}

Note that you may want to reset the count from time to time. I added an
optional parameter to totalVolume() for this purpose. If you never
reset the counter, it will overflow after approximately
9544 m3.

source: Stack Exchange

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

sort: votes


text:
Make arduino board controler for watering system with power bank
I am trying to build an off-grid automatic watering system, and I was thinking of many options and the most reliable one that I found is to use a power bank which is charged by a solar panel.
So, I have a solar panel that outputs 5V, and I can charge a standard power bank with it. In addition to this, I bought a USB pump which I can also power with the power bank and controlled using an Arduino board. The problem is that the power bank doesn't support charging and discharging at the same time, and I thought that I could use an Arduino board to control this, but I have no knowledge on this. Therefore, I need help.
Is it possible to have a system like the one sketched below, where the Arduino board controls the input/output of the power bank?

The black path is my current path, but I was wondering if I could do the red path so that I can have both chargings from the solar panel and discharge due to the pump and Arduino board.

Is it possible? Yes.
Is it easy? Maybe.
A relay shield or similar would allow you to break the power connection from the solar panel to the power bank input, wait 5 seconds and then connect the power bank output to the pump.
Once you are done with the pump you could disconnect power from it and reconnect the charging power.
That is all fairly straight forward, maybe a dozen lines of code and some very simple wiring.
The issue is where does the arduino get power from? Or more accurately how does the arduino maintain power during the transitions between different power sources. How much of an issue this is depends a lot on how quickly the power pack transitions from charging to outputting and back and how you want the system to behave overnight or other times when there pump is idle but there isn't much sun light.
Also have you done a power budget? How much power does your pump take and how much power does your solar panel output under normal usage? Based on those two how long per day can you run the pump for assuming an ~80% efficient battery pack.

You should be able to solve it with two diodes, preferably Schotty diodes, they have a low forward drop voltage.

Simple, but I'm not sure a 5v solar cell itself can run the pump...

Well if the voltage from the solar panel drops below the voltage from the power bank, then will the pump/arduino be get its energy from the power bank.

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


text:
Arduino code not starting at beginning after poweroff
I created a few Arduino-XBee temperature sensor nodes that send data to another XBee node.js server. I'm running into a few issues trying to write a function to initiate a handshake and receive an identifier number to start sending data (so its scalable rather than hard-coded on each) while the receiver is already communicating with pre-established nodes.
The first issue I'm having is that the Arduino nodes do not seem to start from the beginning of their code when I unplug them and then reapply power. They already think they have their identifier number if another node is running, and I have to push the reset button on them to get them to run their code fresh and establish their own handshake ID. Is there anything I can put in the code or a way that I can easily modify the circuitry to make them actually reset and start fresh when they lose power?
The circuitry I'm using is a basic thermistor voltage-divider, XBee module, and 5V battery pack. Here's what I've got so far for the code on the Arduino side:
#include <SoftwareSerial.h>
#include <math.h>

// Global variables
int AnalogPin = A2; // has much less jumpy readings than A0 (maybe A0 slightly damage from overuse)
float V_source = 4.90; // measured
SoftwareSerial XBee(2,3); // RX, TX
String identifier = "";
int receivedID = 0;

// Calculate thermistor voltage
float Voltage(float RawADC) {
  float meter_calibration = 0; // don't seem to need, matches my multimeter exactly
  float V_therm = (V_source * RawADC) / 1024.0;
  V_therm += meter_calibration;
  return V_therm;
}

// Calculate thermistor resistance
// sometimes a bit off what voltage divider eq says it should be (probably due to input impedance of ADC)
float Thermistor(float V_therm) {
  float resistance_calibration = 25; // possibly small breadboard/wires resistance
  float R_known = 560 + resistance_calibration; // measured (1% tol resistor)
  float R_therm =  ((R_known * V_therm) / (V_source - V_therm));
  return R_therm;
}

// Base conversion
float log2(float num) {
  return (log(num) / log(2));
}

// Calculate temperature
float Temperature(float R_therm) {
  float A = 0.0164872;
  float B = -0.00158538;
  float C = 0.0000033813;
  float temp_K = 1 / (A + B*log2(R_therm) + C*pow(log2(R_therm),3));
  return temp_K;
}

// Convert to Celsius or Fahrenheit
float ConvertTemp(float temp_K, char T) {
  if (T == 'C')
    return (temp_K - 273.15);
  else if (T == 'F')
    return (temp_K * 1.8 - 459.67);
}

// Setup
void setup() {
  int idStart = 0;
  receivedID = 0;
  Serial.begin(9600);
  pinMode(AnalogPin, INPUT);
  XBee.begin(9600);
  for (int i=0; i<100; i++) {
    Serial.print("\n");
  }
  Serial.println("Broadcasting...");
}

// Main
void loop() {
  delay(1000);

  // Initiate handshake
  if (identifier == "") {
      XBee.print("BROADCASTING"); // ascii text
      XBee.write("\n");  // binary data
  }
  delay(3000);

  // Receive buffer, check for and confirm ID
  if (XBee.available() && (identifier == "")) {
    String msg = "";
    char r = XBee.read();

/*
    // Error checking for first-only numeric ID (testing)
    msg = msg + r;
    String intString = "";
    int intStart = 0;
    int i = 0;
    while (intStart != 2 && i < msg.length()) {
      if (intStart == 0) {
        if (isDigit(msg[i])) {
              intString += msg[i];
              intStart = 1;
           }
      }
      else if (intStart == 1) {
        if (isDigit(msg[i])) {
              intString += msg[i];
              intStart = 1;
           }
      }
      else if (!isDigit(msg[i])) {
        intStart = 2;
      }
      i++;
    }
    Serial.print("testing: ");
    Serial.println(intString);
    identifier = intString;
*/

    identifier = r;
  }

  // handshake established
  if ((identifier != "") && (receivedID == 0)) {
    Serial.println();
    Serial.print("RECEIVED IDENTIFIER: ");
    Serial.println(identifier);
    Serial.println();
    receivedID = 1;
  }

  // Calculate and send temperature along with identifier
  while (receivedID == 1) {
        // ADC and V_therm values
    /* Good to get two or more analog readings and discard the first or take the average
    apparently analog pins are multiplexed so this gives it time to settle */
    float RawADC_1 = analogRead(AnalogPin); // toss 1
    float RawADC_2 = analogRead(AnalogPin); // average 2,3
    float RawADC_3 = analogRead(AnalogPin);
    float RawADC_avg = (RawADC_2 + RawADC_3) / 2.00;
    Serial.print("Raw ADC value: ");
    Serial.println(RawADC_avg);
    float V_therm = Voltage(RawADC_avg);
    Serial.print("Voltage across thermistor: ");
    Serial.println(V_therm);

    // Thermistor resistance
    float R_therm = Thermistor(V_therm);
    Serial.print("Resistance of thermistor: ");
    Serial.println(R_therm);

    // Temperature in Kelvin, Celsius, Fahrenheit
    float temp_K = Temperature(R_therm);
    Serial.print(temp_K);
    Serial.print("K   ");
    float temp_C = ConvertTemp(temp_K, 'C');
    float temp_F = ConvertTemp(temp_K, 'F');
    Serial.print(temp_C);
    Serial.print("C   ");
    Serial.print(temp_F);
    Serial.println("F   ");

    // XBee
    String mytemp = String(temp_F);
    String msg = String(identifier + " " + mytemp);
    XBee.print(msg); // ascii text
    XBee.write("\n");  // binary data
    Serial.print("Message sent to XBee: ");
    Serial.println(msg);
    Serial.println();

    delay(2000);
  }

}

You can put that idea out of your head right now! Do you think that the compiler inserts some "jump to random location" code? Of course it starts at the start. The problem is somewhere else.

They already think they have their identifier number if another node is running - how do you know that?

@NickGammon because they start sending temp data as if they have already received their identifier which is the same as the currently running node. If I hit the reset button as I plug them in, this problem goes away. Is there any capacitance on the board or something? Also if I have one node running on battery and plug the other node into my computer then upload the sketch it works properly. For some reason if I plug the second to battery, it uses the same identifier as the first.

My guess is that the problem is with the XBee. Variables don't keep their values between power cycles or resets.

Yeah so my pre-connected nodes were broadcasting to everything and sending their identifier to the new nodes. I still don't know exactly why using the reset/upload buttons made it work properly, but I fixed the issue with correct addressing.


text:
Arduino Due randomly slows down, serial communications stops
I've got an Arduino Due connected to a Raspberry Pi via Serial3. The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours. Using an oscilloscope, I can see that the Pi keeps transmitting to the Due, but there is no response from the Due. I'm also getting the Due to echo everything it gets from the Pi to Serial, which is connected to my PC. I can see that the Due will stop echoing characters mid way through receiving a message from the Pi.
I then set one of the pins as an output and just keep toggling that regularly. When the Due is waiting for data from the Pi, this signal has a frequency of about 100Hz, i.e. a period of 10ms. I have a counter that goes from 0 to 1000 to control this frequency somewhat. When this error happens and communications stops, I can see that the pulses now have a period of 2.14 seconds, i.e. 214 times slower.
I'm using Arduino-MemoryFree to check for memory leaks but I haven't found any problems yet and I don't seem to be running out of memory. In case it matters, I'm also using the ArduinoJson library. Arduino IDE version is 1.6.7, I've updated the Arduino SAM Boards package to version 1.6.9 (problem was present before the update as well).
Could someone please advise me on what could be causing this slow down?

Memory leaks don't just show up as memory shrinking - they also show up as variables being corrupted from such things as buffer overruns. You need to post your code so we can see where it's likely to be failing.

Its most likely a memory leak, but another option could be memory fragmentation, due to overuse of the new and delete command.

Maybe PMC registers gets corrupted and Main Clock was switched to Slow Clock. You can try to lock PMC settings so it can't be changed accidentaly.

@KIIV How do I lock those settings? Once locked, what happens when code attempts to overwrite them? Will the Arduino Due reset, or crash thoroughly (in which case the watchdog timer can still recover so I'm happy with that too)?

@Matt I suspected that too, except I'm not using new/delete and the ArduinoJson library uses a fixed size buffer on the stack. Could the built-in String class be causing problems (it sees a lot of use)? I read there was a problem with it, but the version number mentioned was v1.0.5 of the IDE.

@chippies It should be enabled by something like PMC_WPMR = 0x504D4301;. Then on write protection violation it sets PMC_WPSR bit 0 (WPVS) and violated PMC Register offset. That should be all.

@KIIV Ah, so that way I can enable it in setup(), then keep checking PMC_WPSR in loop() and reset the Due immediately when bit 0 changes to 1. I'll add that on Monday.

@KIIV where can I find PMC_WPSR? I've searchedmy Arduino directory and haven't found any file mentioning it. I've installed the Arduino SAM Boards package already. Thanks for the help.

@chippies additional packages are hidden in different directory than arduino one. Somewhere in user directory.

The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours.

Here is the typical manifestation of heap fragmentation in an Arduino sketch.
Solution:

Remove as many Strings as possible and replace them with char[]
Use a StaticJsonBuffer instead of a DynamicJsonBuffer

If you remove all the Strings and use a StaticJsonBuffer, your program will run without any heap. No heap, no fragmentation! Not only it will be more reliable, it will also be smaller and faster.
If you must use String, then call String::reserve() to make sure the size is the same at each iteration. Indeed, repeated allocation of the same size doesn't increase fragmentation.

In the end, I changed the system architecture to avoid JSON processing on the Due. That fixed the issue, so I'm marking this as the solution.

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


text:
What happens when code is uploaded using the bootloader?
When I upload a new sketch to my Arduino Uno using the Optiboot bootloader, what really happens?

What is sent to the Arduino?
How does it respond?
What does "not in sync mean"?
What is "in sync" anyway?

Note: This is intended as a "reference question".

very interesting post! Just a more question. Which software are you using to trace the serial communication (images) ?

It is the output of a Logic Analyzer, such as Saleae Logic 8. https://www.saleae.com/ Very nice little analyzer. Used to be 24 MHz sample rate for ~$125, 150. Current capture speeds are 100 and 500 MHz.

SPI, I2C & more >Most digital communication uses a particular protocol that specifies how information is transferred. The Logic software has protocol analyzers that can automatically decode SPI, I2C, serial, 1-Wire, CAN, UNI/O, I2S/PCM, MP Mode, Manchester, Modbus, DMX-512, Parallel, JTAG, LIN, Atmel SWI, MDIO, SWD, LCD HD44780, BiSS C, HDLC, HDMI CEC, PS/2, USB 1.1, Midi – or create your own

When you reset a Uno running the Optiboot loader, the bootloader first flashes pin 13 three times.

Top line (gray) is sent to the Arduino, middle line (orange) is sent from the Arduino.
While that is happening, the program avrdude running on your computer is sending a query to the device:
STK_GET_SYNC / CRC_EOP  (0x30/0x20)

The Arduino doesn't notice the first "get sync" because it is busy flashing pin 13. Once it is done it notices the "get sync" (it would be buffered by the serial hardware) and replies:
STK_INSYNC / STK_OK (0x14/0x10)

It looks like avrdude got a bit impatient, and timed out, because it tries again with the "get sync" query. This time Optiboot responds immediately.

The rest of the uploading is described in the next image. Example produced uploading the stock "Blink" program.

(Click on the image above for a larger version)

The steps are:

Query: Get Sync? Reply: In Sync.
Query: Get parameter? (major version) Reply: version 4.
Query: Get parameter? (minor version) Reply: version 4.
Set device parameters. The following device parameters are sent to the chip:
0x42  // STK_SET_DEVICE
0x86  // device code
0x00  // revision
0x00  // progtype: “0” – Both Parallel/High-voltage and Serial mode
0x01  // parmode: “1” – Full parallel interface
0x01  // polling: “1” – Polling may be used
0x01  // selftimed: “1” – Self timed
0x01  // lockbytes: Number of Lock bytes.
0x03  // fusebytes: Number of Fuse bytes
0xFF  // flashpollval1
0xFF  // flashpollval2
0xFF  // eeprompollval1
0xFF  // eeprompollval2
0x00  // pagesizehigh
0x80  // pagesizelow
0x04  // eepromsizehigh
0x00  // eepromsizelow
0x00  // flashsize4
0x00  // flashsize3
0x80  // flashsize2
0x00  // flashsize1
0x20  // Sync_CRC_EOP

Optiboot ignores all those and replies with In Sync/OK. :)
Set extended device parameters:
0x45  // STK_SET_DEVICE_EXT
0x05  // commandsize: how many bytes follow
0x04  // eeprompagesize: EEPROM page size in bytes.
0xD7  // signalpagel:
0xC2  // signalbs2:
0x00  // ResetDisable: Defines whether a part has RSTDSBL Fuse
0x20  // Sync_CRC_EOP

Optiboot ignores all those as well and replies with In Sync/OK.
Enter program mode. Reply: In Sync/OK.
Read signature. Optiboot replies with 0x1E 0x95 0x0F without actually reading the signature.
Write fuses (four times). Optiboot does not write the fuse but just replies In Sync/OK.
Load address (initially 0x0000). The address is in words (ie. a word is two bytes). This sets the address for where the next page of data will be written.
Program page (up to 128 bytes are sent). Optiboot replies "In Sync" immediately. Then there is a pause of about 4 ms while it actually programs the page. Then it replies "OK".
Load address (now 0x0040). This is address 64 in decimal, ie. 128 bytes from the start of program memory.
Another page is written. This sequence continues until all the pages are written.
Load address (back to 0x0000). This is for verifying the write.
Read page (up to 128 bytes are read). This is for verifying. Note that even if the verify fails, the bad data has already been written to the chip.
Leave programming mode.

What does "not in sync" mean?
As you can see from the above, every step through the programming sequence the Arduino is expected to reply with "In Sync" (0x14), possibly followed by some data, followed by "OK" (0x10).
If it is "not in sync" that means that avrdude did not get the "in sync" response. Possible reasons could be:

Wrong baud rate used
Wrong serial port selected in IDE
Wrong board type selected in IDE
No bootloader installed
Wrong bootloader installed
Board not configured to use the bootloader (in the fuses)
Some device plugged into pins D0 and D1 on the Arduino, interfering with serial commications
The USB interface chip (ATmega16U2) not working properly
Wrong clock for the board
Wrong fuse settings on the Atmega328P (eg. "divide clock by 8")
Board/chip damaged
Faulty USB cable (some USB cables provide power only, and are not for data, eg. cheap cables for USB fans)

What is "in sync"?
As mentioned above, the response "In sync" means that the Arduino (bootloader) is synchronised with the uploading program.

What protocol is being used?
The protocol is the STK500 protocol as documented by Atmel. See the references below.

References

Optiboot source code - GitHub
AVR061: STK500 Communication Protocol
AVR068: STK500 Communication Protocol version 2
Have I bricked my Arduino Uno? Problems with uploading to board
AVR Downloader/UploaDEr - avrdude

Note: STK500 Version 2 is not used in Optiboot, but it is included for information in case you are using boards like the Mega2560.

STK500 constants
/* STK500 constants list, from AVRDUDE */
#define STK_OK              0x10
#define STK_FAILED          0x11  // Not used
#define STK_UNKNOWN         0x12  // Not used
#define STK_NODEVICE        0x13  // Not used
#define STK_INSYNC          0x14  // ' '
#define STK_NOSYNC          0x15  // Not used
#define ADC_CHANNEL_ERROR   0x16  // Not used
#define ADC_MEASURE_OK      0x17  // Not used
#define PWM_CHANNEL_ERROR   0x18  // Not used
#define PWM_ADJUST_OK       0x19  // Not used
#define CRC_EOP             0x20  // 'SPACE'
#define STK_GET_SYNC        0x30  // '0'
#define STK_GET_SIGN_ON     0x31  // '1'
#define STK_SET_PARAMETER   0x40  // '@'
#define STK_GET_PARAMETER   0x41  // 'A'
#define STK_SET_DEVICE      0x42  // 'B'
#define STK_SET_DEVICE_EXT  0x45  // 'E'
#define STK_ENTER_PROGMODE  0x50  // 'P'
#define STK_LEAVE_PROGMODE  0x51  // 'Q'
#define STK_CHIP_ERASE      0x52  // 'R'
#define STK_CHECK_AUTOINC   0x53  // 'S'
#define STK_LOAD_ADDRESS    0x55  // 'U'
#define STK_UNIVERSAL       0x56  // 'V'
#define STK_PROG_FLASH      0x60  // '`'
#define STK_PROG_DATA       0x61  // 'a'
#define STK_PROG_FUSE       0x62  // 'b'
#define STK_PROG_LOCK       0x63  // 'c'
#define STK_PROG_PAGE       0x64  // 'd'
#define STK_PROG_FUSE_EXT   0x65  // 'e'
#define STK_READ_FLASH      0x70  // 'p'
#define STK_READ_DATA       0x71  // 'q'
#define STK_READ_FUSE       0x72  // 'r'
#define STK_READ_LOCK       0x73  // 's'
#define STK_READ_PAGE       0x74  // 't'
#define STK_READ_SIGN       0x75  // 'u'
#define STK_READ_OSCCAL     0x76  // 'v'
#define STK_READ_FUSE_EXT   0x77  // 'w'
#define STK_READ_OSCCAL_EXT 0x78  // 'x'

AVR061: STK500 Communication Protocol

Good point! I added a few references to the answer. Thanks.

Note that the verification process described here specifically uses a page read, which means that any bootloader supporting avrdude's default verify behavior is a bootloader which supports reading out the flash contents.

This extensive and descriptive program instruction and the analysis of Optiboot/STK500 is mind-blowingly awesome. Thank you, the great Nick Gammon!


text:
Is there any library for use Arduino Uno with esp8266-01 module?
I have a Arduino Uno and the esp8266 module,(NOT THE SHIELD).
I was looking for some library that I could use to connect to Wifi and set a webserver, but I can't find anything. I just found for Arduino Wifi Shield which uses SPI.
It is possible to use arduino lets say to read a LM35 and then send that data to the ESP8266 module and serve it in a page as webserver?
I know that I can use AT commands with ESP8266 to connect to wifi and to create a server, but I cannot find any function to set the data to be served.
https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf

For a webserver, program the ESP8266 directly. This allows you to make use of the internal SPI flash memory to store your webpages. You can't do this with AT commands.
The Arduino UNO does not have enough processing power and/or memory for advanced internet stuff. If you want a webserver over AT commands, the Arduino has to do all the hard work, the ESP8266 is just a dumb slave that establishes a TCP connection.
The ESP8266 is much faster, and has many times more memory, so it makes sense to let it do all the heavy lifting.
Take a look at this guide:
ESP8266 temperature logger
You can copy pretty much all code, but instead of measuring the temperature from an actual sensor, read it from the Serial input.
Then just connect the Arduino to the ESP8266 over Serial (or SPI or I²C or SoftwareSerial, whatever you prefer), and have it send the temperature to the ESP8266, for example every second.
To program the ESP8266, you can use the USB-to-Serial adapter of one of your Arduinos.

In this case, where you just want to read a single LM35, you could even use only the ESP8266. It is true that the LM35 requires at least 4V, but this is not a problem, since most ESP8266 dev boards also provide a 5V supply. The analog input range of 0-1.0V would allow for a temperature up to 100°C.

No thanks! I was just looking for a tutorial for AT and arduino, I already have something from Expresif but programming the ESP8266 is not what I want to do right now and I don't have the tools required for the job.

You don't need one. You have an Arduino and a NodeMCU, both of them can be used as a USB programmer for the ESP-01. But you're free to do it the hard way, of course.

4 AT commands are harder than wiring and programming esp8266 with arduino? I'm just returning json

If it were easy, would you come to this site to ask for help? All I'm saying is that it is much easier to use the mature and well-written Arduino ESP8266 Core libraries for network communication, and that it's pretty wastful to use both an Arduino and an ESP8266 if you just want to read a temperature sensor. The most basic temperature logger could be written in ~20 lines, it would work great and have good error handling. From my own experience, I know that it is much more cumbersome to do the same thing using AT commands.

Why involve the UNO at all.  The ESP88266 could be programmed with the Arduino IDE to read the sensor and deal with the internet all by itself.  It doesn't need the UNO to do what you want.

The sensor that I'm using LM35 needs at least 4V, besides I will need to program the esp8266 and I don't have tools for that, and I bought for provide wifi to arduino. I have a nodemcu too btw

If you have the tools to program the Arduino UNO then you also have the tools to program the ESP8266.

You didn't google hard enaugh.
There are plenty of examples serving your environment.
This instructables is just one of it.

The main aim of this instructable is to show how you can create a simple web server using Arduino and Wi-Fi module which displays the sensor data in the webpage.

That is not what I need check my description again.

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


text:
trying to discover other nrf24 modules
Today I started messing with the idea of getting an arduino uno to autoconnect with another arduino uno using the nrf24l01 breakouts.
I dont have a particular goal in mind per se but was just wanting to get the logistics down so I started simple as pie.  One arduino at address 0x0000000B LL sends a one element array over and over.  Easy.
The second arduino goes through a for loop in the void loop().
The for loop is set to loop 16 times.  It starts with the address 0x00000000 LL and checks to see if radio.available is true.  if it is, the program simply states it has found an address over serial.  If not it states the address is invalid.  afterwards it increments the address by one and repeats until the address gets to 0x0000000F LL (or the for loop repeats 16 times.)
once the address gets to 0x0000000B (or the transmitter address) it states that it has found an address over serial.  So far so good!
Now the problem arises when the address increments to the next address.  No matter what I seem to do or change, once radio.available() becomes true once....it seems to stay true until the function is called again from the main loop in which case it repeats the same scenario.  I have worked hours on such a small program to no avail.  Can someone help please???  I must be overlooking the most simple of things but for the life of me I have no idea what.
Super Simple TX Code.
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(8,9);
uint64_t myAddress = 0x0000000BLL;
byte txData[] = {1};

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

  radio.begin();
  radio.setRetries(15, 15);
  radio.openWritingPipe(myAddress);
}

void loop()
{
  if( Serial.available() )
    {;}

  radio.write(txData,sizeof(txData) );
  Serial.println("Sent a packet");
}

RX CODE
#include <nRF24L01.h>
#include <RF24.h>

RF24 myRadio(8, 9);

byte rxData[] = {0};

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

  myRadio.begin();
  myRadio.setRetries(15, 15);
}

void loop()
{
  if( Serial.available() )
    {;}
    //function that searches through a set of 16 addresses
    searchAddresses();
}

void searchAddresses()
{
  //declare a temp address variable
  //and initialize it to first possible address
  uint64_t tempAddress = 0x00000000LL;

  myRadio.openReadingPipe(1, tempAddress);
  myRadio.startListening();

  for (int x =0; x < 16; x++)
  {
      if ( myRadio.available() )
      {
        myRadio.read(rxData, sizeof(rxData) );
        Serial.println("Found an address");
      }
      else
      {
        Serial.println("Address Invalid");
      }
      //increment temporary address to next address
      tempAddress++;

      myRadio.openReadingPipe(1, tempAddress);
      myRadio.startListening();
  }
}


text:
how to send large strings (> 100 characters) from arduino serial monitor
I am a newbie to arduino programming. I wish to send big strings which are in range of 100 to 1000 characters to my arduino uno. I saw that arduino cannot read more than 63 characters at a time.

The strings can be received in parts (~40 characters) which will be processed by my program and few minutes later they will get deleted. Then another ~40 characters will be received and the process continues till all the characters are received.

Can you please help me with this. If the question is not clear, you're free to ask in the comments. Thanks in advance :-)

Running 1000 bytes through the serial port will take quite some time: the bytes are sent one after the other. Your Arduino should just process each byte as it receives it.

Do you have any code yet?

@EdgarBonet The bytes are commands to be executed by the machine. So processing might take long

@DaveX Do you mean the code for serial communication?

@dark32 I mean have you got any semi-working code to show what issue you are having.  From the Q, it seems you can process about 40 bytes per few minutes, and you seek to buffer 2-25 commands worth of data within the Arduino.    There's code in 3D printers that processes megabytes worth of serial commands on-the-fly at command-execution speed by using buffering and handshaking on the sending end.  They rely on a state machine to assemble a command and its parameters from a serial stream, and don't pull data out of the the buffer until they are ready for it.

Sorry, no code that was able to read more than 63 characters. I am newbie so i simply used Serial.read() to fetch the strings.

I saw that arduino cannot read more than 63 characters at a time.

Not strictly true. The Arduino core HardwareSerial library has a 64 byte buffer, so it can only buffer up to 64 characters. If your sketch is reading the characters from the buffer whilst you are sending the characters from your PC then that limit is irrelevant. As long as you are reading the characters as fast as they are coming in.
Serial is actually quite slow (on the scale of things) and unless you're doing silly things like using delay() or long blocking loops, then reading the data fast enough is not that big a problem.  If you do need more time the simplest way is just to slow down the serial data somewhat - i.e., use a lower baud rate. The slower you send the data the longer you get between each character arrives to do things.
For strings the size you are on about you are probably best off processing the data on the fly rather than storing it all then post-processing it - simply because the Arduino doesn't have much RAM, so storing large strings isn't always an option.

I do believe that it's possible to change the size of the buffer though. Which may be neccesary if only a high baudrate is possible, on a device where the execution of the messages takes longer than the receiving. In all other cases, your answer will do (:

@Paul Yes, you can always hack the core to increase the SERIAL_BUFFER_SIZE from 64 to something bigger - at the cost of more wasted RAM...

But you'll avoid having to copy it from one buffer to another, in order to be able to receive one message at once. But indeed, if possible, another way of fixing it may be preferable

@Paul: For that, you would have to make the RX buffer public, and you would need to be ready to deal with the message not being contiguous, because it's a ring buffer.


text:
measure very small ( negative and positve ) Voltage with Arduino
How can I measure Voltage in Range -100mv to +100mv with Arduino ,
Is that an Arduino-shield can do that ?

You need to turn it 100% positive. Make it 2.4V to 2.6V by adding 2.5V to it. Then just use the ADC.  If you like, increase the range by amplifying the signal at the same time.

@Majenko that is output from circuit , so i can't add any voltage to this output

Yes you can. You take your existing voltage and add another voltage to it. It's commonly done with op-amps. Here's examples: http://hyperphysics.phy-astr.gsu.edu/hbase/Electronic/opampvar5.html

@Majenko can I use UA471cp ? , can you draw and post the Schematic please ?

Yes, you can probably use that chip, and there are plenty of summing amplifier examples online to pick from.


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

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


text:
Arduino Button interference
With a push button on an Arduino (or Raspberry Pi), instead of wiring a high voltage (5v) through a button and to a pin to read the input, you often want your input pin set to HIGH (high impedance) and wired through a switch to ground to avoid interference like EM waves. My question is what exactly does setting the input pin to HIGH do (besides making it high impedance)? Does it make the circuit less sensitive to EM interference? I like to understand more of the physics behind circuit design.

In Arduino, just setting the pin as input already makes it high impedance.
Writing HIGH on an input pin actually enables its internal pull-up resistor.
This way, the voltage at the pin is always defined (instead of floating when the switch is open).
Just search for "pull-up resistor" if you need more information.
Note that this code:
pinMode(n, INPUT); // set as input, high-impedance
digitalWrite(n, HIGH); // activate the internal pull-up resistor

is equivalent to this (in recent Arduino IDEs):
pinMode(n, INPUT_PULLUP)


text:
Communication between two Arduinos over RF module
I want to communicate Arduino A to Arduino B by using RF module. But my RF module (Tx- XLPCF20, Rx- XY-R01A) only consist of 4 pins of data pin where it can send 4 bits of data only. So, I want to develop a new encoding to send data by using 4 bits of data. How should i do for the coding since I don't want to use serial write for coding. Any suggestion? Help me please. If u can give me the coding, I'm beyond thankful.

You have 4 channels of raw HIGH/LOW communication.  How you use them is up to you.
The simplest method is to use an asynchronous serial protocol:

Use Serial: Connect the TX of one Arduino to channel 1 at the TX, and RX channel 1 to RX on the other Arduino
Use SoftwareSerial: The same as above but you choose the pins
Use VirtualWire: very similar to SoftwareSerial

For higher speeds, since you have 4 channels, you could use a synchronous serial communication protocol. It should be perfectly possible to connect three of the channels to SPI and communicate as if it were talking directly to an SPI device - one channel to SCK, one to MOSI and one to SS. The other end has SCK, MOSI and SS but running in slave mode.
No need to "invent" a 4-bit protocol, it's too much work.


text:
Arduino PWM fading led in assembly
I'm writing Arduino UNO (=ATMega328P-PU) programs in assembly to save memory, so I use avra.exe (same as atmel studio's avrasm32) to compile and avrdude to upload, and simple programs like blinking run fine. But now i tried to half-bright a LED with pwm. I checked up my code for errors but I didn't find any, and the LED just full brighs. I checked wiring too. I'm getting struck :c. Here's my pwm.asm code:
.nolist
.include "m328pdef.inc"
.list

.cseg
.org 0x00
     rjmp start
.org 0x34
 start: sbi ddrb, 5 ;pin 13
        sbi portb, 5 ;pin 13 on, just to compare with the PWMed led
        sbi ddrd, 5 ;pin 5 pwm
        ldi r16, 0b00100011 ;fast pwm mode, non inverted pwm at oc0b = pin 5 (right?)
        out tccr0a, r16 ;I'm using Timer0
        ldi r16, 0b00000001 ;no prescaler
        out tccr0b, r16
        ldi r16, 128 ; duty cycle = 50%
        out ocr0b, r16

  loop: rjmp loop

Try writing the code in C and see if you get any other output using avr-objdump -S <filename>.elf. From my limited knowledge of assembly, the code looks file. What happens if you connect the led the other way around (VCC--resistor--led--pwm-pin vs. pwm-pin--resistor--led--GND)? Out eyes don't perceive different light levels in a linear scale.

I tried your program, after converting it to GNU-as syntax. It works as expected, as seen on the scope. Your problem may be simply that the difference between 50% ON and 100% ON is not very obvious to the eye because of its logarithmic perception.

Got it! i tried to set the duty cycle to 16 (6.25% duty cycle) and I noticed a difference. I didn't know about its logarithmic perception. Thanks!

you have to set the PRR timers on
start:  lds     r16,PRR
andi    r16,0b10010111 ; PRTIM2 | PRTIM0 | PRTIM1
sts     PRR,r16

I'm having trouble making sense of this as an answer to the question, which has an accepted answer which mentions nothing about PRR.  PRR defaults to 0x00 on reset, which is to say nothing is being shut off to reduce power by default.  This is not changed by the bootloader or his code.  Why would they need to change PRR?


text:
AVR timer overflow interrupt not working
My problem is an interrupt service routine (ISR) that seemingly never executes! Here's some info on my set up: I am flashing an avr attiny85. I have the bare bones of a project set up so far with simply a main.c and two modules: timer and hardwareInit. In the timer module, I have a timer0_init function that I am using to set up timer0 for CTC mode to overflow ever 1 ms. Here is the function:
void timer0_init( void )
{
    cli();
    TCCR0B |= 3;    //clock select is divided by 64.
    TCCR0A |= 2;    //sets mode to CTC
    OCR0A = 0x7C;   //sets TOP to 124 so the timer will overflow every 1 ms.
    TIMSK |= 2;     //Enable overflow interrupt
    sei();          //enable global interrupts
}

with the timer set up, I added an ISR to increment ticks every time the counter overflows, so I can keep track of how much time has elapsed, etc.
ISR(TIMER0_OVF_vect)
{
    cli();
    //ticks ++;
    PORTB |= ( 1 << PORTB0 );
    sei();
}

as you can see, I commented out the ticks++ because it wasn't working, and replaced it with PORTB |= ( 1 << PORTB0 ); which simply turns on an LED, so if the interrupt is ever executed, I will know by proof of the LED being on.
Unfortunately, I can't get it to turn on and can't see what I'm missing. (to prove that I 1. have the LED set up on the right pin, and 2. am manipulating the correct bit in the correct register, I put just this statement PORTB |= ( 1 << PORTB0 ); in my infinite loop and confirmed the LED came on)
For further explanation, here is my main.c:
/*================================= main.c =================================*/

#define F_CPU   8000000UL

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#include "timer.h"
#include "hardwareInit.h"

int main(){

    //Initialize hardware HERE
    DDRB |= ( 1 << PORTB0 );    //set this pin as an output for an LED

    SetClockPrescale(1);    //internal clock divided by 1 = 8 MHz, from hardwareInit

    timer0_init();          //set up timer0 for 1 ms overflow

    while(1)
    {
        /* if( getTicks() > 0 )
        {
            PORTB |= ( 1 << PORTB0 );
            _delay_ms(1000);
            PORTB &= ~( 1 << PORTB0 );
            _delay_ms(1000);
        } */

    }
    return 0;
}

So, what you see in the infinite loop is what I tried first, but after that didn't work, I tried something simpler, just having an empty loop (commented out previous stuff), and waiting for the interrupt to get triggered which would turn on the LED.
Any help you could give would be really appreciated. I'm quite puzzled why this hasn't been working.

None of this is Arduino.

cli() and sei() are useless in your ISR as interrupts are automatically disabled at ISR start and re-enabled on return.

@jfpoilpret Thank you!  I was told that it was a good practice to disable and then re-enable interrupts in an ISR so you don't have interrupts interrupting your ISR.   Can you point me to a source that says ISR does that automatically?

Try commenting OCR0 register's value for overflow interrupt to work .Well it worked for me.

You are misunderstanding what an overflow interrupt is. That is called when the timer overflows (ie. it reaches TOP which in the case of an 8-bit timer is 255). Since you are counting to 124 that will never happen, and thus the interrupt will not fire.
You want the "compare A vector" which is called when the "A" register compares to the limit. Example code:
void timer0_init( void )
{
    TCCR0B = bit (CS01) | bit (CS00);    //clock select is divided by 64.
    TCCR0A = bit (WGM01);     //sets mode to CTC
    OCR0A = 0x7C;             //what to count to
    TIMSK = bit (OCIE0A);     //Enable compare match A interrupt
}

ISR(TIMER0_COMPA_vect)
{
    PINB = bit (PINB0);   // toggle pin 5
}

int main(){

    DDRB |= bit (DDB0);    //set this pin as an output for an LED
    timer0_init();         //set up timer0 for 1 ms overflow
    sei ();                // allow interrupts
    while(true) { }        // forever
    return 0;
}

I changed it to toggle pin 5 (which happens extremely quickly) so it will seem to be on but a bit dim. You can see on an oscilloscope or logic analyzer that it is toggling rapidly.
You don't need to turn interrupts off or on inside an ISR. You are better off using the bit names rather than "magic numbers" in your code, as my example shows.

Also note how Nick change TCCR0B |= to TCCR0B =. Since the arduino code uses timer0 for millis, TCCR0B isn't the default value.

Yes, never assume you know what values registers have in them, unless you set them yourself.

Great! I was missing the point of CTC mode. When I set OCR0A to 124, I thought that since the TOP was changed to 124, the timer would overflow when it hit 124. It's now clear to me that overflow is only when the timer reaches the "true" top, in this case 255.  Thanks for your help.

@Gerben and Nick, is it ok to assume the value of the registers when I am flashing the attiny itself, separate from Arduino or anything else that would have already set them?  I was going based off of the datasheet for the attiny85 which shows the initial values of each bit in each register:
http://screencast.com/t/ry9FSpyWQt9

Probably it is. However I don't really see the point of "or"ing in a bit, when in less (or the same) machine cycles you can just set the desired value. If you assign you definitely get what you want, if you "or" you are just hoping.

Please note that the overflow occurs when trying to increment to 256, resulting in 0. Also, it is perfectly fine to use an actual overflow interrupt here, just preload TCNT0 with the diff between TOP and your desired cycles every time the overflow occurs.


text:
How to keep a specific bit set all the time for bit masking I2C operations?
I've been working on I2C and I learned how to initialize, send and receive with I2C communication protocol.
Next, I wanted to run the LCD1602 I2C adapter. But the module has a different bit masking, it turns out that I have to keep a specific bit set so I can control the remaining 7-bits, because otherwise I can't control the upper 4-bits if this bit is 0.
So, I put the 8-bit variable for the bit masking operations in the global section and initialize it with uint8_T bitmasking = 0x08; but it's volatile. I used static keyword, but the bit is not constant.
So what's the solution?
Regards,

'static' just avoids reinitialization and is used for local vars in timed interrupts for example.
volatile is another keyword you should not be using without thinking about it and does not appear to be useful for your case. See https://stackoverflow.com/questions/4592762/difference-between-const-const-volatile for more information
The appropiate keyword would be const, which tells the compiler this var mustn't be changed.
But I suspect there is another problem with your code, which will make the compiler throw an error as soon as you use const in the declaration.
I assume you are not using the variable correctly. You are meant to use a bitwise OR | in order to set the required bit along your actual data.
So do it like this:
data_byte |= bitmasking;
write8(data_byte);

Well, after thinking about it, I don't know, I don't think it's what I want because it may change anytime.

wtf? what may change at any time?

Sorry that method works fine. I figured out another method which is to initialize the variable in the global region with that bit set. Regards,


text:
Can't send Data to LCD1602 with I2C
I've been doing fine with my LCD1602 I2C configuration but I discovered that command and data functions are the same even though I change the RS command/data bit, but the result is the same.
This is really strange, I really can't do anything about it??!
#define E   2   // E  bit
#define RW  1   // RW bit
#define RS  0   // RS bit

#define LCDadd_WR  0x4E
#define LCDadd_RD  0x4F

uint8_t bitmask = 0x08;
uint8_t i, arr[]={0x48,0x65,0x6c,0x6c,0x6f ,0x10 ,0x3a,0x29 ,0x10 ,0x48,0x6f,0x77,0x10
,0x61,0x72,0x65,0x10,0x79,0x6f,0x75,0x65,0x76,0x65,0x72,0x79,0x10,0x6f,0x6e,0x65};

// LCD prototypes
void LCD_Init(void);
void sendCMD(uint8_t CMD);
void sendData(uint8_t data);
void LCD_string(uint8_t arr1[]);
void move_cursor (uint8_t row, uint8_t col);

// I2C prototypes
void I2C_init(void);
void I2C_start(uint8_t address);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

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

void loop() {
//sendData(0x0E); /* I commented this line because it has the same effect as sendCMD(0x0F); in sendCMD function */
}

///////////////////////////////////////////////////
///////////////////////////////////////////////////
void LCD_Init(void)
{
  sendCMD(0x33);
  sendCMD(0x32);
  sendCMD(0x28);
  sendCMD(0x0F);
  sendCMD(0x01);
}

void sendCMD(uint8_t CMD)
{
  bitmask = 0x08;
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask &= ~(1<<RS));
  Serial.println("CMD");
  Serial.println(bitmask, HEX);
  I2C_tx(bitmask &= ~(1<<RW));
  I2C_tx(bitmask = CMD & 0xF0 | 0x08);
  _delay_ms(5);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  _delay_ms(1);
  I2C_tx(bitmask = (CMD<<4) & 0xF0 | 0x08);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  I2C_stop();
}

void sendData(uint8_t data)
{
  bitmask = 0x08;
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask |= (1<<RS));
  Serial.println("data");
  Serial.println(bitmask, HEX);
  I2C_tx(bitmask &= ~(1<<RW));
  I2C_tx(bitmask = data & 0xF0 | 0x08);
  _delay_ms(5);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  _delay_ms(1);
  I2C_tx(bitmask = (data<<4) & 0xF0 | 0x08);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  I2C_stop();
}

uint8_t BF(void)
{
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask &= ~(1<<RS));
  I2C_tx(bitmask |= (1<<RW));
  I2C_stop();
  I2C_start(LCDadd_RD);
  I2C_rx();
  while (!(TWDR == (bitmask & (bitmask<<3))));
  I2C_stop();
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask |= (1<<RS));
  _delay_ms(500);
  I2C_tx(bitmask &= ~(1<<RS));
  _delay_ms(500);
  I2C_stop();
}

void move_cursor (uint8_t row, uint8_t col)
{
  if (row==1)
  sendCMD(0x80+col);
  if (row==2)
  sendCMD(0xC0+col);
}

void LCD_string(uint8_t arr1[])
{
uint8_t cnt=0;
  for (i=0;i<29;i++)
  {
    sendData(arr1[i]);
    _delay_ms(500);
    cnt++;
    if (cnt==16)
    sendCMD(0xC0);
  }
  sendData(0x10);
}

///////////////////////////////////////////////////
///////////////////////////////////////////////////

void I2C_init(void)
{
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
  TWDR = address;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
}

void I2C_stop(void)
{
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
  TWDR = data;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
}

uint8_t I2C_rx(void)
{
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

You might want to try a more specific / complete Arduino library specifically for LCDs and, perhaps, specifically for the LCD1602.  That way, if that works, you can eliminate hardware problems.  Then return to your raw i2c code and feel more assured the problem is in the code.  Also, you can check the library solutions against your own and see if there is anything you might have missed.  The i2c protocol allows for some flexibility and, unfortunately, that leads to some confusion from time to time.

Yes, I used a very good Arduino library which works fine, the problem is in my code. And specifically in the sendData function because it works as sendCMD the same, so if I changed the function calls in LCD_init function from sendCMD to sendData, then it works the same, even I set the RS in sendData to 1 !!? But I don't know where is the problem.

You might like to try attaching a logic analyser to examine precisely what is being sent from the Arduino to the LCD.

Hello friends :) I discovered the problem!! One member told me about. Which is that I override the bitmask for the RS in data function, so it would still work as a command function, he solved that for me by adding the RS bitmask with I2C_tx(bitmask = (data<<4) & 0xF0 | 0x08 |= (1<<RS));

I2C_tx(bitmask |= (1<<RS));
I2C_tx(bitmask &= ~(1<<RW));
I2C_tx(bitmask = data & 0xF0 | 0x08);

RS is overridden in the third line, so the solution is:
I2C_tx(bitmask = data & 0xF0 | 0x08 | (1<<RS));

And delete the first two lines :)


text:
HMC5883L not working in continuous mode!
I'm just starting with the HMC5883L, I'm writing my code with C and also my own I2C library.
I noticed that the values on the Arduino IDE's serial monitor are constant.
Then I developed a function to read the mode register. So the value should be 0x00 for continuous mode.
But, what I get is that the device work in single mode which has the value 0x01 at first cycle of the program, then it goes to idle mode with the value 0x03.
So, why is that and what to do?
#include <I2C.h>

#define HMC5883L_read   0x3D
#define HMC5883L_write  0x3C

#define Configuration_Register_A    0x00  //Read/Write
#define Configuration_Register_B    0x01  //Read/Write
#define Mode_Register               0x02  //Read/Write
#define Data_Output_X_MSB_Register  0x03  //Read
#define Data_Output_X_LSB_Register  0x04  //Read
#define Data_Output_Z_MSB_Register  0x05  //Read
#define Data_Output_Z_LSB_Register  0x06  //Read
#define Data_Output_Y_MSB_Register  0x07  //Read
#define Data_Output_Y_LSB_Register  0x08  //Read
#define Status_Register             0x09  //Read
#define Identification_Register_A   0x10  //Read
#define Identification_Register_B   0x11  //Read
#define Identification_Register_C   0x12  //Read
#define declination_angle 3.46

void HMC5883L_init (void);
int16_t data_read (int16_t *results);
uint8_t HMC5883L_read_reg (uint8_t reg);

int16_t results[3];
float m_scale = 1.0;

void setup() {
  // put your setup code here, to run once:
  I2C_init();
  Serial.begin(9600);
  HMC5883L_init();
  Serial.print("mode register ");
  HMC5883L_read_reg(Mode_Register);
  Serial.println();
}

void loop() {
  // put your main code here, to run repeatedly:
  data_read(results);
  Serial.print("x-axis = ");
  Serial.println(results[0]);
  Serial.print("z-axis = ");
  Serial.println(results[1]);
  Serial.print("y-axis = ");
  Serial.println(results[2]);
  Serial.println();
  Serial.print("mode register ");
  HMC5883L_read_reg(Mode_Register);
  Serial.println();
_delay_ms(500);
}

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

int16_t data_read (int16_t *results)
{
  uint16_t lsb,msb;
  int16_t status_of_process = 0;
  I2C_start(HMC5883L_write);
  I2C_tx(Data_Output_X_MSB_Register);
  I2C_start(HMC5883L_read);

  msb = I2C_rx();
  lsb = I2C_rx();
  results[0] = msb << 8 | lsb;

  msb = I2C_rx();
  lsb = I2C_rx();
  results[1] = msb << 8 | lsb;

  msb = I2C_rx();
  lsb = I2C_rx();
  results[2] = msb << 8 | lsb;

  I2C_stop();

  return status_of_process;
}

uint8_t HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  Serial.println(reg_dat);
}

Regards,

Try it with the Arduino Wire library. Why did you make your own I2C library ?

Because I want to know how to activate communication protocols. I can't proceed to further topics in programming without knowing to how program SPI, I2C and USART, that's very important to me. Because I can't do advanced things before doing easy things like writing a library for I2C.

Perhaps it is more useful when you explore the PWM modes of the timers. It took many, many years (far too many years) until the Arduino Wire library for AVR microcontrollers was working well. You seem to use some kind of repeated start, but I don't know if your own I2C library supports that. There are a number of working libraries for I2C. But they will probably only work when used in a straight forward way for only the most compatible sensors. Do you have a logic analyzer ? That makes it possible to pinpoint the problem.

No I don't have a logic analyzer. But in regard to my I2C library, it works well and I even have a message checking function to check the result of each I2C operation, which I don't apply anymore because I tested it while I was developing the library and when I approved that my tx and rx are working well, I removed the checking function.

When you are serious about learning communications, then you should buy a logic analyzer. It really helps a lot. I prefer 8-channel, 24MS/s with unlimited data length and software that can decode I2C and UART data. The Saleae Logic8 costs 219 dollars, perhaps the Logic4 is good enough for I2C. If you want it very cheap, here are some that costs only 5 dollars: https://sigrok.org/wiki/Supported_hardware . Get one today!

Yeah, I know but it's not that I don't respect logic analyzer, but it's that this process of programming with Arduino IDE is easy enough to debug with Serial monitor, I have a function to check the process of I2C communication which tells what is going on, if your data transmission is successful or not! So in this situation, I don't think of a logic analyzer because the Arduino IDE's serial monitor helps a lot in debugging or displaying data.

It helps a lot. It helps even more than a lot.

I noticed this: http://www.avrfreaks.net/forum/undefined-reference-function-i2c-library-and-hmc5883l-read-function You have asked the same question at avrfreaks, and many people have problems with your own I2C functions. If you want to make it work, then use code that is known to work, if you want trouble, then go ahead and wander around. The I2C is too complex as a start to learn programming.

Well, knowing that I2C is too complex to start with, and the fact that I learned something in I2C and developed a good library << to my perspective. Is really encouraging to me that I can do hard things in programming in C. I learned things in the past weeks, I ran an I2C I/O expander, I2C LCD module and this HMC5883L. That's a good advancement to me. Applying a working code from the web is one of my strategies too, it's also a good way to test your hardware and learn something in software :)

Okay. But everything is already available (Wire library, many HMC5883L libraries, and so on). Use them as an example. How about that logic analyzer ?

Yeah, I know but I can't get into those libraries because I have little experience about reading other codes. If I'm a professional programmer, then I can look into other codes to save time and apply them in my projects. But to me, it's hard to read those codes, I've been into the process where I was in the beginning of Arduino and PIC platforms, then I switched to Arduino for the wide information sources, then I was in the middle of many many codes where I have little experience in coding. In start I applied some of Arduino libraries, and then when I went into advanced codes ...

... I realized that I need to start learn how to code and time is running, and I have to learn a lot of things in future, I have to learn about Raspberry pi and ESP32. And there are a lot of projects where if I relied on pre-written codes from other people, I would be asking and waiting for them to write me a code! Why won't I learn how to code?

I really don't need a logic analyzer right now, I'm moving to an advanced college where they have different electronics laboratories. Oh, I forgot to tell you, I'm an electronics trainer, so in future if I want to teach trainees how to code, then I better learn how to write some good codes. I have different reasons which force me to learn coding.

The problem stems from this function:
void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

The way I2C in most chips work, when writing, is that the first byte defines the register to write to. All subsequent bytes are the data to write into that register and successive registers.

To minimize the communication between the master and this device, the address pointer updated automatically without
  master intervention. This automatic address pointer update has two additional features. First when address 12 or higher
  is accessed the pointer updates to address 00 and secondly when address 08 is reached, the pointer rolls back to
  address 03.

So you are actually writing:
REG  CONTENT
0x00 0x07
0x01 Configuration_Register_B (0x01)
0x02 0x01
0x03 Mode_Register (0x02)
0x04 0x00

You need to either start a new transaction for each register you want to set a value in (explicit setting) or rely on the address pointer increment to move to the right register for you (implicit setting).
So either:
void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_stop();

  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_stop();

  I2C_start(HMC5883L_write);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

Or, since the registers are in sequence in the address space:
void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(0x01);
  I2C_tx(0x00);
  I2C_stop();
}

Oh, and don't forget to have an I2C_stop() after reading your register in:
uint8_t HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  I2C_stop(); // <----- MISSING
  Serial.println(reg_dat);
}

Thank you so much, now I get 0x00 for mode register but the readings still constant.

Your configuration settings look messed up. You're setting an invalid measurement mode in Config Register A, and setting only an unused bit to 1 in Config Register B. I use 0x78 in register A and 0x20 in register B (which gets changes when I select a different gain).

OMG, you're so right! How did I miss with the configuration values, I followed the values in the HMC5883L datasheet.

OK, now how to learn about gain and the other calibration stuff? Regards,


text:
Using SPI without driving MISO
I am developing an application where an Arduino Pro Mini communicates with a 12-bit ADC over SPI. The communication is one-way, meaning that the ADC will only send data back to the Arduino, not receive any. The MOSI pin is therefore not required in my application, only SCK and MISO.
I wish to know if there is a way to have the Arduino SPI library ignore the MOSI pin, and controlling the clock pin directly. The ADC requires 16 clock cycles to perform one conversion, sending the data back on the last 12 clock cycles. The way I have implemented it is by using SPI.transfer16() to get 16 clock cycles, and storing the return value in a 16bit variable. The downside to this is that the MOSI pin is driven, and I can therefore not use it for other purposes. I would very much like to be able to generate 16 clock cycles without the need for driving MOSI. Any ideas?

SPI devices communicate in full duplex mode. Cant you use other interfaces that use less wires in their standard?

Switching it to an input should disconnect it from SPI. Otherwise, it will be MOSI.

You could always use bitbanging in the form of shiftIn.

@IgnacioVazquez-Abrams That would be a good solution if I wanted to use the MOSI pin as an input. However, I require it to be an output.

@Gerben That looks viable. But I worry that it might not be as reliable as the hardware implementation.

The SPI feature varies on different processors.  The Arduino Pro Mini uses a ATmega328.  Either you need to download the appropriate SPI (and other) libraries from github and alter them - or read the ATmega328 chip spec.  It may be you can control the ATmega328 MOSI pin by simply using the pinmode() call and defining it as an output like you want.  Or you may be stuck in a situation where the ATmega328 is either in SPI mode and controlling all SPI pins or not in SPI mode and letting you control all SPI pins.

@st2000: I guess I'll just have to do some experimenting and see what works and what doesn't.

@yabbadabba: Yes, as Gerben already recommended. Could possibly be a solution.

The hardware features are so nice, because they're implemented in hardware. Theoretically, it would require changing the hardware itself. If you really need one extra pin, you could use an I/O expander (SPI or I2C) or a bigger chip.

In microcontrollers, the GPIO pins have a multiplexer to select what the pin is used for.  When you use the Arduino SPI library, the initialization function will set the multiplexer to MOSI for that pin.  You should be able to run your own initialization for that pin and overwrite whatever the SPI initialization function did.  Just make sure to call your initialization after SPI.begin().  This is the simplest solution.
If that doesn't work for some reason then you can dig into the source code for the Arduino SPI library.  This isn't too hard either.
Bitbanging is the hardest solution and shouldn't be necessary for your application.

This solution worked for me.  I wanted to use the MISO pin for DC on a SSD1331 display.  I privately modified the AdaFruit library constructor to call pinMode after SPI.begin() and it worked.

You are using ADC which I suppose you have no way of changing firmware or anything to modify the protocol.
According to SPI protocol, when Slave receives a byte, it sends byte kind of a two shift registers in circular buffer. So even if your ADC finish the conversion it wont start communication protectively the protocol doesn't allow it.
In case if you have other ADC IC which is programmable you can implement your protocol but it wont be SPI it will be your own protocol, so be assure of it.


text:
How to generate Analog Signal (Voice) to the microphone
I have question about microphone and generating sound signal. I have microphone in my intercom at home. It is simple analog microphone, not digital.
What I want is to connect arduino analog output to the microphone and generate some signal that will be heard like a voice at least few words.
Is it possible to do this ? Or it would be quite hard ?
Please suggest the easiest way to implement this.

This might help https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

It will be impossible to "generate some signal that will be heard like a voice" using an Uno - or perhaps any Arduino. Playing a pre-recorded track is possible, as linked in a previous comment, but you will need a board with a digital to analogue convertor built in, like a Due.


text:
Can I connect an Arduino wifi module directly to my android phone?
I would like to use my arduino even where there's no wifi router. I've only found people saying that it needs to connect to a router, but isn't the phone like a router when it's in tethering mode? Do I still need a mobile internet connection or can I do it directly?

A phone running in wifi tethering (mobile hotspot) mode is no different to a wifi access point or router. So yes, you can use that.
Chances are though that you will need a mobile internet connection in order to activate mobile hotspot mode in the first place.

My Galaxy Mini 2 lets me turn mobile router while not connected to mobile connection. The matter's that the example sketches that I've seen by now are all something like this: connect to a router, get the ip, and then from android you put the ip and connect to the arduino. I'd like to skip the ip part: arduino connects to the mobile router, and (since when you connect to a router you need to send data back and forth from router to user and vice versa) they exchange data even if the mobile phone has no connection. Can I do this?

You need the IP. Without that you don't know where to send data. You may be able to find it in the tethering settings under the list of connected devices depending on the version of Android.

So I always need an internet connection. I thought it would have worked like bluetooth, since router and user need to talk to each other, but what you're saying suggests me I can't. Unless I can use the "internal IP" (don't know if it is its name), the one that is always 192.something. If I can use that, isn't it given before the connection to the internet starts?

An IP is an IP. Every device connected on a network needs one. The phone can hand one to the Arduino through DHCP. You don't need an internet connection for that, not if you can turn on mobile hotspot without one. It sounds like you need a crash course in how networks work. Browse around wikipedia a bit and learn the basics first.

If you are using the Arduino UNO WiFi Board (http://www.arduino.org/products/boards/arduino-uno-wifi) with the built in ESP8266 chip then your phone can connect directly to the Arduino's network and you can interact with it that way.
With the default firmware, this board can simultaneously connect to a local WiFi network, and create its on access point. This is very handy because it means that you can connect and access its hosted web pages even without a WiFi router with no extra setup steps, or special configuration.

Sounds like the OP wants the opposite.  Not using a phone to connect to the ESP8266 module (as AP or captive portal).. but use the ESP8266 to connect to the phone and use it as an AP.

@whispers That could be, but the question isn't clear, and often when the question isn't clear it is because the OP didn't know that the other method was even an option.


text:
How should I use an optocoupler to control a 12Vcc load with Arduino?
I am developing a project to operate a load of about 12Vdc.  I considered the use of an optocoupler to avoid mechanical wear of a relay.  The design I have tried is this:

This configuration seems to work OK, but I am a biologist and this is my first attempt with an opto of any kind!!!!  I had a lot of trouble with the transistor until I changed to a PNP.  Is this right?  Can it be done with an NPN or even without any transistor at all?

If your load draws a small amount of current (less than about 30 mA current), your 4N35 optocoupler could drive the load directly on 12 volts.
Ignore my use of 4N28 (similar to 4N35). It is the symbol that I had.
It appears that your PNP transistor circuit is something like this :

The PNP transistor circuit can work well depending upon your load current.  The PNP circuit has some problems with the transistor not turning on fully (and won't be described here).  You may not get the full 12 volts to your Load. But, if it works for your load, then be happy with the PNP circuit.
The circuit below is for a NPN transistor circuit  :

Using the NPN circuit allows (in this case) for the transistor to turn on fully, leaving almost the full 12 volts for your Load.
Important Note :  The NPN transistor circuit produces an output that is the LOGIC opposite of the PNP circuit.   Notice that for the PNP circuit, a logic 1 to the input of the optocoupler (LED on) turns on power to your Load.
On the NPN circuit, a logic zero (0) to the optocoupler LED is required to turn on your Load.
Another variation of the circuit is below, and does NOT have the reverse logic situation.  In other words, it will behave like the PNP circuit. When LED is on, the Load will be on  :

You can experiment with the value of R1 in the NPN circuits. You could experiment with lower value, down to 1K (1000 ohms) if you are using a power transistor to drive high current loads.

Very informative and useful solution to my question Marla.  Thank you very much.


text:
Arduino Audio Shield Problems
I recently bought a Velleman KA02 Arduino Audio Shield (http://www.velleman.co.uk/contents/en-uk/p579_ka02.html), which uses an ISD1760PY audio chip and soldered it together. The first time I fired it up, it worked fine, I had freshly soldered it together. But from the next time up to now, if I press any button but the reset button, the onboard LED blinks 7 times and it doesn't record or do anything. I checked the solder joints and nothing fell out and I also checked the ISD1760PY datasheet but found nothing about my problem. Is there a way to fix this and why it it happening? Please note that I am not controlling the shield with SPI or with the Arduino.
This question was put on hold in the EE section so I an posting it here because the reason was that it has something to do with Arduino.

Look at page 35 of winbond datasheet.
If the LED is blinking 7 times either the chip is in isp mode or in an unstated mode. This can happen after power off during erase function.
I held erase button for about 20 seconds and after that I was able to record messages.


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:
troubleshooting - Turn on a single led in a ws2811 ledstrip with an arduino Uno with FastLed
I want to to turn on a single led in a ledstrip running on ws2811 with an Arduino Uno.
The problem is that when I try to turn just one of them on, they all three light up. The strip is a 3-wire strip, with GND, 12V and DIN. I am just running an example from the Arduino library FastLed
My code can be seen below
// Use if you want to force the software SPI subsystem to be used for some     reason (generally, you don't)
// #define FASTLED_FORCE_SOFTWARE_SPI
// Use if you want to force non-accelerated pin access (hint: you really don't, it breaks lots of things)
// #define FASTLED_FORCE_SOFTWARE_SPI
// #define FASTLED_FORCE_SOFTWARE_PINS
#include "FastLED.h"

///////////////////////////////////////////////////////////////////////////////////////////
//
// Move a white dot along the strip of leds.  This program simply shows how to configure the leds,
// and then how to turn a single pixel white and then off, moving down the line of pixels.
//

// How many leds are in the strip?
#define NUM_LEDS 3

// Data pin that led data will be written out over
#define DATA_PIN 6

// Clock pin only needed for SPI based chipsets when not using hardware SPI
//#define CLOCK_PIN 8

// This is an array of leds.  One item for each led in your strip.
CRGB leds[NUM_LEDS];

void setup() {
    // sanity check delay - allows reprogramming if accidently blowing power w/leds
delay(2000);
FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);

}

// your leds.
void loop() {
  leds[0] = CRGB::Red;
  leds[1] = CRGB::Black;
  leds[2] = CRGB::Black;
  FastLED.show();

}

There appears to be several versions of this chip.  Does your chip have pin 7 (SET) populated?  Also, are you building this from scratch?  (If so please post the schematic.) Is there a resistor between 12V and the VDD of the chip?

That is just the way those led strips are wired. They are sets of 3 leds connected to a single WS2811 chip. Those chips only have 3 color channels.