text:
Best method of detecting peg in hole
I’ve got a large wall with 1” holes scattered about. I’ve got some wooden pegs that fit perfectly into these holes. Now I’m thinking of creating a light installation based on the pegs, but i’m Struggling to find a way of detecting when a peg has been inserted into any hole.
What’s the best method of detecting them? I was thinking a stop switch that’s just placed on the edge of the hole to the peg activates it, but i’m Not sure how well that can be detected or if it would bend with use

Maybe photo interrupters, reflective photo interrupters or even switches

I prefer not using switches. Moving part will wear out over time.

do an image search for microswitch .... some are rated for more than 10 million operations

Thats the term – stop switch is just what it's used for the 3D printer here.  I think it's the most analog way of detecting it, which means it's the less complex of all the options

We can't tell you the "best" method.  It depends on too many details we don't have.
Here are some options:

A reed switch at the bottom of the hole and a magnet on the peg.
A photo sensor at the back of the hole -- the peg blocks the light.
As you suggest, a switch at the side of hole.
Use contrasting colors on the wall and the pegs and detect the pegs using a camera and some sort of image processing (not an Arduino solution)

I think you are going to need to build some prototypes and experiment to find the best option for you.

Reed switch might be an option, have to think of how this is mounted and how the peg has a magnet integrated, or maybe a line detector sensor and paint the pegs black in a similar vein to the colour detection?

Alternative for the reed-switch would be a hall-effect sensor. Alternative for the photo-sensor on both sides of the hole, would be to measure reflected light instead using e.g. a  TCRT5000.


text:
Capacitive Sensor and Thread
Looking for a great way to detect when someone touches thread, or if 4 people touch thread etc.
I'm not looking for a hand count, but I'm going to try to translate it into MIDI for use in a project.
Am I looking for a form of capacitive sensor?

what kind of thread?

something like this: https://www.ebay.co.uk/itm/50m-Orange-Builders-Line-PACK-OF-2-Rope-String-Building-Brick-Masonry-Home-DIY-/311438519959

No, unless you use wire.  Or, maybe, conductive thread.  Mentioning MIDI implies you want to make music.  Indicate if this is so - as I'm thinking there are much more reliable alternative that you could use.

The Arduino Lilypad boards might be the right place to start https://learn.sparkfun.com/tutorials/sewing-with-conductive-thread

I have conductive thread, but it might be a case of finding a nicer looking thread with conductivity, this thread is very thin, not appealing to touch at all

source: Stack Exchange

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

sort: votes


text:
Overview of compiled code size
When I compile my code, the Arduino IDE returns the binary sketch size in byte.
Is there a good way to find out (approximately) what function or what part of my code takes up how much memory in flash, so that I get a feeling what feature takes most of precious flash memory or where I may be wasting flash and should start optimizing?

One approach is to look at the assembly listing of the program.

After compiling the program (via the Verify or Download button) locate the directory where the .cpp, .hex, and .elf files for the program have been stored.  (If you have trouble finding them, briefly turn on verbose compile options in the arduino IDE and look at the directory names in the output.)
In that directory, run avr-objdump -S fn.cpp.elf > listing.txt where fn.cpp.elf is the name of your sketch with .ino taken off and .cpp.elf added on at the end.  For example, with sketch serialecho.ino:
avr-objdump -S serialecho.cpp.elf > listing.txt
View the listing.txt file, and subtract each function's starting address from its ending address, using hex arithmetic.  For example, with setup code
void setup(){
  Serial.begin(9600);
}

in the listing we will see
00000144 <setup>:
...(6 lines snipped)...
 144:   26 e0           ldi     r18, 0x06       ; 6
 146:   40 e8           ldi     r20, 0x80       ; 128
 148:   55 e2           ldi     r21, 0x25       ; 37
 14a:   60 e0           ldi     r22, 0x00       ; 0
 14c:   70 e0           ldi     r23, 0x00       ; 0
 14e:   80 e1           ldi     r24, 0x10       ; 16
 150:   92 e0           ldi     r25, 0x02       ; 2
 152:   db c1           rjmp    .+950           ; 0x50a <_ZN14HardwareSerial5beginEmh>

00000154 <loop>:

The calculation 0x154–0x144 = 0x10 shows this portion of setup is 16 bytes long.
These examples were generated on a linux system.  I think the approach is the same on a MSWindows system except you may need to say avr-objdump.exe instead of avr-objdump, and may need to specify its path.  See, eg, the Assemler results, where? thread at forum.arduino.cc.

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


text:
Big endian or little endian?
I need to pass a 16-bit long address (for an external EEPROM) to a function (twi_writeTo) in a buffer.
I am currently doing this
byte buffer[2];
buffer[0] = (byte)(eeaddress >> 8);
buffer[1] = (byte)(eeaddress & 0xFF);

where eeaddress is an unsigned int with the address.
I then do
int8_t ret = twi_writeTo(eeprom_i2c_addr, buffer, 2, 1);

Before I tried
int8_t ret = twi_writeTo(eeprom_i2c_addr, (uint8_t*)&eeaddress, 2, 1);

but that returns garbage. Probably the byte order is swapped. Is that the case?
And if so, is there a better way than copying the two bytes to a buffer?

If you think endianness is the problem, just change buffer[0] to buffer[1] and vice versa, and check if that fixes your problem.

The use of (uint8_t*)&eeaddress and buffer is mutually exclusive, so I don't understand your comment.

Swap the buffer[] bytes over and see if that creates the same garbage that (uint8_t*)&eeaddress does.  If so, then yes it is an endian problem.

What do you mean exactly by it returns garbage? Please give some examples with hex numbers.

Garbage as in it reads "arbitrary" addresses so that the result doesn't make sense. I checked and indeed the first approach swaps the bytes w.r.t. the second. So, yes, it's the byte order.

If it's the byte order that causes a problem that's likely compiler specific and I don't think one can change it. Even if it were possible, changing the global endianness might break libraries that depend on it, so you likely can't escape using a function to swap the variable.
If you know you only need one value at a time you could write something like the following code, with a global buffer (untested but in principle should work (and I know global variables are evil, but should work for an Arduino project)):
byte buf[2];

byte* reverse(int val) {
    buf[0] = (byte)(val >> 8);
    but[1] = (byte)val;
    return buf;
}

So you could use it like:
int8_t ret = twi_writeTo(eeprom_i2c_addr, reverse(eeaddress), 2, 1);

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


text:
Store floats in and reading them from flash
How do I store floats in flash and how do I read them from there? (I need a look-up table for pairs of float values.)
The storing part doesn't seem to be so difficult as this compiles:
PROGMEM float value1 = 1.23456;

But how do I read them? Do I need to copy them byte by byte to a float variable, or is there a better way? (I am using an Arduino ATmega 328p with 4-byte floats.)

There is a helper macro in avr-libc that is designed just for this purpose:
#define pgm_read_float_near(address_short) __LPM_float((uint16_t)(address_short))

Read a float from the program space with a 16-bit (near) address.

Note
    The address is a byte address. The address is in the program space.

Use it like:
PROGMEM float pi=3.141592653;  // constant value in flash
float diameter = 24.332154;    // variable user value

float circumference = diameter * pgm_read_float_near(&pi);

I realize that the OP asked about a single value, but I thought I'd add info on retrieving from an array.
const float pmdata[] PROGMEM = {1.0, 2.0, 3.0};

then retrieve thusly:
float val = pgm_read_float(&pmdata[idx]);

what "&" means on &pmdata

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


text:
SRF04 Ultrasonic sensor - inaccurate readings
I have an Arduino Uno linked up to an SRF04 ultrasonic sensor. I'm using the library from here: https://code.google.com/p/srf04-library/
I'm then using the basic script "Centimeter" that comes in the examples. This gives me a reading, but it seems to be ~20-25% inaccurate. When it reads 100cm, the distance is actually nearer 80cm.
I've replaced the SRF04 with another, and the same issue occurs. Additionally, it seems when it reads out of range (or even on surfaces that give an uneven "bounce"), I get very random figures (e.g. -5cm).
Has anyone experienced something similar?

Have you used the setaverage method? If yes, what value did you use?

No, I didn't use it, just the default setting

