text:
Simple Arduino - 74hc595 shift register construction [tmli5]
I'm quite new to Arduino world and I'm trying to understand how shift registers work.
I built this construction :

In fact, it is an Arduino Duemilanove with AtMega on it, but afaik it doesn't matter.
The tutorial I try to follow use SPI library so I try to do it too. I kind of understood that data input, latch and clock had to be pins 7, 4 and 11.
Basically, all I try to do is sending a byte to light the LEDs. As for me now, the sequence should light all LED, then no one, then one after another.
I know there is one more input ont the right side of the SR but I didn't plan this model so I ran out of LEDs...
This is the code I use :
#include <SPI.h>
#include <StandardCplusplus.h>
#include <vector>
#include <iterator>
#include <size_type>

using namespace std;

//pin du shift register
#define DATA_PIN 13
#define LATCH_PIN 4
#define CLOCK_PIN 11
//à utiliser plus tard
#define INPUT_PIN 2

void setup() {
  pinMode(DATA_PIN, OUTPUT);
  pinMode(LATCH_PIN, OUTPUT);
  pinMode(CLOCK_PIN, OUTPUT);
  //pinMode(INPUT_PIN, INPUT);

  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  SPI.begin();

  //SPI.transfer(getBit(3));
  //digitalWrite(LATCH_PIN, HIGH);
  //digitalWrite(LATCH_PIN, LOW);

  Serial.begin(9600);
  Serial.println("start !");
}

void loop() {
  shift(B11111111);
  shift(B00000000);
  shift(B10000000);
  shift(B01000000);
  shift(B00100000);
  shift(B00010000);
  shift(B00001000);
  shift(B00000100);
  shift(B00000010);
  shift(B00000001);
}

void shift(int n){
  SPI.transfer(n);
  digitalWrite(LATCH_PIN, HIGH);
  digitalWrite(LATCH_PIN, LOW);
  Serial.print("shift : ");
  Serial.println(n);
  delay(1000);
}

When I upload this code, LEDs sequence has no sense, but serial output was totally OK.
What I see (without the output 0 of course) is :
1111111, 0111111, 1011111, 1110111, 1111101 and then 1111111 without further changes, whereas serial output is 255, 0, 128, 64, 32, 16, 8, 4, 2, 1, 255, 0, 128 and so on.
I assume I didn't understand something important, and it prevent me from finding answers in google.
Thanks for helping, it's really disturbing for me.
EDITS :
changed the title, it is a 74HC595.
Strangest behavior too (not gonna create another topic for that now), I dont have to connect both the gnd and VCC from my arduino for this to light LEDs. It changes a little the brighness of LEDs, but surprisingly VCC< GND< both
This is the tutorial I use to understand shift registers : https://youtu.be/6fVbJbNPrEU?t=195, and the one that uses SPI is nXl4fb_LbcI
I am now aware that I should get one resistor for each LED but I don't have that much resistors and as far as I can see this don't harm my LEDs nor underpower them.

Which part are you using? - question says 74HC165, Fritzing drawing shows 74HC595. You show a resistor between the right and left "ground" busses - the IC's ground pin must be connected directly to ground.  You also need current-limiting resistors in series with each LED.

On a 74HC595,  pin 12 (wired to Due pin 13) is STCP, storage register clock input, while pin 14 (wired to Due pin 4) is DS , serial data input.  This conflicts with your
#define DATA_PIN 13, #define LATCH_PIN 4 statements.  Maybe your other code compensates; but anyway fix it on your board and in your code and in your fritzing diagram then edit the question to match.  I suggest you wire Ard pin 12 to '595 pin 12 and  Ard pin 13 to '595 pin 13 to reduce cognitive dissonance.  Also, wire pin 8 of the '595 directly to a ground bus, not to the LED bus that has a resistor between it and ground.

@PeterBennett just a typo, thanks. I didn't know about the resistor, and this conflict with what I understand about current, I will investigate.

@jwpat7 the tutorial video I watched uses different names as yours so it confuses me a little. It also says that these pins are mandatory to use SPI, but maybe I misunderstood. I corrected the Fritzing drawing, it was just an error in drawing.

I dont have to connect both the gnd and VCC from my arduino for this to light LEDs. - that is called "parasitic power" and it isn't good for the chip. Effectively the chip is being powered by the data inputs, which it is not designed to do. my LEDs don't die - not yet, no.

LEDs sequence has no sense - you acknowledge something is going wrong, but you are rejecting the advice which would correct it.

You have a number of problems here. The first is the wiring.

My wiring diagram above is for the Uno / Duemilanove. Since that is what you have, you should follow that.
The pins are fixed in hardware, except for the slave select pin. Thus D13 on the Duemilanove should go to pin 11 on the 595. D11 on the Duemilanove should go to pin 14 on the 595. And your slave select (which may as well be pin 10 on the Duemilanove) should go to pin 12 on the 595.

Your code looks more complex than it needs to be. This code will exercise the 8 LEDs:
#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

As other responders have said, you should have a current-limiting resistor for each LED. You can't share it like that.
Also the 595 ground (pin 8) should be wired to the Duemilanove ground, not via a resistor.

Reference
Using a 74HC595 output shift register as a port-expander

I corrected my diagram, is it OK now ? I'll let resistor like that because my LEDs don't die and I dont have enough resistors yet.
"The pins are fixed in hardware", I assumed that but I cannot find it on the web. Also the tutorial I use (https://youtu.be/nXl4fb_LbcI?t=777) don't really agree with you.

Yes, well that is certainly sad. I trust you don't believe everything you see on YouTube. :) He is bringing the chip select low and high at the wrong time. See SPI - Serial Peripheral Interface - for Arduino. Have a look at my post about Hacking a scrolling LED strip sign - as I sit here that sign is still showing me the temperature and humidity, so I think my recommendations are correct.

When you're still a young newbie, you trust anyone who's brave enough to make a youtube tutorial you know :-) Also there is quite a lot of different names for pins and concepts. I cannot figure out what are MOSI, SS and SCK compared to data_in, latch, clock clear...
Your LED strip sign is so cool ! I hope someday I'll have the level to do stuffes like this !

In a couple of cases, it's ok to use a single resistor for all the LEDs (supposing the LEDs all have comparable Vf):  1, if only one LED is ever on at once;  2, if you don't care that LEDs get dimmer as more of them are turned on.  For a simple lashup like this it's reasonable to use a single dropping resistor.

Hopefully my diagram clears up the pin names. MOSI (Master Out, Slave In) = Data_In (on the slave), SCK (Serial Clock) = Clock, SS (Slave Select) = Latch (in this case).

Victory !!! Thanks to your last comment, I finally understood it all and everything works perfectly fine ! Last little question : you don't need "beginTransaction" or anything else, as stated in the SPI manual ?

See SPI - Serial Peripheral Interface - for Arduino reply #9. The way I did it above uses deprecated function calls. It still works, or you can use beginTransaction. Read that link for details.


text:
Motor shield power from Arduino pro mini 5v RAW Pin 150mAh cannot run servo
linked to my old question, Pro Mini 5v with Adafruit motor shield v1 power sharing problems

I figured out and use one 7.2v battery (6 AA cells), and link it with RAW pin to Pro mini and join its 5v pin to motor shield 5v. It works but as I have a servo on this shield, 2 distance sensors so servo does not work well all the times. Stops or does not move as directed, shaking etc. I figured out that pro mini output 5v but only 150mAh which is not sufficient to run a servo which while sharing same 5v for motor shield. I need to know if I want to supply 5v 2000mAh from AA cells or 5v regulator, should I use these pins on motor shield (5v, Gnd, 9v)? I tried but it did not work. I did not find it anywhere on net.

How can I use these pins shown in the picture.
What is the min/max mAh value of current I can provide at these pins?
If supplying input current at these pins, should I connect/disconnect power jumper?
I am totally stuck. Need help. And here is the quick diagram how things are attached. All other pins are attached at shield connects to UNO when stack on it.

How well does it work in the following situation? : Jumper off;  motor-power battery  connected to Ext_Pwr;  separate Arduino-power battery connected to pro-mini RAW  (or 5V power supply connected to pro-mini Vcc); a ground pin on the shield wired to a ground pin on the  pro-mini

It worked but servo is not getting enough power so it gets lost many times and does not move at right time so left-right-center readings from u-sonic sensor not correct and car hits wall or stops in the middle.

What are the rated voltages of the servos and the sensor? How do you know the servo is not getting enough power? To hold down electrical noise, power the sensor from pro-mini Vcc instead of from motor battery if sensor is rated at 5V.  Minimizing electrical noise is one reason to use two separate power supplies.  The motor driver and the pro-mini need to have a common ground but don't have to have common Vcc

You can't, or at least you can't do it the way you want to. Each pin can give you a maximum of 40mA. You may try using more than one pin but that possibly wont work for you. I suggest you supply additional power from a separate source and control On/Off from Arduino. It would be like a relay. Or simply buy a relay to do this.

source: Stack Exchange

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

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

sort: votes


text:
Using arduino Due for camera control
Could the arduino Due take and send image data from 5MP camera module to PC in the following condition?

frame rate = 1fps
resolution = 2592 x 1944
format = 10 bit bayer raw RGB
interface : parallel ports (DVP) between camera and Due
           spi between Due and PC(or SD card)
FIFO(frame buffer): would not be used
SDRAM: would not be used
(But if it is needed, I would SDRAM via spi. Also I can use a frame buffer like AL422B. But if it is possible I would avoid using them.)

The camera would send 50Mbit image data per second and they will be transferred via 8 parallel lines(D0~D7) to the Due. And then they would go to PC directly or after passing SDRAM. But how can one evaluate if the 84Mhz is enough to do this job by calculation?
Arduino Due specs
https://www.arduino.cc/en/Main/arduinoBoardDue
camera module example (OV5642)
http://www.uctronics.com/cmos-camera-adapter-board-for-omnivision-image-sensor-p-248l.html
But this is not what I want to use. In my project I need to build a camera module and it would not include FIFO unless it's highly recommended.

