text:
Is it possible to make 4hz readings with the DS18S20 temperature sensor?
My current code that doesn't convince me:
#include <OneWire.h>

int DS18S20_Pin = 3; //DS18S20 Signal pin on digital 3
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
//Temperature chip i/o
OneWire ds(DS18S20_Pin);  // on digital pin 3

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

void loop(void) {
  if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        float temperature = getTemp();
        Serial.println(temperature);
    } //just here to slow down the output so it is easier to read

}

float getTemp(){
  //returns the temperature from one DS18S20 in DEG Celsius

  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
      //no more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44,1); // start conversion, with parasite power on at the end

  byte present = ds.reset();
  ds.select(addr);
  ds.write(0xBE); // Read Scratchpad

  for (int i = 0; i < 9; i++) { // we need 9 bytes
    data[i] = ds.read();
  }

  ds.reset_search();

  byte MSB = data[1];
  byte LSB = data[0];

  float tempRead = ((MSB << 8) | LSB); //using two's compliment
  float TemperatureSum = tempRead / 16;

  return TemperatureSum;

}

the outcome of few seconds of recording:
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31

EDIT: I inserted the suggestion of @frarugi87 and I inserted the sensor in my pants to test it:
22.50
22.50
22.50
23.69
23.69
23.69
23.75
23.75
23.75
23.75
23.75
23.75
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
24.00
24.00
24.00
24.06
24.06
24.06
24.19
24.19
24.19
24.25
24.25
24.25
24.31
24.31
24.31
24.44
24.44
24.44
24.50
24.50
24.50
24.56
24.56
24.56
24.56
24.56
24.56
24.62
24.62
24.62
24.69
24.69
24.69
24.75
24.75
24.75
24.81
24.81
24.81
24.87
24.87
24.87
24.87
24.87
24.87
24.94
24.94
24.94
25.00
25.00
25.00
25.00
25.00
25.00
25.06
25.06
25.06
25.12
25.12
25.12
25.12
25.12
25.12
25.19
25.19
25.19
25.25
25.25
25.25
25.25
25.25
25.25
25.31
25.31
25.31
25.37
25.37
25.37
25.44
25.44
25.44
25.44
25.44
25.44
25.50
25.50
25.50
25.50
25.50
25.50
25.56
25.56

I still find the change of temperature slow

I would expect some variations in temperature, but I would not say that is a problem caused by the 4Hz readings. You can test my assumption by reading every 3 seconds, does the temperature value change or is it still the same?
I see two potential problems:

your DS1820 is defect.
from your code I assume that you use parasitic power. In that case the chip consumes power from the data wire ( one wire ;-) ) through a pull up resitor (~4.7 kOhms). If you do not provide a special handling, to drive more current while the DS1820 is converting or copying data to EE or from EE memory to the scratchpad, then there will be (most likely) voltage drops.
Then the Temperature conversion will not happen and you read the old value from the scratchpad in your read cycle.

You can test point 2 by adding VCC to the DS1820, and do not use parasitic power.
If that is your problem, you can fix it with a switching FET Transistor, that provide more current (see DS1820 Datasheet from Maxim) or by using an additional VCC wire.

There's no variation because it's just measuring the room temperature.

But the DS18S20 produces heat. So a change of +-0.01 should be probable. Your second time series is very interesting. There are blocks of  some measures (3-5) with the same value.  Why isn't it increasing continously. It seams that the conversion speed is too high. The first jump is over 1.07 degree, followed by 2 times 0.06 degree, followed by 0.07 degree. Then 2 times 0.6 degree, followed by 0.07 degree and so on. That may be by coincidence but I think it is interesting. Perhaps it's a matter of resolution or conversion time. It's time to reactivate my old DS18S20 and uv your question. ;-)

I hope it will be the same with your sensor

Not sure if this is the only problem, but when shifting bytes you will lose the msb. This can be solved by casting the variable to an int.
And moreover you don't need the two variables MSB and LSB.
Try to correct it with this:
float tempRead = ((((int)data[1]) << 8) | data[0]); //using two's compliment

The temperature change is still slow when I apply the finger.

@GabrieleGiordano Ok, so it is slow. But.. Is it accurate? I mean, after a lot of time, is the reading correct or not?

I suppose yes. Seems also in other fields the reading of skim temperature has a low variance

If it is accurate, then the problem can be a bad thermal coupling or a high thermal capacitance, even if it seems too high. Can you make measurements at "full speed" and see if the time is the same? Can you try to make a measurement, leave it running for some seconds *just tu see the trend) and then reset the device? If it is a software problem you will see a "jump" in the temperatures, if it is a thermal problem nothing will change the trend

"and see if the time is the same?" which time?

Is it possible to make 4hz readings with the DS18S20 temperature sensor?

Yes, but only at 9-10 bits resolution. See Table 2. Thermometer Resolution Configuration. At full resolution, 12 bits, the conversion time is 750 ms. With the commands, reset, etc, this gives just over 1hz.
I guess this also gives you a hint on what to fix in your sketch.
Cheers!

unfortunately no, this doesn't give me an input

for (int i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
}
this is the part to modify? It's the only option I see at the moment

no I think it's here the hot spot
}
int16_t raw = (data[1] << 8) | data[0];
if (type_s)
{
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10)
{
// "count remain" gives full 12 bit resolution
raw = (raw & 0xFFF0) + 9 - data[6];
}
}
else
{
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw & ~7;
else if (cfg == 0x20) raw = raw & ~3;
else if (cfg == 0x40) raw = raw & ~1;

The rate of change of the temperature reading depends on the thermal properties of the sensor package, not on the rate at which you read it. The less expensive, plastic packaged sensors that most of us use will be the slowest to respond to change just because that is the thermal nature of the plastic. Do note that the ground pin of that package has more influence than the package itself, so do your best to ensure the ground pin is exposed to the temperature you're trying to measure, or is at least thermally insulated from the surrounding air, unless the air temperature is what you are trying to measure. If you need faster response to temperature change, you'll need to pay attention to keeping the entire device at or close to the temperature of interest and insulated from surrounding temperatures.


text:
Getting NaN error in Processing when Xbee is used and trying to create a popup window.
I am trying to get data from D6T Omron thermal sensor. It works fine with both Arduino and Processing when I connect it to pc directly. However, it seems to always cannot read my last data in my data array when i use Xbee on them. It results in a NaN for my last data in my array in processing display [Fig 1].
Anyone having any thoughts on this? Any help will be much appreciated! =D
Another problem i having here is that i was trying to make a popup window when my sensor senses a sum of 34*4 in the center pixels with no success currently. The last data in the array returns in NaN error again and the program is not responding after that. [Similar with Figure 1.] D:
It actually works fine until we reach this stage "Serial.write(0x03)" from Arduino to processing when it senses a sum of 34*4 in the center. I am confused. Any idea on how to improve that? =) Thanks a lot in advance!
Attached below is my code (Arduino sketch):
#include <Wire.h>
#include <WireExt.h>

#define D6T_addr 0x0A
#define D6T_cmd 0x4C

int rbuf[35];
float tdata[16];
float t_PTAT;
float top_sum, bottom_sum, left_sum, right_sum, center_sum, center_row_sum;

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

void loop()
{
  int i;

  if (Serial.available() > 0) {
    int inByte = Serial.read();
    if (inByte == 0x0001) {

      Wire.beginTransmission(D6T_addr);
      Wire.write(D6T_cmd);
      Wire.endTransmission();

      if (WireExt.beginReception(D6T_addr) >= 0) {
        i = 0;
        for (i = 0; i < 35; i++) {
          rbuf[i] = WireExt.get_byte();
        }
        WireExt.endReception();

        t_PTAT = (rbuf[0]+(rbuf[1]<<8))*0.1;
        for (i = 0; i < 16; i++) {
          tdata[i]=(rbuf[(i*2+2)]+(rbuf[(i*2+3)]<<8))*0.1;
        }

        output_csv();
        delay(250);
      }
      top_sum= tdata[0] + tdata[1] + tdata[2] + tdata[3];
      bottom_sum= tdata[12] + tdata[13] + tdata[14] + tdata[15];
      right_sum= tdata[0]+ tdata[4] + tdata[8] + tdata[12];
      left_sum= tdata[3] + tdata[7] + tdata[11] + tdata[15];
      center_sum= tdata[5] + tdata[6] + tdata[9] + tdata[10];
      center_row_sum= tdata[1] + tdata[2] + tdata[5] + tdata[6] + tdata[9] + tdata[10] + tdata[13] + tdata[14];

     if (center_sum>34*4)
    {
      //Serial.flush();
      Serial.write(0x0003);
      delay(100);

    }
}
  }
}

void output_csv() {
  for (int i = 0; i < 16; i++) {
    Serial.print(tdata[i]);
    if (i < 15) {
      Serial.print(",");
    }
    else {
      Serial.println();
    }
  }
}

Attached below is my code in Processing:
import processing.serial.*;
import controlP5.*;
import javax.swing.JOptionPane.*;
ControlP5 cp5;
javax.swing.JOptionPane JOptionPane;

Textlabel myTextlabelA;
boolean canStart = true;
boolean canInput = false;
boolean Start = false;
String typedText = "Comments: ";
PFont font;
int confirm;

float[] tdata = new float[17];
float tptat; // PTAT
String portName;
//int serialport = 0;

String buf;
float colourGreen; //change green in relation to temperature

int lbTemp = 25; //lowest relative temperature
int hbTemp = 40; //highest relative temperature
Serial myPort;  // Create object from Serial class