Just don't use that library, it seems poorly designed.
Here is how the distance for roundtrip is calculated (code excerpts):
long sum = 0;
for (int i=0;i<_average;i++)
{
    digitalWrite(_trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(_trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(_trigPin, LOW);
    _duration = pulseIn(_echoPin, HIGH);
    sum=sum+_duration;
}
return(int(sum/_average));

If we remove the averaging stuff (as _average is 1 by default), this boils down to:
digitalWrite(_trigPin, LOW);
delayMicroseconds(2);
digitalWrite(_trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(_trigPin, LOW);
return int(pulseIn(_echoPin, HIGH));

pulseIn normally returns an unsigned long which is the number of microseconds for a roundtrip of the sound wave emitted by the sensor.
If we consider the speed of sound in the air to be about 340m/s (under average conditions of temperature and altitude), and if we consider an object that is 3m away from your sensor (which is the approximate max range of the SRF04 sensor), then pulseIn() should return:
3 x 2 / 340 x 1000000 = 17646 us

So far we don't see any particular problem, that's fine.
Now, if we take a look at the SRF04 datasheet timing diagram, it is mentioned that if no object is detected, an echo of 36ms will be sent by the sensor; in this situation, pulseIn() will return 36000us.
The problem here is that 36000 does not fit into an int (max value = 32767), the conversion to an int will change it into a negative value! That explains your strange negative outputs.
Now regarding accuracy, the library you are using has another issue; here is how the distance in cm is calculated:
int DistanceSRF04::getDistanceCentimeter()
{
        return (getDistanceTime()/29/2);
}

The problem here is the int calculation, it should rather be performed as float. For a speed of sound of 340 m/s, one should divide the time of the echo in us by 29.4 (ie 1000000 / 340 / 100), not 29, that can make a difference in the final calculated distance!
If you want to go on using this library, then just forget about the getDistanceCentimeter()method and replace it with the following code:
distance = (int) (sensor.getDistanceTime() / 29.4 / 2);

All calculation is then performed as float and converted to int distance only at the end.
Your code should also explicitly detect negative values as meaning "no object detected".

Thank you for your comprehensive answer. That makes things a lot clearer for me, both on the electronics and the physics side!

You wrote: “one should divide the time of the echo in us by 29.4 [...] not 29” Outdoors maybe. 29 is likely to be better at room temperature.

I am afraid you misunderstood my poitn: it was not 29 Vs. 29.4, but rather 29 (int) Vs. 29.4 (float). Could have been 29.0 as well. Now of course the speed of sound depends on many factors, not only pressure, but also temperature and humidity, but I would not want to enter into physics here (because it is a long time since I last went to school :-))

While BrettM discussed some excellent points that can occur with ultrasonic/sonar/'Ping' sensors I've noticed a few others when I have used these sensors.
The first and most common issue with sensors of this type is accurately identifying what is triggering the distance value. Consider at an abstract level how these work. You've got the bit that transmits a 'ping'. It transmits the 'ping' and stops. At this point the bit that listens for the 'pong' activates and starts listening. These sensors work by sending out that 'ping' and starting a timer, the first 'pong' the sensor hears triggers a stop response to the timer and distance is, roughly, figured out from here.  Notice that there is no way for the sensor to distinguish where the 'pong' is coming from. If you yodel on a mountain you don't know which surface echoed back and this is the same issue you are potentially facing with your sensor.
Typically when I work with people who are getting inaccurate readings from their sensors of the sort you are describing some variation of this issue is occurring. Often readings that are 'short' are so because there is an obstacle in the cone of the 'ping' that causes the sound to reflect back more quickly than expected for the surface you are measuring. Recall that sound is not a accurate,directed laser. Rather it spreads out in waves from the source. In my experience any objects within a roughly 160 degree arc(in my experience) in front of your sensor can cause these readings to be unusual. That can include the floor, your shoes, measuring devices. In theory the sensor is created to avoid these readings, in practice not so much.
To test if this is the case with your sensor setup I would recommend a few experiments. First setup the arduino and sensor in a fixed position and in such a way that the sensor is at the edge of a support surface with nothing but the surface you desire to measure in front of it. So, for example, set up the sensor on the very edge of a table facing a wall. Measure the distance from the wall to the support surface edge(table's edge). Some variation is normal, as described by BrettM, but 20% on 100 cm is a bit much in my experience. Once you get a solid, repeatable reading start changing the environment. Put something in the front arc of the sensor and see how that effects it. Move the sensor/support surface towards and away from the object. Typically when I see values like -5 that means something was too close to the sensor or, potentially, another sensor is interfering.
It is worth checking to confirm that there are no other range sensing devices in the area you are working within. Other devices sending out similar 'ping's can cause unusual readings(since they don't distinguish who's ping/pong is whose).

Thanks. I had done some testing as you describe, but the minus values threw me somewhat. Ill sort out a more accurate calculation then will proceed with further tests.

I can totally appreciate that. Ping sensors, what we called these sensors in my lab, are disgustingly noisy(as are most sensors honestly). They're certainly useful and valuable but there are so many things that can cause them to behave unexpectedly that data from them should always be suspect and filtered.

This saved my project:
https://create.arduino.cc/projecthub/panagorko/next-level-ultrasonic-sensor-a67478?f
Please spread the word, I almost gave up. This gem seems widely unknown, I spent two full days in vain trying to improve my ultrasonic sensor's accuracy.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

This is pretty standard. Altitude and air temperature will change the speed of sound enough to cause these errors, and minor variations in sensors could compound the problem. I would try calculating your own scale to convert ping time to distance using actual measurements from where you live; The library probably uses the speed of sound at sea level.
Similarly, any shape that poorly reflects or absorbs ultrasound will cause erroneous readings. There is really not much to do about this, sorry. If you have multiple sensors aimed a few degrees apart you are more likely to get one that will read the right distance.

In this case, the distance accuracy isn't so important - i'm trying to detect if someone walks by through two sensors, but it's useful to know the readings can be affected.

Distance is 25% more than expected, while the speed of sound is only 5% slower at 15,000ft (13% slower at 60,000ft). source.

That chart includes a temperature difference that would not be the case at room temperature at each altitude. Heating and AC systems also mess with pressure quite a bit. Add the 1% error coded into the library that jfpoilpret found and the variation in sensors, which I've seen be surprisingly large in other brands. Still, I agree the error is quite extreme; There may be some other unknowns.

Have you got a satisfying answer to this question?
I'm having a same issue with my HC-SR04 sensor.
It's supposed to be mm-accurate, instead I'm getting ~30%+ off values.
E.g.) @ 30cm, the readout is ~40cm.
      @ 15cm, the readout is ~20cm.
This isn't exactly a "solution" but here's what I did.
For calculating distance, I divided by additional 1.25.

distance = (duration/2.0)/29.4/1.25

Now my readings look a lot more accurate(+/-0.5cm) within ranges of 0~30cm. And although it wasn't perfect, at 2m it read 202cm.
Not sure if this is sensor issue or Arduino issue... Maybe it's lacking power such that a portion of echo pulse is not being registered at Ardu as High. I'm running my board on USB 5V, which is in turn taken off raspberry Pi2.
Still, 25% is a huge discrepancy...
WOWOWOW OK I FOUND SOMETHING!
After writing that last paragraph, I connected Arduino to my PC (instead of RPi), uploaded the s/w without 1.25 factor, and the readings are correct! (more or less. NOT like +30% before)
So yeah, it's because of lack of power.
Hope this is the case with you as well, in which case we can finally put this issue down for good.

Very bad idea to solve an observed default of the library by adding a hard-coded constant that "seems" to compensate the default and has no scientific meaning at all. Rather change for a better library!

Yeah well if sensor was poorly manufactured and has a proportional offset, this is just about the only way to "fix" the problem. Luckily this wasn't the case!

The OP mentioned he had replaced the sensor with another one, without any effect, hence I would not consider the sensor faulty.


text:
Ubuntu class string has no member remove
I am running some code that works fine on my windows system using the .remove method.  On Ubuntu 16.04 I get the following errror:
error: ‘class String’ has no member named ‘remove’

To see if it was installation, I uninstalled arduino with
sudo apt-get purge arduino arduino-core

then
sudo apt-get update
sudo apt-get upgrade

sudo apt-get install arduino arduino-core

and the issue remains.  I have seen some people say opening arduino through the terminal (from this), although that does not fix it.
Arduino version
2:1.0.5+dfsg2-4
Any help is appreciated.

Why are you running 1.0.5?

@IgnacioVazquez-Abrams I didn't realize that, for some reason I thought it was 2.  Ubuntu is installing 1.0.5 even after the updated package list, is arduino not maintained on the repo? Or am I missing something obvious?

You'll probably have to download the tarball from the Arduino site, but don't quote me on that.

The remove method was added to the String class in 1.0.6.
Installing Arduino IDE from the Ubuntu repository gets you a really old package (1.0.5).
You should download and install the newest version from the official Arduino page.

Yep, that's what I always do. Download the newest version and bang it into some place like your home directory.


text:
Linear acceleration from MPU 6050
When reading the MPU 6050 has accelerometer and gyro, I assumed it was linear acceleration, but now I second guess that.  From this video https://www.youtube.com/watch?v=qmd6CVrlHOM it seems like they are using acceleration and gyro to make one rotation direction.  I need to know what direction the mpu is moving, not just a rotational value.  Is there a way to extract this information?

Please tell us more. Do you want to measure the acceleration and deacceleration in a direction, or the motion with a constant speed in a direction ?

I am trying to find vertical velocity with mpu6050 but I failed. Did you find any benefical thing ? Thanks.

The MPU6050 has an accelerometer and a rate gyro (which tells you how fast it is rotating). The accelerometer will tell you which direction is down and in a motionless situation, that is all the information you have.
You'll probably want something like the MPU9150, it has a compass, which will give you the directional information you're asking for.

A compass will not tell you direction of movement, only direction of (apparent) orientation

When you're motionless you're ok, no movement information to report :-) The bigger problem, I think, is that at a steady speed you also have 0 acceleration, but you are moving. A compass will tell you your heading, but that may or may not be your direction of movement. I think you're talking about building an INS (inertial navigation system), you'll need to be able to determine a starting state and then track changes (accelerations) from there. You may want a GPS.

The MPU6050 has accelerometers in the x, y, and z axis. When placed on flat surface with no acceleration, you should get 0g (or whatever unit it uses, I cannot remember off the top of my head) in the x and Y directions, and 1g in the z axis. By continuously polling these values, you can find out the linear  acceleration of each axis at a given moment in time.
What you saw is probably because the chip also has three Gyroscopes, for measuring rotational acceleration and speed. The chip can do both.


text:
iterate through values in an array of strings to print
I (think I) am trying to iterate through the values of an array and print the string to a tft. I have declared the array of 4 strings, and that works fine. But when I try to print it, I get garbage. Am I missing a nuance of print? Or do I just not understand how to use arrays and strings...?
The code is as follows:
Declarations:
//Active System
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;
String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"

Use (note the fake if statement for the question)
  if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
    tft.print(displayActiveSystem);
  }

Instead I get random characters most of the time, sometimes nothing.
In case its a memory thing, please know that:
Sketch uses 26,480 bytes (92%) of program storage space. Maximum is 28,672 bytes. Global variables use 1,126 bytes (43%) of dynamic memory, leaving 1,434 bytes for local variables. Maximum is 2,560 bytes.

Maybe the baudrate is wrong? Or activeSystem is bigger than 3 and it gets out of bounds?

^ Bingo. I didnt have a catch on activeSystem.

I didnt realize how fast it looped and it went over in milliseconds. it then progressed through a bunch of memory spitting garbage all the way. Man I feel stupid right now

If the variable activeSystem exceeds the length of the array, it's out of bounds, at which point the behavior is undefined.
In your case you get "garbage data", which is actually just data in memory after the array.
Because the is no implicit check for array bounds, you need to check them yourself.