So a quick feasability assessment:
2592 W * 1944 H * 10 bit = 50388480 bits
50388480 bits / 8 bit data bus = 6298560 packets
84000000 clocks per second / 6298560 packets = ~13 clock cycles per packet
I think that by itself, from a purely data perspective, without looking too deep into datasheets, you could feasibly read data from a port and push it out the USB port, and clock the data in less than 13 cycles. But what this means is you'd have to get into the nitty gritty of the processor and figure out how to do that as low level as possible because DigitalRead() and Serial.print() aren't going to cut it as they won't be fast enough.
The real challenge is that the above totally depends on being able to clock the data from the sensor yourself, which if I recall correctly, these sensors can actually be pretty picky about their clock.
I would highly recommend a FIFO, that way the sensor data can be clocked to it as fast as it wants to be clocked, and then you could read from the FIFO at your own pace as it will clock data out at exactly the rate you want it. Also 1 FPS is a pretty lofty goal if you are only a beginner. Like I said, it is probably possible, but it requires a lot of optimizations and planning that are not very straightforward to implement, especially if you are just starting out.

Thank you for the reply. But I wonder if it is possible for the ARM to 'save' data on sdram or sd card via spin. It seems there are more factors I should care. Like interrupts in cpu causing data loss.

There is no such thing as SPI connected SDRAM. You could write the data to an SD card, but the data throughput on that is going to be much slower than what you'll be reading the data at. In that case I would once again recommend using a FIFO, that way you can read from it at the same speed you are writing to the card.

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


text:
Pass Several Values to Library
Unfortunately I have yet to learn C++ though I have experience with C# and other non-C languages. After trying for the past 5 hours to pick up what I can from Stack and other sites I haven't found a workable solution that actually works with Arduino IDE (hence why I'm posting here and not stackoverflow).
Im trying to create a simple library to handle some analog inputs. I need to be able to compare the value from a pin to a list of values and handle the result accordingly. I can easily send the number of the pin to the constructor and read it. My issue is actually defining that list from the setup() function.
The list can be variable in length so I can't hard code an array in the library class and then pass values one by one. I can pass the length in the constructor but then I'm not really sure how to use it to initialize the array length without having the values to assign.
In C# or other languages I'd either use a list or pass the array directly. Neither of these seem to be an option with C++ (or at least I couldn't pass the array correctly). How could I solve this problem? If it helps I'm using a teensy++ 2.0.

I've chosen to undelete your question because there doesn't seem to be a reason for deletion. If you feel this was a mistake, feel free to reply to this comment. Thanks!

@jimjimmy1995 - please don't delete a question once you have an answer to it. The question and answer are intended to help other people in the future with similar problems. Thanks!

I deleted it before there were any answers as I realized my mistake when trying to pass the array. I no longer needed to ask the question and the solution was more fitting of stackoverflow.

If the list is a static list you could conceivably pass a pointer to it in the constructor. Example:
class myClass {
  const int num_;
  const int * values_;

  public:

  // constructor
  myClass (const int num, const int * values) : num_ (num), values_ (values) { }

  // other stuff here

  // demo
  void printThem ();
};  // end of class myClass

void myClass::printThem ()
  {
  for (int i = 0; i < num_; i++)
    Serial.println (values_ [i]);
  } // end of myClass::printThem

const int NUMBER_OF_VALUES = 6;
const int myValues [NUMBER_OF_VALUES] = { 22, 33, 44, 55, 66, 77 };

// make an instance of the class with the wanted values
myClass foo (NUMBER_OF_VALUES, myValues);

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

  foo.printThem ();
  }  // end of setup

void loop ()
  {

  }  // end of loop

That is the simple method. The values in the list are passed to the constructor as a pointer, the class remembers the list and uses it when necessary.

Here are a few examples how to pass vectors and variable number of arguments to a function in C/C++:
void foo(int* vector, size_t nmemb);

The function foo takes a vector of integers and the number of members, nmemb.
const size_t VECTOR_MAX = 5;
int vector[VECTOR_MAX] = { 0, 1, 3, 5, 7 };

foo(vector, VECTOR_MAX);

The next variant is generalization. A vector of whatever, number of members, and size of each member;
void fie(void* vector, size_t nmemb, size_t size);

This allows the function to handle different types of element.
fie(vector, VECTOR_MAX, sizeof(int));

Examples of usage are the standard library functions qsort() and bsearch().
The next variant is variable arguments. C/C++ allows the syntax "..." for a list of arguments.
void fum(size_t nmemb, ...);

This allows the following call:
fum(5, 0, 1, 3, 5, 7);

The implementation of function must be able to "parse" the argument list.
#include <stdarg.h>

void fum(size_t nmemb, ...)
{
  va_list ap;
  va_start(ap, nmemb);
  int arg;
  for (size_t i = 0; i < nmemb; i++) {
    va_arg(int, arg);
    ...
  }
  va_end(ap);
}

There are four primary methods to determine the number of arguments and value types; 1) number of arguments as parameter and fixed data type, 2) special end parameter value, 3) indirect through format descriptor such as printf() format string, and 4) attribute-value pairs.
Below is an example of variable number of arguments as attribute-value pairs.
void set_attrs(size nr, ...);

set_attrs(5, X_POS, 10, Y_POS, 110, R_COLOR, 0, G_COLOR, 255, B_COLOR, 0);

A usage of this notation can be found in Motif.

Arrays in C/C++ are handled as a pointer.  That means the value of the pointer is the location in memory of the first element in the array.  The next element is at that starting address, plus the size of each element.  So for an array of 1-byte characters, each item in the array is at the very next address.  For 32-bit members, it's at +4, and so forth.
You're storing an array of values to compare with analogRead() - so uint16_t (aka: short int) will be large enough for each element, without wasting too much memory.  But we also need to store a count of them, I'll assume 32-bits is enough readings.
uint16_t *comparison_points;
uint32_t  comparison_point_count;

These can be declared statically like:
uint16_t  comparison_points[] = { 2, 4, 6, 8, 47 };
uint32_t  comparison_point_count = 5;

Giving you a comparison function like:
bool readingInSet(uint16_t reading, uint16_t *check_points, uint32_t check_points_length)
{
    bool found = false;
    for (uint32_t i=0; i<check_points_length; i++)
    {
        if (reading == check_points[i])
        {
            found = true;
            break;
        }
    }
    return found;
}

But you could also make the array into an object, embedding this functionality
class AnalogueVector
{
public:
    AnalogueVector(uint32_t size, uint16_t *points)
    {
        comparison_point_count = size;
        comparison_points = points;
    }

    bool readingIn(uint16_t reading)
    {
        bool found = false;
        for (uint32_t i=0; i<comparison_point_count; i++)
        {
            if (reading == comparison_points[i])
            {
                found = true;
                break;
            }
        }
        return found;
    }

private:
    uint16_t *comparison_points;
    uint32_t  comparison_point_count;
};

Giving a usage like:
uint16_t  comparison_points[] = { 2, 4, 6, 8, 47 };
uint32_t  comparison_point_count = 5;

AnalogueVector cmp_points(comparison_point_count, comparison_points);

if (cmp_points.readingIn(analogRead(A1)))
    Serial.println("Matched");
else
    Serial.println("no");

Obviously if you're reading these data points in from a file, or other external media, then you would need to allocate space for the items, and store them in the object.
As with most coding problems, there's multiple solutions.  Here I've tried to keep it simple, and explore different ways of handling array data, without getting to far away from that fact that an array in C/C++ is just a big contiguous block of data in memory somewhere.  The address of that data, (aka the pointer), is simply the address of that first element.


text:
Arduino Mega as a USB device
My need is to connect an Arduino board (any board that has around 3 UARTs support) to a host PC via USB and expose the 3 UART connections as 3 USB devices (say /dev/ttyUSB0, /dev/ttyUSB1, /dev/ttyUSB2) in the host PC. From my search, I found Arduino Mega 2560 supports upto 3 UARTs. My question is can we expose these UARTs into individual USB ports to the host system?
Thanks,
Alexander

Not directly, no.  You have basically have 4 UARTs on the Mega2560 - one of them (USART0, pins 0&1) is connected to the USB interface chip, and the others are left unassigned for you to use as you like.  It's the USB interface chip that is being seen in your computer as /dev/ttyUSB0, not the UARTs in the Mega2560 chip.
That's not to say that what you are after is not possible - it is perfectly possible, but it will require some clever programming on your part.  You will need to:

Define a protocol that will multiplex 3 streams of serial data through the one USB serial connection
Write a sketch that works with that protocol to direct the incoming data to the right UART ports and multiplex the UART traffic into the protocol stream you have defined
Write software on your computer to perform a similar task - read in data and multiplex it, and read the multiplexed data stream and split it out to three separate destinations.

What the destinations on the PC end can be is a bit of a wooly area.  If you want to make it look like serial ports in /dev then you can use a pty pair, which is a master/slave pair of pseudo TTY devices that you can use to pass data through.  On most Linux systems they are numbered devices in /dev/pts, so /dev/pts/1 would be an example.
The function openpty(...) creates and opens a pty pair for you to use in your program.  You would do that 3 times to make three pairs and each one would be the endpoint to a sub-stream in your multiplexed data.
For instance, here is a bit of code I use to open a pty pair:
struct termios options;
openpty(&_masterfd, &_slavefd, _dev, NULL, NULL);
fcntl(_masterfd, F_SETFL, 0);
tcgetattr(_masterfd, &_savedOptions);
tcgetattr(_masterfd, &options);
cfmakeraw(&options);
options.c_cflag |= (CLOCAL | CREAD);
if (tcsetattr(_masterfd, TCSANOW, &options) != 0) {
    fprintf(stderr, "Can't set up PTY\n");
}

That makes it appear to almost be a serial connection in style.  Of course you don't have the concept of a baud rate over a pty connection, so it will be down to your software to define how you control the baud rate (probably easiest to have it hard coded to the baud rates you need).
In that snippet you talk internally to the _masterfd with normal read() and write() functions as you would any other device or file.  Some other piece of software would open the other end of the pty pair (the _slavefd), the name of which is placed in _dev when the pty pair are opened.  You could use that _dev name to then create a symbolic link to a better named device instead of using the /dev/pts/x name that could change without warning from one run to the next.


text:
2,5m cable too long for LCD connected to Arduino UNO?
So i got that 2,5m cable wired with the LCD and the arduino, but i keep getting those weird characters showing up on the LCD. Clearly there is a signal loss between the components but there has to be a solution to the problem. Perhaps by connecting capacitors/resistors to the wires will help? Is there any solution other than not using this long cable?

Try shielding the cable. Wrap it in tin-foil or something.

2.5m of what cable? What interface are you using for the LCD?

If the interface you're using is I2C(only two cables from arduino to lcd, vice versa)you have a problem,you need to pull up the sda-scl channel with appropriate resistors, you could (maybe) boost the I2C signal using ti-p82b715 bus extender, I just assume you use I2C (2,5m length?), what interface do you use? SPI? I2C?