void setup() {
  size(600,768);
  background(ControlP5.BLACK);
  myPort = new Serial(this, "COM15", 9600);
  myPort.clear();
  cp5 = new ControlP5(this);

  myTextlabelA = cp5.addTextlabel("label")
                    .setText("GUI of Alive Human Detection System.")
                    .setPosition(120,10)
                    .setColorValue(#FFFAF0)
                    .setFont(createFont("Georgia",20))
                    ;

  cp5.addButton("Start")
     .setPosition(115, 670)
     .setSize(100,30)
     ;

  cp5.addButton("Stop")
     .setPosition(375, 670)
     .setSize(100,30)
     ;
}

public void Start(int theValue) {
  println("Initialising...");
  println("Connected.");
  Start = !Start;
}

public void Stop(int theValue) {
  println("Shuting Down...");
  myPort.write(0x02);
  Start = !Start;

}

void draw() {
    if (Start){

    myPort.write(0x01);
    delay(100);
    while (myPort.available() > 0) {
    delay(500);
    buf = myPort.readString();
    myPort.clear();
    tdata = float(split(buf, ','));
    for (int i = 0; i <16; i++) {
    colourGreen = map(tdata[i],lbTemp,hbTemp,255,0);
    fill (255,colourGreen,0);

      if (i == 0)
    { rect(450,64,150,150);}
      else if (i == 1)
    { rect(300,64,150,150);}
      else if (i == 2)
    { rect(150,64,150,150);}
      else if (i == 3)
    { rect(0,64,150,150);}
      else if (i == 4)
    { rect(450,214,150,150);}
      else if (i == 5)
    { rect(300,214,150,150);}
      else if (i == 6)
    { rect(150,214,150,150);}
      else if (i == 7)
    { rect(0,214,150,150);}
      else if (i == 8)
    { rect(450,364,150,150);}
      else if (i == 9)
    { rect(300,364,150,150);}
      else if (i == 10)
    { rect(150,364,150,150);}
      else if (i == 11)
    { rect(0,364,150,150);}
      else if (i == 12)
    { rect(450,514,150,150);}
      else if (i == 13)
    { rect(300,514,150,150);}
      else if (i == 14)
    { rect(150,514,150,150);}
      else if (i == 15)
    { rect(0,514,150,150); }

    if (tdata[i]<5) {fill(255);} else {fill(0);}
      if (i ==0)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),525, 139);}
      else if (i == 1)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),375, 139);
      }
      else if (i == 2)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 139);
      }
      else if (i == 3)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),75, 139);
      }
      else if (i == 4)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 289);
      }
      else if (i == 5)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 289);
      }
      else if (i == 6)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 289);
      }
      else if (i == 7)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 289);
      }
      else if (i == 8)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 439);
      }
      else if (i == 9)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 439);
      }
      else if (i == 10)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 439);
      }
      else if (i == 11)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 439);
      }
      else if (i == 12)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 592);
      }
      else if (i == 13)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 592);
      }
      else if (i == 14)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 592);
      }
      else if (i == 15)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 592);
      }
    }
    delay(250);
    CheckSerial();
  }

    }

}

void CheckSerial()
{
    confirm = myPort.read();
    if (confirm == 0x03)
  {
  int dialogResult = JOptionPane.showConfirmDialog (null, "Human found? Please Confirm!!", "Alert!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
  if(dialogResult == JOptionPane.YES_OPTION)
  {
  //futher action
  }
  }
}

Have you tried displaying the string you are receiving in order to confirm it's correct?

Okay! i will try again. =) thanks! @Majenko

@Majenko I tried to change my code a bit but still no positive result. Whenever it detected 32*4, Arduino should be sending Serial.print("found"); to processing and processing should be reading the string "found" and then showing a popup window in result.
In real scenario, when it meet the condition, and Arduino started to Serial.print ("found") , I got ArrayIndexOutOfBoundException :1 in processing and the program is not responding after that. I have no idea where seems to be the problem. D: Any suggestion on how to improve these?

source: Stack Exchange

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

sort: votes


text:
Can you use both 3.3v and 5v
Can you use an Arduino EtherMega's 3.3v and 5v pins with two sensors, one requiring 3.3v and the other 5v and a sketch that combines both?

Yes. As long as you take into account that the outputs of the Arduino will be 5V so you may need to reduce that to 3.3V for the 3.3V sensor (if it has any connection to an output).

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


text:
RTC interrupts and coin batteries
Summary
I'm having problems with my RTC draining its coin cells quickly - fresh batteries are drained in a few months. The RTC is set to signal an interrupt every 5 minutes, and I wonder - if there is no other power attached to the circuit, is that enough to drain the coin cell?
Details and my troubleshooting:
Problems with my RTC - if I leave the circuit unpowered for a few days (so that the only power to the RTC is from the coin cell backup), the time resets to 00:00 January 1, 2000. This doesn't happen immediately when I unplug it. If I disconnect it from the computer, plug it back in the next day, the time is ok. If I leave it unplugged for a few days, then plug it in, the date is reset.
This suggests the battery is bad. So I tested it with my meter (and an 100 ohm load, as described here: https://www.youtube.com/watch?v=HcikzMG7mMU). And sure enough, the batter has dropped quite a bit from its 3V start value.
That's all good, except that this battery is only a few months old, and it should last for years in an RTC. I've got two batteries purchased in the last year and used in RTC modules, and both are now drained.
My current hypothesis is that, after I unplug my circuit from the computer, the RTC continues to run on the coin cell, firing interrupts every 5 minutes, and it is these interrupts that are causing the drain. Does this make sense? If not, what else could I check?
Setup
Breadboard arduino, DS3231 RTC on a breakout, connected

RTC SDA -> Arduino A4
RTC SCL -> Arduino A5
RTC GND -> Common GND
RTC VCC -> Common 5V (from ftdi/USB cable, when plugged in)
RTC SQW -> Arduino D2

The RTC is 'active-low', and the SQW pin is held at 5V between interrupts. With my multimeter, the brief drop to 'LOW' is undetectable. I also can't detect any current flow from the SQW pin with my multimeter.
Sketch
Including only the code related to the RTC (SD card and temperature bits removed).
/*-(Import required libraries)-*/
#include <Time.h>
#include <DS3232RTC.h> //source: https://github.com/JChristensen/DS3232RTC

/*-( Declare Constants )-*/
const int wakeUpPin = 2;
#define resolution 5 // frequency in minutes to wake from sleep

/*-(Declare Variables)-*/
time_t t;
int nextLoop;

/****** SETUP: RUNS ONCE ******/
void setup()
{
  Serial.begin(9600);

  Serial.println();
  pinMode(wakeUpPin, INPUT);

  t = RTC.get();

  nextLoop = ((minute(RTC.get()) / resolution) + 1) * resolution;
  if (nextLoop >= 60) {
    nextLoop -= 60;
  }
  Serial.print(RTC.temperature());
  Serial.print(",");
  Serial.print(RTC.oscStopped());
  Serial.print(",");
  Serial.println(nextLoop); // the minutes when the next reading will be taken

}

/****** LOOP: RUNS CONSTANTLY ******/
void loop()
{
  t = RTC.get();

  Serial.print(year(t), DEC);
  Serial.print("/");
  Serial.print(month(t), DEC);
  Serial.print("/");
  Serial.print(day(t), DEC);
  Serial.print(",");
  Serial.print(hour(t), DEC);
  Serial.print(",");
  Serial.print(minute(t), DEC);
  Serial.print(",");
  Serial.print(second(t), DEC);
  Serial.print(",");

  goToSleep();
}

void goToSleep(void) {
    Serial.print("Sleeping until: ");
    Serial.println(nextLoop);
    Serial.flush();
    RTC.setAlarm(ALM2_MATCH_MINUTES, nextLoop, 1, 1);
    RTC.alarmInterrupt(ALARM_2, true);
    attachInterrupt(0, wakeUp, LOW);

    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
    detachInterrupt(0);
    RTC.alarm(ALARM_2);
    nextLoop += resolution;
    if (nextLoop >= 60) {
         nextLoop -= 60;
    }
}

void wakeUp(){
  // Handler for the pin interrupt.
}

Sorry, that probably isnt why your battery is getting drained. Is there anything else connected to the battery other than the RTC?

Nothing else is connected to the coin cell - it's part of an RTC breakout board.

Do you have another RTC to compare against this one in case its damaged in some non-obvious way? What was the voltage when you measured it after a few days and it couldnt power the RTC any longer? The coin cell is a CR2032, right?

If I remember correctly, interrupts are disabled while the DS3231 is not getting power (except through the battery). Are you saying the battery is drained after a few months of no-power, or after a few months of power (and sometimes no power). What breakout are you using? Some breakouts use rechargeable batteries. Putting a regular battery in those will damage the battery and would explain the short lifetime.

Does the breakout board have a pullup resistor for SQW? If not you could try INPUT_PULLUP pin mode or an external pullup.

If the DS3231 is connected to the circuit(power) and the Arduino itself is not powered down, then it shouldn't use the battery at all, alarms or no.  Either some wire is connected wrong or the RTC should be swapped out to see whether the problem persists.  btw, DS3231s have internal pullups.  They work so well that if you have one on your I2C you do not want to add others because they are then in parallel, which reduces their effective resistance.  Also, I2C is connected to analog pins (A4 & A5) so INPUT_PULLUP would not apply.

Just caught where you say the problem happens when you unpower the circuit entirely.  I have done that for weeks by preprogramming a few DS3231's that I leave disconnected, on my workbench for quick installation.  They have always kept the time and date, though with some drift.  So if your RTC is good then it must be some external drain caused by the circuit.

Check your battery, it is behaving like a rechargeable one without a charger.  Mine have the letter "R" at the end of the part number.  There are a lot of RTC modules that charge the battery. Conversely they are some that do not charge the battery. Are you powering it with something other then the coin cell.

1) Could be a short in your PCB. As suggested, try another module if possible.
2) Shouldn't you somehow program SQW pin to be an interrupt? By default I remember it outputs a squarewave.
3) Try calling clearAlarm(); for your RTC to see how it goes.
4) Having the RTC sitting there, by connecting GND and a digital input from an Arduino, can you digitalRead(); the pin? That way you'll see if it keeps firing interrupts.

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