I think this is the correct way to create an array of C strings:
    char * hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    char * displayActiveSystem = hvacSystems[activeSystem];

    if(systemNeedsToBeCycled){
        activeSystem++;    // make sure to set a bound for this variable
        displayActiveSystem = hvacSystems[activeSystem];
        tft.print(displayActiveSystem);
    }

Since strings are basically stored as char pointers so an array of strings is an array of char * variables. Or you could create an array of Arduino strings:
    String hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    String displayActiveSystem = hvacSystems[activeSystem];

    if(systemNeedsToBeCycled){
        activeSystem++;    // make sure to set a bound for this variable
        displayActiveSystem = hvacSystems[activeSystem];
        tft.print(displayActiveSystem);
    }

I am not sure I understand 100% but here is my best shot. If the below is wrong
the issue is not due to being out of memory.
Try this
//Active System
char hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
// or char hvacSystems[4] = {"Off", "Fan", "Cool", "Heat"}
int activeSystem = 0;
String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"

if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
    tft.print(displayActiveSystem);
}

Your line
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
You are attempting to create a two dimensional array here. Essentially a 4x5 table. With your code if you do
tft.print(hvacSystems[0][1]);
It should give you "Off".  Basically you made a table that looks like
0{"Off", "Fan", "Cool", "Heat", null}
1{null, null, null, null, null}
2{null, null, null, null, null}
3{null, null, null, null, null }
Arrays:
https://www.arduino.cc/en/Reference/Array
2d Arrays:
http://forum.arduino.cc/index.php?topic=220385.0

It wont compile without the second dimension or with no dimension. Which makes sense if you consider that a string is an array of char's
[4][5]
0{"O","F","C","H"}
1{"f","a","o","e"}
2{"f","n","o","a"}
3{"/0","/0","l","t"}
4{null, null, "/0","/0"}

The problem does not appear to be what you think it is, because I can't reproduce it.
See this:
//Active System
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;

String displayActiveSystem;

bool systemNeedsToBeCycled = true;

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

  displayActiveSystem = hvacSystems[activeSystem]; // <-- Should now be String "off"

  Serial.println (displayActiveSystem);

  if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; // <-- Should now be String "Fan"
    Serial.println (displayActiveSystem);
    }
  }  // end of setup

void loop ()
  {

  }  // end of loop

Output:
Off
Fan

Please post a complete sketch that reproduces the problem. The placement of variables, and their type, might influence the result.
I used Serial.println() to show the variable contents, which are what you expected.

Possibly this will work better:
tft.print(displayActiveSystem.c_str ());

while you were hindered by my lack of code, the problem was there. activeSystem was unlimited and indexing invalid areas of hvacSystems after 3 loops. The loops run so fast that I missed the valid data at the beginning.


text:
How do I read the fuse bits from within my sketch?
How can I read the fuse bits from within my sketch?

You can use the boot_lock_fuse_bits_get function from <avr/boot.h>.
#include <avr/boot.h>;

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

    cli();
    uint8_t lowBits      = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
    uint8_t highBits     = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
    uint8_t extendedBits = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS);
    uint8_t lockBits     = boot_lock_fuse_bits_get(GET_LOCK_BITS);
    sei();

    Serial.print("Low:  0x");
    Serial.println(lowBits, HEX);
    Serial.print("High: 0x");
    Serial.println(highBits, HEX);
    Serial.print("Ext:  0x");
    Serial.println(extendedBits, HEX);
    Serial.print("Lock: 0x");
    Serial.println(lockBits, HEX);
}

void loop()
{
}


text:
mthread and multiple header files
I'm using mthreads (https://github.com/jlamothe/mthread) for my arduino. But now as the project is getting bigger, it would make sense to break it up in several files.
I successfully outsourced already a part which is not threaded. But somehow I cannot make up my mind how to use mthread in conjunction with several header files.
here is what I got:
main: call header:
#include "tcan.h"

tcan.h:
#ifndef tcan_h
#define tcan_h

#include "Arduino.h"

class tcan : public Thread {
  public: tcan();
  protected: bool loop();
  private:
};
#endif

tcan.cpp
#include "Arduino.h"
#include "tcan.h"
#include <mcp_can.h>

bool tcan::loop() {
  // lala
  return true;
}

but I get an error when compiling:

tcan.h:6:28: error: expected class-name before '{' token  class tcan :
  public Thread {

Thanks in advance

Check for circular #includes... The error can be caused by including Arduino.h twice.

The compiler error is due to that the compiler does not know what Thread is.

tcan.h:6:28: error: expected class-name before '{' token class tcan : public Thread {

The issue is that the header file is not complete. A good practice is to include all header files that are needed to read the header file. As Thread is defined in mthread.h the tcan.h file should be:
#ifndef tcan_h
#define tcan_h

#include <mthread.h>

class tcan : public Thread {
public: tcan();
protected: bool loop();
private:
};
#endif

Cheers!

that was the right hint "Assuming that Thread is defined in mcp_can.h".
Of course I need to include "<mthread.h>". Thanks for the hint! It's working now.

Great! I will update the answer with the correct include.


text:
Can't program Atmega644p over ISP
I am using the Arbotix-M (Atmega644p). I am trying to program it using an ISP from Pololu. Until yesterday, everything seemed to be working okay and we were able to upload to it without problems. However, recently our board intermittently returns the error.

"avrdude: stk_500() initialization failed, rc =-1,
    Double check connections and try again or use -F to override this check"

Most of the other people who get this error appear to have damaged the microcontroller in some way, but our board appears to still be functioning because it can still run the code that is already installed on it. At the moment, it basically always fails to upload, so we aren't able to change the code on the board very easily.
I have checked the voltage outputs from the device and they seem to be right. (12.5 from the main line and 5V from the auxiliary one). I don't have an oscilloscope to check the signals with, but it seems to be able to output commands fine. Thanks for reading.


text:
Remote temperature and humidity sensor with long battery life
I want to build a remote sensor which will measure temperature (range 5-30°C) and humidity (range 20-90%) and provide regularly (in the range of one measurement every minute or tenth of minutes) the measurement via wireless. This sensor will be used indoor, mostly in dark areas.
Note: measurement could be done every minutes and sending them could be done immediately or in batch of 10 measurements or more).
I was looking to build this solution using an Arduino, DHT22 sensor and a radio transmitter using ZigBee or Z-Wave protocol, and power it via AA rechargeable batteries. But after studying this solution, I found that it would be challenging to even get a week of battery life, this would require using the radio sparingly and to try to use as much as possible the power modes of the Arduino ATmel controller.
That's not enough, I want a battery life in the range of several months, 1 month would be "acceptable", 6 months would be the target, breakthrough would be > 1 year.
Note: I don't want wifi, this seems to suck even more power than the other mentioned radio protocol
Questions
Is there another more power efficient way to wireless-ly transmit the data?
Or shall I reconsider Arduino all together and look for another more power efficient controller?
Or is there another way?

I made a Temperature and humidity sensor - battery powered in 2013. It is powered from 3 x AA batteries, and lasted, as I recall, until a couple of months ago before I changed the batteries. That is, almost two years.
It logs to an SD card every 15 minutes. You could change that interval of course, it would probably not last as long logging every minute.

I certainly wouldn't attempt it with a pre-made board, because of the drain by the power LEDs, the USB chip, the voltage regulator, etc.
I measured 6 µA consumption when asleep.

Schematic

(RH-click and "View Image" to see a larger version)
The schematic is deliberately presented as "blocks" of parts of the circuit. To understand it from scratch, make up individual parts, test them and get the code working to your satisfaction. For example, the clock or the temperature sensor.
Some of the parts (like the clock) are already available as pre-assembled boards, if you prefer to reduce soldering.
You could manage without the 7-segment LED readout, however I found it useful for confirming it is working "in the field". The readout LEDs can be purchased cheaply from eBay for around $US 3. Search for MAX7219 8-Digit LED Display Module 7-Segment or similar.

Example output
Example of measuring temperature and humidity every minute:

You can see from the graph that I left the room at 9:30 pm, and the temperature slowly dropped until 6:30 am the next morning. The zig-zag effect is the central heating turning on and off.

Construction details
See the linked page for construction notes, schematic, and code.
Power saving details at Power saving techniques for microprocessors.

Estimated life at logging once a minute
If my calculations are correct, logging every minute might reduce battery life to 7 months (these things are best tested of course), but that is because the consumption is much higher when you power up the SD card. It would probably be best to take 15 readings, and then write to the card every 15 minutes. The extra time writing would be minimal, and that would keep the need to power up the card low.

The 7-segment LEDs
To clarify, those 8 LEDs are not normally on. The battery wouldn't last long if they were! If you press the switch it gives an immediate reading through the LEDs, and also tells you how many writes to disk it has done, and how many write errors it has had. This confirms all is operating properly.
The "busy" LED is there to warn you to not remove the SD card while it is writing to it.

Radio communication
To transmit information you could use a NRF24L01 transceiver module. You get those for a couple of dollars on eBay. Example:

Underneath:

You would need another one at the other end to receive (you would need two of whatever radio you chose).
I did a solar powered project using a couple of those. The NRF24L01 uses about 0.9 µA in power-down mode, so that is pretty minimal.
It also uses SPI, so the connections would be very similar to the SD card connector.
I suggest if you are going to attempt this to first get confident with a normal Uno, get the code tested, make sure you have the sleeping/waking going OK, then move it to a low-power board. There are places like Evil Mad Scientist that make "bare" boards, with a prototyping area, which you can use to put things like your temperature sensor on.

I'm new to hardware making, and this looks like complicated but doable with the right instructions. How do you "plan/design" such a board? Do you use special software to verify voltages, etc.? I'm asking because I would like to replace your SD card reader by a radio module (e.g. RFM12B or XBee) and I'm sure it is not just a swap of the 2 modules...

I just start simple and work my way up. The bare-bones board for example is described here and here. I don't "verify" voltages because they can't get much higher than the battery supplies. If you take it slowly and connect and check one thing at a time it should all be pretty easy.

See amended reply for details about radio transmission.

There is an excellent article on power reduction at http://www.gammon.com.au/power , but it's definitely worth looking at the parts of your project OTHER than the arduino - that is, your sensor, and your radio. These tend to use much more than your Arduino.
There is some persistent storage on the Arduino - EEPROM - write all your data to that as you read it, then send it all in bulk. Most of the time your radio will spend will be start/end communication.
Making your board is not as daunting as it seems. Use a breadboard to develop & test your project, then use stripboard (aka veroboard) to build your project. You can cut the tracks with a sharp utility knife, or with a specialized stripboard cutting tool (accurate & easier than a knife).
If you are still nervous, find your local makerspace or hackerspace - there are people there that would be happy to teach you to solder, and help you work out your ideas.

Sleep mode of a Zigbee is around 5uA. Power-down mode of an arduino is about the same. You can power the DHT22 via one of the digital pins, so it only uses power if you need it (though I thing you need to give it some time to "warm up"). So I don't see much of a problem. You just need to get the software working right.
Also, don't use an Uno, but one of the more bare-bones boards (e.g. Pro Mini) that don't have an usb-to-serial chip on board. Remove the power-led. Maybe remove the voltage regulator, and use 3 AAs for 4.5V.
I use blank ATMega328 chips, and build my own "arduinos" without all the unnecessary parts. I'm currently working on something similar, and plan on using an CR2032 coincell for power. >1 Year should be possible as far as I can see. If not I'll switch to AAs (11 times more power).

How do you design such hardware build? I know how to program, but putting electronic components together is "terra incognita" for me, e.g. I didn't know the UNO had a voltage regulator, and apart from a few clues I get from the name, I don't know what it does really. :-) So if I want to go the low level way, is there some nice resource where I can learn this stuff? (not just duplicating someone else project, but really understanding what I'm doing)

Have a look at the bareduino. The voltage regulator on the arduino takes any voltage above 5v and brings it down to a stable 5v by "burning off" the excess voltage. Kind of wasteful. It also requires current, even when nothing is connected (quiescent current). Not a lot, but when using batteries, it becomes significant. See Amadanon's answer about breadboards and stripboard/protoboards. You could use e.g. Fritzing if you like to design on you PC first.

If you first build on a breadboard (BB), you can fix a lot of mistakes for free, as long as no parts get damaged. Then you can choose whether to use PCBs that mimic the layout of a BB, or strip-board, which requires a little bit of re-laying out but may let you reduce the board size. In the US, Adafruit.com sells Perma-Proto boards, high-quality PCBs in 1/4, 1/2, and full-size BB layouts, so you can quickly transfer your design from the solderless BB to the PCB. I use both and I can recommend both approaches. The Perma-Proto wins on time to 1st prototype.


text:
Regarding using I2C with Arduino for Silicon Micro-structure 5852 D 1.5 psi
I am trying to get output from a sensor (micro-structure 5852D), but I only get two outputs: 11 and 255 for even applying pressure.
The following is my code, please show me how to over come this problem.
#include "Wire.h"
#define addrs 0x5F // I2C bus address

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

void loop()
{

   byte lobyte;
   byte hibyte;
   int Press;

   Wire.beginTransmission(addrs);
   Wire.write(1);
   int x = Wire.endTransmission();

   Serial.print("endTransmission: ");
   Serial.println(x, DEC);

   Wire.requestFrom(addrs, 2); // contents of your first two registers
   while(Wire.available() < 2 );          // Check for data from slave
   {
      delay(1000);
      lobyte = Wire.read();       // Read press high byte
      Serial.println(lobyte, DEC);
      hibyte = Wire.read();      // Read press low byte
      Serial.println(hibyte, DEC);

      Press = toPressure(hibyte, lobyte);
      Serial.print("Pressure: ");
      Serial.println(Press);

      delay(1000);
   }

}

float toPressure(byte hi, byte lo)
{
  int a = (hi * 256 + lo) & 0x3FFF;  // see pdf, mask 14 bit

  float rv = (a - 116)* 0.8606; // faster //(t - 1638.0) / 30.84 + 600.0
  return rv;

}

The issues in your code:

When communicating with the sensor, the sensor expects a register address after the device address. Instead of providing it the register address, you sent the number of bytes you would like to receive. Good guess, but unfortunately the device was not designed that way.
You did not combine the least significant bits and most significant bits of the sensor output correctly. The LSB contains the 6 (not 8) least significant bits, while the MSB contains the 6 most significant bits. You first combined them like 00MMMMMM00LLLLLL (where bits marked L come from the LSB and bits marked M come from the MSB), and then masked off the upper two bits as in MMMMMM00LLLLLL. The proper way would have been to only left shift the MSB 6 bits, producing 0000MMMMMMLLLLLL, and then masking away the upper 4 bits leaving MMMMMMLLLLLL.
You should avoid 32 bit floating point math on 8-bit microcontrollers at all costs unless you have a huge amount of processor cycles to spare.

In order to read data from the sensor you must first select the register you want to read. To select a register you must first send the device address (95 in decimal, 5F in hexadecimal) with the write request bit set, and then the register address of the byte you want to read.
You can then read the contents of the selected register by first sending the device address, this time with the write request bit clear, and then receiving one byte of data immediately followed by a not acknowledge (NACK) to end the transmission.
The internal registers are organized as in the following table:

Here is my take on the code. It compiles fine, but obviously I cannot test if it actually works as I don't have the sensor. I removed the scaling routine, as it would be wise to first get it working to some level before implementing less essential features.
#include "Wire.h"
#include <stdint.h>

#define SENSOR_I2C_ADDR 95
#define SENSOR_REG_PRESSURE_LSB 128
#define SENSOR_REG_PRESSURE_MSB 129

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

void loop()
{
    Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the least
    Wire.write(SENSOR_REG_PRESSURE_LSB);            //..significant bits of the pressure measurement are found
    Wire.endTransmission(false);                    //Send a repeated start
    Wire.requestFrom(SENSOR_I2C_ADDR, 1, false);    //Request 1 byte of data, followed by a repeated start

    Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the most
    Wire.write(SENSOR_REG_PRESSURE_MSB);            //..significant bits of the pressure measurement are found
    Wire.endTransmission(false);                    //Send a repeated start
    Wire.requestFrom(SENSOR_I2C_ADDR, 1, true);     //Request 1 byte of data, followed by a stop, ending the transaction.

    uint16_t pressureRaw;

    //There should now be two bytes of data in the receive buffer.
    if(Wire.available() == 2)
    {
        uint8_t lsb = Wire.read();                  //The first byte contains the 6 least significant bits
        uint16_t msb = Wire.read();                 //The second byte contains the 6 most significant bits
        pressureRaw = (msb << 6 | lsb) & 0x0FFF;    //The most significant bits are aligned and combined with the
                                                    //..least significant bits. As the resulting value only has
                                                    //..12 bits of precision the upper 4 bits are masked to zero.

        Serial.print("Raw pressure value: ");
        Serial.println(pressureRaw);
    }
    else                                            //If more or less than 2 bytes have been received something isn't right.
    {
        while(Wire.available())                     //Clear the buffer
            Wire.read();
        Serial.println("I2C transaction error");
    }
    delay(1000);
}

For some unfathomable reason Silicon Microstructures decided to not include the I2C interface specification in the datasheet itself. The information is instead found in a separate application note.
EDIT:
Apparently Wire.flush() does absolutely nothing. Implementation from Wire.cpp:
void TwoWire::flush(void)
{
    // XXX: to be implemented.
}

And no, the implementation isn't in the base class either: virtual void flush() = 0;. To work around this, I replaced the flush call with a read() loop.

Thanks I do try this , and replay you what dose come it out!!!!!

Hi james we were working as per your solution but got result as lsb going increasingly form 3 to 61 at 0 mbar pressure and msb remains constant 65535 cont.so got confused how to get exact output.Please help in another way. Thanx in advance.

@ShripadPuntambekar I cannot help in any other way, as I don't have the sensor. My code only outputs the combined value, so you must have modified the code to get a separate byte with the high bits and another with the low bits. Could you please test if my code works, without modifying it? I found a possible source for bugs in the arduino Wire library which I worked around in the update of the above code, so please copy the above code again.

Sorry if I'm late to the party. I solved this years ago. Here's my YT video demo and google drive link to the code. It works with the entire SM58XX series of sensors. Just input the parameters for your particular model in the top lines of the code and you'll be off to the races.
MY_MANOMETER_PROTOTYPE: https://www.youtube.com/watch?v=fh5GaqTO7pw
BASIC_SM58XX_EXAMPLE(i2c): https://drive.google.com/file/d/0B8kDkKQ8ZyXrQnNmVnFMSUk3eElob284Um5kMWtJYXdWUi1R/view?usp=drive_link&resourcekey=0-JPT5uBVtgmu0fv6nxLuMpQ


text:
Error loading Blink sketch in esp01 (esp8266)
I have the esp01 connected the serial port using a usb to ttl serial cable and also using the Arduino UNO as suggested in some tutorials. I can execute AT commands. But loading a sketch from Arduino IDE results in error messages show below. If anyone can help, it would be greatly appreciated. Note the error message:

serialport_receive_C0: F0 instead of C0

Build options changed, rebuilding all

Sketch uses 219,211 bytes (50%) of program storage space. Maximum is 434,160 bytes.     Global variables use 31,416 bytes (38%) of dynamic memory, leaving 50,504 bytes for local variables. Maximum is 81,920 bytes.
      /Users/syedtariq/Library/Arduino15/packages/esp8266/tools/esptool/0.4.8/esptool -vv -cd ck -cb 115200 -cp /dev/cu.usbmodem14221 -ca 0x00000 -cf /var/folders/hx/m49nxmvn0799w816ct3tgsjm0000gp/T/build10f6b721887f9efd16f05460daf22810.tmp/Blink.ino.bin
esptool v0.4.8 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
setting board to ck
setting baudrate from 115200 to 115200
setting port from /dev/tty.usbserial to /dev/cu.usbmodem14221
setting address from 0x00000000 to 0x00000000
espcomm_upload_file
espcomm_upload_mem
opening port /dev/cu.usbmodem14221 at 115200
tcgetattr
tcsetattr
serial open
opening bootloader
resetting board
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
resetting board
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: FF instead of C0
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
resetting board
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

How is it wired up? Are you pulling down pin 0 and resetting to enter firmware upload mode? You might want to read this: http://www.esp8266.com/wiki/doku.php?id=getting-started-with-the-esp8266

I have pin 0 grounded as suggested in various tutorials. It appears that this has to do with inability to flash since I am able to use AT commands without any problem.

The problem is related to the Arduino Uno, seems that you haven’t bypassed the Arduino board (since you need to program the esp you should communicate directly with it).
To do this you need to wire the reset pin of Arduino to the ground (also the GPIO1 of esp should be connected to the ground in order to go in programming mode).


text:
Measure SRAM usage
I am using an Arduino with 2048 bytes of SRAM. I have a complex project so that it is no longer obvious how much SRAM it would use in total (there is not one large dominant object but many different routines, many libraries most of which I have not written myself etc. Each of these uses some small buffers, global variables etc.).
Can I determine how much SRAM I have left in the live system?

In the preferences set the compiler to verbose output. You'll get a message like Global variables use 9 bytes of dynamic memory.

It's already set to verbose (Show verbose output during compilation) but there is no such output?

@Gerben: this only tells you the amount of static RAM usage, i.e. the data and bss sections of the memory. When the program runs, it will also consume memory in the stack, and possibly in the heap. You can estimate the amount of free memory by looking at the gap between the heap and the stack, at runtime.

Expanding on my previous comment... The RAM memory map of an AVR-based
Arduino looks like this:
┌──────┬─────┬──────┬──────────┬───────┐
│ data │ bss │ heap │→  free  ←│ stack │
└──────┴─────┴──────┴──────────┴───────┘

The data and bss sections are fixed, and their size can be known at
compile time. However, the stack and the heap grow and shrink
dynamically as the program runs. You can estimate the amount of free
memory at run time by measuring the gap between the heap and the stack.
The result may be pessimistic if the heap contains usable holes.
Here you have:

a very simple function that does exactly that, and
a more complex version that also counts the holes in the heap.


text:
Camera VC0706 not found
I tried connect my Arduino Uno R3 with module camera VC0706 following this instruction of Adafruit: https://learn.adafruit.com/ttl-serial-camera/using-the-camera.
[VC0706] --- [Arduino]
  Vcc    ---   +5V
  GND    ---   GND
  Tx     ---   PIN 2
  Rx     ---   PIN 3

And upload this example source code: Snapshot.ino of Adafruit_VC0706 library to my Arduino:
// This is a basic snapshot sketch using the VC0706 library.
// On start, the Arduino will find the camera and SD card and
// then snap a photo, saving it to the SD card.
// Public domain.

// If using an Arduino Mega (1280, 2560 or ADK) in conjunction
// with an SD card shield designed for conventional Arduinos
// (Uno, etc.), it's necessary to edit the library file:
//   libraries/SD/utility/Sd2Card.h
// Look for this line:
//   #define MEGA_SOFT_SPI 0
// change to:
//   #define MEGA_SOFT_SPI 1
// This is NOT required if using an SD card breakout interfaced
// directly to the SPI bus of the Mega (pins 50-53), or if using
// a non-Mega, Uno-style board.

#include <Adafruit_VC0706.h>
#include <SPI.h>
#include <SD.h>

// comment out this line if using Arduino V23 or earlier
#include <SoftwareSerial.h>

// uncomment this line if using Arduino V23 or earlier
// #include <NewSoftSerial.h>

// SD card chip select line varies among boards/shields:
// Adafruit SD shields and modules: pin 10
// Arduino Ethernet shield: pin 4
// Sparkfun SD shield: pin 8
// Arduino Mega w/hardware SPI: pin 53
// Teensy 2.0: pin 0
// Teensy++ 2.0: pin 20
#define chipSelect 10

// Pins for camera connection are configurable.
// With the Arduino Uno, etc., most pins can be used, except for
// those already in use for the SD card (10 through 13 plus
// chipSelect, if other than pin 10).
// With the Arduino Mega, the choices are a bit more involved:
// 1) You can still use SoftwareSerial and connect the camera to
//    a variety of pins...BUT the selection is limited.  The TX
//    pin from the camera (RX on the Arduino, and the first
//    argument to SoftwareSerial()) MUST be one of: 62, 63, 64,
//    65, 66, 67, 68, or 69.  If MEGA_SOFT_SPI is set (and using
//    a conventional Arduino SD shield), pins 50, 51, 52 and 53
//    are also available.  The RX pin from the camera (TX on
//    Arduino, second argument to SoftwareSerial()) can be any
//    pin, again excepting those used by the SD card.
// 2) You can use any of the additional three hardware UARTs on
//    the Mega board (labeled as RX1/TX1, RX2/TX2, RX3,TX3),
//    but must specifically use the two pins defined by that
//    UART; they are not configurable.  In this case, pass the
//    desired Serial object (rather than a SoftwareSerial
//    object) to the VC0706 constructor.

// Using SoftwareSerial (Arduino 1.0+) or NewSoftSerial (Arduino 0023 & prior):
#if ARDUINO >= 100
// On Uno: camera TX connected to pin 2, camera RX to pin 3:
SoftwareSerial cameraconnection = SoftwareSerial(2, 3);
// On Mega: camera TX connected to pin 69 (A15), camera RX to pin 3:
//SoftwareSerial cameraconnection = SoftwareSerial(69, 3);
#else
NewSoftSerial cameraconnection = NewSoftSerial(2, 3);
#endif

Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);

