text:
Need help with the syntax for a function that takes a closure
My C++ is very out-of-date. (20+ years, before C++ had closures).
I'm a senior SW engineer, and I spent several hours yesterday trying to figure this out, but I could not work it out.
The background:
I'm trying to create a class, ClosureButton, that is a subclass of another class, ArduinoObject. (An ArduinoObject has setup(), start(), stop(), and loop() methods so that the main program can invoke it.)
(C++ uses the terms closure and lambda to mean different things. In other languages the terms are interchangeable. Forgive me if I'm not using the correct term.)
A ClosureButton's constructor would take a pin number, and a closure with a bool parameter (pressed). I would save that closure to a member variable. When the button's state changed, it would invoke the closure and pass the new button state to the closure.
The question:
I need help with the syntax for the constructor, as well as how to declare the instance variable that would hold the closure.
The constructor would look something like this:
ClosureButton::ClosureButton(uint8_t pin, _unkonwn_syntax_ closure);

(Where I need help with the _unkonwn_syntax_ bit.)
Then I need to declare a member variable on my ClosureButton to hold the closure:
class ClosureButton: ArduinoObject {
  //other stuff
  _other_unkonwn_syntax_ closure;
}

Again, I need help with the syntax to declare a member variable closure of type "closure that takes a bool parameter". (The _other_unkonwn_syntax_ bit.) At this point I don't think my closure will capture variables from its enclosing scope, but at some future date I might need to do that, so help with that would be appreciated as well.)

C/C++ always had pointers to functions

Yup, I'm aware (and I've always found the syntax for C function pointers to be really hard to decipher. I can figure it out, but not easily.) Are you suggesting I use a C function pointer rather than a closure?

There is no difference using a function pointer or a simple (non-capturing) lambda (C++ calls them lambdas).  The only difference is that you provide a lambda instead of a function pointer.
For example:
void (*func)(bool b);

void setup() {
    func = [](bool b) {
        Serial.println(b);
    };

    Serial.begin(115200);
}

void loop() {
    func(digitalRead(0));
}

It's just a normal function pointer, but instead of assigning a function pointer to it you assign a lambda to it - which is just an anonymous function pointer.
To make life easier you can make a typedef for your function pointer variable type:
typedef void (*buttonCallback)(bool);

Then your functions would look like:
ClosureButton::ClosureButton(uint8_t pin, buttonCallback closure);

and:
class ClosureButton: ArduinoObject {
  //other stuff
  buttonCallback closure;
}

The basic syntax of a lambda is quite straight forward:
[](bool foo, int bar) { ... }
^  ^                    ^
|  |                    +- Function body
|  +- Normal parameter list
+- Empty capture list

If you want to return a value and you don't want to rely on the function being an "auto" return type you can specify the return type after the parameter list:
[](bool foo, int bar)->int { ... }
^  ^                   ^     ^
|  |                   |     +- Function body
|  |                   +- Return type
|  +- Normal parameter list
+- Empty capture list

If you don't specify the return type it is inferred from the type of variable/value that is used with return (as if the function were auto).

Here's a full example passing the lambda to a class which stores the pointer to it in a variable to call later:
typedef int (*callback)(bool b);

class MyClass {
    private:
        callback func;
        int pin;

    public:
        MyClass(int pinno, callback myfunc) {
            func = myfunc;
            pin = pinno;
        }

        void doit() {
            Serial.println(func(digitalRead(pin)));
        }
};

MyClass foo(3, [](bool b)->int {
        Serial.println(b);
        return rand();
});

void setup() {
    pinMode(3, INPUT_PULLUP);
    Serial.begin(115200);
}

void loop() {
    foo.doit();
    delay(100);
}

If you want to do capturing with your lambdas then I'm afraid you're out of luck.
The data type for that kind has to be std::function<void> but unfortunately the cut-down C library AVR-LIBC doesn't support that. The STL is generally not included for small microcontrollers since it uses far too many resources to be practical.

Ok, that looks like what I need. Thanks. (Using a typedef definitely makes it easier for me to read). I'll have to try that when I get home.

This won't work for capturing lambdas though. Dealing with those is a whole other kettle of fish.

@ratchetfreak I'm unsure what you mean by "capturing" the lambda. You can pass a lambda through a function, assign it to a variable, whatever - exactly the same as a function pointer.

A capturing lambda is a lambda that captures variables. A non-capturing lambda, like the ones in your examples, is just a plain anonymous function, hardly deserving the name “lambda”.

@EdgarBonet Ah, I see what you mean. I am fairly new to lambdas in C++.

@EdgarBonet Without STL there's no way to pass capturing lambdas as far as I can tell.  There's no std::function.

A functor (an object with operator()(bool) defined) may be a viable alternative.

Or, just don't try and capture variables. Just arrange to have the right parameters available. Or worst case use a variadic function.

@EdgarBonet can you elaborate? I find the syntax of C++ pretty obtuse, so I get kinda lost. I read some info about functors and my eyes started to cross.

I suggested in a comment that a functor may be a viable alternative to a
capturing lambda. This answer is mostly meant to answer the OP's request
to elaborate on that suggestion.
Let's define a ButtonCallback as an object that can be called like a
function taking a single boolean parameter:
class ButtonCallback {
public:
    virtual void operator()(bool) = 0;
};

To break down the syntax:

void operator()(bool) declares a method that allows the object to be
called as if it were a function taking a bool argument and returning
nothing. In other words, if you issue a call such as
my_object(true), that method will be called.
virtual _method_declaration_ = 0; says that the method is not going
to be defined for this class (it's a “pure virtual method”), but it
can be defined by derived classes. A class with such a method is
called an “abstract class”: it defines an interface, it cannot be
instantiated, and it's meant to be used as a parent for classes that
do implement the missing methods.

Now the Button class can be defined like this:
class Button {
public:
    Button(uint8_t pin, ButtonCallback &callback)
    : pin(pin), callback(callback) {}
    void push() {  // for testing only
        Serial.print("press: ");   callback(true);
        Serial.print("release: "); callback(false);
    }
private:
    uint8_t pin;
    ButtonCallback &callback;
};

Notice that the callback is stored as a reference to a
ButtonCallback object. The object itself cannot be stored because it
has an abstract type. Alternatively, a pointer could be used, which
would practically be equivalent.
For using this class, you first have to create the callback as a
concrete class that inherits from from ButtonCallback. Any data you
wish to capture should be stored as class data:
class CapturingLambda : public ButtonCallback {
public:
    CapturingLambda(int data) : some_data(data) {}
    virtual void operator()(bool pressed) {
        if (pressed)
            Serial.println(some_data);
        else
            Serial.println(0);
    }
private:
    int some_data;
};

With all this in place, the following test:
void setup() {
    Serial.begin(9600);
    int data_to_capture = 42;
    CapturingLambda callback(data_to_capture);
    Button the_button(2, callback);
    the_button.push();
}

void loop(){}

outputs:
press: 42
release: 0

Did you said you “find the syntax of C++ pretty obtuse”? I can only
concur with you!

Addendum: Another alternative is to define the callback using the
good old C idiom: a “lambda” is the combination of a function pointer
and a generic data pointer. The function pointer looks like this:
typedef void (*ButtonCallback)(bool, void *);

The second argument is used to provide the callback whatever data it is
supposed to have “captured”. It is a generic pointer (a void *)
because the library does not know what kind of data its client may need.
Now the Button class has to store both the function pointer and the
data pointer, and always provide the data pointer to the callback:
class Button {
public:
    Button(uint8_t pin, ButtonCallback callback, void *callback_data)
    : pin(pin), callback(callback), callback_data(callback_data) {}
    void push() {  // for testing only
        Serial.print("press: ");   callback(true, callback_data);
        Serial.print("release: "); callback(false, callback_data);
    }
private:
    uint8_t pin;
    ButtonCallback callback;
    void *callback_data;
};

The user would have to decide what kind of data it needs, and do
explicit pointer casts to/from the proper pointer type and void *. For
example, assuming we need an int, the callback may be:
void callback(bool pressed, void *data) {
    int *actual_data = (int *) data;
    if (pressed)
        Serial.println(*actual_data);
    else
        Serial.println(0);
}

Here is the test, with the exact same output as before:
void setup() {
    Serial.begin(9600);
    int data_to_capture = 42;
    Button the_button(2, callback, (void *) &data_to_capture);
    the_button.push();
}

void loop(){}

Notice that, syntactic differences apart, this solution does essentially
the same as the previous one. The main difference is that the data is
given to the callback as an explicit pointer instead of the implicit
this pointer. If you have to choose between these two solutions, I
would suggest going for whichever syntax you find easier to work with.
Beware also that in both cases it is the programmer's responsibility to
manage the storage of the callback data and make sure the corresponding
reference (or pointer) remains valid throughout the lifetime of the
Button object.

Excellent answer. Thank you! (Voted). The one part of it that I couldn’t parse is the constructor of CapturingLambda. Can you explain that bit? The some_data(data) part looks a little like the syntax for invoking a parent class’ constructor, but not quite.

@DuncanC: It's a member initializer list. some_data(data) means that the some_data class member is initialized with the value of the data constructor parameter. More or less equivalent to writing some_data = data; within the braces. In some cases (not here) an initializer list is the only way to do an initialization.

Ok, that helps. Why use a member initializer list instead of an explicit constructor that initializes the member variables? And in what cases is a member initializer list the only way to initialize an instance?

@DuncanC: 1. It doesn't really matter. 2. When invoking the parent class’ constructor and when a member is an object with no default constructor.

So can you both invoke the parent class' constructor AND use a member initializer list? And if so, what does that syntax look like?

@DuncanC: parent class' constructor is just a special use case of a member initializer list. I will not digress longer on this.


text:
Would a 100KΩ resistor connected to ground pull an open analog line down to 0
I have a project that has a photoresistor wired into a voltage divider and connected through a 3.5mm “stereo mini plug”. When nothing is in the mini plug, the analog line is an open circuit, and floats, creating jittery spurious readings.
I’d like to wire a pull-down resistor into the project box to tie it to ground so I get a zero reading when the light sensor is not connected, but want to alter the voltage reading from my photo sensor voltage divider circuit as little as possible.
If I connect a 100KΩ resistor between my analog input and ground, that would give me zero readings on the analog pin when the photo sensor is not plugged in, wouldn’t it? I can’t see how < 20 CM of 26 gauge wire would pick up enough interference to pull my analog pin up from 0 through a 100kΩ resistor.
What is the effective range of an analog pin on an Arduino? (A Mega 2560, if that matters) What’s the lowest voltage that will register above 0?
(The project box is getting crowded, so experimenting is getting tricky. I’d like to make a single change rather than trying different resistor values.)

To whoever voted to close as not being about Arduino, how is this not about Arduino? My question is about the behavior of the analog pins on an Arduino Mega.

Sound fine to me. I'd probably even go with a higher value. You'd have to do the calculations as to how it would affect the readings of the photoresistor. PS. A lot of 3.5mm sockets have switches in them to detect if there is something plugged in. You could use one of those switches to connect the analog pin directly to ground if nothing is connected. Or you could connect it to a digital pin, and have the software ignore the analog input.

I would expect a 100K pulldown to quiet the A/D, but I'd have to actually try it. I'd think testing it on the bare board, outside of your project box would still give you useful information. But I would sketch up the schematic of the proposed voltage divider with the parallel pulldown and run the numbers to convince yourself of what effect it will have on your measurement. You may be able to ignore it, or you may want to correct for it.

What is the effective range of an analog pin on an Arduino?

0 - (1023/1024)*Vref, whichever reference, 1.1v, 2.56v, or Vcc applied to the Vref pin, you have selected.

(A Mega 2560, if that matters) What’s the lowest voltage that will
  register above 0?

Appx (Vref * 2^-11), i.e.,  1/2 an LSB of the 10-bit A/D range.
Update:
Is that a jumper selection?
No, it's programmable; the external Vref is reset default. See ch. 25 of the 2560 datasheet for the low-level details; Arduino.cc's function-reference, for the analogReference() function for the quick & dirty how-to. Remember to take and discard a measurement whenever you change the reference.

Is that a jumper selection? (I haven’t changed anything on the factory settings on my Arduino.) Based on the testing I did when I was building the voltage divider, it seemed to treat 5V as max, which is what I expected.

Thanks for the thorough answer. (Voted). I do have a 4 channel 5V (optically isolated) relay inside the box that switches 120VAC outlets at up to 10a, and will also be driving a pulsed 9V electromagnet (which will be outside the case) with about 200 mA of current, but the Arduino and it’s low power components, the relay, and the electromagnet all have separate power supplies. So there may be a fair amount of electromagnetic noise inside the box.

With a 100 kΩ resistor to GND, it is not guaranteed that the value will be zero. If a (servo)motor is connected, it might get some noise.
The pull down resistor can be any value, because it is possible to calculate the value of the photoresistor.
There is an alternative solution. I think that all the analog pins of the Arduino Mega 2560 are digital pins as well. You can do a pinMode(A0,INPUT_PULLUP); to pull the input high. When a photoresistor is connected, you can turn the internal pullup resistor off with pinMode(A0,INPUT);.

To repeat my comment on JRobert's answer:  I do have a 4 channel 5V (optically isolated) relay inside the box that switches 120VAC outlets at up to 10a, and will also be driving a pulsed 9V electromagnet (which will be outside the case) with about 200 mA of current, but the Arduino and it’s low power components, the relay, and the electromagnet all have separate power supplies. So there may be a fair amount of electromagnetic noise inside the box.

I tried it with a 100K resistor, and sure enough, when the relays are active and driving AC loads, the analog input still picks up noise. In fact it looks a lot like 60 Hz noise. I guess I need lower value resistor, and to just adjust for the lower voltage into my analog input.

@DuncanC do you use the average of a number of samples? That is often done to reduce noise. However, noise around zero volt will not average to zero, but it will average to the positive part of the noise above zero.

I don't do averaging yet. I like that idea (a software change) better than opening up the box and swapping out the resistor.

Averaging was a good idea. It works well. Thanks for the suggestion. I should have thought of that.

source: Stack Exchange

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

sort: votes


text:
How to get data from 9DOF razor IMU directly to arduino mega
My final project goal is to make Brushless gimbal for drones using only Arduino MEGA 2560 and 9DOF IMU for control. On Instructables I found two excellent tutorials. Both are different than mine in selected components.
I use the following components:
Arduino MEGA2560
Motors - Quanum 2208 Precision Brushless Gimbal Motor ( httpx://goo.gl/RDBvJL)
Motor Driver - H bridge L298n (httpx://goo.gl/A4ZQi5)
9DOF Razor IMU (httpx://goo.gl/myg9oj )
I'm stuck with 9DOF Razor IMU. Surfing on the internet I found a great tutorial and  github repository (httpx://goo.gl/jh2pfU). This tutorial is excellent and AHRS works great with the FTDI Basic Breakout 3.3V. They gave me a good starting point, but my goal is use only Arduino MEGA2560 and sensors.
I want to connect the Arduino and 9DOF IMU directly and use the accelerometer data (Yaw, Pitch, Roll) for directly control the engines. On the website of the manufacturer Sparkfun (httpx://goo.gl/myg9oj ) I can’t find any datasheet exclusively for 9DOF IMU that could help me to connect Arduino and IMU. There are only datasheet of sensors that are on IMU ( ITG-3200 (MEMS triple-axis gyro), ADXL345 (triple-axis accelerometer), and HMC5883L (triple-axis magnetometer)  which are useless for me.
That's why I decided to use code from this site ( httpx://goo.gl/zOnYjN ) and he works great. I connected everything as is in tutorial and  Arduino SerialMonitor show me the desired values YPR. Values load very quickly directly from IMU and printed on SerialMonitor.
Values on SerialMonitor looks like this:
YPR=72.13,1.74,-16.38
YPR=72.14,1.72,-16.39
YPR=72.12,1.71,-16.39
YPR=72.13,1.71,-16.37
YPR=72.13,1.70,-16.40 …
HELP ME
This is my first solo Arduino project and I have a lot of questions about it.
How could I parse the data that appears on SerialMonitor to get new variables eg. Yaw = 72.12, Pitch = 1.74, Roll = -16.39?
Is it possible to do that?
Does anyone have any experience with 9DOF razor IMU and maybe know  better way to collect information from the accelerometer 9DOF razor IMU?
I want to achieve three separate variables which i will use to control the brushless motor. I think this should be an easier method as it is just comma separated numbers but then again i am new to arduino serial communication so i would appreciate any help with this. Even if it's only how to parse and extract the values.

I am stuck in the same situation as yours and i have referred a lot of tutorials but couldn't come to a proper solution. I also want the #YPR values to be read from the IMU.
As you have mentioned you found a code which helped you achieve the same, the link you have attached for that program seems to not be working. if you can guide me to that program it would be a big help. Thanks in Advance !

sscanf should be enough. There is also other options, String class for example with substring method.
Take a look at the example:
#include <stdio.h>

char myString[] = "#YPR=72.13,1.74,-16.38";

void setup() {
  // put your setup code here, to run once:
  float yaw = 0;
  float pitch = 0;
  float roll = 0;

  sscanf(myString, "#YPR=%f,%f,%f", &yaw, &pitch, &roll);
  Serial.println(yaw);
  Serial.println(pitch);
  Serial.println(roll);
}

void loop() {

}

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/


text:
Atmega328 standalone not working unless Pin1 connected to Arduino RESET
I'm new into this domain field. My principal occupation is as a .NET developer.
I'm trying to do a personal project in which a AtMega328 takes some output from a scale using HX711 and sends a SMS via SIM800L GSM module. Before creating the whole module I tested each part separately with Arduino and the specific modules directly on breadboard. Everything works fine.I created a standalone using the guide from Arduino website(16Mhz crystal, 2x22 picoFarad capacitors, 10k Resistor to PIN1, RX/TX connected to PIN2/3). I designed the circuit using EasyEDA, printed it into pcb and assembled it. The only issue is that, when the standalone is not connected to the Arduino, and powered up by an external 5V source, unless I connected the pin1 to Arduino(connectd to PC)RESET pin, it's not working. I tried to attach a button for RESET to PCB, and connected it to PIN1 and GND, but like this I cannot upload to Atmega328, unless i disconnect the button from 10k Resistor/PIN1 and GND. In the first picture is the standalone which is not working if powered by an externalSource, unless I remove the button and add wire between Arduino-RESET and Atmega-PIN1. In the 2nd picture is my circuit, without HX711 module and in the 3rd picture is my circuit, working only because I connected the ARDUIN-RESET to Atmega328-PIN1 .[![ATmega328 powered by wallplug, not working][2]][2][![PCB schema, working, after connecting PIN1 to Arduino RESET][4]][4]enter image description here][5]][5][

Comments are not for extended discussion; this conversation has been moved to chat.

So, the comments went to chat. Somebody recommended to use decoupling caps as close as possible near the VCC/GND of Atmega. I have 10uF in my workbench, so I used on of these caps and the issue was solved.

Not having bypass caps can cause some very weird errors. Guess you learn a lesson here, as I did some time ago (-;


text:
Controlling mains (230 V) supply up to 5/10 amps using Arduino
I am looking for a simple, low cost solution to control on/off of mains supply to certain equipment. The control will be done using one of the output pin of Arduino Uno.
The input trigger and how to control it is application dependent.  e.g. controlling an equipment or controlling supply to section of home but in principle mains control module implementation remains same. So looking for solution which is safe while doing connections as well as while in use in  indoor conditions for years.

Your question brings up an important point: make sure you know what you're doing because anything that involves mains is potentially deadly. While you are specifically looking for something safe, you will likely have to tweak and debug it, which won't ever qualify as safe. If you're just trying to do something useful or didatic with your Arduino, please choose something else to play with. Prefer to power your stuff with a quality wall wart or ready-made power supply.

I don't mean to be rude, but your question seems to lack research. Have you google for a solution? Did you find anything similar to what you're looking for? If you found something but it doesn't quite serve your purpose, show us and tell us why. Share your research with us.

I second Ricardo's comment. Handling mains in any way can be extremely dangerous. Do not do so on your own just for the sake of experimentation or if you haven't handled mains before. The smallest mistake can result in major damage, in more ways than one.

Have you google for a solution?      OK I should have mentioned it in first place. The googled solutions where on the lines of http://playground.arduino.cc/uploads/Main/relays.pdf. Which I thought not safe while assembling as well as in use, as typically putting everything in box in home might not be temperproof.  So looking for solution which is actually takes care of issue pointed  by Ricordo and Asheesh.

The PowerSwitch Tail 2 is a great way for experimenters to control mains voltages. It is insulated and internally decoupled, so you only have to hook up 5v, gnd, and a signal line to control it.
This model supports only 120V, but there are also kits for 230V.

image from sparkfun

Safe but not cheap. But +1 for addressing safety over cost.

Note that this model supports only 120V (US) whereas the OP needs a solution for 230V. Might be good to look for an equivalent for European market.

Oh, right. EU version here

Thanks TheDoctor, I am looking for this kind of solution.

That link points to a page with US and EU kits

Playing with mains is dangerous - so best to use a kit designed for that purpose. Be careful with units designed in the US - their safety requirements are a bit different from UK and Europe.
For example the Power Switch Tail kits do not include a fuse - if the appliance being controlled goes faulty and starts drawing a bigger current, the switch could burn up.
Here is one designed with Uk safety features in mind:
http://www.sf-innovations.co.uk/mains-switch-widget.html

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


text:
47Effects MIDI Library and serial debugging
I noticed that since I use the MIDI library from 47effects, I cannot use the print(ln) for the serial port for debugging purposes, neither I can find it in the documentation.
It states that the MIDI library uses the serial port, but I really miss the serial port now for debugging.
Update: so my question: The MIDI library uses the RX (pin 0) and TX (pin 1) on my Arduino One. However, I think the internal Serial.print/println also uses these same pins, so I was wondering how I can use Serial.print and Serial.println statements being visible on the Arduino IDE Terminal (emulator) while using the MIDI library.

I assume you have one or more Arduinos, are trying to do MIDI control, and want to know how to debug with the MIDI library having commandeered the hardware serial port.
One approach is to use I2C or SPI to communicate with a second Arduino, which uses its serial port to deliver debugging data to a host system.  See Nick Gammon's excellent page  Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329), which illustrates communication between two Arduinos, using one of them as a slave to forward information sent by I2C or SPI from a system being debugged.
Another approach might be to use a serial bridge.  I don't know the ins and outs of this or exactly what it does but have read that, for example, the Hairless bridge (which is an open-sourced software package) can display both sides of MIDI communication, possibly depending on use of Serial.write vs Serial.print.  You could designate certain note sequences as standing for various debugging cases.
A third approach is use of Arduino software serial to send debugging data to a serial port on your host system.  This would use some Arduino pins other than the hardware Rx, Tx pins.
Edit 1:  Pin Usage –
For approach 1, using I2C ties up two specific pins, SDA and SCK.  These are shared with other I2C devices, if any.  SPI typically shares three signals – SCLK, MOSI, and MISO – among all SPI devices, and generates one SS signal per device.  For pinout and protocol details, see Nick Gammon's well-organized and clearly-illustrated I2C and SPI pages.
Approach 2 would use no extra pins.
Approach 3 would use one or two extra pins:  one for half-duplex or output-only communication (which may be adequate for debugging), two for separate Rx, Tx lines.  Compared to hardware serial, software serial is CPU-intensive, does not support as-high data rates, and has a higher error rate.  It should work ok for light-weight debugging output, such as occasional text to show what tests succeeded or failed or what branch was taken, or values of a few variables.

Thanks for all the possibilities ... A second Arduino seems a bit like overkill (but if it works, it works, just have one so far, I'm a beginner).
The second sounds a bit troublesome, since my program might be rather complicated in time. However, the third seems very good and exactly what I need.
Can I also ask one additional question? I'm intending in time maybe also to use SRAM, SD and/or an extra EEPROM ... will I get similar problems again (that the SD /SRAM/EEPROM (SPI) also uses hardware RX/TX ?)

@MichelKeijzers, see edit 1

Thank you (again ) for the extra explanation ... it seems the CPU might be a problem if I would go debugging by approach 3. Maybe an extra Arduino is not so bad idea after all. At least it will give many more things to try (still in 'learning' mode).

All of the approaches are easy to try – if you have time to experiment and if you have a  serial port on your host computer  – and you can take debugging out after using it.  Anyway, if you have a serial port or a USB-serial device, it's probably worth trying out software serial, since the extra bit of CPU usage for debugging might be not a problem.

Yes I will go for the software solution first, probably for debugging, timing is not so much a problem.


text:
How to find out the maximum used stack space?
I am creating an Arduino sketch which involves quite some classes, and I want to check if it will run on an Arduino Uno or Mega (2 KB vs 8 KB SRAM).
So far my global variables take up around 1,200 bytes, and I expect this will rise. However, beyond that I need to make sure the stack memory is not using up too much. How can I find the maximum used stack size?.
I can check manually by calculating the maximum function stack and calculating all parameters + local variables, but this is a very tedious job (especially since my application changes still a lot).
Or another way: I know it is possible to get the free space, but should I add this in 'strategic' locations or in the beginning of all functions and continue from there? (there will be many of them).
Or is there preferable some static way of checking this?
The application works within Visual Studio C++ as stand alone too, so maybe that helps for some solution.
I expect the stack size easily to be a few hundred bytes (which is quite a lot for the Arduino Uno SRAM).

Could always use Atmega1284P as well with 16K SRAM space.  I had a project with 45 shift registers, 325 rows of data, that were updated and blasted out over SPI at 20 KHz rate, used 14,625 bytes of SRAM.

@CrossRoads: Can I find a (cheap) Arduino compatible-board with an AtMega1284P? . Actually, as alternative I can use a Mega, and for my 'main' project where I need more memory, I am intending to use an STM32 later.

Look here, www.crossroadsfencing.com/BobuinoRev17  Add 1284 core files to the Arduino IDE  https://github.com/MCUdude/MCUdude_corefiles

You should clarify: are talking about the heap (as in the title) or the stack (as in the question body)?

@CrossRoads cool to be able to use that, but I saw beyond the not so cheap price I rather use a Mega, and another CPU to do the real work. But good to know there are AtMega CPUs capable of more (I didn't knew that.)

@EdgarBonet Yes, mistake from my side, I fixed it, thanks.

You'd maybe want to use stack painting or ask GCC about the stack usage by adding -fstack-usage, for both see https://stackoverflow.com/a/6390246/5296568. There are also post-analysis tools like https://github.com/PeterMcKinnis/WorstCaseStack. Also see https://ucexperiment.wordpress.com/2015/01/02/arduino-stack-painting/

@MaximilianGerhardt Thanks for this info; maybe I can use it on the Windows version to get a good idea already beforehand.

Knowing the stack size is pretty easy: the stack pointer is initially
set to RAMEND and goes down as the stack grows. Thus:
static inline size_t stack_size()
{
    return RAMEND - SP;
}

should I add this in 'strategic' locations [...]

Obviously, the result will depend on where this is evaluated. Ideally
you should test this in the deepest parts of your call chain, as this is
where the stack will be at its maximum size. Note that ISRs stack on top
of all your regular code.
Edit: There is no easy way to know the maximum stack size. You
could get an approximation by sampling the stack at regular intervals,
e.g.:
#include <util/atomic.h>

volatile size_t min_sp = RAMEND;

ISR(TIMER0_COMPA_vect)
{
    if (SP < min_sp)
        min_sp = SP;
}

static inline size_t max_stack_size()
{
    size_t min_sp_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        min_sp_copy = min_sp;
    }
    return RAMEND - min_sp_copy;
}

If you enable TIMER0_COMPA interrupt in setup():
TIMSK0 |= _BV(OCIE0A);

then the stack size will be sampled every 1.024 ms. Note, however,
that this ISR is itself using some stack space for its own purposes
(9 bytes in my experiment), and that this is not sampling other
ISRs or critical sections.

Thanks, the interrupt way is indeed great to check the maximum size. And good to know about the RAMEND / SP variables (registers).

@MichelKeijzers: RAMEND is actually a constant defined in <avr/io.h>. SP is indeed an IO register or, rather, a pair of registers.

Thanks for the clarification.

This assumes you do not use the heap: no new, no malloc, no String objects. A good idea on small controllers, anyway.

@DataFiddler: The question title was about heap (has been fixed since), but the question body is about stack. My answer specifically addresses the stack, not the heap.

I do not zing you for your response, @Edgar. SP is very easy to use. Much nicer than (int)&aTempLocalVariable. My comment were just my two cents on "stack size is irrelevant if you do not know your dynamic heap requirements".

Initialize the entire SRAM space from the top of the heap to the bottom of the stack, either during setup, or in a modified version of the Arduino-provided main() function, with some unlikely pattern, such as {0x55, 0xAA, ...} or "UnusedUnused...".
After your program has run a while, examine memory for dirty footprints, reading up from the top of heap to find the highest heap excursion, and down from the stack-pointer to find the lowest address used by stack. You could use a debugger if you have one, or just a hex & ASCII dump to the terminal. Pick through it with whatever tools you have handy on your PC. If there's been no collision and you're using a memory dump, it's pretty easy to start somewhere in the middle that wasn't disturbed, and scroll in either direction. The place where your initialized pattern has been overwritten usually stands out very plainly.

I upvoted it because it's another idea, but I think just printing the value seems easier.... or is it possible to download a 'hex dump' from a running program? (e.g. by the Arduino IDE)

I send the hex dump to the Arduino terminal, save it to a PC file, and inspect it on the PC.

Thanks also sounds like an interesting idea. Thanks


text:
Can I use NodeMCU with Arduino to connect to wifi or do I need a separate module?
I am just starting out with electronics. I got a Arduino Mega 2560 board and am able to do simple things like blink. Now I want to start a project on IoT and want to connect this board with internet. I got some leads here. While googling ESP8266, I came across NodeMCU which has a processor too. I already have Arduino, so can I use only the wifi module of NodeMCU and connect it to Arduino?

imho, slaving an ESP to an ATMEGA is like pulling a racecar with a horse; you should be coding in the ESP and using the MEGA as a mere IO expander.

NodeMCU already has a processor built in with the WiFi so you don't need a separate processor. If you just want to add WiFi to your Arduino board use an ESP8266 board connected to the Arduino. That is essentially the WiFi part of NodeMCU.

I went through almost the exact same thing you are going through when I was looking at the ESP8266 boards (the NodeMCU is one of those).  I too discovered that the NodeMCU is a micro computer in itself, even more powerful than the Arduino UNO!
You can even code the NodeMCU using the Arduino IDE.  As has been said previously, I'd use your NodeMCU directly to accomplish what you want to do.


text:
Arduino IDE COM Port error on Windows 10
I have an Arduino micro, uno, and mega and none of them will connect to the com port on the Arduino IDE. I went to the device manager aand it is recognized but when I try to update the driver I get this:

Any help of how to fix this problem?

An easy thing to try but might not help: Use another USB port of your computer and see if the driver is reinstalled.
Otherwise, go to control panel and find the drivers (Device Manager), search for the Ports (COM & LPT) drivers and remove the driver for the Arduino manually, reconnect the Arduino and check if it is installed correctly. Possibly a wrong version of an Arduino driver is installed. If another driver is installed at COM3 (where is my Arduino), remove that driver and try again.

Option 1: Try to update or reinstall com port driver in control panel/device manager...
Option 2: There might be problem while installing Arduino IDE or problem occur during Arduino gets board and library updates over air itself. Try to reinstall IDE.


text:
GPRS and Weather Shields
I have GPRS(GPRS_Shield_V1.0), weather shield and arduino uno R3. When I use Arduino and GPRS it works perfectly and when I used Weather Shield it also worked perfectly. But weather shield needs wire library, to use sensors. And when I use GPRS library with wire library, my program prints the same string many times. How I can use these two shields together?
These are some pics of my connected shields:
http://puu.sh/gcvk3/85595c38c7.jpg
http://puu.sh/gcvpc/22185212d3.jpg
As you can see, I'm not using A0,A1,A2,A3,A4,A5 pins for GPRS Shield. Thank you!

Have you checked whether you are running out of memory?

Yes. My arduino are running out of memory. Thank you!


text:
Multiple shields on one Arduino/Linker base shield
I'm using an Arduino Uno R3 along with an Ethernet shield as well as the linker base shield for interfacing with three linker modules, light, temperature and some LEDs as I believed this would be simpler than using a breadboard and look neater. Are there any problems I'm likely to run into regarding compatibility or power consumption? It's a prototype for a hydroponic garden automation system. As a secondary, are there any c02 sensors under $60 available on the market?

I would recommend looking up the power consumption specs on the datasheets for each shield. Then determine whether the current used by all of the shields exceeds the limits for any given pin and for the board as a whole. I highly recommend the following article: http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino/


text:
Mirf not sending reply
I am trying to create a server - node connection with NRF24L01+ chip and Mirf library with interrupts. It seem to work, but server does not seem to get reply from node. If I put it in the loop it receives. Can you check what is wrong with my code?
Server:
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>

typedef struct{
  long int packet;
  byte address[5];
}
Test;
Test Toolkit;

void setup(){
  Serial.begin(9600);
  Serial.println("Configuring NRF24L01+ module ...");
  Mirf.cePin = 9;
  Mirf.csnPin = 10;
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setRADDR((byte *)"clie1");
  Mirf.setTADDR((byte *)"serv1");
  Mirf.payload = sizeof(Test);
  Mirf.config();
  Serial.println("Configuring internal script variables ...");
  Serial.println("Setting system interrupts ...");
  Toolkit.packet = 9;
  attachInterrupt(0,wakeupFunction,FALLING);
}

void loop(){
  strcpy((char *)Toolkit.address,"CLI");
  Mirf.send((byte *)&Toolkit);
  while(Mirf.isSending()) { }
  //Mirf.setRADDR((byte *)"clie1");
  /*if(Mirf.dataReady()) {
    Mirf.getData((byte *)&Toolkit);

    Serial.println("Got data!");
    Serial.print("Packet number: ");
    Serial.println(Toolkit.packet);
  } else Serial.println("NO DATA");*/
  delay(1000);
}
void wakeupFunction() {
  //while(Mirf.isSending()) { }
  if(Mirf.dataReady()) {
    Mirf.getData((byte *)&Toolkit);
    Toolkit.packet = random(300);
  }
}

and this is client
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>

typedef struct{
  long int packet;
  byte address[5];
}
Test;
Test Toolkit;

void setup(){
  Serial.begin(9600);
  Mirf.cePin = 9;
  Mirf.csnPin = 10;
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setRADDR((byte *)"serv1");
  Mirf.setTADDR((byte *)"clie1");
  Mirf.payload = sizeof(Test);
  Mirf.config();
  Serial.println("Listening...");
}

void loop(){
  if(!Mirf.isSending() && Mirf.dataReady()){
    Serial.println("Got packet");
    Mirf.getData((byte *)&Toolkit);
    Serial.println("Packet number:");
    Serial.println(Toolkit.packet);
    Serial.println((char *)Toolkit.address);
    //Sending
    delay(50);
    Mirf.setTADDR((byte *)"clie1");
    Mirf.send((byte *)&Toolkit);
    while(Mirf.isSending()) Serial.println("Sending");
    Serial.println("Reply sent.");
  }
}

I suppose that function Mirf.dataReady() does not work properly in Server interrupt. I have the same problem.


text:
How do I know if a board fits my requirements?
I'm new to Arduino and I saw on their website that there are many different kinds of boards.
What are the differences, or to be more specific, how would I know which board meets my requirements? I understand that the shields can be connected to the board, but are some boards that do not support certain shields?
Another thing, is it possible to connect external sensors to an Arduino board or there are special sensors that can communicate with the board? I want to use weight sensors.

Things to consider when picking an Arduino board:

Do I want native keyboard/mouse support? If yes: you'll need the Leonardo (or it's breadboard mountable equivalent) or the TRE (not released, dual MCU board).
Do I want a small form factor and/or have it breadboard mountable? If yes, choose a board like the Mini/Micro/Nano/etc.

If you want to make it even smaller, either get a board without USB built in or try using an ATTiny

Am I computing large numbers with it? If yes: use the Due, Galileo, or TRE (not released yet)
Do I want video/audio? If yes: TRE is the only way to go as of now (but it's not released yet).
Do I need a USB host (and not want to have an external shield)?  If yes, use the Mega ADK (limited support), Yun, TRE (again, not released yet), or Galileo.
Do I need WiFi/ethernet built in? If yes; use the Yun, TRE (still, not released yet), Ethernet board, or Galileo.
How many pins do I need (and how many of each type)?

Digital: simple ON or OFF. Use these for buttons, simple lights, some communication, etc.

Stay away from the Due if you don't want to mess with 3.3V logic. Most other boards are 5V. You can work around this with either voltage dividers (doesn't always work) or level shifters. As far as I know, you can't really do much if a sensor provides max 5V; level shifters AFAIK only work with digital signals.

UART Pins: these are the pins that you can use the serial library on. (Note: this doesn't include the software-serial library). One of these on most boards is connected to a USB chip.
SPI Pins: These are pins which are used by a form of communication (like on the Ethernet shield).
Inturupt Pins: These can trigger an event when the signal getting sent to the board changes. There are a couple of different settings, but this can be used for near-instant response time when low latency is critical.
PWM Pins: pins that go on and off to simulate a lower voltage. It does this by turning it on and off very rapidly. This is used often for dimming LEDs and controling the speed of a motor.
Analog pins: pins that can read a voltage and convert it into a number.

The Arduino Due has a much higher precision rate, as it has more possible values and it has less voltage, thus much more accuracy.

All of these types of pins can act as a digital pin. All of these, except the analog pins, are under the "digital pin" section of your Arduino board. I didn't go into the technical aspects of the pins; I explained then in the simplest way I could.

I left a lot of boards out of this list, but this should give you some things to think about when choosing a board. There's a lot of weird quirks with this list, so it's incomplete, especially with the types of pins. You'll just have to do research and figure out what you need and if a board can meet your needs. Just make sure to not plan two things on the same pin, especially when mixing different shields and sensors! Shields do take up pins.

Shields: they are pretty much compatible with every board except for if the board is 3.3V (newer shields can adapt automatically) OR if it's a breadboard mounted board, like the Nano. There are ways to work around this problem, but it's very difficult.

There are some good answers already, but here are a some secondary considerations

Many Arduino boards use a ceramic resonator rather than a crystal as their timing source. This rules out using them in critical timing applications. For instance you might need to add a real time clock board if you need to keep track of time of day.
The boards based on the Atmega328 chip only have three timers, and one of these (Timer 0) is used by the delay() function, which is in turn used by other libraries. Timer 1 and timer 2 get used if you include the PWM and tone libraries. The boards based on  the 2560 chip have 6 timers, which is a lot more generous.
If you want to count external inputs at speed (i.e. up to 4MHz), you need to access the Tn pin of the appropriate timer counter(s). On the UNO, only T0 is exposed to the outside world, and the timer is already in use. Even the Mega2560 boards only seem to expose T0 and T5.

The usual suggestion I give to people new to Arduino is to get a Starter Kit (either from the store or from a local reseller): it contains an UNO, plenty of sensors and actuators and a projects book.

To start with arduino you need to have some factors in consideration, for example the board you will chose, arduino UNO being the starting board for most beginners, if you are already an experienced programmer in C++ you might want to try more powerful boards.
You have a pretty good overview of all of them in this link :
http://arduino.cc/en/Main/Products
Also there are hundreds of shields out there, you will find some in the link above.
Adafruit also has some interesting ones, https://www.adafruit.com/search?q=arduino, you can even find them on ebay, and you can always buy individual sensors, LEDs, buttons etc, and plug them in directly or in a breadboard.
Sparkfun has a big variety of very interesting sensors.
There is also a lot of open source shields out there, you can check a very simple one i designed myself :
http://electropepper.org/projects/prototyping/item/proto-i-os-arduino-v1-0

thanks for the help :) , I am familiar with C++, I just want to know if any board is supporting on the various shields or there are some special requirements?

I forgot to say most, if not all shields are compatible across the several arduino boards, that’s supose to be the idea at least.


text:
Where can I find a better pinout diagram for "Arduino Ethernet" board?
I'm looking for a complete pinout of the Arduino Ethernet R3.
I've found one here which is low quality, and seems not complete (where are the digital I/O pins?).

BTW, it was not a good idea for Arduino to name this board "Arduino Ethernet", as this is pretty useless for searching online :-(

... What? The digital I/O pins are the cyan ones...

The pinout is Arduino Uno compatible, except for pins 10-13

Clicking on the image on Arduino's site reveals a much higher resolution version.

@AnnonomusPenguin: Not sure what you mean. The low quality I 'complain about' is for the image in the question (board with pinout, not an image of the board itself), which is not on the Arduino site. Thanks anyway.

That's a better one from :
https://pinoutguide.com/images/arduino/ethernet.png
This one also presents the Arduino Ethernet R3 board and
has the extra I2C pins (SCK=A5,SDA=A4) next to the AREF pin.

The formal Arduino.cc website mentions, somewhat obscurely, that the Arduino Ethernet is pin compatible with Arduino Uno:

The Revision 3 of the board introduces the standardized 1.0 pinout

Except for pins 10-13:

Pins 10, 11, 12 and 13 are reserved for interfacing with the Ethernet
  module and should not be used otherwise. This reduces the number of
  available pins to 9, with 4 available as PWM outputs.

The other difference is the onboard LED is connected to pin 9 rather than the Uno's pin 13:

On most other arduino boards, this LED is found on pin 13. It is on pin 9 on the Ethernet board because pin 13 is used as part of the SPI connection.

You can use any Arduino Uno pinout diagram as a reference, the one you have found seems to be pretty elaborated.

Except that it does: "The Revision 3 of the board introduces the standardized 1.0 pinout..."


text:
Use transistor to press button on external device
I have a small device with a simple push button. I'd like my Arduino to be able to make the device register button pushes. It seems like the best way to do this is to use a transistor to close the circuit for the button when my Arduino sends it a pulse from one of its pins. I've mapped out what I think the circuit should look like on a breadboard. I didn't include the device in this diagram, but it's powered by a CR2032 watch battery, which seems to give 220 mAh at 3Vs.
Basically, the two sides of the button would be connected to the transistor's collector/emitter leads. Then the digital pin on my Arduino would be connected via a resistor to the base lead on the transistor. When the pin sends some current to the base lead, the transistor will make current flow through it and the device will register a button press.

I made this by adapting the circuit here, which looks like this:

Basically I got rid of the motor/load and flyback diode, and hooked the two ends of the device's button up to the collector/emitter leads of the transistor.
I'm concerned that I've screwed up this circuit somehow, and will fry either the device or the Arduino or something else when I try and run it, otherwise I'd just test it right away.
Could anyone give me feedback if I'm on the right track here? I couldn't find other answers which dealt with quite this setup, where you are pressing a button on another device, though this question seemed related.

Yes, you have screwed the circuit up slightly.
You want to lose the red wire between the collector and +5V otherwise when you turn the output pin HIGH the transistor will explode.
Also you need to make sure that the ground of the Arduino (emitter of the transistor) is connected to the - of the target circuit and that the button you are "pressing" is an active-low system with internal pullup. If it's not then you will have to come up with another way.
An opto-isolator is a better choice than a transistor when you don't know the internal circuitry of the target device:

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Control Arduino through ethernet. How to contact from outside network and securely
I'm new to Arduino so please bear with me if my question is too simple or broad (I did try and research it) or guide me if it belongs elsewhere (networking forum?)
I would like to be able to control my Arduino remotely.  By remotely, I mean I would like to be able to access it over the internet.  I've done some research and know about the Arduino Ethernet Sheild (see:  How can I connect to an Arduino using WiFi?)
But I'm a newbie and it's not clear to me how I'm going to make my device "discoverable" from outside my local network.  I gather it involves "opening a port on my router"  Can someone expand on this or provide an example/tutorial? If I can do this, it would also be nice if there was some security so that not just anyone could control my robotic killer dog or whatever :).  I would think these are both common desires,  and there is probably tons of material (maybe even tutorials) but perhaps because I'm new to Arduino, I'm having a hard time finding material.
I thought a nice first step would be to have my Arduino Uno board connected to a single LED.  If I could then have a simple webservice on it, I could connect via my phone from work with a http post request.  Of course, I'd need someone at home to verify the led went on/off (or set up a camera for remote access).
Let me know if I can provide more detail or clarifications.  And Thank you!
Dave

The same way you would access a server on your PC. You need to forward a port on your router and if you have a dynamic IP, you would want to make use of a DDNS service.

But this isn't really an Arduino problem. You should probably look into some standalone ESP8266 modules (Wemos d1 mini, NodeMCU) and use them without an Arduino. You can program them the same way as an Arduino. They are faster, but have some differences (no analogue input, 3.3v)

@gre_gor an ESP8266 does indeed have some advantages, but they are not relevant to this problem.  Switch to an ESP8266 and this problem - which is not an Arduino problem - remains.  Realistically putting holes in the firewall and dynamic DNS are dubious solutions; much better to use an external server as an intermediary.

Pagekite might be a solution for you.

Yes you can forward a port and do DDNS, but personally I think its opening up a whole world of grief.  How long is it going to take some one to hack your Arduino, the security isn't exactly top notch is it?
So what about creating a web service on a web server and then getting you Arduino to poll that webservice at intervals

Thanks Matt.  That's a creative idea I didn't even consider and I think it would be a good solution to the example I posed (an LED).  The LED was to get me started.  Ultimately, I was thinking it would be cool if you could control a robot in your home from your cell phone.  Have it go around taking pictures or vacuuming or whatever.  For that, I don't think your polling would work too well.  Unless it was polling very quickly.  Thanks for the response!

The easiest way to do this is to use Blynk, an Internet Of Things (IoT) web service that includes an Arduino library, apps for iOS and Android, and a central server that the smartphone app and the Arduino both connect to. Since both connections are outgoing (and matched up by the Blynk server), each one works just fine from behind NAT routers without any ports needing forwarding. See Blynk's demo video for how to create a basic working app in 5 minutes (including your described LED controller and much more). Ok, I'll admit that starting from cold, it takes most of us a little longer than 5 minutes to get it going, especially if you like to read about and understand what you're doing as you do it. But it will still be minutes, not hours. This is the quickest, most painless way to get an IoT device up and running.
That basic app (which can read & write to ports, PWM, and A/D) is then extensible to work with your own code & hardware. The functions available lend themselves to just what you are looking to do, with the possible exception of uploading the images it takes. And the Arduino itself isn't really well suited to that task, given its memory constraints.
Update:
I use the ESP8266 like the one you linked to. They're cheap and easy to use but with a gotcha: they are 3.3v only on both power & signal lines, which can be a challenge when working with a 5v MCU board. Here's how to wire one up for a 5v Arduino. Note the dedicated 3.3v regulator; the Arduino's on-board 3.3v supply isn't sufficient for an ESP8266:

For quick & dirty, you can wire this up on a breadboard. Ultimately you'll want something more stable (mechanically) than breadboard wiring. I made up a few 5v ESPs on strip-board (aka Vector board or Vero board), but that's another project:

--
** (Disclaimer: I have no connection to the organization other than as a happy user/experimenter.)

Thanks JRobert for the idea.  I'm actively pursing it.  As this is a hobby for me, it might take some time :)  May I ask, do you use an Arduino Wi-Fi shield or something else?  I notice the shield is quite expensive for a student.  I did come across this (which is mentioned in comments above) WiFi Module - ESP8266 (https://www.sparkfun.com/products/13678).  I'm not sure how easy it is to use with Arduino though...


text:
problem with using String()

I'm new to arduino and currently trying to build a small program with multiple screens and buttons and a counter. when I try to convert a int to a chararray it messes up the world. with out it what I have so far works any suggestions on what I'm doing wrong? with the code to convert the int to chararray it seems to lock up the program when I switch from main screen to options screen then back. I put some serial outs to narrow down where the flaw is.
My results are it is between
   test1++;  Serial.println("oops check");
   str = String(test1); Serial.println("sanity check");

Something hangs it up after it outputs "oops check" so I figure it is str = String(test1); I have been searching and trying every thing I can find. if someone can give me a kick in the right direction. I'm usin the tft seedstudio v2 display with the modified tft library for text direction.
   /*
  Title: TouchScreenButton Tutorial
  About: Example/tutorial file for how to create buttons with the TouchScreenButtons library
  Author: Richard Kirkpatrick
  Date: 20 July 2014
*/

// Libraries
#include <stdint.h>
#include <SeeedTouchScreen.h>  // Library for the Seeed Studio TFT Touch Shield
#include <TFTv2.h>      // Library for the Seeed Studio TFT Touch Shield
#include <TouchScreenGeometry.h> // Library for drawing geometric shapes for the touch screen
#include <TouchScreenStrings.h> // Library for drawing strings for the touch screen
#include <TouchScreenButtons.h> // Library for creating buttons for the keypad
#include <SPI.h>

//Measured ADC values for (0,0) and (210-1,320-1)
//TS_MINX corresponds to ADC value when X = 0
//TS_MINY corresponds to ADC value when Y = 0
//TS_MAXX corresponds to ADC value when X = 240 -1
//TS_MAXY corresponds to ADC value when Y = 320 -1
#define TS_MINX 890*2
#define TS_MAXX 116*2
#define TS_MINY 913*2
#define TS_MAXY 83*2

TouchScreen ts = TouchScreen(XP, YP, XM, YM);

// Global variables
String str;
Button bigButton;
Button buttons[12];
Button reset;
Button back;
int screen = 1;
int test;
int test1 = 0;
char b[5];

void setup()
{
  // Initializes the TFT library
   Tft.TFTinit();

  // Start the Serial port. Used to determine which button was pressed.
  Serial.begin(9600);
 screen = 1;

}

void loop()
{ test1++;  Serial.println("oops check");
  str = String(test1); Serial.println("sanity check");
  str.toCharArray(b,5);

  Serial.print("screen = "); Serial.print(screen );
  // A point objects holds x, y, and z coordinates
  Point p = ts.getPoint();
  p.x = map(p.x, TS_MINX, TS_MAXX, 240, 0);
  p.y = map(p.y, TS_MINY, TS_MAXY, 320, 0);

  // Determine which button was pressed
  int userInput = -1; // -1 means no button is pressed
  if (p.z > __PRESURE){
    userInput = getButtonNumber(p.x, p.y);
     Serial.print("X = "); Serial.print(p.x);
     Serial.print("\tY = "); Serial.print(p.y);
     Serial.print("\tPressure = "); Serial.println(p.z);
  }

   // Show which button was pressed on the Serial monitor

   if (userInput == 13) {
    Serial.println("Options button was pressed!");
    bigButton.buttonDisplay();
  }
   if (userInput == 15) {
    Serial.println("back button was pressed!");
    back.buttonDisplay();
  }
  else if (userInput == 14) {
    Serial.println("reset button was pressed!");
    reset.buttonDisplay();
  }

  delay(10);

if (screen == 1)  {

if (test == 1) {

    Tft.fillScreen();    }

  Serial.print("test1 =  "); Serial.println(b);      // prints "Hello String"

    // Draw reset button
   reset.setValues(75, 215, 35, 100);
  reset.draw();

 // Draw the big button
  bigButton.setValues(15, 185, 35, 130);
  bigButton.draw();
Tft.drawRectangle(40, 15, 70, 120,BLUE);

Tft.setDisplayDirect(UP2DOWN);

  Tft.drawString("Frays",100,20,2,RED);

   Tft.drawString(b,65,20, 2, BLUE);

  //Draw reset buttons text
  TouchScreenString resetText("RESET", 100, 230, 2, RED);
  resetText.drawText();
 Serial.println("a");      // prints "Hello String"

  // Draw the big button's text
  TouchScreenString bigButtonText("OPTIONS", 40, 197, 2, WHITE);
  bigButtonText.drawText();
test = 0;

}

if (screen == 2)  {

  if (test == 0) {Tft.fillScreen();}
 // draw back button
  back.setValues(15, 15, 35, 85);
  back.draw();

Tft.setDisplayDirect(UP2DOWN);

   // Draw the back button's text
  TouchScreenString backText("BACK", 40, 30, 2, WHITE);
  backText.drawText();
test = 1;
}}

// Gets which button was pressed.  If no button is pressed, -1 is returned.
int getButtonNumber(int xInput, int yInput)
{

if (screen == 1) {
  if (bigButton.isPressed(xInput, yInput)) {
    screen = 2;
    return 13; // Signifies big button was pressed
  } }
  if (screen ==2) {
  if (back.isPressed(xInput, yInput)) {
    screen = 1;
    return 15; // Signifies big button was pressed
  }}
  if (screen == 1) {
  if (reset.isPressed(xInput, yInput)) {
    test1 = 0;
    return 14; // Signifies reset button was pressed
  }}
  else {
  return -1; // Signifies no button was pressed
  }
}

When you say 'hangs it up', is there no error output? Have you tried printing String(test1) to see what happens? From what you've said I guess 'oops check' printed out but 'sanity check' didn't?

when I say it hangs up the touch screen stops responding and the serial output stops with "oops check" being last thing printed. when this happens have to reboot processor. no I have not tried printing String(test1) will see if I can do that now.

just tried printing (test1) and (str) both will print but it still locks up when it goes to execute the  line str = String(test1); I can't figure why. the way the screen acts it's like the program corrupts. I'm getting stray lines and shapes on the screen at times.

just tried removing all serial prints from the program and even removed str.toCharArray(b,5); and test1++ and it still fragments. which I find odd. if I set test1=20 it locks up. am I still running out of ram? it just doesn't seem right. I know I'm over looking something. guess I will go back to trying to get the drawnumber to work again.

Hmm weird. Have you tried commenting it all out then uncommenting it bit by bit? Then you can pin point exactly which line is causing problems. It is a problem with stuff that is happening before the while loop starts by the sounds of it, although considering you are using library functions for the stuff other than initialisations, I have no idea why it doesn't work. Do you have the correct library versions for the hardware you are using?

My guess is you are running out of RAM. Your various string constants alone take up 202 bytes. Then there is this:
  test1++;
  str = String(test1);
  str.toCharArray(b,5);

That is very likely to fragment memory, as test1 gets larger and larger. So you are fragmenting RAM, of which you don't have much to start with.
Why are you even converting test1 into a String object? And then converting it back into an array?
The array b can only hold 4 digits as it needs one byte for the trailing null-terminator.
I suggest you stop doing that String stuff, and also use the F() macro like this ...
Change:
    Serial.println("Options button was pressed!");

to:
    Serial.println(F("Options button was pressed!"));

Ditto for all the other places you are displaying stuff.

I agree with this solution, too. Although I find it curious that it runs out of memory during the first iteration. Printing using flash memory strings is something that I do most of the time now with my Uno/Mega, although if you're using a small micro-c there may be limited flash space to use (you probably wouldn't be printing anything then anyway as smaller devices often don't have serial ports).

I agree it is running out of ram and fragmenting. as far as the Serial.println and all the other serial stuff I do not need. the reason for the String stuff is this. the device I'm trying to make I wanted the screen orientated so it is wider than it is tall. I can get the characters to display in the correct orientation but when I try to Tft.drawNumber(1024, 0, 0, 1, RED); the numbers are turned the right way but reads from bottom to top not left to right. can't get it to do right. this was my work around.  I used to use avrgcc but been years.  any suggestions?

Thanks for the responses I'm still learning and trying to remember.


text:
What does serial data look like on an oscilloscope?
How I can find the data field on oscilloscope at 300 baud or at 9600 baud?
Could someone show me picture on oscilloscope plase.
This is the picture
at 9600 Baud

At google images, type scope rs232 into the search box.

I had these images lying around so here is an example of "Fab" being sent at 9600 baud:

And now a single byte (the letter "F"):

A - no data (Tx is high)
B - The "start bit". The line is taken low to tell the receiver that a character (byte) is commencing to be sent. The receiver waits for one and a half clock times before sampling the line.
C - First character arrives (the letter "F" or 0x46 or 0b01000110). There is no clock bit as such, the incoming data is simply sampled at the baud (transmission) rate. In contrast to SPI communication the data arrives least-significant bit first (in case you are not sending 8 bits per byte). Thus we see 01100010 (rather than 01000110).
D - The stop bit. This is always high, to ensure that we can distinguish between the end of this byte, and the start of the next one. Since the start bit is a zero, and the stop bit is a one, there is always a clear transition from one byte to the next.
E - The start bit for the next character.

The time for one bit is shown on the logic analyzer as 0.1041667 ms (that is, 0.0001041667 seconds). This agrees with the inverse of the baud rate:
1 / 9600 bits per second = 0.0001041667 seconds per bit

Looking at your photo, my guess is you have inverted logic here. That is, RS232 levels (where 5V is a 0-bit and 0V is a 1-bit). Thus (and this is a guess because all the bytes are close together):

I marked the start and stop bits, and put a dot for each bit inbetween.

Also see What is Serial.begin(9600)?

Note that there are quite a few different setting on serial, besides just the speed. Parity bits, Stop bits. Data size.


text:
Why when I press the reset button
Why when I press the reset button it takes 2 second before I see my sketch start?
The model of Arduino is UNO, and the text in serial communication.

This is not a particularly helpful question. Reset button on what Arduino model? What is "some time"? A second? A minute? What is "output"? Text in the serial monitor? An LED flashing?

The model of Arduino is UNO and it takes 2-3 second and the text in the serial monitor. The output is the Sketch. I will say the question again Why when I press the reset button it takes 2 second before my Sketch stast?

Please edit your question to improve it with this new information. The question should stand on its own without having to skim through the comments. Thanks! And welcome to Arduino StackExchange. :)

Because first the bootloader is executed and takes 2 seconds (or more on a Leonardo) to time out when it doesn't receive a proper response from the computer.

You can set the fuses on the processor to not run the bootloader, in which case it will start a lot faster. However uploading sketches then is harder, as you have to use ICSP programming to do that.

Thanks for replay, but can tell me the reason of why it takes some time to start sketch ?

Because first the bootloader is executed and takes 2 seconds (or more on a Leonardo) to time out when it doesn't receive a proper response from the computer.


text:
Connect Arduino to MySQL database online problem

I'm trying to connect Arduino with MySQL database on my online server.
I manage my project to work on WampServer locally on localhost, but when I try to move everything online I have problem... on the serial monitor I get the message that the server is connected and my sensor readings, but I can't put them in to my database on my online sever.
Here is my code:

dbconnect.php
<?php
$MyUsername = "*******";  // enter your username for mysql
$MyPassword = "*******%";  // enter your password for mysql
$MyHostname = "*************";      // this is usually "localhost" unless your database resides on a different server

$dbh = mysql_pconnect($MyHostname , $MyUsername, $MyPassword);
$selected = mysql_select_db("tanjamayaarduino",$dbh);
?>

add_data.php
<?php
    // Connect to MySQL
    include("dbconnect.php");

    // Prepare the SQL statement
    $SQL = "INSERT INTO tanjamayaarduino.temperature (sensor ,celsius, light, moisture1, moisture2) VALUES ('".$_GET["serial"]."', '".$_GET["temperature"]."','".$_GET["light"]."','".$_GET["moisture1"]."','".$_GET["moisture2"]."')";

    // Execute SQL statement
    mysql_query($SQL);

    // Go to the review_data.php (optional)
    header("Location: review_data.php");
?>

Arduino code
#include<Ethernet.h>
#include<SPI.h>
const int temperaturePin = A3;    //LM35 Temperature sensor
const int lightPin = A2;          //LDR photoresistor sensor
const int moisture1Pin = A4;          //Moisture1 sensor
const int moisture2Pin = A5;          //Moisture2 sensor

// **** ETHERNET SETTING ****
// Arduino Uno pins: 10 = CS, 11 = MOSI, 12 = MISO, 13 = SCK
// Ethernet MAC address - must be unique on your network - MAC Reads T4A001 in hex (unique in your network)
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x3A, 0xDC };
// For the rest we use DHCP (IP address and such)
IPAddress ip(192, 168, 2, 121);
EthernetClient client;
//IPAddress server(192, 168, 2, 100); // IP Adres (or name) of server to dump data to
// IP Adres (or name) of server to dump data to  (godaddy baza server 37.148.204.140) (User: tanjamayaarduino@188.121.42.33) (goddady glavna adresa na hostingot 188.121.46.1)
//IPAddress server(188, 121, 46, 1);
char server[] = "188.121.46.1";

int  interval = 5000; // Wait between dumps

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

  Serial.println("Tweaking4All.com - Temperature Drone - v2.0");
  Serial.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
  Serial.print("IP Address        : ");
  Serial.println(Ethernet.localIP());
  Serial.print("Subnet Mask       : ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("Default Gateway IP: ");
  Serial.println(Ethernet.gatewayIP());
  Serial.print("DNS Server IP     : ");
  Serial.println(Ethernet.dnsServerIP());
}

void loop() {
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)==1) {
    float tem = getTemp();
    Serial.println( tem );
    float lig = getLight();
    Serial.println( lig );
    float mois1 = getMoisture1();
    Serial.println( mois1 );
    float mois2 = getMoisture2();
    Serial.println( mois2 );

    Serial.println("-> Connected");
    if (client.connected()) {
      // Make a HTTP request:
      client.print( "GET /advertacs/test/arproekt/add_data.php?");
      Serial.println("-> add_data");
      client.print("serial=");
      client.print( "TempSensor" );
      client.print("&&");
      client.print("temperature=");
      client.print( tem);
      Serial.println("-> add_temp");
      client.print("&&");
      client.print("light=");
      client.print( lig);
      Serial.println("-> add_light");
      client.print("&&");
      client.print("moisture1=");
      client.print( mois1);
      Serial.println("-> add_mois1");
      client.print("&&");
      client.print("moisture2=");
      client.print( mois2);
      Serial.println("-> add_moi2");

      client.println( " HTTP/1.1");
      client.println( "Host:" );
      client.println(server);
      client.println( "Connection: close" );
      client.println();
      client.println();
      client.stop();
    }
  }
  else {
    // you didn't get a connection to the server:
    Serial.println("--> connection failed/n");
  }

  delay(interval);
}
float getTemp() {
  float temperatureC = (5.0 * analogRead(temperaturePin) * 100.0) / 1024; //converting from a 0 to 1023 digital range to 0 to 5 volts (each 1 reading equals ~ 5 millivolts
  return temperatureC;
}
float getLight() {
  float light;
  light = analogRead(lightPin) ;
  return light;
}

float getMoisture1() {
  float moisture1;
  moisture1 = analogRead(moisture1Pin) ;
  return moisture1;
}
float getMoisture2() {
  float moisture2;
  moisture2 = analogRead(moisture2Pin) ;
  return moisture2;
}

Why all the && in your URL?

Oh, and do you know the term SQL Injection Attack?

Thanks for security tips:),  as I sad I'm very new to coding, when I used this code locally without "&&" sings wasn't working, so I put them... btw I try it now without "&&" sings still not working... any idea?

You should reduce the && to just & not remove them altogether.

ok, I remove it &... still not working

What do your webserver logs tell you?

My server is on Godaddy... in Acces Logs folder there is nothing from today... last log is from 18.09.2015

Well I'd give up now then ;) We moved away from GoBadly because they are just so flipping useless. So no logs probably means no communication. Chech you are really connecting to the right address and with the right Host: entry, and if you have the technology and skills, some Ethernet sniffing could be useful.

Ok thank you for every thing, I'll keep trying... maybe I will make it :(

After Wales have finished creaming Uraguy I will try your code on my system and analyse the ethernet data to see what is being sent. By the way, wrap all your string literals in _F()

I just spotted an error in your code... println("Host: ");

ok... I corected in client.println( "Host:188.121.46.1" ); ... still no result... just to chek with you... mu server ip is the master IP on my hosting when I go in control panel... not the numbers that are given in Admin URL (phpMyAdmin), becouse they are different

No, you misunderstood my pointing out of the error. The error was the use of println instead of print, so the server name (not the ip) was ending up on the next line and breaking the header formatting.

still no result ...can I send you user and password brom my database to your email, so you can check it?

I am back at my computer now and I can craft a proper answer for you.

I see that you have posted this question as an answer here, as the user tanja

There are two basic things wrong with your code.  First is the formatting of your headers - you have mistakenly used client.println for sending the first part of the Host: header, so it becomes split onto two lines:
client.println( "Host:" );
client.println(server);

Secondly you are using the server's IP address instead of the actual host name in the Host: header. That means the server can't work out which website you are wanting to talk to and just rejects your request.
You need to have something more like:
client.print("Host: ");
client.println(servername);

where servername is the name of the server (www.website.com) not the IP address.  You can put it all in one line if you don't ever want to change the website name, since it makes it slightly harder to find and edit:
client.println("Host: www.mywebsite.com");

Dear Majenko No luck, I give up :( I tried every thing that you told me still no luck.. Thank you for your effort, I will send you the info on your email

Making those changes worked for me locally. So if you made the changes correctly then there must be either a problem with the server or you are communicating to the wrong address.

First of all, are you now connected to SQL? If so, and it still doesn't work... Have you tried to escape your ", so instead of:
$SQL = "... VALUES ('".$_GET["serial"]."', '".$_GET["temperature"]."',...')";

doing something like:
$SQL = "... VALUES ('\".$_GET[\"serial\"].\"', '\".$_GET[\"temperature\"].\"',...')";

If it still doesn't work, once you send to SQL with your code, print on screen what you are effectively sending, copy it with your mouse, paste it in your phpadmin-sql console and execute it. There you should see any helpful tips on what is really happening.
Hope this helps!


text:
Yun did not connect to WiFi after configuration and restart
When examined we find that Yun is still in master mode and 0% signal.
Any procedure known to solve this problem manually?
We can access Linux command under Mater mode AP-mode and print WiFi status
/usr/bin/pretty-wifi-info.lua

We know procedure to change REST API access
Method II:  config file

opkg update
opkg install nano
nano /etc/config/arduino

config arduino
        option password '775e9f944188a7bcb36e9ca5dc51672b44bcceeb7d56d89dfb914e$
        option wifi_reset_step 'clear'
        option secure_rest_api 'true'
...

Merhod 1:  UCI API    need access to the Linux system by YSM program

PASSWORD
uci set arduino.@arduino[0].secure_rest_api=true

OPEN:
uci commit arduino

Is there any procedure manually to perform the configuration by hand for the mode:

change to client?
then restart?
from master mode where we have access to Linux command line?

This question has been left unanswered before in all forums examined.
Maybe someone knows the answer.
The problem lies in the Linux not in the hardware or routers or PC, as proven by testing.

My wireless config is in the /etc/config/wireless, not in the /etc/config/arduino
How do you configure your Wifi ?
There is at least 4 methods  :
you can do this through OSJS, through LUCI, through ARDUINO IDE, or with UCI.


text:
I2C Master send reset command to the slave counter
My name is Gianni, I live in Olbia Sardinia Italy and I have some experience in electronics.
For several years I have been passionate about Arduino.
They are now engaged in a project to counter with hall sensors.
The slave sends data to the master via I2C, for my project. I'm using the sketch of Gammon which uses a structure enum to send a request to the slave.
I have the need to send a reset command from master to slave.
I edited the sketch and I can see the command on the slave but will not let me use it to reset the counter.

Master code section
   void RstCounter()
  {

  Serial.println ("funzione azzera attivata");
   Serial.println (sensor);
  char key = keypad.getKey();
  if (key !='A')
  {

   char cmdrst = 'a';
   //set=key;

     if (sensor==11)
    {
    sendCommand (CMD_WRITE_D2, 1);

    Wire.beginTransmission(SLAVE_ADDRESS); // testiamo questa istruzione
    Wire.write(cmdrst);
    Wire.endTransmission();

    delay(100);
    Serial.println (cmdrst);
    }

   else
  {
  m=0;
  }

   azzera =true;
  }
   else if (key=='A')
    {
   Serial.println("");
   Serial.println("AZZERA close");
   azzera = false;
   }
     delay(100);
    }

SLAVE code section
#include <Wire.h>

const byte MY_ADDRESS = 42; // address in valore esadecimale

/************  VARIABILI SENSORI **********************/

#define Sensor11 2
int lastValueSensor11 =0;
int ValueSensor11=0;
int contatore11=0;
int counter11;

// various commands we might get
/************  VARIABILI ENUMERATORE **********************/
enum {
    CMD_ID = 1,
    CMD_READ_D2  = 2,
    CMD_READ_D3 = 3,
    CMD_READ_D4 = 4,
    CMD_WRITE_D2 = 5
    };

char command;
int sensor;
char cmdrst;

/************  SETUP **********************/
void setup()
  {
  command = 0;

  pinMode (Sensor11, INPUT);
  digitalWrite (Sensor11, HIGH);  // enable pull-up

  Serial.begin(9600);
  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

  }  // end of setup

/************  LOOP **********************/
void loop()
  {
        /************************ CONTATORE SENSOR 1 ***********************/
   ValueSensor11  = digitalRead(Sensor11);

            if ( ValueSensor11 != lastValueSensor11)
               { if ( ValueSensor11 == LOW)
                    {
                      contatore11 = contatore11 + 1;

                        }
                     }
   lastValueSensor11 = ValueSensor11;

/************  I2C RECEIVE **********************/
void receiveEvent (int howMany)
  {

  command = Wire.read ();  // remember command for when we get request
  //Serial.println(command);
  switch (command)
     {
     case CMD_WRITE_D2:
     Serial.println("comando 5 ricevuto");
     char cmdrst=Wire.read();
     delay(100);
     Serial.println (cmdrst);
     break;
    }
} // end of receiveEvent

void sendSensor1 (const byte which)
  {
  int val11 = contatore11;
  Serial.println(contatore11);
  byte buf11 [2];

    buf11 [0] = val11 >> 8;
    buf11 [1] = val11 & 0xFF;
    Wire.write (buf11, 2);
  }  // end of sendSensor

void requestEvent ()
  {
  switch (command)
     {
     case CMD_ID:
     Wire.write (0x55);
     break;   // send our ID

     case CMD_READ_D2:
     sendSensor1 (2);
     break;  // send A0 value

     case CMD_READ_D3:
     sendSensor2 (3);
     break;    // send D8 value

     case CMD_READ_D4:
     sendSensor3 (4);
     break;

     }  // end of switch

  }  // end of requestEvent

void receiveEvent (int howMany)
  {

  command = Wire.read ();  // remember command for when we get request
  //Serial.println(command);
  switch (command)
     {
     case CMD_WRITE_D2:
     Serial.println("comando 5 ricevuto");
     char cmdrst=Wire.read();
     delay(100);
     Serial.println (cmdrst);
     break;
    }
} // end of receiveEvent

Don't do serial prints inside an interrupt service routine (ISR). That is, not here.
Don't do delay inside an ISR.

  if (key !='A')
  {

I would be checking for NO_KEY first, otherwise you will assume that no key press is not 'A' and be doing that transmission to the slave a lot.

Was the answer helpful? If so, please accept it by clicking on the "tick" icon next to the answer, and also possibly upvote it. This indicates to other users that you found the answer useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!


text:
Read speed between two ultrasonic sensors
I'm new to Arduino and in need of help for this small project.
I'm trying to build an Arduino code that reads the speed of an object passing through two ultrasonic sensors. The plan now is to ping the first ultrasonic sensor once an object passes. The second sensor will then activate and wait for the object to pass by. The time it takes to reach the second sensor will be given into the equation.
Speed will be calculated by the distance between the two ultrasonic sensors divided by the time for the object to reach the second sensor. I would like to display the speed if possible on my computer screen.
Here is my code so far. Any help will be appreciated:
int trig1 = 3; //Trig 1
int trig2 = 4; //Trig 2
int echo1 = 5; //echo1
int echo2 = 6; //echo2
int ECHO1;
int ECHO2;
double first_time;
double second_time;
double final_time;
double speed;

void setup()
{
   pinMode(trig1, OUTPUT);  //sets the digital pin 3 as output
   pinMode(trig2, OUTPUT);  //sets the digital pin 4 as output
   pinMode(echo1, INPUT);  //sets the digital pin 5 as input
   pinMode(echo2, INPUT);  //sets the digital pin 6 as input
}

void loop()
{
  ECHO1 = digitalRead(echo1);

  while (ECHO1 == 0)
  {
    digitalWrite(trig1,HIGH);
    delay(100);
    digitalWrite(trig1,LOW);
    ECHO1 = digitalRead(echo1);
  }

  first_time = time();

  ECHO2 = digitalRead(echo2);

  while (ECHO2 == 0)
  {
    digitalWrite(trig2,HIGH);
    delay(100);
    digitalWrite(trig2,LOW);
    ECHO2 = digitalRead(echo2);
  }

  second_time = time();

  final_time = second_time - first_time;

}

Delay(100) means your measurement can be of by as much as a tenth of a second. This could cause quite a big error in the calculated speed.

What is your question, exactly?

There are several issues with these ultrasonic modules and your code:

How fast are these objects moving? If you don't have any reflection, it'll take almost 20ms for one measure. So precision will be low.
What if the object is moving in oposite direction?
What if the object stucked between?

and so on.
Anyway Laser interrupter circuit (or similar) would be much more suitable for this job.
Or if you want to use ultrasonic, you can use Doppler effect. But it's not possible with those PING))) modules (or clones).

So its not really possible to measure the speed with a ultrasonic sensor?

@flyer3110 It might be possible to measure something slow. Or, you can measure distance of approaching object (again it must be slow). For example little faster walk is about 6km/h (1.67m/s) which means 32cm per measure.

If I understand correctly you are using the ultrasonic sensors like light barriers.
Measuring speed with ultrasonic would be done by sending the sound towards the object of interest and measuring the time for the reflected sound. The traveling speed of sound in air is somehow a constant. You will get the distance of the object * 2. With two measurements in a defined time period you are able to determine the speed of the object.
When using light barriers (infrared) I would try to trigger interrupts with the photo diodes and measure the time between the triggerings like you described. If hooked to the same interrupt the direction of the object should be irrelevant. If two interrupts are used even the direction is known.


text:
How do I see underlying code and definitions inside Arduino IDE on MacOS X El Capitan
I'm a newbie to Arduino so please excuse the easy question and guide me to the appropriate sources or forums.  I just bought an Arduino Uno Starter Kit that comes with the "Arduino Projects Book" by Scott Fitzgerald et al and I'm happily working my way through the projects.  I downloaded the Arduino IDE (version 1.7.10) onto my mac and am turning on lights, etc.  However, I'd like to see the underlying code.  For example, I use the code "digitalWrite" to turn off/on LEDs.  I'd like to see the code for this.  I can imagine that it's just a write of 1 or 0 to a particular memory address, but I'd still like to see it.  I was hoping there was a right-click->"Go To Definition", but I don't see it. I downloaded the Arduino IDE to my Downloads folder and run it just from there. It's called Arduino.app.   I don't see a folder with .c and .h files as suggested in this post:  Arduino IDE, Underlying Code and Libraries  Maybe I'm missing them?
Also, is it possible to set a breakpoint?
Again, sorry if these are "obvious" questions.  And I did look at the Arduino site without any success.
Thanks,
Dave

The simplest way is to look at the source on Github:

https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino

Can you set a breakpoint? No. The Arduino IDE and the bootloader don't support such functionality. To do that you need a real IDE (like Atmel Studio) and a hardware debugger.

Thanks Majenko.  Can you suggest (1) a way to pull all relevant files, and (2) how to search for a specific method.  For example, how would one know which file to find "digitalWrite" in?  The link you gives seems to list files in date order in which they have been last modified. Presumably, it would be better to just pull an entire directory structure with all files that went into making Arduino Studio version 1.7.10  Thanks

use git. 2) use grep. Both from the command line. And no, they are listed alphabetically (case sensitive).

Or alternative to 1), click the root of the repo, then download the zip.

Yes, they need a right-click->"Go To Definition"
Assuming the first appearance of a variable is the definition (variable declaration), use the following easily learnt "hack"..
Double click variable, then ^F, Esc, ^Home, ^G
..(where ^ = Ctrl).

what? In Arduino IDE?

Yes Juraj. It is in reply to his I was hoping there was a right-click->"Go To Definition", but I don't see it. (where OP states which IDE). On re-reading the question, he wants to see the library code, not really the definition at all, but for others googling here simply wanting to see variable definitions (which is how I found this), I think my advice is as good as it gets (without getting a better IDE). IMHO, the other answer, "The simplest way is to look at the source on Github" is not a great answer for beginners.


text:
How do I read numbers from a serial sequence
I have read through a number of posts including How do I split an incoming string? However I cannot work out how to extract numbers from a serial string.
My challenge is this;
I send a serial command 'freq\r' to a radio which will return a string like this 'FREQ: 10138.7 RX, INHIBIT TX'. The only thing I want out of this is the 1013 so I can then manipulate it and send out a second serial port. It sounds easy enough but I just don't seem to be able to extract those numbers easily because I don't have a separator to use.
The other thing is if the number is below 10 e.g. 9138 I only want to extract the first 3 numbers then add a leading 0 so I end up with 0913.
Once I have the four numbers I can then divide them so I end up with e.g. 09 and 13 or 10 and 13. I can then send these as HEX to my second serial device.
If you are wondering what the numbers are they are frequencies in kHz which I am extracting from a radio then converting to HEX to tune a pre-selector.
Any help would be greatly appreciated as this is my last stumbling block on this serial translator project. I hope this makes sense.
Thanks
Callum

I don't have a separator to use

You do. There is a space before the integer part of the frequency, and a
decimal point just after it. You can use strchr() to find them. Then,
you will have to prepend a zero if needed, and terminate the string one
character before the decimal point.
The following code does this by overwriting the original string. If you
need to keep that string, you will instead have to copy the relevant
characters to another buffer:
char * get_freq(char *message)
{
    char *space = strchr(message, ' ');
    char *dot   = strchr(message, '.');

    if (!space || !dot || dot - space < 5)
        return NULL;    // invalid message

    if (dot - space == 5)
        *space = '0';   // prepend a zero

    *(dot - 1) = '\0';  // terminate the string

    return dot - 5;
}

Forgive me if I sound a little dense with this question but how do I fit that in to a routine that is called every 5 seconds. I call the serial command 'freq\r' command every 5 seconds to check the frequency of the radio? Not sure why this is not obvious to me but I am, obviously, a beginner.

@Callum: Standard approach: whenever a char is .available() on the Serial port, you .read() it into a buffer[]. When you see a '\n', you know you have a complete message and you can get_freq(buffer). Do this in loop(), not in the query-sending routine that you call every 5 seconds.


text:
Determining if an LED on another device is on
I'd like to check if this circuit I'm making is correct -- I'm concerned I'll mess up my Arduino. Essentially, I would like to determine if an LED on another device is on or not by measuring the current etc running through it. I know that device uses a CR2032 watch battery, with 3V and 220 mAH. I'd rather not do this using a photosensor since there will usually be a lot of ambient light.
I looked at this answer, and tried to adapt its circuit, which looks like this:

The solution I came up with would look like this on a breadboard:

Not pictured is the existing connections to the two leads of the LED of the device, which send current through it.
I was hoping that with this setup I could measure the current hitting the analogue input of my Arduino when the LED is turned on by the device, and in doing so figure out when the device LED is on.
Does this circuit seem accurate, or is there something I need to change? Thank you!
Edit:
Would this simpler circuit work, given that the device only has 3Vs?

Since the device is only 3v you could connect the "power" directly to a digital pin and read HIGH when the led is on and LOW when it is off.

Would the edited connection diagram I made above reflect what you mean by this? Basically just connecting straight to the Arduino.

Depending on the led type you might need to connect to the resistor, but that's basically it.