text:
Pro Mini Fuse Repair
It looks like I broke my Arduino (Compatible) Pro Mini board using AtmelStudio to change the fuses. I was having trouble with speed and using some basic sketches. For example, the LED blink was on for 2 seconds and off for 2 seconds instead of 1 second. I tried to change the fuses to Ext Clock + 65 ms, and now I can't use the thing at all. Cannot enter programming mode. Any ideas?

Sound like you selected a Pro Mini 16MHz in the IDE, but are actually using a Pro Mini that is running at 8MHz.

Sounds like you broke your fuses.
You may be able to enter programming mode by applying an external clock signal to the clock in pin (use another Arduino to generate it).  If that doesn't work then the only way to fix it is with a "High Voltage Programmer".
Nick Gammon has a very good tutorial here: http://www.gammon.com.au/forum/?id=12898

Also if you managed to get a clock divider activated, you may need to slow down the clock rate of the programmer to something sufficiently slower than the effective internal clock rate.


text:
Arduino on breadboard, and then soldered using a board made on Eagle but won't work
So I'm looking to create an arduino clone to mount on one of my robots. I started off making the arduino on a breadboard, using the instructions found on Arduino's own website and I succeeded. It works as well, I've checked it with the "blink" project.
I then drew the schematic in Eagle:

Next, I created a board and routed it, giving the following result:

Finally, I transferred it onto a copper clad, soldered it, but it doesn't work. Tried pretty much everything I could think of but there seems to be something wrong and I cant work out what it is.
Can someone please help?
Hassan

I haven't worked out why it's "not working", but some comments on your PCB:

Your crystal is too far from the clock pins
Your crystal capacitors are most definitely too far from the crystal
There are no decoupling capacitors on your Vcc / AVcc pins

Your crystal should be right next to the pins on the chip that it is connected to, and the capacitors for it should be immediately next to that. The layout you have at the moment, if it actually works, will be radiating huge amounts of EMI and would immediately fail any emissions test you'd care to perform.
Without decoupling capacitors on the power pins the chip may not function properly.
Edit: I have just found your main mistake
You haven't linked the output of your regulator sub-circuit to Vcc. Power gets regulated but goes nowhere.

Thank you very much Majenko
.
http://i.imgur.com/rnENfP1.png
Here are the changes -- Is this what you meant? I'm not sure what you mean by your point 3. about the decoupling capacitors, no idea :( maybe you could elaborate if I havent already corrected the mistake? Thanks so much once again :D

It's worth fixing the power and decoupling issues by soldering wires and components onto the present board before you make a new one.  The crystal should work in the near term, but do move it closer, however the crystal loading capacitor position is indeed terrible - chisel those traces and add replacement caps keeping both the crystal-signal and also ground connections to the caps short.  Or you can test the chip with its internal oscillator - point being use modifications to your existing board to make sure nothing else is wrong before you fabricate another.


text:
I²C between 2 Arduinos sends additional receive event
I hooked up two Arduino Nanos with I²C, using 3 wires between GND <-> GND, A4 <-> A4, A5 <-> A5Ω and 1kΩ pull-up resistors on A4 & A5.
When I use the following code to communicate between them I get a weird empty receive event.
master.cpp
#include <Arduino.h>
#include <Wire.h>

#define SERIAL_BAUD 9600

#define I2C_SLAVE_ADDRESS 8

void setup () {
    Wire.begin();
    Serial.begin(SERIAL_BAUD);
}

void getFromState (unsigned char state) {
    Wire.beginTransmission(I2C_SLAVE_ADDRESS);
    Serial.print("s");
    Serial.print(Wire.write(state));
    Serial.print("e");
    Serial.print(Wire.endTransmission());
    delay(5000);
    Wire.requestFrom(I2C_SLAVE_ADDRESS, 2);
    int c = (unsigned char) Wire.read();
    Wire.flush();
    Serial.print("r");
    Serial.println(c);
    Wire.endTransmission();
}

void loop () {
    Serial.println("loop");
    getFromState(0);
    delay(10000);
    getFromState(1);
    delay(10000);
}

slave.cpp
#include <Arduino.h>
#include <Wire.h>

#define SERIAL_BAUD 9600

#define I2C_ADDRESS 8

unsigned char state = 0;

void requestEvent () {
    Serial.print("Request ");
    Serial.println(state);
    Wire.write(state);
}

void receiveEvent (int amount) {
    Serial.print("a");
    Serial.print(amount);
    Serial.print("r");
    state = (unsigned char) Wire.read();
    Serial.println(state);
}

void setup() {
    Serial.begin(SERIAL_BAUD);
    Wire.begin(I2C_ADDRESS);
    Wire.onRequest(requestEvent);
    Wire.onReceive(receiveEvent);
}

void loop() {
    delay(10);
}

Serial Output Master After 1.5 Loops
loop
s1e0r0
s1e0r1
loop
s1e0r0
s1e0

Serial Output Slave After 1.5 Loops
a1r0
Request 0
a0r255
a1r1
Request 0
a0r255
a1r0
Request 0
a0r255
a1r1

Question
Why is there an empty receive event a0r255 after every request? Is that normal? Am I doing something wrong? Is this some sort of hardware issue?
EDIT: I opensourced this project here, take a look if you want to!

The main culprit that is causing your problem is the second
Wire.endTransmission();

after your requestFrom.  That causes the previous startTransmission() to be repeated with no data in it - thus giving you a second receiveEvent call with no data.

That's a quite weird behavior, but sounds like it could truly be the reason this happens. Will have to check this out tomorrow moring since it's quite late in Germany already. :(

It's late here in the UK too, but I'm still firing on all cylinders ;)

yeah I know that feel, I sometimes try not to stay up that long, today is one of these days where I may get a reasonable bedtime.

Thanks, this actually was the reason I was seeing the empty packets. Accepting this answer, since it is more tailored towards the actual problem. Doesn't mean I don't appreciate the other one a lot, but this solved & explained the "real" issue.

Your code has several issues:
For the master:

Your I2C transactions should be quick and not delayed with Serial.print()s like in getFromState()
You requested 2 bytes from the slave but you are reading only one from the buffer. Wire.flush() flushes the outgoing buffer, not the receive buffer. Use while (Wire.read() != -1); instead.
Its also advised that you use Wire.available() to iterate through the receive buffer when read()ing; its how you check if anything was received at all and how many bytes were received.
After using requestFrom(), you shouldn't call endTransmission(). Its self-contained.

For the slave:

You should never call Serial.print() or delay() in requestEvent() or receiveEvent(); both functions are called from within ISRs and ISRs are meant to execute quickly and return.
You are requesting 2 bytes from the slave in your master code, whereas your slave's requestEvent() writes only one byte.
In receiveEvent(), again its best to use either Wire.available() to iterate through the RX buffer or you use the variable amount. This way, you read everything in the buffer; you can also flush the RX buffer like I showed you before.

Finally those delays are rather long; 10ms would do, if they are even needed at all.

Most of these issues are in the code for debugging purposes (serial and ultra long delays so I can actually see whats happening) The thing with 2 bytes is: as soon as I set it to one, it doesn't work anymore, it just stops. The endTransmission is an accident/leftover from code I previously used, will check if any of this changes anything tomorrow morning. I literally tried to debug this code for hours, so I tested a lot of things, one initial issue actually was that I needed the pull ups because otherwise the slave couldn't send anything to the master (except. somehow ACK bits).

Accepted the other answer, because it had a better explanation and was more precisely addressing the actual problem. Thanks for your input nevertheless, if possible I'd accept yours too. :(


text:
Troubleshooting duplicate libaries (Arduino motor shield and stepper motor)
I have tried a software. It work flawless on the first laptop in a fresh install arduino IDE environment with the libraries I imported.
However when I copy the exact same program over. I get lot of errors and tried to clean up some of the old libraries from earlier programs. Then rerun the compiler; got even more errors and I am not sure what to do except completely clean everything including older libraries that I may need to keep around for older programs.
My includes are as following:
#include <AccelStepper.h>
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Error from the Arduino IDE from the second laptop is as following:
Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"

Invalid library found in C:\Users\B Family\Documents\Arduino\libraries\examples: C:\Users\B Family\Documents\Arduino\libraries\examples

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\libraries\Adafruit_Motor_Shield_V2_Library-master\utility/Adafruit_MS_PWMServoDriver.cpp:28: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::setPWM(unsigned char, unsigned int, unsigned int)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::write8(unsigned char, unsigned char)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::reset()'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::begin()'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::read8(unsigned char)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::setPWMFreq(float)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling.

This report would have more information with
"Show verbose output during compilation"
enabled in File > Preferences.

The diagnostics tell you exactly what is wrong! You have multiple copies of the same library, probably because you installed it at different times from different places. The diagnostics even tell you which libraries are duplicates. Remove them and everything will work fine!
While we are at it: another source of duplicate definitions is badly written .h files that define (as opposed to only declaring) external symbols. Those you have to deal with as they happen, there is no global solution.

While there were some stuff you got wrong. Turn out that Arduino was looking for libraries in TWO places and it didn't specific which one in compiler errors. So I had to delete those in Document > Arduino > Libraries. Turn out the %arduino install path% > libraries had the correct libraries after all.