// Using hardware serial on Mega: camera TX conn. to RX1,
// camera RX to TX1, no SoftwareSerial object is required:
//Adafruit_VC0706 cam = Adafruit_VC0706(&Serial1);

void setup() {

  // When using hardware SPI, the SS pin MUST be set to an
  // output (even if not connected or used).  If left as a
  // floating input w/SPI on, this can cause lockuppage.
#if !defined(SOFTWARE_SPI)
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
#else
  if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
#endif
#endif

  Serial.begin(9600);
  Serial.println("VC0706 Camera snapshot test");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }

  // Try to locate the camera
  if (cam.begin()) {
    Serial.println("Camera Found:");
  } else {
    Serial.println("No camera found?");
    return;
  }
  // Print out the camera version information (optional)
  char *reply = cam.getVersion();
  if (reply == 0) {
    Serial.print("Failed to get version");
  } else {
    Serial.println("-----------------");
    Serial.print(reply);
    Serial.println("-----------------");
  }

  // Set the picture size - you can choose one of 640x480, 320x240 or 160x120
  // Remember that bigger pictures take longer to transmit!

  cam.setImageSize(VC0706_640x480);        // biggest
  //cam.setImageSize(VC0706_320x240);        // medium
  //cam.setImageSize(VC0706_160x120);          // small

  // You can read the size back from the camera (optional, but maybe useful?)
  uint8_t imgsize = cam.getImageSize();
  Serial.print("Image size: ");
  if (imgsize == VC0706_640x480) Serial.println("640x480");
  if (imgsize == VC0706_320x240) Serial.println("320x240");
  if (imgsize == VC0706_160x120) Serial.println("160x120");

  Serial.println("Snap in 3 secs...");
  delay(3000);

  if (! cam.takePicture())
    Serial.println("Failed to snap!");
  else
    Serial.println("Picture taken!");

  // Create an image with the name IMAGExx.JPG
  char filename[13];
  strcpy(filename, "IMAGE00.JPG");
  for (int i = 0; i < 100; i++) {
    filename[5] = '0' + i/10;
    filename[6] = '0' + i%10;
    // create if does not exist, do not open existing, write, sync after write
    if (! SD.exists(filename)) {
      break;
    }
  }

  // Open the file for writing
  File imgFile = SD.open(filename, FILE_WRITE);

  // Get the size of the image (frame) taken
  uint16_t jpglen = cam.frameLength();
  Serial.print("Storing ");
  Serial.print(jpglen, DEC);
  Serial.print(" byte image.");

  int32_t time = millis();
  pinMode(8, OUTPUT);
  // Read all the data up to # bytes!
  byte wCount = 0; // For counting # of writes
  while (jpglen > 0) {
    // read 32 bytes at a time;
    uint8_t *buffer;
    uint8_t bytesToRead = min(32, jpglen); // change 32 to 64 for a speedup but may not work with all setups!
    buffer = cam.readPicture(bytesToRead);
    imgFile.write(buffer, bytesToRead);
    if(++wCount >= 64) { // Every 2K, give a little feedback so it doesn't appear locked up
      Serial.print('.');
      wCount = 0;
    }
    //Serial.print("Read ");  Serial.print(bytesToRead, DEC); Serial.println(" bytes");
    jpglen -= bytesToRead;
  }
  imgFile.close();

  time = millis() - time;
  Serial.println("done!");
  Serial.print(time); Serial.println(" ms elapsed");
}

void loop() {
}

But when I open my Serial Monitor, it says:

No camera found?

Where did I go wrong ?


text:
FFT (or similar) library for the Arduino
I'd like to build a "low fidelity" spectrum analyzer to run on an Adafruit Trinket Pro. My primary goal is to intrigue my seven year-old niece with something that can be hacked. The plan is to pick up sound from a violin with a mic and use a set of 5 or 6 NeoPixels to represent octaves and use color for amplitude.
My first pass at this used Amanda Ghassaei's frequency detection code. It kind of worked, but seemed to be having problems with complex waveforms. After doing some more reading and looking at simple spectrum analyzers it seems that I'd do better using something like a FFT to collect the frequency information. It also seems that that might be stretching the capability of an Arduino…
Are there any FFT libraries that run well on the Arduino (over a range of about 200 to 4000 Hz)? Or are there other approaches that might work better?

A Trinket might be too slow; there are a number of FFT libraries for things like the Teensy which runs at 72MHz+, as in this Adafruit article

I tell a lie, there do appear to be ones that run on slower processors. This article, also from Adafruit, describes one that samples at around 9.6kHz, which should be enough for up to 4.8kHz analysis.

DFT is an alternative to FFT.