I'm presuming this is I2C or SPI, because a Serial cable of 2.5 m should still work.
You can slow both I2C and SPI down.

In the case of SPI you can call something like this:
SPI.setClockDivider(divider);

Where "divider" is one of:

SPI_CLOCK_DIV2
SPI_CLOCK_DIV4
SPI_CLOCK_DIV8
SPI_CLOCK_DIV16
SPI_CLOCK_DIV32
SPI_CLOCK_DIV64
SPI_CLOCK_DIV128

The default is SPI_CLOCK_DIV4, so try a larger divider.

In the case of I2C you can change the clock speed and the prescaler. The default frequency is 100 kHz, but you could make it slower.
TWBR   prescaler   Frequency

  12       1       400   kHz  (the maximum supported frequency)
  32       1       200   kHz
  72       1       100   kHz  (the default)
 152       1        50   kHz
  78       4        25   kHz
 158       4        12.5 kHz

For example, to run at half the frequency (50 kHz) use:
  Wire.begin ();
  TWBR = 152;

To run at 25 kHz you also need to change the prescaler, eg.
  Wire.begin ();
  TWBR = 78;
  TWSR |= bit (TWPS0);

In the case of I2C make sure you have pull-up resistors on SDA and SCL in order to get a clean signal. 4.7 k is a reasonable value to try (for both of them) with the other ends connected to +5 V.

Sorry. I probably should have mentioned hat my LCD is connected to an arduino expander - a mcp23017 to be specific - which is connected to the arduino. Therefore I guess that I use I2c?

Yes, the MCP23017 is I2C. The MCP23S17 is SPI. You should have four wires in that case: +5V, Gnd, SDA, SCL. Make sure you have the 4.7 k pull-up resistors on SDA and SCL (at the Arduino end). Also try dropping the I2C frequency as shown above.


text:
Model Rocket Sensors
My idea is to record the acceleration/altitude of a small model rocket launch using these sensors and record all the data onto a microSD card which I'll retrieve afterwards. I'd like to be able to plot all of the data to analyze the performance of the rocket. This data will also help compare the experimental results to the theoretical ones.
Accelerometer
OpenLog/SD Card
(Was only allowed two links so couldn't include barometer)
I have a few questions to make sure that my logic is sound when trying to design this circuit;
1.) Since the OpenLog contains the ATmega328 microcontroller I was going to use the Arduino to write the instructions to this which will initialize the two sensors and start logging data. Is this the correct way to do this? From what I could tell the other sensors did not contain any EEPROM/Flash so there was no way to store any code on there.
2.) If I have multiple sensors running at the same time is this going to cause a data conflict when writing to the SD card? Would it be possible to save two different .txt files, one for each sensor?
Thanks

Model rocket flights are short enough you might consider an SPI flash instead of a micro SD card.  Write time will likely be a lot more deterministic.   Given that most model rockets are small, you would ideally use a thin purpose-made board having exactly the components you need, for minimum weight.  Another option could be to re-use the board from a tiny quadcopter, since that has a microcontroller and an 6-axis accelerometer, and solder a tiny SPI flash to it with flying leads.   Or try to send the data over its 2.4 GHz radio, which can transmit as well as receive...

One thing about determining heigth. An accelerometer will not give you the exact height as far as I know. You can estimate the height by checking the acceleration but it won't be very accurate.

Not what you asked, but check if that accelerometer range is big enough for your rocket application.

The OpenLogger was designed to be paired with and Arduino Pro or Arduino Pro Mini and just log the serial output from one of those. You could theoretically use the OpenLogger itself to do the sensor reading and writing, however, the I2C pins that your sensor needs haven't been broken out on the OpenLogger.
This means if you really wanted to make this happen, you would have to hand solder those pins and break them out yourself. After that the process is pretty straightforward. SparkFun provides both the source code and directions on programming it.
If trying to break those out is a little too tricky, you can either pair it with one of those Arduino models and use it to read the data, or find another similar logger device that has more pins broken out.
Two answer the second part of your question, reading multiple sensors isn't a problem. Usually the way these sensors work is you send a request for data to them and they return the reading, so you would just request from the first sensor, request from the second sensor, write out to the file.
You can write to two different files no problem eiteher. I would not however, recommend writing to two different files. Switching from one file to another, back and forth introduces a little extra overhead which will slow down your loop. In rocketry, things happen very fast, and you'll probably want keep your loop running as fast as possible. I would recommend just writing to a single file and include data from both sensors probably something along the lines of time,accelX,accelY,accelZ,bar.

Thanks for the help, glad I'm somewhat on the right track. Could you elaborate what you mean by breaking out the pins? Do you mean that I would need to wire the sensors up individually to the components on the OpenLog board such as the ATMEGA328 chip or SDsocket? Would I not be able to wire it using the predetermined pins that were labeled on board? I considered using an Arduino but my concern was that it wold be too big to fit inside a rocket. Maybe I could try to find a 'Mini Microcontroller'.

To use the open logger you would have to wire it straight to the pins on the chip. If you look at this picture you'll see that not all of them have trace coming out from them (and some of those pins are the ones you need). There are plenty of options for small arduino compatible boards: Arduino Micro, Adafruit Trinket Pro, Sparkfun Pro Micro to name a few, Then all you would need to do is wire in a micro sd breakout like this.


text:
NRF24L01+ PA not working with Arduino Mega (works with Nano)
Full disclosure: I'm a newbie.
I've got an Arduino Nano and a Mega, and a pair of NRF24L01+ PA modules (exactly these: http://www.elektrotedarik.com/Images/Urun/11122013173429.jpeg)
I'm trying to get them to work. I am on this tutorial with the RF24 library: https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
On Arduino Nano, it works perfect. I wire everything as told, and set up my radio:
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
fdevopen( &my_putc, 0);
radio.begin();
radio.setPALevel(RF24_PA_MAX);
radio.setDataRate(RF24_250KBPS);
radio.openWritingPipe(pipe);

When I call radio.printDetails(); I get a nice output in serial monitor:
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1    � = 0xe8e8f0f0e1 0xc2c2c2c2c2
RX_ADDR_P2-5    � = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe8e8f0f0e1
RX_PW_P0-6  � = 0x20 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR   � = 0x03
RF_CH        = 0x4c
RF_SETUP    � = 0x27
CONFIG       = 0x0c
DYNPD/FEATURE   � = 0x00 0x00
Data Rate    = 250KBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_HIGH

Everything as expected. If I remove a wire (for testing), it displays all zeroes, when I plug it back, it displays right again, so I assume that it's in working condition. I then try the same with Mega, but even after re-checking the wiring after 4 times, it's not working. Here's what I get with the same code:
STATUS       = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1    � = 0x0000000000 0x0000000000
RX_ADDR_P2-5    � = 0x00 0x00 0x00 0x00
TX_ADDR      = 0x0000000000
RX_PW_P0-6  � = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x00
EN_RXADDR   � = 0x00
RF_CH        = 0x00
RF_SETUP    � = 0x00
CONFIG       = 0x00
DYNPD/FEATURE   � = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = Disabled
PA Power     = PA_MIN