text:
Arduino Uno Constantly Resets with WiFi and 4 Relay Module
I am using an Arduino Uno with a 4 relay module (found here: http://www.amazon.com/JBtek-Channel-Module-Arduino-Raspberry/dp/B00KTEN3TM?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_detailpage_o04_s00) and an Adafruit CC3000 WiFi breakout board.  However, once I connect the power source, the board just constantly cycles on and off, e.g. about 1 second per cycle.  Could this have to do with too much current being drawn? Or that the current output of the digital pins isn't enough for all of the relay inputs? I'm new with this, but I am sure all of the pins are appropriately connected.
EDIT: If I use the USB connector (5V 1A) instead of the external power supply, I can connect 1 or 2 of the relays without problem, but must do so AFTER the wifi has already connected to the network, otherwise the wifi chip will never connect.  Also, if I toggle the relays a few times, the wifi becomes unresponsive.  I suspect a current issue maybe?. Any ideas? Thanks!

It Will be a power issue you need to supply power direct to the relay modules VCC independent of the arduino, ensure the earths are connected and just use the digital outputs from the arduino to control the relays. Digital low normally switches the corresponding relay on.


text:
Resistor on SPI Chip Select Pin
I'm working on a modular CANBUS system for offroad racing. The idea right now is that the main Arduino (1284p at the moment) will be the only one connected to CANBUS, and other modules will have their own atmega's that will communicate with the master over I2C. They will not be physically on the same PCB, but will be physically within inches of each other. One module will have 8 MAX31865 IC's for interfacing with RTD's. The 31865 is not compatible with 5V microcontrollers, which right now we planned on running the Atmega's at 5V. Since the IC's are SPI, they can all share a MOSI, MISO, and CLK bus, so only two channels of a hex converter. For the Chip Select pin, would it be acceptable to use a resistor to decrease the voltage instead of using an additional 8 channels of hex converting?
What would the upsides/downsides be of using an atmega running at 3.3v for the module with the MAX31865's and just using a hex converter on SDA/SCL for the I2C communication to the master? What atmega I use for this is flexible.

using a hex converter on SDA/SCL for the I2C communication to the master

I2C is not straight forward for level shifting.  The I/O pins operate in open drain mode. That is, they don't send out any voltage of their own, they just pull down (like a button) the signals pulled up by resistors.
To level shift you have to read the state of those lines and then replicate that open drain connection to the signals of a different voltage.
But that is not all of course. I2C is a bidirectional protocol on a single data line. That means that data goes in both directions on the data line, so your level shifter has to be able to work in both ways.
There are special I2C level shifter chips available that do that exact thing. Some people sell them on breakout boards if you google around.
But with all that said, if you run your I2C bus purely at 3.3V it should work quite happily with both 3.3V and 5V devices.  To do so you need to:

Use external pullup resistors (~3.3KΩ) to 3.3V
Disable the Arduino's idiotic use of the internal pullup resistors on the I2C pins (will need modification of the Wire library)

In short: It is possible to mix 3.3V and 5V I2C devices on a 3.3V I2C bus, but not on a 5V I2C bus.

would it be acceptable to use a resistor to decrease the voltage

I don't see any big problem with using a voltage divider for chip select.

What would the upsides/downsides be of using an atmega running at 3.3v for the module with the MAX31865's

At 3.3V you can only run at 13 MHz or less (so in practice, 8 MHz, unless you want to do a lot of fiddling around). This may or may not matter to you. At a lower voltage it uses less power which can be a plus, and you don't need to worry about level converters.

and just using a hex converter on SDA/SCL for the I2C communication to the master?

Do you mean a level converter?


text:
Two or More Arduinos Handshaking
research would show that there are numerous ways for two arduinos to talk to one another. But i was looking for a 'basic robust protocol' (..it doesn't sound basic ....I know!), to allow for two arduinos to talk to one another. The idea is , Arduino One(slave), is linked to a sensor and it reads data from the sensor and sends the data  to Arduino Two on 'request' of the data by Arduino Two(master). Arduino Two would have to 'request' for the data from Arduino One, before it can read the data, if its available. A popular method on most sites (e.g https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing/shaking-hands-part-1) is the use of the method below. I added a comment in search of clarity.
              void establishContact()
                     {  //This while loop does baffle me as it suggests that
                        //while there is nothing in serial, send A???
                        while (Serial.available() <= 0)
                       {
                         Serial.println("A");   // send a capital A
                         delay(300);
                       }
                     }

Now this method was used in handshaking between Arduino and processing. This method was called on the Arduino sketch. On the processing sketch, a method there just checks to see if 'A' was received. If it is, it reads in the data from serial, clears the serial buffer and  writes 'A' back to Serial. I tried using this method on both of my arduinos as i felt it was 'basic' enough, but it didn't work at all. Does anyone has a better idea on how my arduinos could handshake?.

That while loop makes perfect sense.  It' basically nudging the other end repeatedly until it replies with something - anything.
It's like sitting next to someone and poking them in the ribs every 300ms until they respond to you. Once they have responded you can then react to that response - be that to run very fast or tell them your important news.
The idea of handshaking like that is all to do with synchronisation. It ensures that both ends are ready for communication at the same time.  Once synchronised you know, to a high probability, that what you are sending will be interpreted properly, and any replies you get back will be correct.
For basic communication between two Arduinos it's really not necessary.
The simplest call-and-response protocol involves Arduino A sending a single byte as a request and Arduino B replying with a single byte. It is up to you what those bytes represent, but ASCII letters for requests are ideal since they are understandable by a human, and numbers between 0 and 255 or -128 and +127 fit in to one byte (unsigned or signed respectively). Should you want bigger numbers being sent back then the reply will have to be delimited in some way. The simplest way of doing that is to format the response as ASCII data and send it with a CR and/or LF.
Something like:
if (Serial.available()) {
    char command = Serial.read();
    switch (command) {
        case 'T':
            Serial.println(temperature);
            break;
        case 'P':
            Serial.println(pressure);
            break;
    }
}

The master end then sends either 'T' or 'P' to request temperature or pressure. It then reads characters up to a line feed and stores them in a string which it can then convert into the desired numeric data type depending on what temperature and pressure are (integer or floating point).

Always to the rescue @Majenko....Thanks alot


text:
Why is my LED blinking?
I have this simple push button schematic:

The idea is that the LED is on as long as the button stays pushed, with the switch closed.
The code is below:
int ledPin=10;
int switchPin=5;

void setup()

{
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  pinMode(ledPin,OUTPUT);

}
void loop()

{
  digitalWrite(ledPin,LOW);//DBG
  if (digitalRead(switchPin)==HIGH)
{
 digitalWrite(ledPin,HIGH);//DBG
 delay(500);
}
 if (digitalRead(switchPin)==LOW);
{
digitalWrite(ledPin,LOW);//DBG
delay(200);
}
}

As I keep the button pressed, the LED blinks regularly, instead of staying on. Why?
I have tried using a capacitor between the switch and switchPin, with no change.

The beginning of your code in the loop:
void loop()  {
  digitalWrite(ledPin,LOW); //remove this line here
  if (digitalRead(switchPin)==HIGH)
{
     digitalWrite(ledPin,HIGH);//DBG
     delay(500);
}
 if (digitalRead(switchPin)==LOW);
 {
      digitalWrite(ledPin,LOW);//DBG
       delay(200);
     }
}

Before your first if(digital read(switch pin) == HIGH)  you turn the LED off, and then you have a delay, which gives the blinking effect, remove that and it will not blink.

@GiuseppeBarbesino not stupid just the formating of the code makes it unreadable, and will cause one to miss read code, happens to many ;)


text:
Do arduino librarys require the arduino to be connected to a computer?
The title pretty much explains my question. If I'm using a library for example one for an accelerometer does the arduino need to be connected to my computer because it's using a library? Or is the library uploaded to the arduino and there for can run with out a computer connected?

No.  Arduino libraries (strictly speaking only the utilized parts) are permanently built-in parts of your compiled sketch.  Effectively they are "statically linked" unlike the situation with modern RAM-based computer operating systems where compiled dynamic link library code may be separately loaded into memory for a program to call at runtime.
(This isn't even really a design choice, as the basic AVR Arduino's cannot load new program code into executable memory at runtime anyway - except by reflashing themselves like the bootloader does, which would be a bit slow compared to normal dynamic linking)
Of course if you have a library which is intended to perform communication with a computer, then that connection would probably be required for it to fully operate.


text:
Integer goes garbage after iteration. struct pointer manipulation messed up other variables in memory
I'm writing a library for Charlieplexed LED display (trying to write a common one actually). The library is working quite fine. In my arduino sketch, I'm using an integer to keep track of the LED, currently on. The integer value increases with time and the LED(s) glow one by one. The problem is, after couple of iterations, this integer value just goes out of chart (in Serial monitor, it has garbage values).
MatrixCharlieplex mch(Pins, 5, MXCHARLIE_CA); // instance of Class
int i = 0, j = 0;
boolean busy = false;
unsigned long time;
void setup() {
  //Serial.begin(9600);
  time=millis();
}
void loop() {
  if(millis() - time > 100){ // runs every 100 ms interval // corrected from (millis() > (time + 100))
    time=millis();
    blink();
  }
}
void blink(){
  if(!busy){
    busy = true;
    //Serial.print("i:\t");
    //Serial.println(i);
    //Serial.print("Node:\t");
    //Serial.println(i+1);
    mch.TurnOn(i+1);
    increase();
    busy = false;
  }
}
void increase(){
  i = (++i % 20); // resets after every 20 intervals
}

Output:
i:  16
Node:   17
i:  17
Node:   18
i:  18
Node:   19
i:  19
Node:   20
i:16 <-- Stopped working here. it should be "i:    0" & "Node:    1"
    16
Node:   17
    17
Node:   18
    18
Node:   19
    19
Node:   20
16
    16
Node:   17
    17
Node:   18
    18
Node:   19
    19
Node:   20

The sketch can also be found here
Update:
There were no hardware-fault. The problem lies in the struct variable declaration as pointers.updated the question & posted answer. The files in the github links have also been updated.

I tried running your code, but I couldn't reproduce your problem.

Unrelated to the question... but: you should not test for millis() > time + 100, you should test for millis() - time > 100 instead. Otherwise your code will fail when millis rolls over. Simple rule: do not compare timestamps, compare duration instead.

@Gerben: Without changing any part of the code? WOW... but mine still freezes. :(

Thanks @Edgar for the millis rollover correction. Corrected in question & github also.

How is the RAM usage?

I commented out the multiplex library. Try changing the name on the variable i to e.g. 'index'.

Does this behaviour happen with no LEDs connected? I presume Gerben didn't attach the hardware. If not, then it is hardware-related, like I said. BTW, inside a class you don't normally put this-> in front of every class variable. That's just clutter. You are already using underscores in the name to show that they are class variables.

@Paul: What's the way to check the RAM usage on runtime?

@NickGammon: Sorry, year old habits of Oops practices. Removed "this" from sources. I'll check the code with no LED matrix attached now.

After much trial and error effort, I've found the solution.
There was no problem in the hardware side (I ran the sketch with serial monitor after detaching the LED-matrix and all non-crutial hardwares. Thanks @jantje and @NickGammon fot the tips).
Apparently Arduino is not capable of handling pointers in advanced Oops fashion. The library itself used it heavily, specially "struct pointers" as function parameters and as return types (Arduino messed up these pointer values with other variable declarations in memory). After removing those pointers from the code and replace them with normal variables, the code runs well.
// correct definition
typedef struct {
    uint8_t vcc;
    uint8_t gnd;
} DiodeNode;

// wrong implementation
DiodeNode* node = new DiodeNode();
node->vcc = x;
node->gnd = y;

// correct implementation
DiodeNode node = (DiodeNode){x, y};
// or
DiodeNode node;
node.vcc = x;
node.gnd = y;
return node; // from functions etc.

If you have a Charliplexing board like mine (or even if you made your own) the problem could be electrical. If you turn on a lot of LEDs you may exceed the current consumption allowed and then the processor hangs or resets.
I suggest current-limiting resistors like this:

Thanks @Nick for replying. Yes, I've made one myself and there are resistors for all pins. The library itself doesn't allow turning on more than one LED at a time. i.e. it keep tracks of which one is currently on and a new request will turn the current one off & then turn the new LED on. Hence, there is no chance of over-current consumption. :(

First thing to do is find out whether your problem is electrical or not.
This can be done by removing the electrical parts not crucial to run the code.
If the problem is code related try using another board to eliminate some hardware malfunction on your board.
Doing these steps will give you some insight on the root cause of the problem.


text:
MQ4 gas sensor is not working with Arduino UNO
I am trying to detect LPG leakage by using MQ4 gas sensor.
I have made this circuit

My Arduino code is
int sensorValue;

void setup()
{
  Serial.begin(9600);      // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);
  Serial.println(sensorValue, DEC);
  delay(100);
}

On my serial monitor, I am getting values like
307
277
289
282
283
283
260
248
265
285
308
278
278
315
321
316
327

These values are not getting change even after putting sensor near gas lighter. Did I made any mistake in circuit or this sensor could be faulty ? Any help is appriciated.

That is what I would expect to see with one of these sensors.
I'm not sure on the wiring, I think you may be wrong.  Have a read of http://playground.arduino.cc/Main/MQGasSensors#readdatasheet and see if you agree.
Did you leave the sensor to warm up?  It takes a few minutes (from memory) and until its warm it won't give you a proper reading.
An MQ4 should be able to detect Methane, butane and propane, so was your lighter using on of these gasses?  When it does detect the target gas, the number will go up, and stay up for a while.
Another thing you can try is blowing on the sensor, the results will vary depending on what you have been eating, but it should shift one way or another.
If it still doesn't work then buzz out your connections, just to triple check, and re-read the manual.

thanks for replying, I let it warms for 5mins or so. One thing I also noticed that when I touch the sensor, its value goes down to range 0-50. Blowing on it doesn't change its value. :(

If the value changes when you touch it I would check the earth connection.

I think my wiring was wrong, after re-doing everything its working fine. Its value getting changed when sensor is exposed to LPG gas. Thanks.

authors: นายสมพงค์ ทุ่งมีผล


text:
Esplora: Connecting a 2-Wire Speaker to Arduino Esplora
I am currently trying to make a simple game system with my Arduino Esplora, however I have noticed something. The Arduino Esplora has no pins for a 2-pin speaker that I get from a RadioShack store (Click here for item description). How would I go about connecting the speaker because I am also using the TFT LCD screen, or is there a workaround with the output TinkerKit pins on the top?
Any help is greatly appreciated. Thanks!


text:
OLED with arduino?
I recently bought a 0.96" Serial OLED Screen. I am not very experienced with this. I'm trying to display some text with the Arduino Uno. I installed the adafruit SSD1306 and GFX libraries but no luck. I've looked for tutorials for similar screens, but my screen has extra pins that others don't.
Mine has:
CS DC RST D1 D0 VCC GND,
others only have 4.
I don't know what each pin should be connected to. Does any one know how to get this to work? Is there a different library that I could use with this screen?

Yes, certain OLED screens do have different pinouts. For yours, the following would be your OLED's pinouts.
OLED ---- Arduino

D0-----------10

D1-----------9

RST----------13

DC-----------11

VCC----------5V

GND----------GND

The CS pin does not need to be plugged in.
As for the code, you can use this include from Smart Prototyping as an extra file, then have some simple code in your loop portion:
void loop()
{

LED_P8x16Str(23,0,"here is");

LED_P8x16Str(40,2,"example");

LED_P8x16Str(20,4,"text");

}

No problem! Glad I could help!


text:
Using an Arduino Weight Sensor, it fails to satisfy a while loop and I can't firgure out why
/*

 This example code uses bogde's excellent library: https://github.com/bogde/HX711
 bogde's library is released under a GNU GENERAL PUBLIC LICENSE

 The HX711 does one thing well: read load cells. The breakout board is compatible with any wheat-stone bridge
 based load cell which should allow a user to measure everything from a few grams to tens of tons.
 Arduino pin 2 -> HX711 CLK
 3 -> DAT
 5V -> VCC
 GND -> GND

 The HX711 board can be powered from 2.7V to 5V so the Arduino 5V power should be fine.

*/

#include "HX711.h"
#include <Servo.h>

float calibration_factor = -4050.0;

#define DOUT  3
#define CLK  2
Servo myServo;

HX711 scale(DOUT, CLK);

void setup() {
    Serial.begin(9600);
    Serial.println("Food Test");
    scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0
    Serial.println("Readings:");
    myServo.attach(9);
    long zero_factor = scale.read_average(); //Get a baseline reading
    Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
    Serial.println(zero_factor);
}

void loop() {
    scale.set_scale(calibration_factor); //Adjust to this calibration factor

    if ((scale.get_units(), 1) <= 5) {
        Serial.print("whoa that is light, more food needed");
        myServo.write(90); // Open food hatch
        delay(2000);
        myServo.write(0);

        do {
            // Do nothing
            Serial.println("It is working somewhat");
            Serial.println(scale.get_units(), 1);
            delay(1000);
            // When weight exceeds 5 it should break out of this loop and go below
        } while ((scale.get_units(), 1) < 10);

        Serial.print("Closing the Hatch");
        myServo.write(0); // close food hatch
    } else {
        Serial.print("Something Went Wrong");
    }
}

Output:
It is working somewhat
10.6
It is working somewhat
10.9
It is working somewhat
10.5
It is working somewhat
6.9
It is working somewhat
-0.8

I will try to explain the problem as best as I can. I am using a scale library and the scale.get_units(),x returns a value as a float. The whole point is that a servo will open and stay open until a specified weight of 10lbs is reached. As seen in the do, while loop that's what I specify. It jumps into the if loop and then into the do while loop, and it continually prints out values of readings which is what I want. BUT, even when I reach over 10lbs it will not break out of the Do/while loop, essentially it never satisfies the while condition and I have no clue why. It prints out values over 10 but keeps reading values. I know the format isn't the best but any help would be greatly appreciated!!

It looks to me like you have an extra bracket in there that you don't want.
At the moment your structure is:
if {
    do {
    }
} while...

As it stands your sketch won't compile. The unbalanced brackets prevent it.  Remove the excess one so that the while is associated with the do not the if and report back.

Part II
The main cause of your problem is the strange bit of code you have in your ifs and whiles.
if ((scale.get_units(), 1) <= 5) {

....

} while ((scale.get_units(), 1) < 10);

In both of those you have the bit (scale.get_units(), 1) which is completely meaningless.  The comma operator in C calls (or evaluates) both sides, and then returns the right hand side.  So that calls scale.get_units() and then returns 1.  1 has always been, and will always be, less than 10, so the while never ends.
I don't know what you were hoping to achieve by having the , 1 in there, but you should delete it from every place you have it.

Thank you for that fix, but it still wont break out of the do loop if the weight is greater than 10. Example: It is working somewhat
-0.6
It is working somewhat
13.8
It is working somewhat
-1.0
It is working somewhat
-5.4

Can you fix your sketch and replace your completely broken one with one that compiles? Also make sure you sort out your indentations - that would have immediately shown you the bad brackets.

Better. Now check my edit (Part II)

Well it hasn't fixed everything but it definitely helped me a ton, thank you so much for your help and support, I've been at it for hours but now I can actually breathe. Thank you!!!


text:
Why is the result shorter than expected when I do longString.toCharArray(bigCharArr, longLength)?
I'm running this on a Particle Photon, but I think the issue is just me failing at C++. I'm trying to retrieve some JSON data from a HTTP API, convert it to JSON, and then extract a few values for display on the screen. I convert the String to a char array for the JSON parser, but it seems to only grab the first 10 characters of the String (unless I manually set length to a number shorter than 10), and then of course, the JSON parser fails.
Here's the relevant bit of code:
int str_len = response.body.length() + 1;
tft.print("Length: "); tft.println(str_len);
char char_array[str_len];
response.body.toCharArray(char_array, str_len);

response.body is a big JSON string, but char_array is always just the first 10 characters of it: {"metadata
Another thing I noticed just now that might be related, str_len is usually reported to be ~500 characters, but when I hit the same URL in a browser it ends up more like ~1500 characters. Neither are pretty-printed, so I'm not sure what the discrepancy is.
Here's my complete code, except I removed the base64'd username and password from the Authorization header:
#include "HttpClient/HttpClient.h"
#include "SparkJson/SparkJson.h"
#include "Adafruit_mfGFX/Adafruit_mfGFX.h"
#include "Adafruit_SSD1351_Photon/Adafruit_SSD1351_Photon.h"

// OLED - You can use any (4 or) 5 pins
#define sclk A3
#define mosi A5
#define dc   D7
#define cs   A2
#define rst  D5

// Color definitions
#define BLACK           0x0000
#define BLUE            0x001F
#define RED             0xF800
#define GREEN           0x07E0
#define CYAN            0x07FF
#define MAGENTA         0xF81F
#define YELLOW          0xFFE0
#define WHITE           0xFFFF

// Option 1: Hardware SPI - uses some analog pins, but much faster
Adafruit_SSD1351 tft = Adafruit_SSD1351(cs, dc, rst);

// Option 2: Software SPI - use any pins but a little slower
//Adafruit_SSD1351 tft = Adafruit_SSD1351(cs, dc, mosi, sclk, rst);

HttpClient http;

// Headers currently need to be set at init, useful for API keys etc.
http_header_t headers[] = {
    //  { "Content-Type", "application/json" },
    { "Authorization", "Basic <snip>" }, // base64encode(username:password)
    { "Accept" , "application/json" },
    { NULL, NULL } // NOTE: Always terminate headers will NULL
};

http_request_t request;
http_response_t response;

void setup(void) {

    tft.begin();

    tft.fillScreen(BLACK);
    tft.setCursor(0,0);
    tft.setTextSize(0);
    tft.setTextColor(WHITE);

    // http://twcservice.mybluemix.net/api/weather/v2/observations/current?units=e&geocode=40.0388067%2C-84.3428471&language=en-US
    request.hostname = "twcservice.mybluemix.net";
    request.port = 80;
    request.path = "/api/weather/v2/observations/current?units=e&geocode=40.0388067%2C-84.3428471&language=en-US";
    //request.body = "{\"key\":\"value\"}";
    http.get(request, response, headers);

    tft.print("Status: ");
    tft.println(response.status);

    //tft.println("Response Body: ");
    //tft.println(response.body);

    int str_len = response.body.length() + 1;
    tft.print("Length: "); tft.println(str_len);
    char char_array[str_len];
    response.body.toCharArray(char_array, str_len);

    DynamicJsonBuffer jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(char_array);

    if (root.success()) {
        tft.print("Current Temperature: ");
        const char* temp = root["observation"]["imperial"]["temp"];
        tft.println(temp);
    } else {
        tft.setTextColor(RED);
        tft.println("parseObject() failed");

        tft.setTextColor(GREEN);
        uint32_t freemem = System.freeMemory();
        tft.print("Free memory: ");
        tft.print(freemem/1024);
        tft.println("k");

        tft.setTextColor(WHITE);
        tft.println(char_array);

        tft.setTextColor(CYAN);
        tft.println(response.body);
    }
}

void loop() {

}

The actual printout on the screen is smething like
Status: 200
Length: 501
parseObject() failed
Free memory: 59k
{"metadata
{"metadata":{"language":"en-US","transaction_id":"1460309558940:-660053703","version":"1","latitude":40.04,"longitude":-84.34,"units":"e","expire_time_gmt":1460310025,"status_code":200},"observation":{"class":"observation","expire_

Finally, here's an example of the JSON response I'm trying to parse:
{"metadata":{"language":"en-US","transaction_id":"1460309558940:-660053703","version":"1","latitude":40.04,"longitude":-84.34,"units":"e","expire_time_gmt":1460310025,"status_code":200},"observation":{"class":"observation","expire_time_gmt":1460310025,"obs_time":1460307900,"obs_time_local":"2016-04-10T13:05:00-0400","wdir":160,"icon_code":26,"icon_extd":2690,"sunrise":"2016-04-10T07:06:23-0400","sunset":"2016-04-10T20:11:13-0400","day_ind":"D","uv_index":3,"uv_warning":0,"wxman":"wx4400","obs_qualifier_code":null,"ptend_code":2,"dow":"Sunday","wdir_cardinal":"SSE","uv_desc":"Moderate","phrase_12char":"Cloudy/Wind","phrase_22char":"Cloudy/Wind","phrase_32char":"Cloudy/Wind","ptend_desc":"Falling","sky_cover":"Cloudy","clds":"OVC","obs_qualifier_severity":null,"vocal_key":"OT48:OX2690","imperial":{"wspd":20,"gust":24,"vis":10.000,"mslp":1018.7,"altimeter":30.09,"temp":48,"dewpt":27,"rh":43,"wc":41,"hi":48,"temp_change_24hour":11,"temp_max_24hour":44,"temp_min_24hour":27,"pchange":-0.10,"feels_like":41,"snow_1hour":0.0,"snow_6hour":0.0,"snow_24hour":0.0,"snow_mtd":1.2,"snow_season":21.3,"snow_ytd":21.3,"snow_2day":0.7,"snow_3day":0.8,"snow_7day":0.9,"ceiling":7400,"precip_1hour":0.00,"precip_6hour":0.00,"precip_24hour":0.00,"precip_mtd":1.10,"precip_ytd":11.76,"precip_2day":0.29,"precip_3day":0.30,"precip_7day":0.96,"obs_qualifier_100char":null,"obs_qualifier_50char":null,"obs_qualifier_32char":null}}}

Any idea what's going on?

Probably something specific to the Particle Photon. I can convert that string to and from String/char array quite happily on a Mega2560.

I tried it with the string hard-coded just now and that worked as expected. So maybe there's something funky with the HttpClient?

It turns out that the HttpClient library has a fixed response length limit of 1024 bytes and whatever it was doing after it hit that limit is what caused all of the trouble.
Forking the library and increasing the limit as recommended at https://community.particle.io/t/issues-with-string-char-array-length-json-parsing/21980 solved the issue.


text:
voltage output at digital pins vs. load
I am trying to convert the signal from digital pin 2 on my Uno to 3.3V.  I set up a voltage divider with 3 x 1000 ohm resistors.  When connected to ground and 5V the divider circuit generates 3.3V correctly, with a calculated input current of 1.7mA.  However I connect it to a digital pin, the digital pin voltage drops from 4.8V to .37V.  I thought the digital pins were to support 40mA, I was assuming 40mA at the 5V supply voltage.  Is my Uno malfunctioning?
Thanks

Sure you got the pin set up as an output and have written a high/1 to it? (have to ask). What's on the output of the voltage divider - i.e. between the resistors? Something with a high/low resistance/impedance?

Just figured out I didn't have the pin mode set, it works fine now, thanks.

Just figured out I didn't have the pin mode set, it works fine now, thanks.


text:
Arduino OOP and [this] keyword
Lets say I have a sketch called mysketch.ino with these contents:
String globalString = "ThisisGlobal";
void setup(){}
void loop(){}

How can I pass THIS sketch mysketch.ino as an object or its reference to a .h file named
StringChanger.h with the following contents, so that StringChanger.h can change somevariables belonging to mysketch.ino.
class StringChanger{
   template <typename T> // or type of mySketch.ino i don't know what i'm doing
   void changeString(T t) {  //a Reference Or Object Or Whatever
      t.globalString = "GotYouAndChangedYou";
   }
}

I wan't to have simple usage in the mySketch.ino.
For instance:
#include "StringChanger.h"

StringChanger change(**this**);  // perhaps default empty constructor here

String globalString = "ThisisGlobal";

void setup(){
    change.changeString(); // perhaps pass reference to **this** here
}
void loop(){}

How can I accomplish this (give a class an object so that it can change some value of that object) in general and not neccesarily in this context.
Errors I currently get:
invalid use of 'this' in non-member function
invalid use of 'this' at top level.

Arduino OOP and [this] keyword - it's C++. So whatever works in C++ works in Arduino.

StringChanger change(**this**); this doesn't make any sense at all, sorry.

I thought stack over flow would bold the string sorry. I meant change(this); and I understand Arduino has less of c++ especially the heavy complex parts because of the speed of micro controllers . I don't think if it works in C++ it's works in Arduino

It's nothing to do with speed. Exceptions are disabled by a command-line option. The rest is just pure C++.

A sketch isn't an object. It is merely a collection of variables, functions and, of course, classes.
Your example seems to be trying to make things incredibly complex when they don't need to be.
There are a number of ways of referencing things in one file from another - whether or not they are in a class.  The simplest is to use the extern keyword.  This is used in a file where you want to reference a variable or function that is defined in the global scope of another file. It says "This variable is global, but it's defined somewhere else."
// Sketch
String myString = "foo";

// Library
extern String myString;
// ... later on ...
myString = "bar";

Of course, that means that the name of the variable is fixed and cannot change.  So you can pass the variable to whatever it is you want to use that variable in.  That could be as simple as passing it to your "changer" function:
// Sketch
String myString = "foo";
StringChanger change;
// ... later ...
change.changeString(myString);

// Library
class StringChanger {
    public:
        void changeString(String &stringToChange) {
            stringToChange = "bar";
        }
};

If you want to "tie" the variable to the class so you don't have to pass it each time you could pass it to the constructor and have the class remember it:
// Sketch
String myString = "foo";
StringChanger change(myString);
// ... later ...
change.changeString();

// Library
class StringChanger {
    private:
        String *_string;
    public:
        StringChanger(String &string) {
            _string = &string;
        }
        void changeString() {
            *_string = "bar";
        }
}

And there's a myriad of other ways of doing it.

First part of your answer is what I want to do because I simply want that calling the constructor changes the string that is finds that extern string named myString and changes it to another. I don't want to use the function that accepts a string reference. Thanks @Majenko

Why not just make a function that changes an external string? I don't see why you would make a class just to change some external thing, which is not in the class, and doesn't do anything else.

@NickGammon Maybe that's just an example and he's really doing something completely different. Who knows with these kids? Either way, what he is doing is most likely not the right way of doing things and using getters and setters is more likely the right solution for managing his class.

Sounds like one of the better examples of the X-Y Problem that I have seen in a while.

@NickGammon Quite probably. I have pretty much given up trying to convince people that they are asking the wrong question though.

Yes, we need a close reason: "this is the wrong question". :)

@NickGammon I'm guilty of falling into x-y situations all the time. Not always but specifically when i write the type of usage i want then try to solve the problem. Speaking of which checkout my other problem here please.


text:
Managing 80 ~ 90 accelerometers with Arduino
If one were to want to keep track of data from 80 - 90 accelerometers using arduino, what would be the best way to go about this challenge?

Please specify what data rate do you need, distance between accelerometers, are you open to using more than one arduino?

1) Use the I2C address select inputs as an "enable".  If you run out of I/Os before running out of bus time, drive the enables from an I/O expandander. If your accelerometers are SPI, drive or use the expander to drive the chip selects.
2) Use a tree of slave MCUs (Arduino or otherwise) reading a number of accelerometers, extracting and batching the useful data, and reporting only that upstream to a master.  Probably use whichever of I2C or SPI your accelerometers are not using (SPI can be much faster, so hopefully that).
Some accelerometer / gyro parts have an on-board processor which you may be able to program to do some of the data extraction for you.
You could also consider using an FPGA to collect the data.  A commonly available one with enough I/O pins to have a dedicated connection to each accelerometer (and so read them all in parallel) would probably also have the internal resources to implement an Arduino-class soft core processor, if not better.


text:
Controlling HC-05 from a sketch
Hi I am making a sketch and circuit with a HC-05 BT receiver to upload sketches via Bluetooth to my Uno.  This requires giving AT commands from the sketch.  I would like to see the response from the HC-05 but so far I haven't got it to work.  I want to view the response via the standard serial connection and serial monitor.  The commands from the sketch are not being recognized by the HC-05 and I would like to see the HC-05 response to troubleshoot it.
If you have a minute would you mind giving me a tip?  I would greatly appreciate it.  See the ArdProgramModeOn() and Off functions at the end.
Thanks

int ATModePin = 2;  // pin for HC-05 AT comand mode
int HC05powerPin = 3;  // pin for powering HC-05 when high
char btserialrx;  // data through from bt connection
char myChar; // data through serial port connection
#define rxPin 8 // HC-05 bt serial pin
#define txPin 9 // HC-05 bt serial pin

#include <SoftwareSerial.h>
SoftwareSerial btSerial(rxPin, txPin); // RX, TX

void setup() {
  pinMode(ATModePin, OUTPUT);
  pinMode(HC05powerPin, OUTPUT);
  pinMode(5, OUTPUT);
  Serial.begin(9600);
  btSerial.begin(115200);

  digitalWrite(HC05powerPin, HIGH);
  delay(2000);
  }

void loop() {

  while (btSerial.available()) {
    btserialrx = btSerial.read();
  }

  if(btserialrx == '1'){  // change to upload / reset mode
    Serial.println("switching to upload mode");
    ATModeOn();
    ArdProgramModeOn();
    ATModeOff();
    btserialrx = '0';
  }
  else if (btserialrx == '2'){  // change to normal mode
    Serial.println("switching to normal mode");
    ATModeOn();
    ArdProgramModeOn();
    ATModeOff();
    btserialrx = '0';
  }
}

void ATModeOn(){  // reset HC-05 and change HC-05 to AT Command Mode
  digitalWrite(5, HIGH);
  digitalWrite(ATModePin, HIGH); // AT command mode on upon reset
  delay(2000);
  digitalWrite(HC05powerPin, LOW); // hc-05 off
  delay(2000);
  digitalWrite(HC05powerPin, HIGH); // hc-05 on
  delay(2000);
}

void ATModeOff(){  // reset HC-05 and return HC-05 to std. operation
  digitalWrite(5, LOW);
  digitalWrite(ATModePin, LOW); // AT command mode off upon reset
  delay(2000);
  digitalWrite(HC05powerPin, LOW); // hc-05 off
  delay(2000);
  digitalWrite(HC05powerPin, HIGH); // hc-05 on
  delay(2000);
}

void ArdProgramModeOn(){
  btSerial.println("AT");
  delay(1000);
  btSerial.println("AT+POLAR=1,0");  // Arduino reset mode upon HC-05 connection for programming
  delay(1000);
  btSerial.println("AT+POLAR?");  // Arduino reset mode upon HC-05 connection for programming
  delay(2000);
  while (btSerial.available()) {  // Show responses from HC-05
    myChar = btSerial.read();
    Serial.print(myChar);
  }
  delay(4000);
}

void ArdProgramModeOff(){
  btSerial.println("AT");
  delay(1000);
  btSerial.println("AT+POLAR=1,1");  // Arduino normal mode no reset upon HC-05 conection
  delay(1000);
  btSerial.println("AT+POLAR?");  // Arduino reset mode upon HC-05 connection for programming
  delay(2000);
  while (btSerial.available()) {  // Show responses from HC-05
    myChar = btSerial.read();
    Serial.print(myChar);
  }
  delay(4000);
}

Unless you've manually set the btSerial speed, you need to be at the default for AT commands which is 38400 -> btSerial.begin(38400);
If you want to read regular Serial communication, you'll need to monitor 9600 -> btSerial.begin(9600);
If you are unable to to send commands, I feel as if you wouldn't have changed the default speeds.
I used this link as a reference with my project: Modify The HC-05 Bluetooth Module Defaults Using AT Commands
Lastly, you didn't mention whether or not you soldered a jumper wire to PIN 32 for your ArdProgramOff/On. Another reference for you as well: DIY Arduino Bluetooth Programming Shield
Hope my answer helps! Good luck!

Thanks for responding.  The Make article is the one I followed to make the setup.  I have wires soldered to the HC-05 32 and 34 pins for the reset signal and AT command mode.  I pre--programmed HC-05 from the serial monitor to operate at 115200 baud to be able to upload to the Uno.  In the example pages you sent the HC-05 and serial monitor are communicating at different baud rates but I guess a buffer handles that difference?  Thanks.

Basically I'm wondering about the While loops to monitor serial received from the HC-05.  I have one at the start of the loop, and then one in both functions (ArdProgramMode...) where I am sending commands to the HC-05 from the Uno sketch.  Do you see a conflict in the code here, should this code design work correctly?  Thanks.


text:
Where can I find a hardware manual (or documentation) for Arduino Uno & ATMega328P?
Where can I find a hardware manual (documentation or a book) for Arduino board?
As far as I know, all hardware details are dispersed (or scatter) in different tutorials.

The Arduino Uno is little more than an ATmega328P microcontroller. In
most cases you will be interested by the documentation of the
microcontroller itself. Anyway, here are both:

The Arduino Uno product page contains the most basic specs, as well as links to

the board schematic
the pin mapping, but see below for a nicer alternative

the ATmega328P product page links to

the ATmega328P family datasheet, a 650 page authoritative document
the ATmega328P Automotive - Complete Datasheet, specific to the Uno's chip.
the AVR instruction set manual, for those who want to play with assembly
many application notes discussing specific uses of some peripherals

Alberto (aka PighiXXX) has published nicer versions of the Arduino Uno
pinout:

I've added the "Arduino specific" guides/help from Arduino.cc, since it's not a completely new answer. Feedback is appreciated, I can revert it/create my own answer if neccesary.

@Paul: The question is about the hardware of the Arduino Uno, and the OP specifically wrote he is looking for reference material (manual, documentation or book) rather than tutorials. The links you added are very general. They are not specific to the Uno hardware, and they tend to cover the software more than the hardware.

Oops! I have reverted my adjustments, it didn't add value to this specific question.

For the hardware part, you can refer to the schematic. It shows all the components so you can find their datasheets for detailed study.
UNO schematic
But to me, if you're just using the board but not designing your own board or writing libraries for the board, I don't think this is necessary. Stick to application level or IO-level and only really dig into the hardware when you're blocked when doing things like using all timers, low-power mode, interrupt with Serial...

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


text:
Are there any advantages to Wifi shields as opposed to a Yun?
I have an Arduino Uno and I have a remote sensing project for which I need Wifi connectivity. After doing research, I've found that I have 2 options:

Buy a WiFi shield for my existing Uno
Buy an Arduino Yun with built-in WiFi

Looking at costs, I found that a WiFi shield costs more than double what it costs to buy a Yun, so it would seem to me that the best option is the Yun as I'd save some cash and get a more capable board. However, I can't help but think I'm missing something.
What are the advantages of an Uno plus Wifi shield as opposed to a Yun?

Have you considered using an ESP8266-based dev board? NodeMCU, for example. This is a single SoC solution that can be had for less than 5USD with integrated WiFi. Remote sensing and logging via HTTP to a web service is ridiculously easy.

I didn't even realize it was an option to be honest @uint128_t, I didn't think anything that inexpensive would actually be a wifi device!

There's a number of things to consider that could sway your choice one way or another:
Power consumption
The Uno is a small low-power chip to which you add WiFi. The Yun is an Arduino Leonardo with a WiFi router (like you have on your desk) strapped to the back of it.  The Yun will therefore consume considerably more power than the Uno.
Boot time
The Uno takes about 1 second to boot up - faster (instant) if you remove the bootloader and program it direct with a programmer.  The Yun takes minutes to boot.
Stability
The Uno is a solid state single item. The Yun has an entire operating system with filesystems and things.  It's far more likely that the Yun will corrupt itself through power loss than an Uno will get struck by a stray neutrino.
Cost
Yes, the Yun is cheaper. But is cheap always good?
Remote-ability
The Yun can be completely reprogrammed remotely. A new sketch can be uploaded to the Leonardo portion of it without you even having to be in the same country. The same can't be said for the Uno.
Power
The Linux portion of the Yun is considerably more powerful than any normal Arduino.

This is very good information @Majenko, probably the best synopsis of the two boards I've seen.

I have more to add now I have been thinking about it.

First of all yun is not the same as uno + wifi shield. yun is more like a linux pcc with wifi and a lenoardo.
If you are asking for your options there are more options. For what you want I would go for a ESP8266. Again there are 2 options here:

uno + ESP8266 (as a wifi shield)
ESP8266 (as a dev board)

I think it is pretty obvious that the ESP8266 (as a dev board) is the most cost effective.
You can program the ESP8266 just like a uno in the arduino IDE.
So I would advice to take that board.

There aren't just two options.
There are also Dragino and Iduino Yun shields, which are (usually) slightly cheaper than an Arduino Yun. These can be plugged into Leonardo/Uno base boards.
Whereas an Uno or Leonardo requires about 6-7v from the power supply, a Yun shield requires 9-12v (due to the Atheros chip drawing a bit extra).
There is also the Tian, which is the Yun's successor (but at higher cost).
If you're willing to look further afield than Arduino only, you might want to consider a BeagleBone Black (which works out slightly cheaper in terms of cost/feature).


text:
Resetting millis() and micros()
I want to know how much time has elapsed since a certain event, and I do not want to use any external timers. It seems logical to reset an internal timer whenever the event occurs (using an interrupt). Unfortunately, as far as I can tell, millis() and micros() cannot be manually reset. Obviously, I could save a time stamp whenever the event occurs; however, I want to avoid overflow problems (micros() will overflow every ~71 minutes, and millis() will overflow every ~50 days).
Is there a way to manually reset these built-in counters? If not, how can I manage the overflow?

millis() and micros() overflow periodically. However, this is not a
problem: as long as you compare durations instead of
timestamps you can
forget about the overflows.
The liked answer also gives the trick for resetting millis(). Can be
handy for testing purposes, but you do not need this to handle the
millis() rollover problem. Notice that there is no clean way to reset
micros(): it relies on a static variable, i.e. a variable private to
the file defining it.

Overflow is never really an issue if you always calculate time difference. (Unless the time difference is more that 50 days.)
unsigned long previousTime = millis();
... wait for some event to happen ...
unsigned long elapsedTime =  millis() - previousTime;

Even if previousTime was before the overflow, and millis() is after the overflow (so essentially millis()<previousTime), elapsedTime will still be the correct value.
This is because the calculation itself will also overflow. Since millis()<previousTime, the result would be negative, but the type of the variable is unsigned, so it wraps around. I hope that makes sense.
Just don't ever do something like if( millis() > (previousTime+1000) )
If you still want to reset millis, you can use the following:
extern volatile unsigned long timer0_millis;
unsigned long new_value = 0;

void setup(){
  //Setup stuff
}

void loop(){
  //Do stuff
  //--------

  //Change Millis
  setMillis(new_value);
}

void setMillis(unsigned long new_millis){
  uint8_t oldSREG = SREG;
  cli();
  timer0_millis = new_millis;
  SREG = oldSREG;
}

I haven't tried the SetMillis() example yet, but this would be perfect to test the rollover. I don't see using it in normal circumstances, but to test my rollover code, this would be great, as I don't see having my Arduino set and run for 50 days and get to the part where it rolls over!

It seems logical to reset an internal timer whenever the event occurs (using an interrupt).

No it doesn't. You don't reset your clock to 00:00 when you put a cake in the oven do you?
What you do is note the time. Then periodically you subtract the start time from the current time, giving you the elapsed time. When time is up, you remove the cake from the oven.

Think about it for a minute. What if you wanted to time two events? Setting millis back to zero would hardly work then, would it? Setting it to zero for the second event would corrupt your timing for the first event.
However noting the time each one starts, and comparing the time now to the start time, will work for any number of events.

For more details see my post about millis() overflow ... a bad thing?


text:
Problem controlling a Stepper motor with AccelStepper
I have an Arduino connected to a stepper motor with an Easy Driver as follows:

I am controlling the position of the stepper motor using the Serial. This is my code:
#include <AccelStepper.h>
AccelStepper stepper(1, 9, 8);

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(10000);
  stepper.setAcceleration(5000);
}

void loop()
{
  char c;
  if(Serial.available())
  {
   int steps = Serial.parseInt();
   Serial.print(steps);
   stepper.moveTo(steps);

  }
  stepper.run();
}

The code works well but I'm facing a problem, when I set a high position value, it starts turning in the opposite direction, like if there was a limit on the steps. Does anyone know why it starts turning to the opposite direction?
I have tried to solve this problem by using:
if (stepper1.distanceToGo() == 0)
         {
            stepper1.setCurrentPosition(0);
         }

so I can set lower values to the serial. But the problem goes back again when the value goes up to the power of 6 (like 1000000).
Any idea?
Thanks!

Per a comment from the developer of AccelStepper, the line  AccelStepper stepper(1, 9, 8); should be written as                 AccelStepper stepper(AccelStepper::DRIVER, 9, 8); for clarity

Ints on vanilla Arduinos are 16 bits, and signed, which means they hold values from -2^15 to +2^15-1, so of course you cannot assign 10^6 to one of them. Use unsigned long (4 bytes), or, better yet, specify the length explicitly by using uint32_t.

could you post me the reference of this?

This has always been the case for 16-bit processors. Plus, it's in the adruino documentation. Plus, you can verify it for yourself by writing a one-line program.


text:
Use object of LiquidCrystal class within another class
I am quite new to C++ and hope that I don't bore you too much with my question.
I want to use an object of LiquidCrystal Class in another class called "Display_ManagerClass". I followed the instructions of the 2nd alternative in the following link:
Use object of other class within class
Unfortunately, I receive a linker error.
.ino-file:
#include "Licht_Manager.h"
#include "Display_Manager.h"
#include "Zeit_Manager.h"

LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7);

void setup()
{

    Licht_Manager.init();
    Display_Manager.init(&lcd);
}

void loop()
{
    Display_Manager.showText("Hello", "World");
    while (1)
    {
        Licht_Manager.blink(1);
    }
}

Display_Manager.h:
#ifndef _DISPLAY_MANAGER_h
#define _DISPLAY_MANAGER_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

#include <LiquidCrystal/src/LiquidCrystal.h>

class Display_ManagerClass
{
    protected:

    public:
        //void init();
        void init(LiquidCrystal* _p_lcd);
        void showText(String DisplayText1, String DisplayText2);
    private:
        LiquidCrystal* p_lcd;

};

extern Display_ManagerClass Display_Manager;

#endif

Display_Manager.cpp:
#include "Display_Manager.h"

void Display_ManagerClass::init(LiquidCrystal* _p_lcd)
{
    p_lcd = _p_lcd;
    p_lcd->clear();
}

void Display_ManagerClass::showText(String DisplayText1, String DisplayText2)
{
    p_lcd->clear();
    p_lcd->setCursor(0,0);
    p_lcd->print(DisplayText1);
    p_lcd->setCursor(0,1);
    p_lcd->print(DisplayText2);
}

Display_ManagerClass Display_Manager;

I receive the following errors:
Display_Manager.cpp.o:In function `Display_ManagerClass::init(LiquidCrystal*)
Display_Manager.cpp:clear()
Display_Manager.cpp.o:In function `Display_ManagerClass::showText(String, String)
Display_Manager.cpp:clear()
Display_Manager.cpp:setCursor(unsigned char, unsigned char)
Display_Manager.cpp:setCursor(unsigned char, unsigned char)
collect2.exe*:error: ld returned 1 exit status
Error creating .elf

I made sure that the correct directory of the library is set up in the project properties. The library also works in the normal way, but in combination with the class it doesn't.
I work with Atmel Studio 7 in combination with VisualMicro, Arduino IDE 1.6 and Arduino Uno.
Thank you in advance.

You must also include LiquidCrystal.h in your sketch. That way the IDE will know to include it in the list of files to compile and link with your sketch.

In the main .ino file is what Majenko is referring to. The IDE uses include directives there to know which libraries to include for linking purposes.


text:
How to get Type name of a variable on Arduino
I found this post and implemented the code in a separate classed and then passed different variables to it in an attempt to get the type name printed to serial.
The code compiled and worked fine but i get the following strange output:
For type int I get Fn on the serial monitor
For String I get ;y on the serial monitor

If I don't make a type using MAKE_TYPE_INFO(type) then try TYPE_NAME() I don't get unknown printed on the serial monitor. I get fÝ.
All this weirdness is consistent and I could use it to make decisions based on type but why do that if their is a solution.

Can you show us your full code? The example you link to works fine for me.

Also, are you sure you don't just have the wrong baud rate selected?

I could use it to make decisions based on type - why do you even need to?