Thanks! As I understand it the DFT is simpler (as in easier to understand the math) than the FFT, but the computational requirements are heavier (O(N^2) vs O(Nlog2(N)), so I think, between the two I'd want to use the FFT – but I am in way over my head here…

I havent used any of the libraries to make the FFT for my personal project, due to complexity. Instead I bought a spectrum chip, which returns 7 frequencies: MSGEQ7  ( 63Hz, 160Hz, 400Hz, 1kHz, 2.5kHz, 6.25kHz and
16kHz ).
Otherwise if you are very keen on using a library, this one is very famous and fast for Arduino processors.
But again, if you dont need to have a precise band and the MSGEQ7 is good enough to detect what you want, go for it.

The MSGE!7 is appealing. I wish I knew where to get one short notice.

I think ebay or maybe from RS or Farnell


text:
Attiny45 wake by Software Serial
I would like to wake Attiny45 from sleep by Serial communication. RX is connected to pin 7 (D2). When I try to use PCINT0_vect routine, I get an error "multiple definition of `__vector_2'" so it looks like Software Serial already uses "ISR (PCINT0_vect)" and pin change interrupt.
So my question is, will incomming communication wake Attiny from sleep?
Is there a possibility to change CLKPR when Attiny starts receiving? For example I set clock divider to 256 for the majority of time and when it starts receiving it changes back to 1.
I was thinking of something like this:
void loop() {
 if (SWSerial.available()>0) {
   noInterrupts ();
   CLKPR = bit (CLKPCE);
   CLKPR = clock_div_1;
   interrupts ();
 }
//other code here
}

I don't mind loosing some bytes, but I need to low Idle current as much as possible.
Thank you.

Have you tried it? What were your results?

Any reason why you don't use the USI on pin 5 to read your serial data? Hardware support for reading in the bits and also ability to wake when a start condition is detected.

I haven't received my attiny yet. I didn't know there is such possibility, I have pin 5 unconnected. But I can modify it.

Question #1: Can a change on pin 7 wake from sleep?
Yes. The lowest power mode for this chip is Power-down, and you can wake from this state with a pin change interrupt. Assuming that the soft-serial code you are using already enables interrupts on the pin for its own purposes, then you should just be able to sleep and the part will wake on the next pin generated interrupt.
Depending on what compiler/libraries you are using, something like this...
include <avr/sleep.h>

...

set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_cpu();
//We will only reach this line after an interrupt has occured

...should work. Note that an interrupt when waking from sleep takes longer than when already running, so you'll need to check your soft serial library to see if it will possibly garble the first bit received- it will depend on how they do their timing.
If you really want the lowest power possible, you could write your own soft serial code that drops the processor to idle in between serial bit transitions. Depending on how much time you will be spending actually receiving data this could drop overall power consumption dramatically.
For low baud rates, I could imagine writing serial receive code that woke on an interrupt from the start bit, and used the timer running at a very low clock speed to wake up in the middle of each data bit and very quickly sample and shift the bit in before going idle again. Done right, this could dramatically drop the power used while receiving.
Question #2: Is there a possibility to change CLKPR when Attiny starts receiving?
Yes. You can change the prescaler any time, but note that...

The clock is not running at all during power-down mode, so there is no reason to scale back before going to sleep - it will just mean that it takes you longer to wake up when a change happens.

Sometimes scaling back the clock can actually use more power, especially when sleeping is envolved. A processor running 1/2 as fast uses more than 1/2 as much power, so it is often more power efficient to wake up at full speed, do what you have to do as fast as possible, and then get back to sleep.

The best option for you will depend on factors like how often will you be receiving data compared to waiting for data, and how much work you wan to put into getting optimal power usage. This chip can be extremely power efficient, but it can take work to take advantage of it.

I don't need low power consumption during communication.

Chip will be conncted to 20Ah battery and it will comunicate only during charging. I  haven't decided whether I will use power down or only slow down the chip. Thank you for your answer. :-)


text:
Connect a USB slave into Arduino using FTDI
Probably I'm asking a nonsense question but I'm new at interfaces.
I want to connect an USB barcode scanner to an Arduino (Uno or Mega). I've read that I need a USB host shield to achieve this. But I don't have any. I have a FTDI, so I suppose I could plug the USB output of the scanner into the FTDI and connect the FTDI to the UART port of Arduino. Then, I would be passing the USB output to Serial.
Is it correct? Thanks and sorry if I said something stupid!

No, that is completely wrong.
In USB you have hosts and devices. A device has to connect to a host. Your FT232 is a device. The barcode scanner is a device. Both of them need to be connected to a host for them to do anything.
So you need a USB host shield to act as that host.
However - check the manual for your barcode scanner: it may well have a RS-232 mode that it can be switched into (may need a different cable attached).

Okay thanks! Yes, RS-232 was my second option. I need extra hardware apart from the cable, don't I?

Maybe, maybe not. It depends on your barcode scanner. Read the manual - see what it says.


text:
Read from analog input "bounces" around
I have a joystick and am using the following code to show the output to the serial monitor:
// Arduino pin numbers
const int SW_pin = 2; // digital pin connected to switch output
const int X_pin = 0; // analog pin connected to X output
const int Y_pin = 1; // analog pin connected to Y output

void setup() {
  pinMode(SW_pin, INPUT);
  digitalWrite(SW_pin, HIGH);
  Serial.begin(115200);
}

void loop() {
  Serial.print("Switch:  ");
  Serial.print(digitalRead(SW_pin));
  Serial.print("\n");
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pin));
  Serial.print("\n");
  Serial.print("Y-axis: ");
  Serial.println(analogRead(Y_pin));
  Serial.print("\n\n");
  delay(500);
}`

Even when I am not moving the joystick, the X and Y axis outputs change continuously. Anywhere from around 50 to 600 (it seems.)
Every read has a new number.
What could be causing this?
I used the guide on https://www.brainy-bits.com/arduino-joystick-tutorial/

Can you observe the voltage at X and Y via a multimeter or an oscilloscope? Your code looks right but the hardware might have a problem. Relaxed position should read 512 (~2.5V)

const int X_pin = 0; should technically be const int X_pin = A0;, but if I recall shouldn't matter.

This is a fairly simple project.  I suspect bad parts and suggest you swap out the joystick then, if that doesn't work, the Arduino.  If that is not an option: consider if only 1 of the 2 analog input has noise on it that wiring for that input from the joystick is wrong or broken.  If both analog inputs have noise on them inspect both the ground and 5 volt wires.  However I doubt that is the problem as if either worked then all the analog readings would always be zero (only ground is connected) or its maximum (only 5 volts is connected) which I believe is 255.


text:
Using Servo with External Power
I am using an MG946R Servo.
When I use the power directly from the Arduino (Uno) and do a sweep, it works as expected.
However, when I replace the Arduino power with external power, the Servo either doesn't move or it moves randomly.
I've tried this with both a multi voltage power adaptor, setting the power to both 4.5V and 6V, as well as with a 4 x AA battery pack.
When I use a multi meter set at 6V and check the pins going into the Servo (when it's moving randomly) the voltage keeps moving to anywhere between  5.20V and 5.70V.
It seems that the Servo doesn't move when using battery pack, even though the voltage on the pins reads 5.75V.
Is there something that I am missing here?

Did you connect the grounds of both power supplies? This has to be done, when using more than one

@chrisl, I'm only using one of the power supplies (adapter or batteries) at one time.

Can you show us your circuit? Where have you checked the voltage with the multimeter? At the supply voltage or at the PWM pin?

@chrisl, sorry to waste your time. I figured it out. I needed to run connect the negative from the external power to the GND on the Arduino. (Which I hadn't done.)

What?! you have to connect BOTH grounds together? If the power supply to the arduino is a wall wart to its dc input and the power supply to the servo is another wall wart and both wall warts are plugged in to the same wall socket, arent the neutrals ALREADY connected?

@aquagremlin, yep, it seems that you do have to. I'm no expert so I'm not sure why.


text:
Counting revolutions of a DC motor with a Photo Interrupter
I have a DC motor which is rated at 11 200 RPM.
I would like to count the actual RPM (it seems to be maybe 1500 RPM from what I can tell manually.)
I bought a Photo Interrupter, and have connected it to pin A0. When the beam of the Photo Interrupter is broken, the reading drops to zero.
All seems to work well when using a delay of 100, but as soon as I drop the delay to less than about 50, I get multiple reads.
This is my code:
int must_print = 1;
int sensorValue = 0;

//the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);

  if (sensorValue > 0)
    {
      if (must_print == 1)
      {
        must_print = 2;
        Serial.println(sensorValue);
      }
    }

  if (sensorValue == 0) {
    must_print = 1;
  }

  delay(100);        // delay in between reads for stability
}

At delay(100) the Serial Monitor looks like this for a single interrupt of 10 seconds:
354

At delay(50) the Serial Monitor looks like this for a single interrupt of 10 seconds:
298
312
328
336
349
360
366
371

Thanks!

You shouldn't use an analog pin with a photointerruptor.  The photointerruptor is a digital device.  Connect it to, preferably, an interrupt pin and use an interrupt to count your revolutions at high speed.

Thanks for the advice. I just read up on the interrupt pins and I see that it's definitely the way to go. I just don't understand how you would write to the Serial Monitor when using an interrupt.

You wouldn't.  You just count in the interrupt - everything else is done in loop().

I'm using the following code, but I don't see anything in the Serial Monitor. :
int pin = 13;
int tcnt = 0;
volatile int state = LOW;
void setup()
{
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, CHANGE);
}

void loop()
{
   Serial.println(tcnt);
   digitalWrite(pin, state);

}

void blink()
{
   tcnt = tcnt + 1;
   state = !state;

}

@DanielGee - You also need to make tcnt volatile and initialize Serial with Serial.begin(9600);

It seems that the Interrupt is incredibly sensitive. If I even touch the wire running from the Arduino Pin 2 to the Photo Interrupter the Interrupt fires - multiple times. Have I done something wrong or is this expected?

@DanielGee - interrupts are sensitive, especially if you have a long cable between sensor and Pin, try adding a small decoupling cap at the microcontroller pin.

You must set the input pin to be INPUT_PULLUP

@Majenko - +1, good point


text:
Hall Effect Sensor for POV Project
I'm making a POV project and need to count the RPM of the DC Motor.
I purchased a Hall Effect Sensor and it seems to work perfectly at slow speeds, however once the motor speeds up, the sensor doesn't pick up the magnet at all.
The datasheet for the sensor is at:
http://cdn.shopify.com/s/files/1/0045/8932/files/AH180.pdf?100744
This is one of my first projects and I'm not sure what I should be looking for on the datasheet.
The sensor came as part of this product:
http://www.freetronics.com.au/pages/hall-effect-magnetic-and-proximity-sensor-module-quickstart-guide#.VZ0Zs_meDGc
There doesn't seem to be a problem with the code:
int pin = 13;
volatile int state = LOW;
volatile int tcnt = 0;

void setup()
{
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, CHANGE);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(pin, state);
  Serial.println(tcnt);

}

void blink()
{
  tcnt = tcnt + 1;
  state = !state;
}

Thanks!

From the datasheet of the hall effect sensor, the thing is only checking for 125usec in every 125msec - so if your magnet whizzes by in <100msec it will miss it.
Obviously you haven't stated the speed your magnet passes your sensor, but as it's only active 0.1% of the time, this seems the likely reason to miss.
Can you put it nearer the shaft/axle ?

Wow, 125 milliseconds is way too long. I've put the magnet as close as I can to the sensor and it hasn't made a difference. From what I can tell, the motor is doing 12 revolutions a second. Should I be using another kind of sensor? Would something as simple as 2 wires touching be a better way of doing this?

There are faster hall effect sensors out there. Just check you regulator suppliers for hall effect sensors and check their datasheets. E.g. US1881 can handle 10kHz Switching Frequency (note that this is a latching sensor, so not ideal for you application (would require 2 magnets)).


text:
Interrupt fires multiple times
I have a Photo Interrupter which I am using to count the RPM of a motor.
I am incrementing an integer to show the amount of interrupts there have been.
The issue is that there can be several interrupts fired for each time the "beam" of the Photo Interrupter is broken.
I have a 5mm length of plastic which breaks the "beam". If I make the plastic shorter than that, the Photo Interrupter doesn't pick up the break.
I am using the following, very basic code:
int pin = 13;
volatile  int tcnt = 0;
volatile int state = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, CHANGE);
}

void loop() {
  Serial.println(tcnt);
  digitalWrite(pin, state);
}

void blink() {
  tcnt = tcnt + 1;
  state = !state;
}

Why can there be several interrupts for each break?  Do you know for sure (eg via oscilloscope) that multiple  interrupts occur for each break?  Also, if you know how many  interrupts occur for each break, just divide by that number.

You appear to be asking a couple of different questions, Why does my interrupt fire multiple times? and Why won't my interrupter detect shorter than 5mm of plastic? I've tried to address both of them below, however, in the future please split them out and ask two separate questions.

How many is “several”? 2) How do you know there are several interrupts? You must have some independent means of knowing the motor speed.

@jwpat7, I don't have an oscilloscope however in the Serial Monitor I can see that the interrupt fires in clumps.

@JakeC, will do.

@EdgarBonet, several can be anywhere between 3 and 8. I think as JakeC mentioned, I should have the mode set as RISING.

What sensor are you using?

I would recommend adding a comparator with hysteresis so as to get a clean digital pulse, pictured below:

simulate this circuit – Schematic created using CircuitLab
This has the correct values.
I recommend the comparator with hysteresis as the phototransistors are prone to cause issues with interrupts even when used with pul-up/pull-down resistors, thus is as they very the voltage more than give a clean 0/1 digitally.
Here is your code, modified with the addition of RISING and of a 10mS delay.
int pin = 13;
volatile  int tcnt = 0;
volatile int state = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, RISING);
}

void loop() {
  Serial.println(tcnt);
  digitalWrite(pin, state);
   delay(10);
}

void blink() {
  tcnt = tcnt + 1;
  state = !state;
}

This method produces very reliable results. It is also accurate with objects moving rapidly because of the interrupt.

I would also say that the problem you have when you use a piece of plastic < 5mm is that the length of the slit in the sensor is 6.0±0.1(seen below). If the plastic is less you probably find that the phototransistor still has enough IR falling on it to allow voltage to flow, but enough to trigger and interrupt. With the comparator you could probably use a smaller piece of plastic and find the voltage swing with a DMM and modify the voltage divider (R1 and R2) to suite the needs.

Thanks for the advice! I'm going to do some reading on comparators first though!

Two other possible problems, apart from what Jake C has adressed in his answer are:
1. Hardware bounce
If your signal from the sensor isn't a clean transition from high to low but rather "bouncy" (see image below). The microcontroller will register multiple transitions in the meantime.

Solution to this would be to add a small capacitor (wil slow it down though) or add debouncing code... Best would be to get a "clean" sensor.
2. Floating contact

When I even move my finger close to the wire running to PIN2 the interrupt fires.

That kinda seems like it's a floating contact, where it's not really connected to anything.
This is usually solved by using a pullup/pulldown resistor. Or maybe there is something wrong with the connection.

Also:

Maybe due to the type of sensor?

You should note the part number of the sensor or link a datasheet, so we can see if it's typical behaviour for this type of sensor.

I've set the pin as a pull up. It does seem like it's a floating contact but I've noticed that when I detach the negative or positive lead, the sensor starts act completely like a floating point. The datasheet for the sensor is at: http://www.jaycar.com.au/medias/ZD1901-dataSheetMain?context=bWFzdGVyfGltYWdlc3wxMzk2OTh8YXBwbGljYXRpb24vcGRmfGltYWdlcy9oZTUvaGJlLzg4MTU3NDgwNTUwNzAucGRmfDJjZjE1NTk3Nzk3YTFlMmM5NjEzNTY5OWU0MjBmOTg0OGE3NzNkYWE5ZjFlMzc1ZWFjZjFkNjI2MzgxMGE0ZTc

I had this issue using buttons as interrupts. Adding a capacitor works like a charm!

If you want to count RPM, maybe this link will help you:
http://rjbotics.blogspot.in/2015/07/counting-real-time-rpm-with-ir-sensors.html

As far as it firing multiple times, are you aware that you have the interrupt mode set to CHANGE? This means the interrupt will fire once when something enters the beam, and again when something leaves the beam. You will probably want to set it to RISING or FALLING so that it only fires on one of those events, not both.
As to the not detecting issue I can think of a few reasons why this could be:

Your motor is moving so fast that the sensor changes again before it has had the chance to finish the interrupt service routine and reset the interrupt on the pin.
The photo interrupter you are using is too slow to report the piece of plastic passing through it. Sensors like this usually indicate a rise time and a fall time, and if it moves through the beam faster than these times it will not register the interruption.
The piece of plastic isn't large enough to block the beam. Depending on the photo interrupter, the beam used could be laser like and very narrow, or it could be wide and more like a flashlight. If it is more like the latter, you will need to have enough material present to block enough light to set off the sensor.

Thanks for the response! I have set the mode to RISING with no luck. The sensor should be fast enough but it seems that the sensor doesn't work well with the pull-up pin. I've set the pin as INPUT_PULLUP but I still get the interrupt firing intermittently. When I even move my finger close to the wire running to PIN2 the interrupt fires. It's like it's not grounded. Maybe due to the type of sensor?


text:
Need assistance with program for POV Project
I've created a very basic POV project.
It has a 12V DC motor with a piece of wood on it.
The wood has 6 LEDs on it as well as a copper ring.
The power is delivered to the LEDs from brushes connecting to the copper ring and from the shaft of the motor (the ground is attached to the base of the motor.) I'm using a TCRT5000L Sensor to count the RPM and have attached the LEDs to pin 13 and ground of the Arduino. (I've attached white tape to one side of the wood so that the sensor only counts one rev.)
I need help (please) with the program.
This is the code that I am using:
int pin = 13;
volatile  int tcnt = 0;
volatile  int lastcount = 0;
volatile int state = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, RISING);
}

void loop() {
  Serial.println(tcnt);
  if (tcnt != lastcount)
  {
     digitalWrite(pin, HIGH);
     delay(10);
     digitalWrite(pin, LOW);
     delay(10);
     lastcount = tcnt;
  }

   delay(10);

}

void blink() {
  tcnt = tcnt + 1;
  state = !state;
}

My first issue is that the when I use the code above, the lights don't seem to switch on / off on the exact same area. They are within 30 degrees but certainly not precise.
The second issue (and the biggest) is that I'm sure that this code is not the best way to do what I need. For example, if I wanted to use this as an analog clock, so that the lights would only show on the current hour / minute, how would I do this?
Any help is greatly appreciated.

If you rotate the arm by hand and observe the position sensor signal does it come up rapidly and cleanly almost independent of speed of arm motion? The sensor may be near its limit and take a finite time to transition when reflection is detected. If so,more LED current or lower separation may help. | Without trying to follow exactly what happens in your cide, are the loop delays (several 10 mS ones, affecting response time? If you change them does response time alter?

Only the first delay is needed. Try removing the other two.

Your third delay is the issue. It means you have up to 10 ms before you notice the need to turn on the light. Try this:
const byte pin = 13;
volatile bool detected;

void setup() {
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, RISING);
}

void loop() {
  if (detected)
    {
    delay(10);
    digitalWrite(pin, LOW);
    detected = false;
    }

}

void blink() {
  digitalWrite(pin, HIGH);
  detected = true;
}

Now that immediately turns on the LED, so it will always happen at the same time. Then in the main loop you notice it is on, wait 10 ms, and then turn it off.


text:
0 value integer does not enter If
I'm sure this is a very basic coding mistake...
I'm picking up a reading from A0. If the value is 0, I want the value of the serial to be written to the Serial Monitor.
I also want it only to write to the Serial Monitor for the first time that the value falls to 0.
I don't understand why, when the value for SensorValue = 0, the if is not performed.
This is my code:
boolean must_print = true;
int sensorValue = 0;

// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);

  if (sensorValue = 0) {

     if (must_print = true)
    {
     must_print = false;
     Serial.println(sensorValue);
    }
  else
    must_print = true
  }

   delay(500);        // delay in between reads for stability
}

Thanks!

  if (sensorValue = 0) {

That assigns zero to sensorValue, which then tests false. You want:
  if (sensorValue == 0) {

No problem. And in case you didn't spot it, you have the same problem with if (must_print = true). That should also be ==.


text:
Sending a double message for action to occur
I'm currently designing a system for my GCSE coursework. For the coursework, I am making a bollard system, controlled by the internet / traffic lights.
I've been experimenting with an Arduino Uno and Ethernet shield, in order to fulfill the control by the internet.
When I telnet into my Arduino, and send it the command "S#UP", the red LED comes on, and stays on for 30 seconds. If I send the command again, the Arduino does not turn on the LED, unless the command was send twice, consecutively. Also, if I were to send a different command, for example "S#DOWN", the LED does not even turn on, no matter how many times I send it.
Does anyone have any ideas for my? Anything I've blatantly missed or got myself confused on?
#include <SPI.h>
#include <Ethernet.h>
String authcode, newstatus, command;
bool UP, DOWN, EMERGANCY;
long UPTime, DOWNTime, EMERGANCYTime, LastFlash;
bool NextFlash;

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

IPAddress ip(192, 168, 1, 177);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

EthernetServer server(1265);

char serverHost[] = "LambdaLaptop";
EthernetClient phpClient;

int R = 8;
int G = 9;

void setup() {
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  Serial.begin(9600);
  Serial.println("=----------------------=");
  Serial.println("=- Traffic Management -=");
  Serial.println("=-    System Loaded   -=");
  Serial.println("=----------------------=");

  Serial.println("");

  authcode = String("4b4fec50eaa13b98934c36863293b5cf");
  LastFlash = millis();
  NextFlash = HIGH;

  pinMode(R, OUTPUT);
  pinMode(G, OUTPUT);
}

void loop() {
  EthernetClient client = server.available();
  if (client) {
    if (client.available() > 0) {
      char thisChar = client.read();
      command += thisChar;
      ProcessCMD( command );
    }else{
     if(command.length() > 0 ){
       command = String("");
     }
    }
  }
  if( UP ){
    if( UPTime > millis() ){
      digitalWrite(G, HIGH);
    }else{
      UP = false;
      digitalWrite(G, LOW);
    }
  }else if( DOWN ){
    if( DOWNTime > millis() ){
      digitalWrite(R, HIGH);
    }else{
      DOWN = false;
      digitalWrite(R, LOW);
    }
  }else if( EMERGANCY ){
   if( EMERGANCYTime > millis() ){
     if( LastFlash + 100 < millis() ){
       digitalWrite(R, NextFlash);
       if(NextFlash == LOW){
         NextFlash = HIGH;
       }else{
         NextFlash = LOW;
       }
     }
    }else{
      EMERGANCY = false;
      NextFlash = HIGH;
      digitalWrite(R, LOW);
    }
  }
}

void ProcessCMD( String CMD ){
  if(CMD == "S#UP"){
    UP = true;
    UPTime = millis() + 30000;
    if(CMD.length() > 11){
      command = String("");
    }
  }else if(CMD == "S#DOWN"){
    // Make the thing go DOWN.
    // GREEN LIGHT
    DOWN = true;
    DOWNTime = millis() + 30000;
    if(CMD.length() > 11){
      command = String("");
    }
  }else if(CMD == "S#EMERGANCY"){
    // Make the thing go DOWN.
    // Flash RED beacon.
    EMERGANCY = true;
    EMERGANCYTime = millis() + 15000;
    if(CMD.length() > 11){
      command = String("");
    }
  }else if(CMD == "TEST"){
    UP = true;
  }else if(CMD == "TEST2"){
    UPTime = millis() + 30000;
  }else{
    if(CMD.length() > 11){
      command = String("");
    }
  }
}

void SetStatus( String newstatus ){
  if (phpClient.connect(IPAddress(192,168,1,10), 80)) {
    phpClient.println(String("GET /setstatus.php?authcode=") + authcode + String("&status=") + newstatus + String(" HTTP/1.1"));
    phpClient.println("Host: LambdaLaptop");
    phpClient.println("User-Agent: arduino-ethernet");
    phpClient.println("Connection: close");
    phpClient.println();
    phpClient.stop();
  }
  else {
    Serial.println("Couldn't connect to the system!");
    phpClient.stop();
  }
}

Two things: don't use String it is very inefficient and messy. Secondly, you have misspelled "emergency".

Another problem is with your times.  Not only should they be unsigned long (or better, uint32_t), but your method of dealing with elapsed time will fail at millis() rollover.

A third issue: your whole method of building up (and clearing, and indeed everything about) your command string is flawed.  What's so special about the magical number 11...?

It would be far better to use char arrays instead of the String class (perhaps 11 bytes, if that is the largest command?).
eg.
const int MAX_COMMAND = 11;
char command [MAX_COMMAND];

 if (client.available() > 0) {
      char thisChar = client.read();
      command += thisChar;
      ProcessCMD( command );

You appear to be processing the command for every received byte. This means you will process "S", "S#", "S#D", "S#DO" etc. You need to wait until the whole command has arrived.
Then, once the command has been processed, empty out the command ready for next time.

void ProcessCMD( String CMD ){

Also all upper-case is usually reserved for constants, not variables like CMD.

Finally, your detection of end-time by addition will fail when millis() wraps. This might not matter in a small test, but you may as well teach the right way. Instead of adding an interval, remember the start time and detect when the interval is up, eg. instead of:
if( UPTime > millis() ){

You would write:
if (millis () - UPTime >= 30000) {

Where UPTime is now the start of the interval (that is, you remember when the interval starts, and do the above subtraction to find the end of it).

References

Processing incoming serial data - the same techniques apply to Ethernet

millis() overflow ... a bad thing? - how to handle millis() wrap-around

State machines - managing events happening on the fly

I do not have and ethernet shield at this moment to test on it your code but hopefully the next observations will help to solve your issue.

If I send the command again, the Arduino does not turn on the LED,
  unless the command was send twice, consecutively.

It seems that your string is not correctly processed, probably caused by "garbage" from previous received string or incomplete string. I think is from this part of the code
 if (client.available() > 0) {
  char thisChar = client.read();
  command += thisChar;
  ProcessCMD( command );

You are trying to append a char (one byte) to your command string; by doing this you are not getting the received string necessarily because the "+=" is for retrieve char by char (for example, inside a while loop). First try to print thisChar variable to ensure what are you getting and also you can print client.available() to see how many bytes you got.
Second, for your ProcessCMD function it could be better to use pointers to handle the command variable, meanwhile you must clean command variable always (and not only when CMD.lenght > 11 ), i.e,
if(CMD.length() > 11){
  command = String("");
}

must be at the end of the ProcessCMD function
  command = String("");

Also you can ensure that when you set UP=true, also set DOWN=false and so on. I prefer the Switch-Case structure to handle commands.
Try to follow arduino examples to better understand.
Cheers.


text:
Identify connected PC per Arduino
Question:
Is there a way to collect any data (e.g. MAC addresses, installed devices, driver versions, etc.) from a PC by simply connecting an Arduino via USB to it, so that this PC can be clearly identified?
Background:
Basically, I`m using an Arduino to send some text to a computer by emulating a keyboard, but I don´t want the text to be sent to any computer I connect the Arduino with. That is why I want the PC to be identified first.
To be clear: this should be done without having to install programs on the PC in the first place.