Tried many times, no avail. Then I've came upon several threads talking about the different pins. Changed the pins to match Mega's MOSI, MISO, SCK, CE, CSN pins, no avail. I've tried exact same configuration with people who say that it's working, no avail. Then I've stumbled upon that Mega ironically can't supply enough current from the 3V3 pin (while Nano perfectly can) and it can't power the NRF24L01+ PA. I've tried drawing 3V from my power supply (my power supply has either 3 or 4.5 volts, I can't risk burning my transceiver with 4.5 volts). It still doesn't work, and it became extremely hot in seconds (the one attached to my nano doesn't heat up at all). I immediately turned it off, thought that I've burned something, swapped with the Nano's transceiver, and it (fortunatelly) works. So there's no problem with the NRF24L01+ PAs. Why would it not work with Mega (I've also tried the lowest power setting too), and why would it get extremely hot when attached to an external power supply? What else can I do?
UPDATE: I've added a 470uF decoupling capacitor to the receiving end (the one attached to Mega), it seems to be worse.
A very interesting observation: If I touch the receiver when it's not working, it starts receiving the signal excellently. If I let it go, signal is lost again.
UPDATE 2: Nevermind the last "when I touch..." update, it appears to be related to wiring (haven't soldered them yet, just using jumper wires)
UPDATE 3: My initial assumption is correct, something happens when I touch the cables. Something more weird is going on. I soldered my module on a prototype board, and my module sometimes works even without CE pin plugged in. When I touch the cable, it transmits, and stops. Here, TX pin lighting up means it's receiving the signal (I'm writing data to serial). It receives the data (and yeah, the correct data) when I touch the CE pin's cable:

How on Earth is this possible? Does the CE pin/cable (and myself) act as an antenna? Makes no sense.
UPDATE 4: If I plug that pin to 5V, the whole receiver starts working absolutely perfectly, with no errors/drops at all. But I can't get it: why? And would it overheat/short something?

Lack of power sounds right, getting hot sounds wrong. Even when not working correctly when powered from the 3v3 pin, did you have a 10uF cap across the nRF power pins?

What is the init code that you use on your mega?

@RogerRowland Nope, I didn't have a cap, should I? by the way, I've tested the power supply and it appears to be a bit off. It outputs about 4 volts in 3V mode. It would explain why it was getting hot, and possibly not working.

@MathieuL the same as Nano with the exception of CE and CSN, which are 40 and 53 respectively.

@CanPoyrazoğlu Well did you change the pin? If NANO and Mega don't have the pinout, you need to change the init code.

@CanPoyrazoğlu If i get it right the first block of code is the code that you run on Nano to init your transceiver?

@MathieuL my bad, initially I've said they are the same. then I've added the changes to the comment.

@MathieuL yes, it sets it up. I try the same (with Mega's pin mapping instead of Nano, but otherwise the same), and it doesn't start.

@CanPoyrazoğlu What value do you assigne to CE_PIN, CSN_PIN on the mega?

@MathieuL 40 and 53. Found them from here http://projectsfromtech.blogspot.com.tr/2013/05/nrf24l01-arduino-communication-on.html

@CanPoyrazoğlu try Ce = 8 , CSN = 53 , SCK = 52 , MOSI = 51, MISO = 50

@MathieuL from (another, this time, measured really at 3.2V) power supply, it returned garbage data. It wasn't zeroes, but it was ever changing and meaningless. Then, I went back to mega as the supply, and it worked.

You never did mention if you applied the capacitor suggested by Roger. Even the tutorial you linked to mentions the Megas in particular exhibit this problem.

@JakeC I've soldered a 470uF capacitor and it made everything worse. Now it connects much harder and disconnects immediately.

@JakeC it transmits at bursts. For a second or two, excellent transmission, then, say about for 5-6 seconds, nothing at all.

I have a NRF24L01 - not that exact model, mine looks like this:

Pin-outs:

I hooked it up to my Mega2560 like this:
NRF24L01     Mega2560
----------   ----------------

  VCC         3.3V pin
  Gnd         Gnd
  CSN         D10
  CE          D9
  MOSI        D51 - (MOSI)
  SCK         D52 - (SCK)
  IRQ         N/C
  MISO        D50 - (MISO)

I used the RF24 library. Then I hit a number of issues.
For one thing, the "Getting Started" sketch doesn't seem to work too well, even between two Unos, for reasons I haven't worked out.
However the "pingpair" sketch worked OK between two Unos. But not when one device was moved to the Mega2560! I tried various things including a separate power supply, and moving the CSN/CE pins around, but to no avail.
Then I had a look at Vcc/Gnd using the scope:

That's over half a volt of ripple! I soldered on a 0.1 µF capacitor between Vcc and Gnd on the NRF24L01 and the problems went away. Using the pingpair sketch I now have:
Now sending 56...ok...Got response 56, round-trip delay: 23
Now sending 1080...ok...Got response 1080, round-trip delay: 21
Now sending 2103...ok...Got response 2103, round-trip delay: 21
Now sending 3126...ok...Got response 3126, round-trip delay: 21
Now sending 4148...ok...Got response 4148, round-trip delay: 22
Now sending 5171...ok...Got response 5171, round-trip delay: 22
Now sending 6194...ok...Got response 6194, round-trip delay: 22
Now sending 7217...ok...Got response 7217, round-trip delay: 22
Now sending 8240...ok...Got response 8240, round-trip delay: 21
Now sending 9263...ok...Got response 9263, round-trip delay: 21
Now sending 10286...ok...Got response 10286, round-trip delay: 21

So, my suggestion is a decoupling capacitor on the NRF24L01.

Extra
I still had some weird issues where the above results actually came from a NRF24L01 without the aerial. The one with the aerial had much more marginal results.
These are the results with the aerial:
Now sending 181378...ok...Failed, response timed out.
Now sending 182581...ok...Failed, response timed out.
Now sending 183784...failed.
Failed, response timed out.
Now sending 185047...failed.
Failed, response timed out.
Now sending 186309...ok...Got response 186309, round-trip delay: 26
Now sending 187336...ok...Got response 187336, round-trip delay: 22
Now sending 188359...ok...Failed, response timed out.
Now sending 189561...ok...Got response 189561, round-trip delay: 22

Still, I think it is worth trying the decoupling capacitor.

and why would it get extremely hot when attached to an external power supply?

Did you have the grounds connected?

Nope, didn't have the grounds connected, moreover, it was a faulty supply, in 3V mode I saw about 4-4.2V in voltmeter. I think those combined explain it.

Whatever else you do, always connect the grounds. Otherwise you may have some massive voltage which happens to be the difference in the grounds in your house wiring appearing at your processor chip.

You are definitely right, and I actually knew about that (and it does make perfect sense intuitively too, GNDs should be equal). My newbie-ness and lack of experience made me forget about that :)

An old thread.
But I want to share my fix when hooking nRF24 with MEGA. I forgot the website where I got the solution.
It is simply adding a pinMode(x, OUTPUT) in the setup, where x is the CSN pin you choose.
I believe the issue is only on pin 53 only on MEGA.
However, add this in all my sketches with or without MEGA just for precaution.


text:
Float arithmetic vs. int arithmetic - is there any power penalty?
It is widely known that float arithmetic takes longer (that is, eats more cycles) than fixed-point (or integer, or bitwise arithmetic), and that surely is something to consider for speed- and time-critical applications.
My question is: supposing I don't have any time-critical need (and I have enough program and RAM memory), should I be worried by any other disadvantage of using float?
Specifically, I wonder if the processor would be more power-hungry because of those extra CPU cycles.

UPDATE:   What will my application do meanwhile?
The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using float to apply filtering to button inputs, in order to debounce the buttons simulating a RC filter + schmitt-trigger. So the loop in pseudo-code would be:

Read all inputs (digitalRead or direct port access);
Filter the readings and decide if a button action has been detected;
Set some control flags that determine which part of the cycle the lights are in;
Check for elapsed time to actually turn blinkers on and off.

So, since I plan to react to button input as realtime as possible, most time would be spent filtering (that is, performing floating point operations), since direct port access and flag-setting are supposed to be nearly instantaneous, right?

port access and flag-setting are supposed to be nearly instantaneous - yes direct port access would take place in about 2 clock cycles.

It depends on what your processor is doing while it has no real work to do:

If you put it to sleep, then yes, using floats will keep the CPU awake for a longer time and burn more energy.
If you are instead doing busy-waits (e.g. with delay()) it should make no difference, since the CPU is busy 100% of the time anyway.

Update: According to your update, it seems your program never
sleeps. Then I would expect no substantial difference in power
consumption between using floats or ints. As Majenko said, there can
theoretically be some small difference depending on the number of
transistor transitions involved in each instruction (and, I would add,
the capacitive loading of the involved transistors), but I do not expect
this to be very significant.
If you are really concerned about the consumption of your Arduino, I
would suggest you use it only for prototyping, then move your code to a
bare ATmega (or maybe even an ATtiny) chip. Also, add at least one call
to sleep_mode() inside your main loop. Each such call will put your
CPU to sleep until the next timer interrupt, which typically happens
every 1024 µs. There is a lot more to say about power savings, see
for example this excellent writeup by Nick
Gammon.
Edit: When trying to minimize power consumption, one of the very
first things to do is figure out how much work has to be done, and make
sure your program never does more work than required. In your case, this
means you have to know how often your main loop should execute, and
prevent it from running more often than needed. For example:
#include <avr/sleep.h>

const unsigned long loop_period = 5;  // run the loop every 5 ms.

void loop() {

    /* Sleep while waiting for the next time slot. */
    static unsigned long last_time;
    while (millis() - last_time < loop_period)
        sleep_mode();
    last_time += loop_period;

    /* Actual work goes here... */
}

If the actual loop work takes significantly less time than the loop
period, your CPU will sleep most of the time, leading to significant
power savings. Then you can start digging into more advanced
power-saving techniques like those mentioned in the article linked
above.

See my update, I described the workflow of my mainloop, thanks! :D

@heltonbiker: I updated my answer to address your updated question.

Perfect! Your answer not only addresses my initial questions, but also shows an array of additional considerations, all of them very relevant and well explained. Thank you very much!

The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using float to apply filtering to button inputs, in order to debounce the buttons simulating a RC filter + schmitt-trigger.

Using floats is way overkill here. To debounce all you need to do is note when the switch changed state, and ignore further state changes during a certain interval, say 10 ms. It is even quite feasible to sleep during that debounce period. One of the watchdog timer intervals is 16 ms which would be about right for that.
In any case, an application that turns lights on is hardly going to be one where you are worried about how much power floating point operations take. I would be 1000 times more worried about how much power the lights use.

Thanks for your answer! I know debouncing is usually something quite trivial, but depending on the electrical nature of your contact, there can be some interesting problems. For a discussion on that - and on why one would want to use smoothing - see the link on my update. Also, the lights and the Arduino board will be possibly running on different power sources - say, hub dynamo for the lights, small battery for the board. But I'll consider all of your tips!

Yes, more power will (theoretically) be consumed.  That is, compared to doing nothing.
Float operations will require more mathematical operations to perform compared with integer or fixed point.  That will mean more gates are being activated and deactivated etc, compared to doing nothing.
Would that increase in power be noticeable?  Probably not.  It'll be so tiny as to be negligible.  As Edgar Bonet has mentioned, if you are making use of sleep modes then the extra time taken to perform the float operations will impact the ratio of running to sleep time, but if all you are doing is a set of mathematical operations a few times a second and using the millis() or delay() functions to control the timing then the difference will be so minimal you'll never notice it.
The effect is more noticeable on a PC when you perform very complex operations (like 3D rendering) and the CPU gets hotter and the fan speeds up.  In this situation the CPU is entering an idle state (like sleep, but less so) when it's not needing to perform any tasks which reduces both power consumption and heat dissipation.  When performing heavy tasks it has less time to be idle and so generates more heat. The more complex the operations the more transistors need to switch and so the more heat is dissipated.
Unfortunately the power dissipation per op-code is not documented, but it should be possible to write some assembly code to execute a single instruction in a tight loop (start with NOP) and measure the current, then change that instruction for a different one and compare the current.  Using NOP as a baseline you should then be able to calculate the increase in current for each op-code.  Of course, the actual data the op-codes are operating on will also have a bearing on the power consumption.
But that would be pretty pointless unless you are budgeting for every single femtowatt of power.

See my update. I don't have timing on the loop itself, so it is free to run as fast as possible. Only the flag-setting logic is based on elapsed time, since the system is supposed to blink leds on a bicycle (yeah, I know...) with traffic-signaling purposes.

If you are interested in power saving, I think it would be more important to check that the standard Arduino library doesn't turn on HW blocks that you do not need.
From an engineering perspective, though, the filter you are pursuing seems a bit overkill, if you only worry about bounces. Waiting for a reasonable amount of time after the first transition should be sufficient and would keep the code simpler to write, test and debug.
The mechanical switch is already a dampened system with its own intrinsic time constant.


text:
Arduino Uno & Simulink - high frequency pulses
I'm trying to control a large stepper motor with high frequency pulses (eventually around 4kHz), but what I get out of the simulink scope is super different from what the Arduino is putting out. I'm using this variable frequency PWM block: www.mathworks.com/matlabcentral/fileexchange/48563-variable-frequency-pwm-block

(yes, I've tried it on pin 5/6, but if I do that there's no difference)
This is the output from the Simulink scope (period of 0.01s):
and the Arduino is putting out pulses with a period of ~4 seconds. This is on pin 6 of the Uno, by the way. Why won't the Arduino output the same frequency as the Simulink program?

Please amend your question and post the Arduino code. How can we tell what it might be doing without seeing the code? What did you get out of the Simulink scope?

I've added the simulink program (didn't use Arduino code)

Why won't the Arduino output the same frequency as the Simulink program - I don't understand your question. You are asking why the Arduino won't output a certain frequency, but you are not using Arduino code? Well, without code it won't output anything. Perhaps if you clarify.

It is outputting something, because I'm using a physical oscilloscope to measure the output (and my stepper motor is moving, just really slowly). Not 100% sure how it works, but I think Simulink uploads code to the Arduino because the Arduino gives the same pattern of blinking light as it does when Arduino code is uploaded. If you've done this before, do you need to use Arduino code too?

No I haven't used Simulink. I gather from your answers and my research just now, that Simulink is supposed to generate code from your block diagram above and upload that to the Arduino, is that correct?

This is on pin 6 of the Uno, by the way. - you have pin 11 on your Simulink block diagram.

Yes, Simulink generates code from my block diagram. And I've been switching between pins 11 and 6, so the pictures aren't consistent, but the output is the same :(

It seems clear from what you have described that this is a Simulink bug.

Why won't the Arduino output the same frequency as the Simulink program?

The Arduino can output quite a lot of frequencies. I have a page about Arduino timers which describes them in some detail.
However since Simulink is generating the code for the Arduino (which we are not being shown) and since it claims to be generating 0.01 s, and the code it is generating does not do this, that is a bug in Simulink.
I suggest you contact their customer support.
Alternatively you could attempt to program the hardware timers yourself. The page I linked could be a good starting point for such an exercise.


text:
Existence of a non blocking and task yield framework for Arduino programming
I've been playing around with Arduino and understand that the standard runtime provides a single thread essentially.
I was wondering if it is possible to write a thin layer (library) that allows one to write code that is non blocking and one where each task yields control manually which allows the master loop to implement some form of timesharing.
I'd appreciate any:

Comments on existing frameworks that can allow me to write my programs this way
Any comments on how hard implementing anything of this order of magnitude would be.

Similar to http://arduino.stackexchange.com/questions/286/how-can-i-create-multiple-running-threads

You are vaguely describing an RTOS, which while there are some out there that target Arduino, (IMHO) they aren't very practical except in a few narrow use cases.

I would recommend NilRTOS.
I like the fact that it's really minimal.
However, you might find that some libraries (which you would like to use) work in blocking mode and cannot be used with this RTOS, because they might do bad things (polling) or worse things (polling in interrupt context with other interrupts disabled).
But that will be the case regardless of the thread framework you choose.
You might want to try also femtoos.
I think that the code could be organized far better, which is one of the reasons I preferred NilRTOS.

My recommendation would be to simply code without needing blocking. I have examples here.
Petri Häkkinen coded a game - Toorum's Quest - without using any real-time library. That game (on a Uno) has multiple sprites, TV output and sound effects, all interleaved.
The basic technique is to know that you have multiple things you need to have done, from time to time, and check in the main loop if it is time to do one of them.
One issue with any sort of real-time library is, you only have limited resources. You need to be really aware, for example, of which bits of hardware are doing what (eg. timers, SPI, I2C, interrupt handlers, serial comms).
Even existing libraries suffer from the problem that one library may require (say) pin-change interrupts, and "requisition" the interrupt handlers needed for that, and another library also uses pin-change interrupts, and they cannot be linked together.

I do not see how the RTOS is a problem in the situation described. It's actually sort of typical (and, frankly, very annoying/disappointing) that 2 or more libraries contend the use of the same timer. I'd rather patch them, drop the meddling with the timer and let the RTOS call them when appropriate. If anything, this shows a shortcoming of the Arduino libraries, where there is no standardized way to do timed stuff and the author of each library is let alone to figure out what HW timer to use.

It's not a problem that has an easy solution. Things like pin-change interrupts, for example, used by SoftwareSerial. Once you add one of the interrupt handlers you are committed to handling 8 pins. And how do you handle when one library wants timer 2 for timing an event, and another one wants it to do PWM?

As I said: let the RTOS replace the direct use of the timer.
If a library just needs a periodic signal, most likely the RTOS can replace the timer handler with a thread. Same goes for PWM.
Of course it depends on the time resolution and precision required. But I think in most cases it would be sufficiently accurate.
Software Serial is something beyond redemption, as it busy loops in interrupt context. It's ok for a simple project, but in a serious application, I would definitely not use it, as the delay is not even fixed, but depends on the baud rate.

For the pin change interrupt, I think that's another short coming of the standard Arduino library. IMHO there should be a default, standard, way of running timed tasks and to get the OS to handle inputs/outputs, like providing the first/last time an input line changed or generate a pwm by sw on an arbitrary pin. I moved away from the Arduino standard libraries after noticing that thy make it harder to do apparently simple tasks.

That horse has probably well and truly left the stable by now. A lot of libraries assume you are only going to use their library (or at least not another one with conflicting requirements). To have imposed a RTOS during the early days of design would probably have been too hard, and now it is too late. The other issue is memory. To have multiple threads you need multiple stacks, and probably multiple heaps. It's going to get rather hard to manage all this when you only have 2 KB of RAM to start with.

True, the horse has left the stable and so have I left those libraries ;) But it is not a big deal, at least for my needs. In the end i'd rather spend time learning the AVR than trying to workaround limitations coming from sw that was in most cases designed to perform only 1 task.


text:
Arrays and Functions
How can I return a char array from a function?
char c[] = getFloat(val, valid);

char getFloat(float val, bool valid){
      if(valid){
        char stringFloat[16];
        dtostrf(val, 10, 8, stringFloat);
        return stringFloat;
      } else Serial.print("No Float");
    }

Allocate it in the heap. Don't forget to free it after.
#include <stdlib.h>
#include <string.h>

 ...

char *c = getFloat(val, valid);
use(c);
free(c);

 ...

char *getFloat(float val, bool valid){
  if(valid){
    char stringFloat[16], *ret;
    dtostrf(val, 10, 8, stringFloat);
    ret = strdup(stringFloat);
    return ret;
  } else {
    Serial.print("No Float");
    return NULL;
  }
}

An alternative method would be to allocate the string statically inside the function, like this:
const char * getFloat(float val, bool valid){
      if (valid)
        {
        static char stringFloat[16];
        dtostrf(val, 10, 8, stringFloat);
        return stringFloat;
        }
      else
        return "No Float";
    }

Now we can use that string:
const char * c = getFloat(24.5678, true);

However note that this is only good for one use at a time!
This would not work properly, for example:
const char * c1 = getFloat(24.5678, true);
const char * c2 = getFloat(42.7654, true);

Now c1 and c2 both point to the same piece of memory, so only the last one would be correct. However this restriction may not matter to you. And it saves you having to free memory afterwards, and possibly saves you from heap fragmentation.


text:
Recover from wrong Wi-Fi password on Arduino Yún
I'm trying to customize my Arduino Yún to work as an access-point (or hotspot) for providing services to clients directly connected and, alternatively, to work as a client on a wireless network for downloading resources from the Internet.
The access to such a wireless network is gained after the user submits a network SSID and password in the web control panel provided by Yún.
How can I recover from a user submitting a wrong password? At the moment the Yún stays stuck without any connection, and thus is unreachable via SSH to attempt any recover.

Perhaps if you posted your code, we could help.

At the end I came out with a button connected to one of the digital input pins and a sketch that, using the bridge to communicate with the "Linux part" of Yún, restores original values in the configuration files and reboots the whole controller.
After the reboot completes the Arduino Yún is accessible again through the Wi-Fi network "Arduino Yun xxxxxxxxxx".

The simplest option is to provide a serial console interface which will either give full access to the OS (pipe through Console) or a menu driven interface that sends instructions to the main chip (through Bridge).
The user would then connect to the USB interface and use a terminal program to access the configuration in whatever way you have chosen.  This could either be via options within your installed sketch, or by uploading a special sketch through the USB connection.

The fact is that the Arduino board will be in a box, and the only channel available will be the wi-fi. I basically would like to replicate the behaviour described in [link] (https://www.arduino.cc/en/Main/ArduinoBoardYun?from=Products.ArduinoYUN) , for the WLAN RST button pressed for more than 5 seconds.

You could always solder wires from the switch to your Arduino such that if after 15 mins you are still not connected to the net. Reset the WiFi by pulling that pin low ( I think)


text:
is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together?
I am lakshman a mechanical engineer,i have a question that is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together???
so that i can take the output value from Accelerometer so that to make a call to a preprogrammed number???
Plz help me.
Thank you.

Please provide links to the devices you have in mind, or is this just a very general question?

Yes, it is possible.

Yes, that is perfectly possible.  Typically:

Accelerometer is either an analog, SPI or I2C interface.
GSM is usually a UART interface
The Arduino UNO has all four interfaces (analog, SPI, I2C and UART) available on separate pins.

The rest is just a SMOP.

A little too much jargon, @Majenko. I had to Google what SMOP meant. ;) (And some of the results probably were not what you meant).

@NickGammon Just a "Small Matter of Programming" - i.e., if you have to ask this then you have a lot of learning to do before you can write the software, and while it would be simple for us, for someone that doesn't even know if you can connect these things together it's not going to be a simple task


text:
Wrong code ouput, when the specific function runs more than once
If I run the following code, I get the correct output, and the path is displayed on the serial monitor. However when I run the code together with the commented out portion (in the code below) I don't get any output; even the output that is printed before this code doesn't print completely. Why is that?
I have figured it out that this happens when the dijkstra functions runs more than once. But it shouldn't happen like this.
   int *path1 = NULL;
    int no_of_nodes_1;
    dijkstra(graph, startingNode1, end1_start2, &path1, no_of_nodes_1);

    /*int *path2 = NULL;
    int no_of_nodes_2;
    dijkstra(graph, end1_start2, end2_start3, &path2, no_of_nodes_2);

    int *path3 = NULL;
    int no_of_nodes_3;
    dijkstra(graph, end2_start3, endingNode3, &path3, no_of_nodes_3);
        */
        delete graph;

    Serial.println();

    Serial.println( "PATH 1:");
    for (int k = 0; k < no_of_nodes_1; k++){
        Serial.print(path1[k]);Serial.print("..");
        }

/*
    Serial.println();
        Serial.println( "PATH 2:");
    for (int x = 0; x < no_of_nodes_2; x++){
        Serial.print(path2[x]);Serial.print("..");
    }

    Serial.println();
    Serial.println( "PATH 3:");
    for (int y = 0; y < no_of_nodes_3; y++){
        Serial.print(path3[y]);Serial.print("..");
    }

*/

::UPDATE::
/******************************************************************************/
    void getNextNode(int node, const int& src, const int predecessor[264], int temp_path[], int& i){

        i = 1;

        if (node == src)
        {
            temp_path[i] = src;
        }

        else if (predecessor[node] == -1)
        {
                Serial.println("No path exists");
        }
        else {
            getNextNode(predecessor[node], src, predecessor, temp_path, i);
            temp_path[i] = node;
            i++;
        }

        return;
    }
/********************************************************************************/
    int* savePath(int predecessor[264], const int& src, const int& targetnode, int & numofnodes){

        int temp_path[200];
        temp_path[0] = src;
        int i;

        if (targetnode == src)
        {
            temp_path[1] = src;
        }
        else
        {
            getNextNode(targetnode, src, predecessor, temp_path, i);
        }

        numofnodes = i;
        int *path = new int[i];

        for (int k = 0; k < i; k++){
            path[k] = temp_path[k];
        }

        return path;

    }
 /****************************************************************************/
    void dijkstra(struct Graph* graph, int src, int target, int **path, int& numofnodes)
    {
        // The main function that calulates distances of shortest paths from src to all
        // vertices. It is a O(ELogV) function

        int V = graph->V;// Get the number of vertices in graph
        int* dist = new int[V];      // dist values used to pick minimum weight edge in cut

        int predecessor[264]; //array to save nearest nodes

        // minHeap represents set E
        struct MinHeap* minHeap = createMinHeap(V);

        // Initialize min heap with all vertices. dist value of all vertices
        for (int v = 0; v < V; ++v)
        {
            dist[v] = INT_MAX;
            minHeap->array[v] = newMinHeapNode(v, dist[v]);
            minHeap->pos[v] = v;
            predecessor[v] = -1;
        }

        // Make dist value of src vertex as 0 so that it is extracted first
        minHeap->array[src] = newMinHeapNode(src, dist[src]);
        minHeap->pos[src] = src;
        dist[src] = 0;
        decreaseKey(minHeap, src, dist[src]);

        // Initially size of min heap is equal to V
        minHeap->size = V;

        // In the followin loop, min heap contains all nodes
        // whose shortest distance is not yet finalized.
        while (!isEmpty(minHeap))
        {
            // Extract the vertex with minimum distance value
            struct MinHeapNode* minHeapNode = extractMin(minHeap);
            int u = minHeapNode->v; // Store the extracted vertex number

            // Traverse through all adjacent vertices of u (the extracted
            // vertex) and update their distance values
            struct AdjListNode* pCrawl = graph->array[u].head;
            while (pCrawl != NULL)
            {
                int v = pCrawl->dest;

                // If shortest distance to v is not finalized yet, and distance to v
                // through u is less than its previously calculated distance
                if (isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
                    /*pCrawl->weight*/1 + dist[u] < dist[v])
                {
                    dist[v] = dist[u] + 1 /*pCrawl->weight*/; // 1 is the weight of the node
                    predecessor[v] = u;
                    // update distance value in min heap also
                    decreaseKey(minHeap, v, dist[v]);
                }
                pCrawl = pCrawl->next;
            }
        }

        delete[] dist;
        delete minHeap;
        *path = savePath(predecessor, src, target, numofnodes);
    }

Please provide the whole code, including the dijkstra function and the values for graph, startingNode1, end1_start2. Also there are two sections commented out. Which one are you referring to in your question?

@Gerben I have updated the question please see it now. And I am referring to both sections together.

I performed a rollback to revision 3, as revision 4 deleted much of the code that was pertinent to the question.

You have likely run out of RAM.
You have 200 integers in the temp_path array. That equates to 400 bytes of SRAM. You also have 3 predecessor arrays each with 264 integers, which equates to 1584 bytes. These arrays combined use 1984 bytes. This is in addition to all your other variables and function calls.
The Arduino Uno only has 2KB of SRAM.
Solution:
Use an Arduino with a greater amount of SRAM.

ARDUINO M0/Zero - 32KB of SRAM
Arduino Mega  - 8KB of SRAM
Arduino Due   - 96KB of SRAM


text:
Make a GET Request GPRS
I'm building a weather station that sends the data to a webserver via GET request.
I was wondering if you guys can look into my code and help me.
I looked all over the internet and can't find what's wrong. I'm using an Arduino mega, an Arduino/Telefonica GSM shield and an EE sim card. Thank you very much!

#include <GSM.h>

GSM gsmAccess;
GPRS gprs;
GSMClient client;

const boolean gprsCheck = true;

char server[] = "";

int value = 112358132134;

void setup(){

  Serial.begin(19200);

  if(gprsCheck) {

    boolean notCon = true;

    Serial.println("Establishing connection...");

    while(notCon) {

      if((gsmAccess.begin("") == GSM_READY) & (gprs.attachGPRS("everywhere","eesecure","secure") == GPRS_READY)) {

        notCon = false;

        Serial.println("GPRS connection successful.");
        Serial.println("");
      }

      else {

        Serial.println("GPRS connection failed. Trying again.");
        Serial.println("");

        delay(1000);
      }
    }
  }

  if(!client.available() && !client.connected()) {

    client.stop();
  }

  if (client.connect(server, 80)) {

    Serial.println("Connection successful.");

    client.print( "GET /add.php?");
    client.print("value=");
    client.print(value);
    client.print(" HTTP/1.1\n");
    client.print("Host: ");
    client.print(server);
    client.print("\nConnection: close\n\n");
    client.stop();
    client.stop();

    Serial.println("Data sent.");
  }

  else {

    Serial.println("Error.");
  }
}

void loop() {
}

You never said what is happening that is wrong. Please describe the actual problem and also include the serial output.

It does not work as I wanted. I want it to run the url just like a brower would do (i got this from arduino.cc: A typical web request looks like "GET pathname HTTP/1.0". print will send the message, just as a browser would.) And when i type on a browser the url i want the arduino to perform, it works just fine. There's no error message.

Either you have implemented this incorrectly, your server is not reachable from your mobile provider, or your GSM device is not in communication with its mobile network, or your arduino is not in communication with your GSM device.  Think about other tests you can run to identify which sort of issue you have.

I say this because you think the code is fine?

int value = 112358132134; - the largest number an int can hold is 32767. Why are you calling client.stop(); twice?

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


text:
Porting SH1106 Oled Driver - 128 x 64 / 128 x 32 Screen is garbled but partially responsive
I'm porting the SH1106 driver to netmf and have found several libraries that more or less accomplish the same thing. A few were much easier to understand and had less abstraction so I followed those.
I've tried the U8glib with my arduino and it works just fine. The ported display driver yields these results:

inverted:

What you're looking at is the screen right after the initialization and attempting to draw a filled circle. You can see the bottom of the circle at the top of the screen. Somehow the origin or page is shifted, but I don't fully understand what's going on. I can send the invert display command and that works as well and turn the display on and off. My initialization code is this:
public void init()
{
    resetPin.Write(true);
    Thread.Sleep(1); // VDD (3.3V) goes high at start,
    resetPin.Write(false); // bring reset low
    Thread.Sleep(10); // wait 10ms
    resetPin.Write(true); // bring out of reset

    dcPin.Write(DisplayCommand);

    SendCommandB(0xAE);    /*display off*/

    SendCommandB(0x02);    /*set lower column address*/
    SendCommandB(0x10);    /*set higher column address*/

    SendCommandB(0x41);//0x40);    /*set display start line*/
    SendCommandB(0xB0);    /*set page address*/
    SendCommandB(0x81);    /*contract control*/
    SendCommandB(0x80);//contrast);    /*128*/
    SendCommandB(0xA1);    /*set segment remap*/
    SendCommandB(0xA6);//invertSetting);    /*normal / reverse*/
    SendCommandB(0xA8);    /*multiplex ratio*/
    SendCommandB(0x3F);    /*duty = 1/32*/
    SendCommandB(0xAD);    /*set charge pump enable*/
    SendCommandB(0x8B);     /*external VCC   */
    SendCommandB(0x30);    // | Vpp);    /*0X30---0X33  set VPP   9V liangdu!!!!*/
    SendCommandB(0xC8);    /*Com scan direction*/
    SendCommandB(0xD3);    /*set display offset*/
    SendCommandB(0x00);   /*   0x20  */
    SendCommandB(0xD5);    /*set osc division*/
    SendCommandB(0x80);
    SendCommandB(0xD9);    /*set pre-charge period*/
    SendCommandB(0x1F);    /*0x22*/
    SendCommandB(0xDA);    /*set COM pins*/
    SendCommandB(0x12);
    SendCommandB(0xDB);    /*set vcomh*/
    SendCommandB(0x40);
    SendCommandB(0xAF);    /*display ON*/

    // Switch to 'data' mode
    dcPin.Write(Data);
    this.ClearScreen();
    this.Refresh();

}

I have two methods to "refreshing"
public virtual void Refresh()
        {
            Spi.Write(displayBuffer);
        }

    /// <summary>
    /// Send buffer to display
    /// </summary>

public void Display()
        {
            //set column address
            dcPin.Write(DisplayCommand);
            SendCommandB(0x21);
            SendCommandB(0);
            SendCommandB((byte)(Width - 1));

            //set page address
            SendCommandB(0x22);
            SendCommandB(0);
            SendCommandB((byte)(_pages - 1));
            dcPin.Write(Data);

            //Spi.Write(displayBuffer);

            for (ushort i = 0; i < displayBuffer.Length; i = (ushort)(i + 16))
            {
                //Spi.Write(displayBuffer);
                SendArray(displayBuffer, i, (ushort)(i + 16));
            }
        }

At this point I'm a little lost. My hunch is something to do with paging and or display RAM. I'm looking for some insight here on how to fix this as I know there's a lot of experience here with these displays. Thanks!

Looks like it's clipped. You are placing the content to high on the screen so only the bottom is visible.

@Gerben yea, something like that. There's a strip only about 1/8 the height of the display. Know how to get it to work?

While your initialization routine looks fine to me (comparing to the datasheet and as evidenced by the fact the display turns on), what doesn't look right is your drawing routine:
//set column address
dcPin.Write(DisplayCommand);
SendCommandB(0x21);
SendCommandB(0);
SendCommandB((byte)(Width - 1));

//set page address
SendCommandB(0x22);
SendCommandB(0);
SendCommandB((byte)(_pages - 1));

The commands 0x21 and 0x22 don't correspond to any commands I can see in the datasheet.  They look more like commands more commonly seen with ILIxxxx or SSDxxxx screens to create an "addressable window" from 0,0 to Width-1, _pages-1.
Instead you should be using the same commands you used in the setup routine to set the current col / page coordinate in RAM to write to.
Commands (0x00 | (col & 0x0F)) and (0x10 | (col >> 4)) set the column position, and (0xB0 | (page & 0x0F)) set the page number.
You then write all 128 bytes for the current page before moving on to the next page.  This means you will have to do it a page at a time, something like:
for (ushort page = 0; page < 4; page++) {

    // Set the current RAM pointer to the start of the currently
    // selected page.
    dcPin.Write(DisplayCommand);
    sendCommandB(0x00); // Set column number 0 (low nibble)
    sendCommandB(0x10); // Set column number 0 (high nibble)
    sendCommandB(0xB0 | (page & 0x0F)); // Set page number

    // Send a single page (128 bytes) of data.
    // Without knowing the rest of your program I don't know the right
    // data sending routines to use, so I made them up. Change it to
    // do it how your program expects.  Maybe with your SendArray
    // function.

    dcPin.Write(DisplayData);
    for (ushort col = 0; col < 128; col++) {
        sendDataB(displayBuffer[page * 128 + col]);
    }
}

Note that this method is very similar to how the KS0108 GLCD drivers work.  Each byte of the page represents 8 pixels on the screen so the screen, at 32 pixels high, is split into 4 pages, where each page is 8 pixels, or one byte, high.
The effect you are currently seeing is because you are never changing the current page number (0) so you are always writing your data to the first page.  This loops around multiple times, so you end up writing all 4 pages to the same strip of the display ending up with the last page being displayed, which is the last 8 lines of your display data.  The rest of the display is never being touched and just contains whatever random data was in the RAM at power-on.

This is a great start. You've confirmed my suspicion and clarified the functionality and the issue. For some reason, I thought the datasheet mentioned that pages will auto-increment when it overflows. Am I wrong? There are still a couple of kinks...The current display I have has 8 pages so I made that change and I'm getting something that's working. I have to figure out the shifting of the start column by 2 as this driver is for 132 columns. Also, the "Hello" should be at the top left.

Just send 0x02 0x10 instead of 0x00 0x10 to start on column 2 instead of column 0. The page never changes. In the DS it states: "When the microprocessor repeats to access to the display RAM, the column address counter is incremented during each access until address 131 is accessed. The page address is not changed during this time.". The location of your "Hello" will be due to where you are telling it to print it since it is drawn in the display buffer not on the screen.

Thanks! That's what I thought..That's from the initialization too. I found the issue with the text too... Regarding the display buffer versus writing directly to the screen. I would still need to increment the pages with direct writes, correct?

@GisMofx Correct.  Unless you manually increment the page the display writes will just loop through the current page over and over again - which is what you saw before where it was stuck on page 0.

Thanks. Is there anything else I should be aware of regarding paging/incrementing while I'm developing some methods for this display?

I always use a framebuffer to store the data locally and output the whole display page in one operation when working with displays of this kind.  It is so much simpler than manipulating the display's RAM.  As long as you do that then there's minimal code for working with the display and everything else becomes completely display agnostic. I recommend sticking to that same approach.

Thanks. I was deliberating over the two approaches. I really appreciate your feedback and help!


text:
Controlling Protoneer CNC shield without PC
I'm building an small CNC using Protoneer CNC shield, GRBL and Arduino UNO.
With this I need to connect the board to PC and send G-Code from there.
My question is, is it possible to use the arduino itself to control the CNC shield?
If yes how?
If not is there any other way to send commands other than USB (as Arduino's USB port is not a host)
Thanks

Have it read the GCode from an SD card.

@Gerben: no; currently I'm sending using Universal GCode Sender through USB port

That wasn't a question, but a suggestion. Using and SD would negate the need for USB.

An Arduino can talk directly to a shield, independent of a PC.
This will, however, need a way to tell your Arduino to do it's thing. Depending on what you want it to do, this may require nothing ("send this pre-defined g-code as soon as you are turned on"), a memory card of some sort, one or more pushbuttons, or even a small screen. I have seen several 3d printers with memory cards, buttons (usually up/down/select/back), and a small screen that, once set up, can print anything you can load onto a memory card.
There are other forms of communication, too - ethernet, wifi, etc., which you can use, with appropriate shields.
In the end, of course, you still have to design your object - 3d graphics are well beyond the ability of an Arduino, so there will still be some form of computer involved.

Thanks but the shield got all of arduino pins, how can i connect the buttons or sd card ? and when I installed GRBL firmware on arduino can I still program it and send commands to gcode from inside?


text:
ATtiny85: Power consumption vs clock speed
Short and simple: What is the power consumption for an ATtiny85 running at 1 MHz and 8 MHz using the internal clock? Not using any sleep modes.
I have googled a lot and can't find any info on this. I ask because I want to know if it is worth using 1 MHz to increase battery life.

The datasheet is the 1st place to look for things like this

I actually did look in the datasheet. But is very long (234 pages) so I searched for strings like "power consumption" etc without luck. If I had just searched for "current" instead I would have found it!

The datasheet shows that current decreases at lower frequencies. Around 1 mA at 1 MHz running at 5 V. More like 5 mA at 8 MHz running at 5 V.

You can save quite a bit by using lower voltages as well, as you can see. For really big savings use a sleep mode. Read about Power saving techniques for microprocessors.

(Edited to add)
To amplify on my remarks, you should be able to get 200 nA consumption at 3.5 V in sleep mode with no watchdog timer. That will still respond to interrupts, such as closing a switch.

If you need to do things periodically you can enable the watchdog, and then get around 5 µA consumption at 3.5 V.

This is so much less current than the 1 mA mentioned above, that it is well worth exploring running in power-down mode, where possible.

Wow. This answer is brilliant and a perfect example why I love Stackexchange so much. Thanks a million!

Nice answer. I would just add that, when using sleep modes, the relevant metric for active mode consumption is not the current (consumed charge per unit time) but the consumed charge per clock cycle. Thus, it seems that running at 8 MHz is more efficient (5 mA / 8 MHz = 0.625 nC/cycle) than running at 1 MHz (1 mA / 1 MHz = 1 nC/cycle).

@EdgarBonet: Is that because it takes less time to run the program when it wakes up at 8Mhz compared to 1Mhz? So it can again go to sleep as soon as possible.

@Nick Gammon: When dealing with low power comsumption, what would be the best option to run the Attiny from 12V? A 7805 is rather inefficient I believe.

@marlar: Exactly! You have some job to do when you wake up, which takes a fixed number of cycles irrespective of clock frequency. Then you care about the consumption per cycle, not per second.

but the consumed charge per clock cycle - absolutely. Which is why I mention on my page about power, that if you operate at a lower clock speed you might be using less power, but you are using it for longer.

what would be the best option to run the Attiny from 12V - if you really must have 12 V as a supply, you may well find a buck-mode switching power supply more efficient.

@NickGammon: Thanks. 12V is used by the stuff that Attiny controls, that's why.

@marlar, if the thing that the Attiny controls uses 12v, then you should first and foremost look at the power consumption of this device - it's no good saving 2 or 4 mA, if you are running something that draws 2 amps.

@AMADANONInc.: you are of course right. But the controlled components are dormant most of the time and use no power except when attiny think it's time to call to action. Apart from that, there is certainly also a learning element here. I really want to investigate low-power mode.


text:
Is there any way to separate this short code into its own function? (webserver, trying to use client.print outside of main loop)
I have an arduino webserver that uses the following code:
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Content-Type: text/html"));
client.println();
client.println(F(""));
...
if (fan1Toggle == 0)
    client.print(F("Fan1•On
"));
else
    client.print(F("Fan1•Off
"));

if (fan2Toggle == 0)
    client.print(F("Fan2•On
"));
else
    client.print(F("Fan2•Off
"));
...

The page is pretty long, allowing the user to toggle over a dozen different switches. Some of the code checks to see the state of a certain switch, and then displays a green or red bullet ("&#8226", like •) on the page if the switch is on or off.
Since the code for the colored bullet is repeating, I wanted to make a function for it. Then I would just call (for example) "displayBullet(fan1Toggle);", and it would determine if fan1 was on or off, and display the correct color depending on the state.
I tried to create the following function:
void displayBullet(int toggle) {
if (toggle == 0)     //switch is off, so display red bullet
    client.print(F("•"));
else    //switch is on, so display green bullet
    client.print(F("•"));
}

But then I got an error saying that "'client' is not declared in this scope".
Is there any way to work around that error, so that I can get the displayBullet() function I want? Or is this something that can't be shortened like this, because the "client" function has to be inside the main loop?
Thanks!

You can pass client to the function by reference, like this:
void displayBullet(EthernetClient & client, int toggle)
  {
  if (toggle == 0)     //switch is off, so display red bullet
    client.print(F("•"));
  else    //switch is on, so display green bullet
    client.print(F("•"));
  }

Now it knows about client. Make sure you pass client when you call it:
displayBullet(client, 1);

Thanks a lot!! That's very useful information to know, and I'm sure it'll help me in the future with other similar problems.


text:
Adafruit DHT22 Library + Arduino Due not compiling?
i recently purchased a DHT22's and tried to get it to work using Adafruit's DHT library on Github.
When i compile it with a Arduino DUE, it gives me the following error:
C:\Users\Moz\Documents\Arduino\libraries\DHT-sensor-library-master\DHT.cpp: In constructor 'DHT::DHT(uint8_t, uint8_t, uint8_t)':
C:\Users\Moz\Documents\Arduino\libraries\DHT-sensor-library-master\DHT.cpp:14:9: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]
   _port = digitalPinToPort(pin);
         ^
Error compiling.

It compiles on a Arduino Uno but not on the DUE.
What is the reason for this?
Edit: Below is the example code i use
#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

#define DHTTYPE DHT22   // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");
  dht.begin();
}

void loop() {

  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
}

That library uses direct pin manipulation to make things faster.  However the Due is a completely different architecture to the Uno, so direct pin manipulation is done differently.
The library would have to be written specifically to do it in the two different ways and select between them depending on which board is chosen for the compilation.  This hasn't been done, and it's unlikely it would ever be done.
This is exactly why digitalWrite(), shiftIn(), shiftOut() et al exists, so that you don't get these kind of problems.  By choosing not to use them Adafruit have basically decided that their library will never work on a Due.

Thank you for your quick answer. I am aware that the port names on the DUE are completely different to the UNO.This might be a stupid question but, would it be enough for me to change the port name in the library manually to the DUE's port name?

@Darellon The whole way the ports work on the Due is completely different.  You would need to write completely different code to do the port manipulation.

I suggest you post on the Adafruit forum, asking for an update to their library, or suggestions about how to fix it to work on the Due.

There are several Arduino libraries for reading DHT22 and related DHT sensors.  The Adafruit DHT library does not compile for the Due since it uses AVR specific functions not available on ARM (Due).
For the Arduino Due use Rob Tillaart's DHTstable library available from his github page where you can download a zip file.  Note that his project also has a "DHTlib" library which does not support the Due.  There exists yet more DHT libraries which Rob has listed on the DHTLib page on arduino.cc.

The same library works with the Due if you use the older version 1.1.13 from the same Github repo, which is the last version that officially supported the Due.
Here are the changelog entries that show the relevant changes:

update: 0.1.13 added support for DHT33 and DHT44 - LAST DUE VERSION
update: 0.1.14 replaced digitalRead with faster code (AVR ONLY!!! better support for lower Mhz devices)


text:
Issues in interfacing relay with Arduino
I want to control AC bulb with Arduino, 5v-relay.
My connections are

My code is
#define RELAY1  7

void setup()
{
  pinMode(RELAY1, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(RELAY1,LOW); // Turns ON Relays 1
  Serial.println("Light OFF");
  delay(15000); // Wait 5 seconds
  digitalWrite(RELAY1,HIGH); // Turns Relay Off
  Serial.println("Light ON");
  delay(20000);
}

Red LED is on according to AC bulb.
Power LED (Green colored one) is also on as I have given 5v supply from Arduino.

The issues are

Bulb is not following the delay given in the code. The output for the above code is 20sec ON - 15sec OFF -20sec ON - 15sec OFF- 20sec ON -15sec OFF -  1sec ON - 20sec ON - 15sec OFF etc. means apart from 20,15 sec duration there is a duration of 1sec is coming in between as noise. What might be the reason?
On monitor also, only first 3 actions are getting printed after that no printing is observed.

==>The relay I am using is:

What relay board are you using? Do you hear the relay clicking?

yes I can here the relay clicking.!

As Gerben says, please state the relay part number, and give a link to it. Are you sure you connected Vcc on the relay to the +5 V pin on the Arduino?

@Nick, I dont have link to relay. But I have uploaded the relay picture in the question it self.  I am sure that 5v pin on Arduino connected to 5v pin on the relay.

There are two transistors there (the small black things with are sort-of a semicircle). Please read the part number and post that.

Part no on the transistor is "CTBC  5478  JS"

Are there any resistors (or parts of any kind) on the back of the board? Can you photograph that please?

Also please measure what voltage is on the 5V pin (with your multimeter) once the sketch is running. Is it 5V? Or something somewhat lower?

There is nothing on the back of the board except the metal connections.

You may want to add capacitor to help shore up your 5v.

what i would do is test the parts one by one.
so first look if you're signal is good by attaching a led to it.
then test you're relay with 5v.
now you should know what the problem is the arduino or the relay

Everything looks good, however Try a different relay, and double check your AC side and be sure the bulb voltage is correct for the AC and the bulb is OK.
You may have a power shortage from your USB or however you are powering it.  If you can monitor the 5VDC and be sure it is stable.
Good Luck


text:
Interrupt variable not getting called while executing another part
volatile byte _incomingFlag = 0;

void onIncoming () {
    _incomingFlag = 1;
    Serial.println(F("You got an interrupt"));
    mySerial.println("ATH0");
}

void setup () {
    /* First Start the module */
    Serial.begin(9600);
    Serial.println(F("Initializing module..."));

    powerOn();

    mySerial.begin(9600);

    sendcommand(F("AT"), F("OK"), 1000);
    sendcommand(F("AT+CLIP=1"), F("OK"), 1000);
    sendcommand(F("AT+CMGF=1"), F("OK"), 1000);

    /* We need to attach ringing Interrupt */
    attachInterrupt(M_RING_INTERRUPT, onIncoming, FALLING);

    delay(100);
}

void loop() {
    if (_incomingFlag == 1) {
        manageIncoming();
        Serial.print(F("_incomingFlag: "));
        Serial.println(_incomingFlag);
    } else  {
        Serial.println(_incomingFlag);
        Serial.println(F("not getting value"));
    }
    get_currentLocation();
    send_Location();
}

I am trying to check the value of incomingFlag from the loop() . When I get a call or an SMS the interrupt function is getting executed and incomingFlag is set to 1 but I am not getting that value from the loop(). Everytime it's getting 0 if I check the value while the send_Location function is executing (data uploading part). How can I access the value of incomingFlag from the main loop().

Using serial inside an interrupt is not advisable. Especially if you talk to the GSM module inside an ISR. The rest of the code looks fine, though I'd like the see the send_Location function.

Hi Gerben, thanks for your reply. Please see my send_Location function and that serial functions inside interrupt is just for testing purpose.

I cannot see your send_Location function personally, because you did not post it.

do not use leading underscores in symbol names.  that can confuse the compiler, which uses 1 or 2 leading underscores for special purposes.

where does the code reset the _incomming_flag to 0 after finding the flag ==1?    Never call any kind of print operation from within a interrupt.   Where is the code resetting the 'interrupt pending' bit for that interrupt?

Interrupt flag bits are automatically cleared upon entering the corresponding ISR. I agree about the underscore. Leading underscores in variable names in global namespace are reserved by the Standard. Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

volatile byte _incomingFlag = 0;
 void onIncoming () {
             _incomingFlag = 1;
            Serial.println(F("You got an interrupt"));
            mySerial.println("ATH0");

        }

Regardless of what your purpose is there, you cannot successfully do serial prints inside an ISR. All bets are off if you do that.
In fact you are doing two prints - is one SoftwareSerial?
If you must have a debugging "flag" turn on an LED. Doing serial printing requires interrupts to be on, and they are off inside an ISR.

Note: You may get the display once, and therefore you think it works. As soon as the serial buffer fills up (probably 64 bytes) then it will just block indefinitely. Your message "You got an interrupt" is already 22 bytes if you count the trailing carriage-return/linefeed.

More detailed explanation
In your main loop, every time through it, you are printing either:
_incomingFlag: 1

or
0
not getting value

Therefore the serial buffer will be definitely full (or almost full). It can't empty the buffer if you are cramming this stuff into it every time through loop.
So now you have an incoming call. You set _incomingFlag to 1, then try to do this:
    Serial.println(F("You got an interrupt"));

That blocks, because if can't fit all that into the output buffer, and the program then hangs, because the buffer is not emptied inside an ISR.


text:
How to pass a filename to a function? What type of variable is the filename?
In the example below, I have two functions that write numbers to two different files on an SD card. I'm using the SdFat library.
Is there any way I can combine the two functions into one, so that I can call (for example): writeToFile(int t, FileName "filename1.txt");?
In the example below, to write a value to the "temperature.txt" file, I would like to be able to call: writeToFile(7, "temperature.txt"); In my sketch I have about a dozen functions that are writing to a dozen different files, so it would be very handy to be able to combine them into one function.
I think the main part I'm stuck on is I have no idea what the filename variable would be, or how to pass the filename to the function.
#include <SdFat.h>
SdFat sd;

void setup() {
  if (!sd.begin(chipSelect, SPI_HALF_SPEED)) {
    sd.initErrorHalt();
  }

  setTemperature(7);
  setFanSpeed(4);
}

void setTemperature(int t) {
  SdFile rdfile("temperature.txt", O_WRITE);
  rdfile.rewind();
  rdfile.println(t);
  rdfile.close();
}

void setFanSpeed(int t) {
  SdFile rdfile("fanspeed.txt", O_WRITE);
  rdfile.rewind();
  rdfile.println(t);
  rdfile.close();
}

String literals are of type const char *. Ordinary char *s can be passed to it though; the const means that the compiler will make sure that the function doesn't attempt to change the contents.
void setFileParameter(const char *filename, int value)
{
   ...
}

Thanks! It worked! I had assumed I'd be able to do the next part on my own, but ran into a smaller problem. I have another function to read the parameter from a file, so for example: readFileParameter(const char *filename, int value). I would like to call: readFileParameter("temperature.txt", currentTemp);, and have it store the value from the file into the integer currentTemp. What would I have to use instead of "int value", in order for it to change a global variable (like currentTemp)? I'm sorry that this is probably very basic stuff that I'm missing.

I think I might've figured out my 2nd problem on my own. It seems to be working if I declare the function like this: void readFile(const char *filename, int &value). I guess the '&' causes it to modify the variable that is passed to it? It's a little too complex for my current understanding, but so far it seems to work. It would be nice if anyone points out if it's incorrect. :)

@Jerry: That's the correct way to do it in C++. https://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29


text:
Arduino Nano with CH340 reboots on OS X El Capitan
I installed OS X El Capitan beta on my Macbook. Now my Nano-sized Chinese Arduino operating on CH340 chip reboots the laptop when USB is unplugged. While plugged, it works fine, I can upload sketches and send/receive data via Serial.
I've tried reinstalling the CH340 driver and running the following command as per this solution and it didn't help:
sudo nvram boot-args="kext-dev-mode=1 rootless=0"

I appreciate any ideas...

If I may ask, how did you get the Arduino to be detected by the computer? Since I updated to El Capitan, I've been unable to get the Arduino detected on the computer.

@duci9y Frankly, I did nothing special. I just upgraded from Yosemite to El Capitan, plugged in my Arduino, did a bit of coding as normal, unplugged it and boom, my Mac reboots after about 3 seconds.

@duci9y It turns out I didn't have the latest Beta. I now updated to the latest and now my CH340-based Arduino doesn't get detected as well! :)

Ah… so we are at the same place now. I'll post a question about it, maybe someone would know.

There is a new signed driver for OS-X El Capitan and Yosemite. This is all you want.
http://kig.re/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

It turns out I didn't have the latest Beta. I now updated to the latest and now my CH340-based Arduino doesn't get detected at all! Pretty much in line with everyone else complaining all over internet.

The command you ran only disables driver signing verification, which means OSX stops blocking it. If it is crashing it is likely to be either a bug in OSX, or a bug in the driver. My guess is it is a bug in the driver and you'll probably have to wait until they release an updated version that is compatible with El Capitan.

Check this video https://www.youtube.com/watch?v=0zuRukW7o0A

Reboot and press CMD+R immediately after reboot to enter in Recovery Mode
Open Terminal from Recovery mode
Run the command csrutil enable --without kext
Reboot
Install driver

helped me, thanks. First I ran csrutil disable and it worked, however I feel better with your suggestion because it doesn't disable Protection System

If you have macOS High Sierra like mine 10.13.4
This is work for me
https://github.com/awangga/NFCReader