No. The Arduino is a dumb device. It can only receive what you program the PC to send to it.

Ok, but what if could find a way to direct the PC to send the data to me, by sending commands when emulating a mouse and or keyboard.

Then you can possibly tell the PC to tell you things. As long as you already know what the PC is and what/how to instruct it to tell you the right things.

@AstronAUT Yes, if you emulate the keyboard to send keystrokes to run a command (hardcoded or from a network share/trusted network location) you can select a command that reports the desired information to some network server.

http://stackoverflow.com/questions/31165217/avr-usb-detect-os

How about a unique two part cable? Make it impossible to connect the Arduino to normal USB without the special adapter.

Is your USB on the PC generating a container ID?

http://arduino.stackexchange.com/q/1689/26072  May provide some ideas on connection of USB such a Leonardo's Class 1 serial.  Another option is I2c to USB.

While not exactly the thing you're looking for, Gobetwino is a pretty sweet tool. You can emulate what you want your Arduino to do, so for prototyping and concept development it is probably what you want: http://mikmo.dk/gobetwino.html

No you cannot. Arduino communicates to pc via UART so there must be a host which can send or receive the data. You have to install software on the host computer which can send and receive data to the com port to which arduino is connected to.


text:
Interfacing 9-Axes Motion Shield with RPi and WiFi Shield
I recently purchased the Arduino 9-Axes Motion Shield. I have two questions:
Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?
Q2. A page here shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?

By providing the right power to the right pins.

Q2. A page here shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

No, it says it is compatible with the Arduino Ethernet which is not a shield, it is an Arduino.
What other shields you can use it with depends on what pins those other shields use.  Look at the schematics. Read the manuals. Do some leg-work.


text:
Problem Uploading to arduino nano (atmega 328p)
I am using Arduino 1.8.1 and arduino nano (mega 328p) and ftdi driver.
In device manager it seems no problem, because it is detected as COM99. But it says a problem while uploading to the board as picture given.
Please Helpp..

It looks like it found an invalid library in your Arduino installation. From the screenshot, though, it is not clear which. You could try de-installing the Arduino software and re-installing it.

Why did you post a screenshot with mostly irrelevant stuff and an incomplete error message? Why not copy paste the error here? There is an obvious button labeled "Copy error messages".

Looking at the error in the end about the invalid library, it seems a configuration problem and not a communication problem.
Try:

Close and reopen the Arduino IDE (and check again)
Remove the library and add it again (in the Manage library options in the menu), close/reopen the Arduino IDE (and check again)
Reinstall the Arduino IDE (and check again)


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?