text:
How to print (or store) gps lat, lng value (TinyGPS++) with Bluetooth BLE nRF8001?
I have a u-blox gps module and I use TinyGPS (http://arduiniana.org/libraries/tinygpsplus/) to get out the lat + lng.
If i write...
Serial.println(gps.location.lat(), 6);

...out in the log I get the correct latvalue.
Right now I however work with a BLE (https://www.adafruit.com/product/1697) and when I try to print it like this:
BTLEserial.print (gps.location.lat()`, 6);

I get a error: no matching function for call to 'Adafruit_BLE_UART::print(double, int)'
If I do this instead, the code runs...
BTLEserial.print ((gps.location.lat(),6));

But I do not get the correct lat, instead I get this value 6.00000000
I have tried to store the lat like this:
double myLat;

myLat = (gps.location.lat(), 6);
BTLEserial.print (myLat);

But with that myLat also has a value of 6.00000000 which is not correct.
I tried this as well:
char sValueOne[16], sValueTwo[16];
char sBuffer[33];

strcpy(sBuffer,dtostrf(((gps.location.lat(),6)), 15, 8, sValueOne));
strcat(sBuffer,",");
strcat(sBuffer,dtostrf(((gps.location.lng(),6)), 15, 8, sValueTwo));

BTLEserial.write((uint8_t *)sBuffer, strlen(sBuffer));

But with that I still get 6.00000000. I am starting to run out of ideas now to make this work. I have tried to send it both directly and store it but nothing works successfully.
So how can I adjust the code to be able to print (or store) gps lat, lng value (TinyGPS++) with Bluetooth BLE nRF8001?
Appreciate every help and tips!

6.000000 is the value of ((gps.location.lat(),6)) where 6 is the last item in the list. C/C++ is a strange language. Remove all the extra () and things will look better.

If i do BTLEserial.print (gps.location.lng(),6); i get a error: no matching function for call to 'Adafruit_BLE_UART::print(double, int)'

Add links to the libraries you are using.

myLat = (gps.location.lat(), 6); gives the value 6.0000 as explained above. It is not a list with the two values or a double with 6 digits.

For gps i use TinyGPS++, this: http://arduiniana.org/libraries/tinygpsplus/ and for my BLE i use this where you can see sample code also: https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail

Yea exactly. And i want the correct lat/lng value so i am not sure on how to proceed to successfully connect that to my ble device when I write/print data

The Arduino Stream/Print classes may sometime need some extra attention.
BTLEserial.println(gps.location.lat()`, 6);

The member function is available in the class Print but gets "hidden". You can help the compiler to find it with a prefix:
BTLEserial.Print::println(gps.location.lat()`, 6);

Cheers!

Hey! Thanks for this answer. Will try it in an hour

Hi! I get the correct value. However, it seems like it sends one number at a time. So when I recieve this on the app the value gets chopped up. So for example if the latitude is: 32.123456, it comes like this to the app: 3, new row, 2, new row etc.

I do not use println btw, instead print

That is a new question! Acknowledge the answer and ask a new one. I can help you with that :)

Ok Mikael! I will create a new thread regarding that issue. Thanks a lot for your example above to get the first part of the problem fixed. Will accept your answer and of course also upvote it!

Created a new post here: http://arduino.stackexchange.com/questions/33115/how-can-i-adjust-my-code-so-that-the-value-that-i-print-with-my-ble-device-does if you want to check it out!

Yapp, answered that :)


text:
How to multiplex multiple displays?
I want to use 2 "displays" with 4 digits. The displays are common cathodes with cathode transistors connected to the digits, as the figure:

The segments of both displays are connected together on the digital pins.
The problem is that I tried to use some libraries for 7 segment displays and they worked with only one 4 digit display, but when I connected the second display, did not display the numbers correctly. The numbers that will be written are integers and I'm using mega 2560 R3.
Here are my attempts:
#include "SevSeg.h"
byte digitPins_1[] = {29, 30, 31, 33};//Digits pins
byte digitPins_2[] = {25, 26, 27, 28};
byte segmentPins[] = {38, 39, 40, 41, 42, 43, 44, 46}; //segment pins
SevSeg disp1;
SevSeg disp2;

void setup() {
disp1.begin(P_TRANSISTORS, 4, digitPins_1, segmentPins);
disp2.begin(P_TRANSISTORS, 4, digitPins_2, segmentPins);
disp1.setBrightness(20);
disp2.setBrightness(20);
}

void loop() {
disp1.setNumber(8888, 0);
disp1.refreshDisplay();
disp2.setNumber(1111, 0);
disp2.refreshDisplay();
}

or using another lib:
#include <SevenSeg.h>
SevenSeg disp1(38,39,40,41,42,43,44);//segment pins
SevenSeg disp2(38,39,40,41,42,43,44);
int digitPins1[4]={29,30,31,33};//digitpins
int digitPins2[4]={25,26,27,28};

void setup() {
disp1.setDigitPins(4,digitPins1);
disp2.setDigitPins(4,digitPins2);
disp1.setDigitDelay(1600);//time delay
disp2.setDigitDelay(1600);
disp2.setActivePinState(HIGH,HIGH);//seg active HIGH, digit active HIGH
disp1.setActivePinState(HIGH,HIGH);
}

void loop() {
disp1.write(8888);
disp1.clearDisp();
disp2.write(1111);
disp2.clearDisp();
}

Check the library code for what would happen if you use the same segments pins. Also add a short delay between write-clearDisp.

How are your segment lines driven?  If driven directly by ATmega pins instead of through a transistor, 8 segments at about 8 mA each is way too much; 4 at 8 mA might have worked ok, without 8 such working

Why are you making two instances of the class when one instance  "Supports arbitrary number of digits and multiple displays"? See: Arduino
SevenSeg v1.2

Because on every 4-digit display I would like to write a different variable at different times in my program.
The segment lines are connected directly to the Arduino, only with a 220 ohm resistor, I'm going to change that.

The code instantiates two instances of the SevSeg class.  This may or may not work.  Really depends on if the class uses any resources are not meant to be shared between multiple instances of that class.  For instance, it is unlikely that one hardware timer can be used for more than one purpose at a time.
But the code continues on to use the same (anode) pin resources for both instances of the class. This is likely not going to work.
Apologies for being vague using qualifier like "unlikely" instead of simply stating that it will not work.  Truth is, one might be able to write a class that can deal with multiple instances of its self.  But it would be very difficult and a far more complex programming task than to simply use one instance for all 8 digits.
In case there is a question as to the maximum number of digits supported for one instance of the SevSeg class, this line is in the one of the SevSeg header files:
#define MAXNUMDIGITS 8 // Can be increased, but the max number is 2^31

Why do you feel you need to multiplex two displays? What is wrong with just having one display of 8 digits? They don't have to be physically together, and it's entirely up to you what you display on each character of the display.

I think it would not make any difference for me to use an 8-digit display, initially it just seemed easier to use 2 different ones.

As the answers suggested, it is better to make a single display with 8 digits. But if anyone needs 2, here is my solution:
As suggested, I checked if the library supported, and the solution was to only increase the delay on each digit.
#include <SevenSeg.h>
SevenSeg disp1(38,39,40,41,42,43,44);//segment pins
SevenSeg disp2(38,39,40,41,42,43,44);
int digitPins1[4]={29,30,31,33};//digitpins
int digitPins2[4]={25,26,27,28};

void setup() {
disp1.setDigitPins(4,digitPins1);
disp2.setDigitPins(4,digitPins2);
disp1.setDigitDelay(4000);//time delay
disp2.setDigitDelay(4000);
disp1.setDutyCycle(10);//decrease the duty cycle
disp2.setDutyCycle(10);
disp2.setActivePinState(HIGH,HIGH);//seg active HIGH, digit active HIGH
disp1.setActivePinState(HIGH,HIGH);
}

void loop() {
disp1.write(8888);
disp1.clearDisp();
delay(1);// don't need
disp2.write(1111);
disp2.clearDisp();
}

source: Stack Exchange

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

sort: votes


text:
pulseIn() function not working

I want to find the length of upper one signal (purple one). So for that, i used pulseIn() function for that. But i just get 0 as a result in serial monitor.
int pulsepin = 8;
int value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH);
  Serial.println(value);
  delay(1000);
}

Here, above is my arduino code which i used. I don't know why I don't get any reading except 0.

Looks like the voltage is too low to be read as a HIGH

@Gerben means pulseIn() not working for this ?

If digitalread doesn't work on this signal then pulseln won't work either.

@Gerben Too low to be read as a HIGH, or too high to be read as a LOW...? Looks like it's a ~2V pulse with a ~3V offset. Hard to work out from that trace, it doesn't give much information.

pulseIn() returns an unsigned long (32 bits) not an int (16 bits), so you may have some truncation occurring in your program leading to a 0 value.
Hence you should modify your program as follows:
int pulsepin = 8;
unsigned long value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH);
  Serial.println(value);
  delay(1000);
}

Also beware that pulseIn() has a timeout (it will not wait forever).
This timeout is used for the whole completion of the pulse, i.e. first waiting for the signal to get HIGH, then waiting for it to get back LOW. If no pulse is detected and complete (LOW -> HIGH -> LOW) within this time, then pulseIn() will return 0.
Default timeout value is 1 second, but you can set any value (in microseconds) you want that can hold in an unsigned long:
e.g. if you need 10 seconds, then:
  value = pulseIn(pulsepin, HIGH, 10000000UL);

I am not sure why you use delay(1000) in your loop(), I would remove it as a pulse may occur during that time and it would not be seen by your program.
Here is a suggested update (I also used const where it made sense but that won't change program behavior):
const unsigned long PULSEIN_TIMEOUT = 10000000UL;
const int pulsepin = 8;
unsigned long value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
  Serial.println(value);
}

You may also want to avoid printing 0 values since they mean no pulse was detected:
void loop()
{
  value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
  if (value > 0)
    Serial.println(value);
}

Thank you for explanation. Here, i used delay(1000) because every time whenever readings are serially printed in serial monitor, it's very hard to identify the changes between those readings. So, delay(1000) used only for my convenient purpose, so i can see every readings after every 1 second,nothing else.

And as you say, value = pulseIn(pulsein, HIGH,10000000UL ) that mean pulseIn() function wait for 10 seconds until signal goes LOW or gets that 10 second long pulse. I can't understand. Can it possible to get 10 seconds or any seconds pulse means length of pulse is 10 seconds or any seconds length with help if this line of code.

The timeout is global this means in these 10 seconds, the signal must first go HIGH then go LOW. If you call pulseIn() at t0, and the signal gets HIGH at t1, then gets back LOW at t2, then you must have t2 - t0 < timeout (10s), then pulseIn() will return t2 - t1; if ever t2 - t0 > timeout, then the pulse will not be recognized and pulseIn() will return 0.

It works strange anyway. It works for 10s and doesn't for 1s. It's always returning zero... pulseIn(buttonPin, HIGH, 1000000UL); - 1s.

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


text:
Use server.arg results as a function parameter?
I've got an ESP8266 (NodeMCU) and I am trying to understand the ESP8266WebServer library, as how to use the results across functions.
In my setup function, I have the following:
   server.on("/marquee", []() {
      varOne = server.arg("baseColor");
      varTwo = server.arg("marqueeColor");
      server.send(200, "text/html", webPage);
      Serial.println("Marquee  activated");
      state = true;
      ledMode = "marquee";
    });

In my loop, I detect the ledMode and if it is set to marquee then it runs the following FastLED function, amongst others:
fill_solid(leds, NUM_LEDS, 0xFF0000);

What I am trying to figure out is how I go from taking a hex color code of say FF0000 from the URL parameter, and use that in my fill_solid function.
server.arg stores get the parameter as a string, so I am not sure what needs to be done.  Also, using a variable name in place of the Hex code in the fill_solid function results in an error due to not expecting the variable

What argument types does fill_solid() take, please?

server.arg stores get the parameter as a string, so I am not sure what needs to be done.

The parameter needs to be converted to an uint32_t (and then to a CRGB or CHSV struct). The simplest way is to use the C library function strtoul
uint32_t color = strtoul(arg, NULL, 16);

This can be improved so that it checks that a number was scanned, etc.
Cheers!


text:
Intermittent LOW reading from input pin set to INPUT_PULLUP
i have an output pin connected to a magnetic reed switch. The pin mode is INPUT_PULLUP. When the switch is closed, it connects the pin to GND and drags the pin to a LOW reading. I check the state of the pin in the loop function. Occasionally the pin reads LOW when it shouldn't (the switch is not closed) - e.g. around once per second. What could cause this? The wire from the pin to the switch is about 1m long - could this be long enough to intermittently drag it down to a LOW? Also, it seems to happen much more when the air temperature is hotter.
Circuit summary: Pin (INPUT_PULLUP) -> Magnetic reed switch -> GND

My guess would be that you're getting noise interference on the line and it's too much for the Arduino's little internal pullup.  Try adding an external pullup resistor - say 5k-10k (exact value is not critical).

Thanks, you are correct. I managed it through code. E.g i'm now taking 10 samples a second, and to change state it needs 10 consecutive samples to be the same reading. This has been working without fail now for days. I suspect noise can only pull the pin down briefly (nanoseconds?)

Yes it will be brief, but how frequent will depend upon where the interference is coming from - it could conceivably happen a lot.  If that's working for you then it sounds like a reasonable workaround.


text:
How do I order the gcc compiler to generate -S flag in Arduino IDE
How can I set the Arduido IDE to generate the -S flag to gcc to see the machine code in Arduino? (the sketches)

avr-gcc's switch "-S" means "Compile only; do not assemble or link". Are you thinking of avr-objdump? It's "-S" switch means "Intermix source code with disassembly".

Compiler flags are defined in the platform.txt of the board you have selected in the Tools > Board menu. You can also add compiler flags via a build.extra_flags property in the boards.txt entry for the selected board.


text:
Turn on a LED when an other LED turn off
I'm a beginner on arduino.

I have an arduino mega with two LED (like the image with only 2 less and without the buzzer). A red LED and a green LED. When the arduino receive the code 200 I want the red LED turn on and the green LED turn off. But when I test that but any led turn off or turn on..
void setup()
{
  pinMode(LR, OUTPUT);
  pinMode(LV, OUTPUT);
  Serial.begin(9600);
}

void readSerial(){
  while(Serial.available() > 0){
    car = Serial.read();

    if(car != '+'){
      buff[i] = car;
      buff[i+1] = '\0';
      i++;
    }
    else{
      sscanf(buff, "%d", &received_code);
    }
  }
}

void loop()
{
  readSerial();
  if (received_code == 200){
    LRstate = HIGH;
    digitalWrite(LR, LRstate); // turn the LED on (HIGH is the voltage level)
    digitalWrite(LR,LOW);
    delay(100);
    digitalWrite(LV,LOW);
  }
}

How can I solve my problem?
Thanks a lot.

Please rephrase But when I test that but any led turn off or turn on., as this sentence isn't very clear.

Based on the connection and coding problems, I read this as "none of the LEDs responded."

JRobert addresses some of the wiring problems in his answer, but also note that the outer two rows on each side of the breadboard (the rows between red and blue lines) are connected the long way – that is, make up 50-pin bus lines – vs the columns-of-5 on each side of the centerline being connected the short way, making 5-pin bus lines.  So the diagram connects a bunch of Arduino outputs together, which is wrong wrong wrong usually

If your circuit is really connected as shown in the diagram, then your Arduino should have grilled already, since this diagram shows all outputs pins for LEDs directly connected to GND: short-circuit when an output pin is set to HIGH!

First, make sure the LEDs are connected correctly: I presume the red LED is connected to whichever pin LR is, and the green LED to LV.
According to your diagram, your LEDs will be on if the output is HIGH, and off if the output is LOW.  Your code sets LR to high, but then immediately to LOW again.
Here's a fixed (I hope) verson of your loop():
void loop()
{
  readSerial();
  if (received_code == 200){
    // Turn the red LED on
    digitalWrite(LR,HIGH);

    // Turn the green LED off
    digitalWrite(LV,LOW);
  }
}

Unrelated to the problem you're having, but worth a mention anyway:
There's nothing in your code to stop you overrunning buf if you get a longer input than you're expecting.  If this happens you'll get unpredictable results as you trash over whatever happens to be in that part of memory.

The code you showed turns on LR and turns off LV if received_code == 200, which I suppose meets the specification as given, since how the LEDs get back to LR off and LV on isn't stated.  But the question's loop() has a delay(100); in it, suggesting switching them back after that delay

@jwpat7 Yes - although I wasn't sure if that was intentional. It's hard to tell which of that group of lines doesn't match the intended behaviour, since it's not absolutely clear what the intended behaviour is.  If the OP clarifies what he wants, I'll adjust accordingly.

In addition to the code changes noted by @MarkSmith, the LEDs are not connected properly. The straight LED pin on the Fritzing diagram is its cathode and must be connected to grounded, and the bent pin is its anode and must be at +V (+5v, in this case), for the LED to light. To turn the LED on, the anode must be at +V and the cathode at ground. To turn the LED off bring both pins to the same voltage, usually by grounding the anode (logic 0 on its connected pin).

To identify the cathode on a real LED, look inside its plastic blob (that's a technical term :) and you'll see two bits of metal, each on a wire, like two flags. The larger flag is the cathode. Usually, the cathode also has a shorter external lead and the plastic blob has a flat edge on that side, but the larger flag is definitively the cathode:


text:
Digital read on voltages between 1 and 31 volts?
Hello Arduino comunity!
I am working on a circuit that uses an Arduino Mini to read values from certain points of a boost/buck converter circuit to determine things like input state, output state, overheat and so on. The circuit is working all right, and the only part left to do is to connect the digital pins of the Arduino to the different points in the boost/buck regulator.
The problem is however that I need to read from a range of voltages between 1 and 31 volts with the Arduino, which isn't possible, because not only will it damage the controller if the voltage exceeds 5V, but values below 3V will be regarded as false.
I thought of putting some potential dividers, which would obviously not do the trick, and I also thought of using a WS78L05 voltage regulator per input pin (because each pin might have a different voltage from the rest) but that isn't dealing with voltages <=5V and 31V exceeds its rating as well.
Lastly I thought of using transistors, which seemed like a good idea, but I would require 2 transistors per input wired as follows:

simulate this circuit – Schematic created using CircuitLab
But it is impractical to do for 4 inputs and there is limited space available on the PCB too :(
Is there any IC that encapsulates the circuit above, or is there any other way to achieve what I want to do?
Thanks very much :)

First you need to look at each individual input and what exactly it is sensing, and what those voltages mean. Then you can work out what you need for that input. Don't try and make a "one solution fits all" system,  unless all your input sense the same thing.

@Majenko Not trying to find a 'fit all' situation. The thing is that the output can either be on, or off therefore 1 or 0. If the output voltage is 10V or if it is 31V makes no difference, the output is open (1) whereas if the voltage in the output is 0V it means that the DPDT switch before it is off therefore the output is closed. Thats what im trying to sense. Same aplies for the input and the overheat switch (it is a 65C thermal switch. if it is off then there is overheat, if it lets n volts through then its alright)

So a voltage divider sized to cope with the highest voltage you want to sense, fed into an analog input. You then read the value and compare it to a threshold for on or off.

@Majenko Well the potential divider i thought of consists of a 51k and a 10k resistor (we dont need much current) at 31V it produces 5.082V which is alright, however at 1V it produces 0.16V which would be hard to sense and would very easily provide false-trigers... Not to mention that it would probably drop even further with a pulldown resistor :(

0.16V would read 32 on the ADC. That's plenty, surely? If you want more, then size your divider a little higher (say 7V) and clip it with a 5V zenner diode?

What are your thresholds for on/off?

Using a simple voltage divider (51K / 10K as you have worked out already) fed directly into an ADC input will give you a reading of 32 on the ADC at 1V input. That should be enough to give a reliable threshold detection.
If you want to have higher sensitivity at lower voltages you can increase the output of your voltage divider to more than 5V and then clip it with a zenner diode. For instance if you reduce the 51K to 33K you get 7.2V out of the voltage divider. A 5V zenner diode can then clip it to 5V. Your 1V input (which would be 0.233V on the output of the divider) would now read 47 on the ADC. Anything over 21V would then read 1023.

simulate this circuit – Schematic created using CircuitLab
Theoretically you could get away with not having the voltage divider at all and just using the zenner and one resistor to clip the incoming voltage to 5.1V. That would give you the greatest sensitivity, but also the greatest current flow through the zenner.

simulate this circuit
Size R1 to limit the current at your maximum voltage to within the rating of the zenner.

Thanks for the response, it does make sense but i dont  think that i can manage all those in the tight space i have :S 4 input pints that need voltage regulation (they are one next to the other) and the space in which i need to fit all that is small (it has to be to fit in the enclosure as well) Also which of the two designs above is going to be the one with the least drop when 1V is in the input? Also isnt there any IC you are aware of that holds the two transistors in the arrangement i showed above? Lastly, it just poped in my mind to use optocouplers. Would that be possible and effective?

Why do you use a zener, instead of clamping the voltage to the 5V rail with a regular diode?

@Gerben Because it gives less noise on the power rail that way. With a regular diode it takes time to switch from reverse to forward bias and you get spikes of noise on the power rail while it is doing that. With a zenner it breaks over at its rated voltage and limits the voltage without needing to switch from reverse to forward bias.

@fillpant The second design will give you 1V out when you put 1V in. It will give you 3V out when you put 3V in. It will give you 5.1V out when you put 6V in. It will give you 5.1V out when you put 31V in. It doesn't scale the voltage, it clips the voltage. Anything above 5.1V is thrown away as heat in the resistor.

@fillpant Opto couplers are possible, yes, but I would have thought a resistor and zenner diode would be the smallest possible footprint. Especially in SMD formats.

Alright i see! I dont have the ability to solder SMD's but i agree they would fit perfectly.
Im probably going to go with the zener and resistor solution.
How many mW will the zener have to handle in the worse-case (31V)?
Lastly i found this: http://www.nteinc.com/specs/2000to2099/pdf/nte2033.pdf will something like that do the trick? an 8 pin chip fits perfectly, so if i find the respective IC but with positive input and positive output i bet it would work just fine wouldn't it?
Thanks :)

Use two quad lm339 voltage comparator chips to make an analog to digital convertor-you will need 2 to read 31 volts accurately. Its a standard ADC circuit, with this common lm339 is,  so a search will find circuit-it may need a simple modification to combine the two circuit.

The junction of a 51KΩ, 10KΩ voltage divider will feed an Arduino ADC input 5.08 V at 31 V input, and 0.16 V at 1 V input.  With a 5 V reference, I think the first of those will give 1023 counts, and the latter, 33 counts.  This is from 1023*(1/5)*10/(10+51) ≃ 33.54.  That may be enough counts for reliable detection, depending on how noisy the environment is.
For more sensitivity at lower voltages, if the first reading is less than 225 counts, one can switch to the 1.1 V internal ADC reference and take another reading.  (1023*1.1/5 ≃ 225.06.)  With a 1.1 V reference, a 1 V input to the divider produces 152 counts, and a 6.7 V input produces about 1023 counts.  (1023*(1/1.1)*10/(10+51) ≃ 152.46 and 1.1/(10/61) ≃ 6.7.)
To change the ADC  reference voltage, say analogReference(DEFAULT) for Vcc reference, or analogReference(INTERNAL) for 1.1 V reference.


text:
How can I adjust my code so that the value that I print with my BLE device does not get chopped up when I receive it on an app?
I am using a BLE device (https://www.adafruit.com/product/1697) that I use to print data to an app. I can successfully connect the BLE to the app and receive the data but the result however gets chopped up.
What I am sending is a lat, lng value (that I gather with a library called TinyGPS++ http://arduiniana.org/libraries/tinygpsplus/) and the code looks like this:
BTLEserial.Print::print(gps.location.lat(), 8);
BTLEserial.print (", ");
BTLEserial.Print::print(gps.location.lng(), 8);

So for example if the latitude is: 32.12345678, it comes like this to the app: 3, new row, 2, new row etc.
So my question is, how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

Your app code is invalidly assuming the data will arrive in a single receive API call.  You can only fix the issue by fixing the app.  Timing related things you do on the arduino mightvstatistically influence the outcome, but the only sound solution is fundamentally correct receiving code.

The answer below fixed my issue though by sending it as string

No, not really.  It may unreliably appear to work more often but it is wrong and based on fundamental misunderstanding.   Between your ardunio and your app you have a serial link and a packetized one neither of which respects your original grouping in a more than happenstance way.

As far as i can see it sends data my app and i receive it nicely just the way i want it (not chopped). I have tested it like 30 seconds though (as it keeps sending data each 2 seconds) and maybe i could face issues with a longer connection you mean? Or will there be a issue with lat, lng accuracay (value not updating)?

Or you could face an issue when the computational load on your phone or the phase of the moon or the local RF environment changes. That is the cost of invalid assumptions in software.  The only valid solution is to find the end of a message by an explicit condition.

how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

The BLE device uses a package approach and the print member functions only support strings (char vectors and Arduino String). Construct the message as a String:
double lat = gps.location.lat();
double lng = gps.location.lng();
String msg = String(lat, 8) + String(", ") + String(lng, 8);
BTLEserial.print(msg);

Cheers!

The first lat value works! But with the lng value a new row is created after 4 decimals has been made, so it look like this when I get it on the app now:
36.02331400, 19.7794(new row)4300

So 4300 in this case gets on a new row

Ah, is it because 20 bytes is max to send?

With "." and "," and "space" the totalt amount of byte is 24

So i cannot send so precise gps values i suppose

Yes, there is a max size on the message. Why not send as two messages/prints?

Yeah that is true. I might as well do that. Will it delay any process by sending two prints instead of one? Like make connection slower or something? Upvoted answer by the way, works great!

Or fix your app so that it reconstructs a line of text, i.e. reads messages until new-line/carriage-return.

This answer was fundamentally erroneous.  There is no problem with the arduino code, rather the app code makes invalid assumptions.


text:
How can I make this code read a page every 10 seconds?
I got problems with the code and I have used most of today, trying to find a solution and it's starting to drive my crazy. I hope one of you guys will be able to help me out.
I need the code to check a specific page every 10 seconds, single character.
This is what I have now, working code:
Where should I start?
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "billigefittings.dk";

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println(Ethernet.localIP());
  Serial.println();

  Serial.println("connecting ...");

  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("GET /lan.php");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if(client.available() > 0) {

    char c = client.read();

    Serial.print("page value:");
    Serial.println(c);

    if(c == '1') {
        digitalWrite(8, HIGH);
        Serial.println("8 HIGH ...");
        delay(5000);
        digitalWrite(8, LOW);
        Serial.println("8 LOW ...");
    }else{
        Serial.println("page value does not match '1' !");
    }

    // The code above should run even 10 seconds

  }

  if(!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;);
  }

}

Update: Edit the loop like the example below does not work either, it stops after the first loop (8 LOW):
void loop()
{
  if(client.available() > 0) {

    char c = client.read();

    Serial.print("page value:");
    Serial.println(c);

    if(c == '1') {
        digitalWrite(8, HIGH);
        Serial.println("8 HIGH ...");
        delay(5000);
        digitalWrite(8, LOW);
        Serial.println("8 LOW ...");
    }else{
        Serial.println("page value does not match '1' !");
    }

    delay(5000);

    // The code above should run even 10 seconds

  }

}

What aspect of it is causing you difficulty? Where to start is moving most of it into the loop(), and pausing for 10s after you've done it.

I tried that, but it does not work. Nothing happens after the first loop, even when I remove the client.stop() part.

You need to connect to the server (client.connect...) and disconnect (client.stop();) each time round.  More generally, try to understand the problem: it isn't true that "nothing happens" - something happens, just not what you want. If you could understand what in fact happens, you'd be closer to understanding why.  You can put trace (serial.prinln()) in, find out where it's going wrong.

As discussed in the comments, you need to connect to the client each time, not just once.
Here's my modified version of your code, which I hope will work -- I'm not set up to test it.
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "billigefittings.dk";

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println(Ethernet.localIP());
  Serial.println();
}

void loop()
{
  // Connect to the server
  Serial.println("connecting ...");

  EthernetClient client;
  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("GET /lan.php");
    client.println();
  } else {
    Serial.println("connection failed");
  }

  // Wait a moment for data to arrive
  // Note: This is NOT a reliable way of doing it!
  delay(1000);

  if(client.available() > 0) {
    char c = client.read();

    Serial.print("page value:");
    Serial.println(c);

    if(c == '1') {
        digitalWrite(8, HIGH);
        Serial.println("8 HIGH ...");
        delay(5000);
        digitalWrite(8, LOW);
        Serial.println("8 LOW ...");
    }else{
        Serial.println("page value does not match '1' !");
    }
  }

  // Disconnect the client
  if(client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }

  // Wait another 9s, which will give us a delay of roughly 10s
  delay(9000);
}

That worked perfectly, will keep in mind that you need to connect upon each try - you saved my day! thank's a lot.

Glad to hear it was helpful!

Got a small question related to your answer. It seems you got quite a lot of knowledge about coding this stuff. Do I need to flush cache, or something, in the code above? It's supposed to run months without stop.

No, I can't see anything there which needs maintenance. The only thing that feels dodgy is that when we connect we wait 1s for data, and if there isn't any, we abandon ship.  That'll probably work most of the time, but what if just occasionally the server is under high load, or your network is laggy or whatever? It'll appear to have failed.  Browsers have much longer timeouts than this.  How to deal with depends on what you're trying to achieve.

Hmm... we have 3 machines each with an arduino. Each arduino check a file to see if a value, matching the machine, is active. If the value is active, then the arduino will power a motor for a short period of time. Each of the machines does this separately, checking a file every 10 seconds.

What do you want to happen if the network is (temporarily?) slow? Would you rather it wait (how long?) or is "slow" equivalent to "not working" for the think you're trying to achieve?

Thats a very good questions. Maybe add a 30 seconds timer, do a GET request to a php page with some info, so I can store some details about the delay in a database for tracking. Is it possible to add a timeout to Arduino and do a GET request to a php page? (e.g. domain.com/machine.php?status=err_delay&machine_id=3)... I need to think this over, have a feeling this will be quite important. Thanks for bringing it up :)


text:
Control RGB led using microphones, getting the right components
Sorry if this is too basic, but I am very new to arduino and electronics. I come from programming, I am trying to start a project where I can control an RGB led strip, I want to be able to control the light intensity and color of the light strip (something like this), using a microphone.
My goal is for frequency to control de color of the rgb light and the dB (Volume) to control the light intensity. I have found several microphones such as this ones. Can I get both frequency and dB input from this microphones?
Would I need some extra controllers for this project? Again I am very new with this, sorry by the basic questions.

It would be well worth having a look at ColorChord.

You are taking on two Arduino projects at the same time (controlling addressable RGB LED strips & frequency discrimination using a microphone).  Judging from past posts here, it would be better if you tried one of your projects first, then post questions about that project before moving on to the to the second.  For instance, many people fail at the RGB LED light strips because of unexpected power supply problems.  And, I am not entirely sure a Arduino Uno can do a good jobs at frequency discrimination.  I do not think it is fast enough to do a good job.

Thanks @st2000, I will do it that way in the future, if an Arduino-uno is too slow for that would you recommend something else?

@MarkSmith are you the creator of that program? can I contact you if I have questions about it's use?

When starting Arduino hacking I find it always best to find someone who's done it before.  @MarkSmith has found you the perfect example project.  I would research it to find out what hardware ColorChord uses.  And don't stop at the GIT web page, the ColorChord guy (I think Charles is his name) had made several YouTube.com videos the show off his work.

@MarkSmith you should flesh out your comment and make it the answer.  Derek, you should accept his answer and complete this question / answer entry into the arduino stackexchange website.

No, I'm afraid I'm not the creator. As @st2000 says, the guy who is has some fascinating projects - I've wasted, er, spent hours watching his youTube stuff. Really worth diving into. ColorChord uses an ESP8266 which is a great little device.

It would be worth checking out the ColorChord project.  It runs on an ESP8266, not an Arduino, but it ought to get you going.


text:
ESP8266 Serial Communication with ATMega328P
I am isolating the ATMega328P from the Arduino Uno. I have used it for many other projects, so it does work as intended. Also, I have used my ESP8266-01 for other projects and works great (including serial communication).
I am trying to get the ESP8266-01 to make the ATMega328P pin 13 blink an LED. That is all.
When the ESP8266 is hooked to the TX/RX of the arduino board, the program works exactly as intended. I hook it up the exact same way to the ATMega328P and it doesn't work.
I am using baud rate of 9600 for the communication and using a 16MHz crystal for the ATMega328P.

simulate this circuit – Schematic created using CircuitLab
The controller is getting 3.3v from the supply as well. And pin 13 is supposed to turn on/off depending on the serial value. Below is the code for the ESP8266:
#include <ESP8266WiFi.h>

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

void loop() {
  delay(10000);
  Serial.write("LED ON");
  delay(10000);
  Serial.write("LED OFF");
}

And below is the code for the ATMega328P:
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

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

void loop()
{
  if(esp8266.available())
  {
    String command = "";
    while(esp8266.available())
    {
      command += (char)esp8266.read();
    }

    if(command == "LED ON") {
      digitalWrite(13, HIGH);
    }

    if(command == "LED OFF") {
      digitalWrite(13, LOW);
    }
  }

  delay(500);
}

As stated, they work great separately, but when I try serial communication with them together, it doesn't work.
P.S. I usually set my ESP8266 baud rate to 115200, but the ATMega328P, I believe, needs to run at 9600 because of the 16MHz clock frequency. Not sure about this part, though.
EDIT:

simulate this circuit

"but the ATMega328P, I believe, needs to run at 9600". Its hardware UART is fully capable of 115200 baud and higher. The 9600 baud limitation applies to a SoftwareSerial port, which is simulated by programmed 'bit-banging' on another pair of digital I/O pins.

Generally, try to debug the problem.  Evidently either you're not getting data from your esp8266.available() and/or esp8266.read(), or it's not the right data.  Put traces (Serial.println(...)) in, print things out, and find out what's going wrong.

Specifically, I suspect the issue here is that you are relying on all the data being available immediately: you check esp8266.available() which will tell you whether one or more bytes is available.  Then you esp8266.read() until there are no more bytes available.  What if there's a 1ms delay between bytes arriving?  You'll get,perhaps LED O, esp8266.available() will tell you there's no more data (there's not, yet!) and you stop reading.
You could probably get it working by putting a small delay() in:
while(esp8266.available())
{
  command += (char)esp8266.read();
  delay(100);
}

That's a solution (probably) but not a good one.  A better solution would be to make your commands LED_ON\n and LED_OFF\n - and read until you get a \n.

I tried the above and still no luck. I don't think that would be the issue because the code works with the atmega attached to the uno. All I truly did was isolate it from the uno and added the 16MHz crystal for the external clock.

I don't know then, sorry. What is actually going wrong? Have you put trace in to find out how far it's getting, where it's failing etc?

I put it back into the uno, and now it is not working. I may have messed up the controller. I will try with a new atmega.

Okay. It works perfectly with the uno. But when I take the controller off and set it up as shown above, it wont work.

Omg. I figured it out. I forgot to power the other side of the chip. wow.


text:
The BOOTRST fuse was disabled, but bootloader code is still running after chip reset
I am experimenting with an ATmega328P bootloader, and I created an Intel HEX (.hex) file with a program with an infinite loop in the beginning and with Optiboot code at the end of the hex file. (Code loaded into the chip is here: http://relliks.php5.cz/stackexchange/DUMP.bin.)
Then I disabled the BOOTRST fuse and pressed the restart button on Arduino Uno R3, but the bootloader still blinks with the LED on digital port 13.
How is it possible, that the bootloader is executed after chip restart and BOOTRST is disabled? My fuse settings are: Only SPIEN and BODLEVEL0 are set.
I found that when I disable the BODLEVEL0 fuse, the bootloader turns off.
BODLEVEL0 is used to set the brown-out voltage and shouldn't affect bootloader start. Where is the issue?

Please post the hex values for all your fuses. One way of doing that is to run my chip detector sketch.

Please do not cross-post the same question on different Stack Exchange sites. See Is cross-posting a question on multiple Stack Exchange sites permitted if the question is on-topic for each site?. I refer to your post on Stack Overflow.

Thank you very much!
I found that when I set fuses using program PONYPROG2000 and native RS232 programmer (http://3.bp.blogspot.com/-2D_0B7...) then I read fuses again using another program (eXtreme Burner) and another programmer(USBASP 2.0), there was difference. The PONYPROG2000 probably sets the fuses incorrectly.
Now the Atmega328P works correctly yet.

You don't seem to have filled in all the interrupt vectors. I get this from your .bin file:
00000000 <.sec1>:
       0:       00 c0           rjmp    .+0             ;  0x2
       2:       00 00           nop
       4:       00 00           nop
       6:       00 00           nop
       8:       fc cf           rjmp    .-8             ;  0x2
       a:       fb cf           rjmp    .-10            ;  0x2
       c:       fa cf           rjmp    .-12            ;  0x2
       e:       f9 cf           rjmp    .-14            ;  0x2
      10:       f8 cf           rjmp    .-16            ;  0x2
      12:       f7 cf           rjmp    .-18            ;  0x2
      14:       f6 cf           rjmp    .-20            ;  0x2
      16:       f5 cf           rjmp    .-22            ;  0x2
      18:       ff ff           .word   0xffff  ; ????
      1a:       ff ff           .word   0xffff  ; ????
      1c:       ff ff           .word   0xffff  ; ????
      1e:       ff ff           .word   0xffff  ; ????
      20:       ff ff           .word   0xffff  ; ????
      22:       ff ff           .word   0xffff  ; ????
      24:       ff ff           .word   0xffff  ; ????
...
    7dfc:       ff ff           .word   0xffff  ; ????
    7dfe:       ff ff           .word   0xffff  ; ????
    7e00:       11 24           eor     r1, r1           <--- bootloader
    7e02:       94 b7           in      r25, 0x34       ; 52
    7e04:       14 be           out     0x34, r1        ; 52
    7e06:       89 2f           mov     r24, r25
    7e08:       8d 70           andi    r24, 0x0D       ; 13
    7e0a:       11 f0           breq    .+4             ;  0x7e10
    7e0c:       89 2f           mov     r24, r25
    7e0e:       de d0           rcall   .+444           ;  0x7fcc
    7e10:       85 e0           ldi     r24, 0x05       ; 5

Now I can't quite see the relationship between the brown-out and those higher interrupts, but if one of them happened to fire I think it would waddle its way past all those 0xFF instructions and hit the bootloader.
The Atmega328P has 26 interrupt vectors (including Reset).


text:
WS2812 - First are white and then they turn red/yellow/orange near the end
I'm trying to power about 150 WS2812 LEDs from my ESP8266 NodeMCU board (running NeoPixel Arduino code). The first few LEDs are white, but about half way down, the LEDs turn yellow, then they turn orange, and at the end they're basically red.
Could this be caused because of the power draw? The strip itself is currently drawing about 900 mAh, and I am powering the ESP8266 with a 1.5A 5v supply. The LEDs are running off 3.3v directly from the ESP8266.
Also, after like 2 minutes, the LEDs turn off completely. The board never disconnects from my WiFi. They just turn off. I can turn them on again right after.

See Powering NeoPixels.

Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue).
...
To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps. Or use 60 (instead of 20) if you want to guarantee an absolute margin of safety for all situations. For example:

So you need at least 3 amps or even 9 amps for absolute safety.

The LEDs are running off 3.3v directly from the ESP8266.

I doubt it is designed for that. The internal traces won't be designed to handle maybe 5 amps.

To avoid colour degradation through the strip you could use multiple power supplies (to avoid the voltage dropping due to the resistance over the strip). You would connect the grounds (and connect the data wires of course) but break the +5V line in the middle and insert another power supply.
However one (fairly powerful) supply directly connected to the NeoPixels might do the trick. That is, not through the ESP8266.
Also see NeoPixels Revealed: How to (not need to) generate precisely timed signals.
On that page:

Q: In the video, when the entire strip is lit full white, it looks like the far end has a orange tint to it. Is this an artifact of the camera or something?
A: Wow, you are very perceptive! Yes, the string did start to get orange at the end at full power. I actually didn’t just run out of apartment when making this long string – I also ran out of power supplies. I had 3 supplies, each 10amps. This is almost enough, but not when every single LED is full brightness white. When that happens, the voltage at the very end of the strip starts to get too low and the LEDs start looking pallid. Why orange? Because blue LEDs need the highest voltage drop to light so when the voltage sags they are the first to go followed by the greens – leaving yellows to oranges and ultimately red.

(He had 1000 pixels). So this guy used 3 separate 10 amp power supplies!

Thanks for the reply! I don't have NeoPixels LEDs. I just use their library (well, Hakuna's library to be specific). Adding power to a 5m strip seems a bit... weird. Is that the only way? They do support 5v if that helps.

WS2812 - same thing. :) Adding power to the strip is perfectly OK. You just take data and ground from your ESP8266 to give them commands, and +5V and ground from your power supply to the pixel string.

Read the page I linked with tips from Adafruit. They have lots of suggestions there.

Oh yeah, powering the strip isn't a problem.. per se. The issue is, I don't want to run additional wires across the entire room, just to power the strip. Surely there is a better way? I have over 15M of LED strip I can power with a single 12v source (just regular RGB 5050 LEDs). Can't this be achieved?

I can see the last LEDs are about 2.2v... That's not good haha.

So I up hooking up the same 1.5A 5V supply directly to the VIN and GND on the ESP8266, then connect 5V and GND from the strip to that same source. Much, much better result. Now the first 3 meters are all the same white, but yellow after that. So from 1 meter to 3 meter just by hooking it up like this. Great success so far.
If I found a suitable 5V supply with high amperage output (like 10A) would that be fine?

A larger supply will almost certainly help. For my Xmas lights I had a strip of 300 NeoPixels, running from a 5V 3A wall-wart. I think there was a slight colour drop towards the end, but not too much.

That's very interesting. I'll look into grabbing a 5V supply with a lot of amperage. I still have to power them both seperately, as the ESP8266 NodeMCU won't output that much amperage :( If I power the strip off the ESP while powering the ESP through it's VIN and GND (5v), I get the exact same result. But if I just move the power from the strip to the power source (same lane as powering the ESP), I get a "good" result.

I bet there is an internal resistance in the Vin traces, because they will be thin copper strips not intended to carry 5 amps.

Yeah I bet. So basically splitting up the connector would be efficient enough I guess.

One thing not to neglect is your power wires gauge. Smaller the wire it is the more resistive it is, causing voltage drop and current pinchoff. Use "big" wires for power.

From the Adafruit Uberguide.
https://learn.adafruit.com/adafruit-neopixel-uberguide/power
I am experiencing the same issue.  This is the solution I found.

Distributing Power The longer a wire is, the more resistance it has.
The more resistance, the more voltage drops along its length. If
voltage drops too far, the color of NeoPixels can be affected.
Consider a full 4 meter reel of NeoPixels. With 5V applied at one end
of the strip, for those pixels closest to this end, power traverses
only a few inches of copper. But at the far end of the strip, power
traverses 8 meters of copper — 4 meters out on the +5V line, 4 meters
back on the ground line. Those furthest pixels will be tinted brown
due to the voltage drop (blue and green LEDs require higher voltage
than red).
leds_brownout.jpg
Pro Tip: NeoPixels don’t care what end they receive power from. Though
data moves in only one direction, electricity can go either way. You
can connect power at the head, the tail, in the middle, or ideally
distribute it to several points. For best color consistency, aim for 1
meter or less distance from any pixel to a power connection. With
larger NeoPixel setups, think of power distribution as branches of a
tree rather than one continuous line.
leds_nobrown.jpg

Just incase anyone else has the problem,
You need to connect the strip as a ring by returning the tail end to the psu,
Electricity basics !!!!

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


text:
How to measure ultrasonic sensor without pulsein method?
I am a front-end developer so I don't really know Arduino. Anyway, my teacher gave me a project.
In short, I have to measure distance with HC-SR04. But the problem is that the teacher wants me to use a timer. But I can't understand how can I do that.
Thank you for helping.

It sounds like you are being assigned to read the ATmega data sheet or programmer's manual and make direct use of the timer peripheral, ie, do what the pulseIn code does, but do it yourself.   If you ask someone else to give you the answer, how is that more beneficial than just looking at the implementation of the pulseIn function?

Rather than give you the straight answer in code form, consider this approach. If you learn how the unit works, you will be better prepared to answer questions presented to you.
The background of an ultrasonic distance measuring device is that it sends out a signal, in the form of sound you cannot hear. The device then listens for any echoes (bounce-back) of that pulse within a certain time period. This time period represents the distance range that the device can register. If the electronics are of poor quality, the minimum distance will be larger than if the device was of higher quality, as the amount of time for the pulse to bounce from a close-in object is going to be very short. The electronics have to be very fast to read such a short period of time.
There are libraries for ultrasonic devices such as the one you note, but that's the "easy way" to use it. If you perform appropriate searches, you will find there are references how to use direct timing for this device, which will satisfy the requirement you have been given.
I could perform the search and provide you a link, but that's half the work. Consider to use terms including your device identifier along with code and timing and you may find useful links. It is also very possible that you will find someone's pre-written code using the timing method.

The solution is, You need to implement custome pulse in funtion
unsigned long rdPulseIn(int pin, int value, int timeout) { // the following comments assume that we're passing HIGH as value. timeout is in milliseconds

    unsigned long now = micros();
    while(digitalRead(pin) == value) { // wait if pin is already HIGH when the function is called, but timeout if it never goes LOW
        if (micros() - now > (timeout*1000)) {
            return 0;
        }
    }

    now = micros(); // could delete this line if you want only one timeout period from the start until the actual pulse width timing starts
    while (digitalRead(pin) != value) { // pin is LOW, wait for it to go HIGH befor we start timing, but timeout if it never goes HIGH within the timeout period
        if (micros() - now > (timeout*1000)) {
            return 0;
        }
    }

    now = micros();
    while (digitalRead(pin) == value) { // start timing the HIGH pulse width, but time out if over timeout milliseconds
        if (micros() - now > (timeout*1000)) {
            return 0;
        }
    }
    return micros() - now;
}

You can read distance
long mm = rdPulseIn(echoPin, HIGH, 37)/5.82; // distance in mm

authors: عبدالرحمن العيدروس


text:
How to store a string in an object and retrieve it safely later?
I'm writing a program where I will be able to toggle between multiple banks, and each bank has 4 presets on it. Right now, I'm trying to give each preset a name that is assigned on creation.
I have an object I called StoredDataManager, which will handle all the banks. In its constructor, I do this:
for (byte i = 0; i < NUMBER_OF_BANKS; i++) {
  Bank bank;
  _banks[i] = &bank;
}

_banks is declared like this: Bank* _banks[NUMBER_OF_BANKS]; in the .hfile of StoredDataManager.
A bank has 4 presets, like this:
Preset* _A;
Preset* _B;
Preset* _C;
Preset* _D;

Which I initialize as this:
Preset preset(presetName, presetData);
...
_A = &preset; ...

Where presetName is "CHR", and presetData doesn't matter, because I'm just trying to get the name to work.
In the preset, the name is saved like this: char _presetName[4];.
It is returned like this:
char* Preset::getPresetName() {
  return _presetName;
}

I try to print a preset's name like this:
Serial.println(_banks[0]->getPreset('A')->getPresetName());

But, right now it simply returns C§.
Why is that? I suspect it has to do with the memory being erased or overwritten.
EDIT:
Here is the code of getPreset:
Preset* Bank::getPreset(char presetLocation) {
  switch (presetLocation) {
    case PRESET_LOCATION_1:
      return _A;
    case PRESET_LOCATION_2:
      return _B;
    case PRESET_LOCATION_3:
      return _C;
    case PRESET_LOCATION_4:
      return _D;
    default:
      return NULL;
  }
}

I think now that I'll turn this into 4 separate functions, like getA, getB and so on, but this what it is the moment. PRESET_LOCATION_1 is just a #define PRESET_LOCATION_1 'A'.
EDIT 2:
I start in the main arduino .ino file with this:
void setup() {
  Serial.begin(9600);
  StoredDataManager storedDataManager;
}

This triggers this constructor:
StoredDataManager::StoredDataManager() {
  for (byte i = 0; i < NUMBER_OF_BANKS; i++) {
    Bank bank;
    _banks[i] = &bank;
  }
  _currentBankIndex = 0;
  Serial.println(_banks[0]->getPreset('A')->getPresetName());
}

This is _banks: Bank* _banks[NUMBER_OF_BANKS];.
The initializing of the bank object runs this constructor: (PRESET_LOCATION_1, 2, 3, and 4 just being 'A', 'B', 'C', 'D')
Bank::Bank() {
  addPreset("CHR", "Some data", PRESET_LOCATION_1);
  addPreset("CHR", "Some data", PRESET_LOCATION_2);
  addPreset("CHR", "Some data", PRESET_LOCATION_3);
  addPreset("CHR", "Some data", PRESET_LOCATION_4);
}

Which calls this function:
void Bank::addPreset(const char* presetName, String presetData, char presetLocaton) {
  Preset preset(presetName, presetData);
  switch (presetLocaton) {
    case PRESET_LOCATION_1:
      _A = &preset; break;
    case PRESET_LOCATION_2:
      _B = &preset; break;
    case PRESET_LOCATION_3:
      _C = &preset; break;
    case PRESET_LOCATION_4:
      _D = &preset; break;
  }
}

Then, above in the StoredDataManages constructor, this line is hit:
Serial.println(_banks[0]->getPreset('A')->getPresetName());

And that's where I try to log out the preset name.

The use of dynamic memory on a constrained system like avr and the word "safely" as a goal probably do not belong in the same posting.  That said, an immediate problem is that 'A' does not mean what you think it does - specifically it is an integer constant of value 65, ie, the ascii code of a capital A  You should probably show the code of getPreset()

@ChrisStratton I posted the code for getPreset(). I do know that it is the character 'A', though. As I mention at the end there, I'm probably going to change how I get the presets.

Where do you call preset()?  With a pointer to what?  That was initialized how?  Without including your code, this is unanswerable.

@ChrisStratton Tried to explain the flow together with the code now.

Just as a style thing, identifiers starting with an underscore and followed by an upper-case letter are reserved by the C++ standard. You should get out of the habit of using them for your own variables.

@Nick Gammon Thanks, didn't know that. Just seemed like the natural name when the preset location name was A :) Ill change it.

void Bank::addPreset(const char* presetName, String presetData, char presetLocaton)
{
  Preset preset(presetName, presetData);

  switch (presetLocaton)
  {
    case PRESET_LOCATION_1:
      _A = &preset; break;
    case PRESET_LOCATION_2:
      _B = &preset; break;
    case PRESET_LOCATION_3:
      _C = &preset; break;
    case PRESET_LOCATION_4:
      _D = &preset; break;
  }
}

I can't see how this is going to work because you are storing somewhere outside a function a pointer to a local variable inside the function. As soon as addPreset exits the variable preset will go out of scope, and a pointer to it will be undefined.

You should probably do a new to make a new instance of Preset which it is then valid to store outside the scope of the function.

Ah, ok. I was thinking as long as I stored a reference to it, the data at that memory location wouldn't be removed. I'll work on changing that tomorrow. Thanks! Any idea as to how I could create an object that would not be garbage collected that would work in this situation?

I'll try newing the objects tomorrow. I guess I have the same problem with the banks, then.

Yes, very much so. Don't assign to some variable a thing that will go out of scope, as you did there. As for garbage collection, there is no default garbage collection in C++.

Ah, right. It has been some time since I coded C++ :) Thanks!


text:
How to fix compilation error for tone() using same timer as other function
I am trying to integrate tone() with the open source program for the Amped heart rate monitor. The error:

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `__vector_7'
sketch\PulseSensorAmped_Arduino_1dot4.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

The program comes in three files. PulseSensorAmped_Arduino_1dot4.cpp I don't think references any timers but references a function in another file with this code:
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED

This uses timer 2; but isn't the error for timer 1? The tone() reference page says that tone interferes with pins 3 and 11. Is there any way to fix this?
references:
https://www.arduino.cc/en/Reference/Tone
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino

In  my case, IR library was conflicting with Tone. Nick's solution works perfectly.

It looks like the Tone library uses Timer 2, and it looks like your other code also uses Timer 2, hence the error message. Vector 7 would be the TIMER2_COMPA_vect (Timer 2 compare "a").
Pins 3 and 11 are from Timer 2.
I wrote a small library that generates tones using the hardware PWM and not interrupts. You can read about it here.
Example code:
#include <TonePlayer.h>

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (220);  // 220 Hz
  delay (500);
  tone1.noTone ();

  tone1.tone (440);
  delay (500);
  tone1.noTone ();

  tone1.tone (880);
  delay (500);
  tone1.noTone ();
  }

void loop() { }

Library can be downloaded from http://www.gammon.com.au/Arduino/TonePlayer.zip
This uses Timer 1 (so that won't interfere with Timer 2) and no interrupts.

For anyone wondering, when defining a tone, all those codes seem to be the address of the single workable pin on Uno/Mega (pin 9). For Mega 2560 there are 3 different pins and TonePlayer.cpp file has the examples.

That's true, thanks for the clarification. In the source are examples of choosing between 3 pins (which are the outputs of the three hardware timers).


text:
Volatile variable not updating from timer ISR
I know this is a problem that has come up many times but I can't seem to get this code fragment to update the count variable on an ATMEGA328P. I am using an Arduino Uno as a development board, with the LED on pin 13 set to flash for debugging. I have confirmed the timer and LED part work by toggling port B pin 5 in the ISR routine.
#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01) | _BV(WGM00);       // WGM mode 7 with OCRA as top
    TCCR0B = _BV(WGM02) | _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);      // Interrupt enabled on OCR0A
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPB_vect) {
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(DDB5);             // Toggle PB5
        }
   }
   return 0;
}

This is being compiled and burned to an Arduino Uno with the following:
avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o test.o test.c
avr-gcc -mmcu=atmega328p test.o -o test
avr-objcopy -O ihex -R .eeprom test test.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:test.hex

I have tried disabling the optimisation with no effect. AVR-GCC is version 4.9.2

Interrupt enabled on OCR0A - don't forget to change the comments if you change the code! You have an interrupt on TIMER0_COMPB_vect!

You want CTC mode for that to work. As in:
#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01);       // CTC mode 2 with OCRA as top
    TCCR0B = _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);      // Interrupt enabled on OCR0B
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPB_vect) {
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(PORTB5);             // Toggle PB5
        }
   }
   return 0;
}

That toggles every 10 ms.

(Edited to add)
The PWM mode you chose will work providing you enable the correct interrupt. This also outputs 10 ms pulses:
#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01) | _BV(WGM00);       // Fast PWM mode 7 with OCRA as top
    TCCR0B = _BV(WGM02) | _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0A);                   // Interrupt enabled on OCR0A  ***
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPA_vect) {                    // Compare A vector ***
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(PORTB5);           // Toggle PB5  ***
        }
   }
   return 0;
}

Changed lines indicated by ***
Note that you should not have enabled _BV(TOIE0) because you have no interrupt handler for Timer 0 overflow. Without an interrupt handler the compiler probably generated code to jump to the reset vector.
The interrupt occurs when the timer matches the Compare A amount (not Compare B) so you need an interrupt on the A side.

You might want to set OCR0B to a defined value, instead of relying on the default value of 0.

Thank you, that worked! Can you please explain why changing to CTC mode has this effect?

See amended answer.


text:
Reading Infrared raw data
I'm trying to understand a few things about this code.

Why is digitalRead() slower than IRpin_PIN & (1 << IRpin)?
What does IRpin_PIN & (1 << IRpin) mean? I translated it to numbers and I figured out it's actually PIND & (0b100). What does PIND translate to and why is bitwise-and with 0b100 performed on it?
Why is the 20-microsecond delay (RESOLUTION) necessary?
What does _BV in while (! (IRpin_PIN & _BV(IRpin))) mean?

/* Raw IR decoder sketch!

 This sketch/program uses the Arduno and a PNA4602 to
 decode IR received. This can be used to make a IR receiver
 (by looking for a particular code)
 or transmitter (by pulsing an IR LED at ~38KHz for the
 durations detected

 Code is public domain, check out www.ladyada.net and adafruit.com
 for more tutorials!
 */

// We need to use the 'raw' pin reading methods
// because timing is very important here and the digitalRead()
// procedure is slower!
//uint8_t IRpin = 2;
// Digital pin #2 is the same as Pin D2 see
// http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
#define IRpin_PIN      PIND
#define IRpin          2

// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000

// what our timing resolution should be, larger is better
// as its more 'precise' - but too large and you wont get
// accurate timing
#define RESOLUTION 20

// we will store up to 100 pulse pairs (this is -a lot-)
uint16_t pulses[100][2];  // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
  Serial.begin(9600);
  Serial.println("Ready to decode IR!");
}

void loop(void) {
  uint16_t highpulse, lowpulse;  // temporary storage timing
  highpulse = lowpulse = 0; // start out with no pulse length
//  while (digitalRead(IRpin)) { // this is too slow!
    while (IRpin_PIN & (1 << IRpin)) {
     // pin is still HIGH
     // count off another few microseconds
     highpulse++;
     delayMicroseconds(RESOLUTION);
     // If the pulse is too long, we 'timed out' - either nothing
     // was received or the code is finished, so print what
     // we've grabbed so far, and then reset
     if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  // we didn't time out so let's stash the reading
  pulses[currentpulse][0] = highpulse;
  // same as above
  while (! (IRpin_PIN & _BV(IRpin))) {
     // pin is still LOW
     lowpulse++;
     delayMicroseconds(RESOLUTION);
     if ((lowpulse >= MAXPULSE)  && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  pulses[currentpulse][1] = lowpulse;
  // we read one high-low pulse successfully, continue!
  currentpulse++;
}

void printpulses(void) {
  Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
  for (uint8_t i = 0; i < currentpulse; i++) {
    Serial.print(pulses[i][0] * RESOLUTION, DEC);
    Serial.print(" usec, ");
    Serial.print(pulses[i][1] * RESOLUTION, DEC);
    Serial.println(" usec");
  }
  // print it in a 'array' format
  Serial.println("int IRsignal[] = {");
  Serial.println("// ON, OFF ");
  for (uint8_t i = 0; i < currentpulse-1; i++) {
    //Serial.print("\t"); // tab
    Serial.print("pulseIR(");
    Serial.print(pulses[i][1] * RESOLUTION , DEC);
    Serial.print(");");
    Serial.println("");
    //Serial.print("\t");
    Serial.print("delayMicroseconds(");
    Serial.print(pulses[i+1][0] * RESOLUTION , DEC);
    Serial.println(");");
  }
  //Serial.print("\t"); // tab
  Serial.print("pulseIR(");
  Serial.print(pulses[currentpulse-1][1] * RESOLUTION, DEC);
  Serial.print(");");
}

I expect the source for digitalRead() will explain a lot about why it's slower.

int digitalRead(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
}

1) so it

calls function digitalRead() (puts value on stack, jumps, prepare function frame - each cost some time)
calls 3 other functions (with all the same problems)
check for sanity of value
check for PWN (and eventually calls another function)
does the PIND & (0b100)
returns from function (so read stack, clear the frame, jumps, set the result)

just to obtain the same functionality

typical for library functions, that each call makes sure the environment is sane and expected each and every time it is called - in close loop you can check it onece before and then just do not broke it
translates parameter from nice arduino numbers to real addresses and bits each and every time again

2) it access the PORT D (see AVR (the processor) internal construction) and reads value of its 3. bit (which maps to the relevant pin of the chip/Arduino board
3) see following comment - it is expected length of the pulse (maybe with some safety limit)
4) _BV is for BitValue - shift 1 to position given by arg (that is macro doind 1 << IRpin) maybe more nice/readable version, compiles to the same. (the ! is ofcourse negaition)


text:
How do you debug SPI connected devices?
EDIT: Changed the title to better express what I'm after.
I've been dabbling in connecting two Arduino Nano 3's with the RFM69HCW breakout for the past 5 days.. but got nowhere.
I've followed the official hookup guide at first, after that didn't work, I've tried the code samples from a Adafruit post, and still nothing.
By 'nothing', I mean that I compiled and uploaded the code to two separate Arduinos that are literally 5cm apart, tried sending messages, broadcasting messages.. etc. but without any success.
Here they are - on two breadboards, but the layout and connections are symmetrical:

Yeah, the bottom one is quite confusing to look at because of the wires, but I lent most of them to friends - so I had to improvise.
To clarify the picture, I connected the Arduino as follows:

D2 -> INT(Interrupt)
D10 -> SS
D11 -> MISO
D12 -> MOSI
D13 -> C(Clock)

One of the codes that I tried: (This is from the official guide, but modified slightly)

#include <RFM69.h>
#include <SPI.h>

#define NETWORKID     0
#define MYNODEID      1 //2 For the other Arduino
#define TONODEID      255

#define FREQUENCY     RF69_915MHZ

#define ENCRYPT       false // Set to "true" to use encryption
#define ENCRYPTKEY    "TOPSECRETPASSWRD" // Use the same 16-byte key on all nodes

#define USEACK        true // Request ACKs or not

RFM69 radio;

void setup()
{
  Serial.begin(9600);
  Serial.print("Node ");
  Serial.print(MYNODEID,DEC);
  Serial.println(" ready");

  radio.initialize(FREQUENCY, MYNODEID, NETWORKID);
  radio.setHighPower();
}

void loop()
{
  static char sendbuffer[62];
  static int sendlength = 0;

  if (Serial.available() > 0)
  {
    char input = Serial.read();

    if (input != '\r')
    {
      sendbuffer[sendlength] = input;
      sendlength++;
    }

    if ((input == '\r') || (sendlength == 61))
    {
      Serial.print("sending to node ");
      Serial.print(TONODEID, DEC);
      Serial.print(", message [");
      for (byte i = 0; i < sendlength; i++)
        Serial.print(sendbuffer[i]);
      Serial.println("]");

      if (radio.sendWithRetry(TONODEID, sendbuffer, sendlength))
        Serial.println("ACK received!");
      else
        Serial.println("no ACK received");

      sendlength = 0;
    }
  }

  if (radio.receiveDone())
  {
    Serial.print("received from node ");
    Serial.print(radio.SENDERID, DEC);
    Serial.print(", message [");

    for (byte i = 0; i < radio.DATALEN; i++)
      Serial.print((char)radio.DATA[i]);

    Serial.print("], RSSI ");
    Serial.println(radio.RSSI);

    if (radio.ACKRequested())
    {
      radio.sendACK();
      Serial.println("ACK sent");
    }
  }
}

Notes:
Everything is powered by a 5V 2A brick - the RFM69 modules are receiving a stepped down 3.3V from those small thingies connecting two separate breadboard power rails.
Also... I don't have any 915MHz antennas, so I used some 433MHz ones that I had laying around - I'm going to get correct ones later, but right now, for testing them 5cm apart it should be good enough..?
P.S.: I HATE when stuff doesn't have status LEDs, I could really use some on the radio modules.

You want to get yourself a cheap USB logic analyser (you can pick them up on places like eBay, DX, Ali, etc for about $6) so you can see what is actually happening on the SPI bus.

@Majenko Oh yeah, I could do that - probably good in the long run when I will do more complex stuff later on. I'm just curious if anyone could spot any mistakes with my setup, because I have no idea what to do until I get a analyser.

Have your code read and print key registers from the part to verify that the SPI is working.  You'll need to look into the library internals to do this.

I'll look into that, luckily the library has all of the registers defined in RFM69registers.h header. Thanks for the suggestion :)

Did you miss this in the hookup guide: IMPORTANT! Do not power your RFM69 with 5V or connect the data lines directly to a 5V microprocessor. Doing so will damage the device.

Huh, now I feel kinda stupid. I didn't realise that.. and I KNOW that the logic pins are indeed 5V on the Arduinos that I own... welp.. gonna get some 3.3V (like a... LC33) voltage regulators and hope that those things still work.

Unless I can do a resistor voltage divider - though I don't see the current (for logic pins) specified anywhere in the datasheets.

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


text:
Arduino due - SAM-BA bootloader is it there even if you replace the original chip
On this page http://playground.arduino.cc/Bootloader/DueBootloaderExplained it mentions the sam-ba bootloader is permanently burned into the rom of the chip.
Does this mean even if I buy a new chip from Farnell, it will still have the bootloader in or is just ones that are specifically made for the arduino due?
That is different from say the mega328, with the mega328 I have to burn the bootloader on manually using isp programmer/ buy it preprogrammed.

Yes, for the Due, but No, for a Zero or Adafruit Feather M0.
The Due uses the Atmel SAM3X8E featuring:

16 Kbytes ROM with embedded bootloader routines

As a ROM the contents are fixed during manufacture, so would be there in a new chip.
However it is worth noting that many SAM devices including this one have the NVM bits that are much like the fuse bits on an ATmega.  Here GPNVM bit 1 defaults to 0, enabling the bootloader, but if set to 1 the bootloader will be skipped.   Hence it may well be possible to get one into a state where the bootloader is not available.  They also have an "erase" pin which if driven high during startup will restore the default state (bootloader invoked) of this NVM bit (and erase whatever you put in flash).

In contrast, the Arduino Zero and the Adafruit Feather M0 also use Atmel "SAM" chips with "SAM-BA", however, they use the SAMD21, where the situation is a bit different:

Unlike
  existing SAM products, ROM monitor is not available in SAM D21 and SAM-BA will
  be loaded in Flash memory.
SAM-BA bootloader is not factory programmed on SAM D21 devices and has to be programmed using an
  external programmer.

Incidentally, congratulations on being willing to step beyond the ATmega DIP packages - more people need to learn that surface mounts part (or at least the TSSOP and LQFP varieties) are something that can be worked with by hand.  If you do not have hot air tools, make sure to only solder one corner, check alignment, solder the opposite and recheck, etc.  But hot air will save you so many headaches and a solder station with it is now in the $60-70 range.
Finally, while you do have the bootloader available in the SAM, to really take advantage of all of its capabilities you will want to get an SWD interface - in addition to programming without reliance on the bootloader, this exposes things like breakpoint debugging, which while almost never "necessary" can still be quite convenient and useful.   Atmel used to offer a great deal on the PCB of the SAM-ICE pod less cables kit and housing, unfortunately there was a massive price increase after the Microchip acquisition.
SWD programming is effectively vendor-unique software operations performed on top of a standard signalling scheme, so you do have options for programmers from other sources - you can make a functional if quite slow CMSIS-DAP from an MBED board (or apparently an Arduino Pro Micro) that will work for debugging but be slow at flashing, you can probably use a Raspberry pi, or the more advanced FTDI devices with the MPSSE engine such as FT232H/FT2232H/FT4232H (but not the everyday FT232RL).  With alternate programmers you will probably need to use something like openocd for the host software - Atmel Studio likely only supports their own and perhaps a few pricey alternatives.

Just out of curiosity what programmer would I need to program this chip if I wanted to use an external programmer. Say I wanted to change some fuses and update the firmware for example.


text:
How to calculate the time it takes before the water valve stops dispensing water in an Automatic Water level controller?
I am making a project about an automated water level controller using ultrasonic, potentiometer and Arduino board. I need a mathematical calculation on how it works. So here's a simple scenario:
I have an open top cylindrical container with a radius of 7cm. The ultrasonic sensed that the half height of the container, which is 15cm, is filled with water. At the bottom part of it, a tube with a radius of 1cm is connected alongside with the water valve. How can I calculate the time needed for the water valve to stop dispensing water if I set the potentiometer to keep the level of water at 9cm only? Can you give me a mathematical formula??
I really need a help, please. Any answer will be highly appreciated. Thank you in advance.

Wouldn't it be easier to measure it?  Configure the system to stop at the desired point, run it, see where the water level actually ends up.  Build in a correction based on the difference, and try it again.   Modeling this is potentially academically interesting but requires information you have not presented about valve actuation time.  Most fill systems don't try to maintain an exact level, but have a deadband to avoid premature wearout of the valve.

One could use a peristaltic pump and skip the complications of using a sensor.  Or, using the keep it simple rule, I would use a float switch.  Or, simpler yet, a mechanical float as the one in your toilet. If you do use an electronic sensor be sure to add a bit of hysteresis so that your solenoid/valve will not prematurely fail.

This looks like a high school physics question wrappen in an Arduino question. But why would you need to calculate the time, if you can just continually measure the distance and turn of the valve if the distance is 6cm?

The concept you have is more complicated than you can imagine. But to answer your question (which is not so arduino-based), the mathematical formula you looking for is Torricelli's Law.
My suggestion for you is design a system which use a feedback concept instead

Sounds like it's the valve's time to close (t_vc) + half (statistically) the measurement interval (t_interval) + the software reaction time (t_sw). So
Add whatever measurement interval the software uses, if any, and the valve's time to close, once activated, and the software's time to react (from decision to actually making the valve-close signal) and you should have it. So:
T = t_sw + t_vc + 0.5*t_interval
Any software reaction time should be negilgible for practical purposes, so we're down to:
T = t_vc + 0.5*t_interval
If the software doesn't include sleeps or delays but loops continuously, measuring and deciding, then the half-interval reduces to negligibility leaving just the valve closure time:
T = t_vc


text:
Stepper motor moves initially but after idle time, clicks and doesn't move for a while
I am using the Accelstepper library to control a stepper motor, according to commands input via Serial.
It works as expected for the first time when I start Serial Monitor and send command.
When left idle for some seconds (> 10 seconds), the motor makes clicking sounds for the first few commands(without moving) and then it starts working again as expected. The longer I leave it, the more commands it misses.
It gets resolved if I restart Serial Monitor on UNO.
#include <Arduino.h>
#include "AccelStepper.h"

#define STEPPER_X_STEP_PIN 2
#define STEPPER_X_DIR_PIN 3

enum Direction { FORWARD, BACKWORD } direction;

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

void blockingRunSpeedToPosition();

AccelStepper stepper(AccelStepper::DRIVER, STEPPER_X_STEP_PIN, STEPPER_X_DIR_PIN);

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(200.0);
  stepper.setAcceleration(50);
}

void loop()
{
  // print the string when a newline arrives:
  if (stringComplete) {
      // clear the string:
      inputString.trim();
      if(inputString == "x") {
          direction = FORWARD;
          blockingRunSpeedToPosition();
      }
      inputString = "";
      stringComplete = false;
    }
}

void serialEvent() {
    while (Serial.available()) {
        char inChar = (char)Serial.read();
        inputString += inChar;
        if (inChar == '\n') {
          stringComplete = true;
        }
    }
}

void blockingRunSpeedToPosition()
{
    int steps = 400;
    stepper.setCurrentPosition(0);
    stepper.move(steps);
    while (stepper.distanceToGo() != 0) {
           stepper.run();
    }
}

I think there is no issue with the code or my Arduino connection since the motor runs fine in the beginning.
I tried the above code on Arduino MEGA, UNO, different motors with different drivers. The problem persists.
I think it is something to do with motor excitation (energized coils).
Please give me some hints and pointer to debug the issue, since I don't know where to look. I am an intermediate programmer and robotics hobbyist.
Here is the video demo of the issue.
I am using:

Arduino MEGA - ATmega2560
NEMA 23.
Rino stepper motor.
Arduino Pin 2 is Step and 3 is Direction.
Driver Vcc is connected to 5V pin.
48 volt, 5 Amps SMPS.
Ubuntu 16.
Accelstepper library

Reopening the serial monitor probably resets your Arduino, clearing problematic state in the code.  Your program is not very well architected - there's no real point to the expensive String operations you do, or to using the serial event to set a flag you read  in the main loop.  Consider handling everything in the main loop on a character-by-character basis.

Just checked, restarting serial monitor fixes the problem only on UNO. On mega restarting doesn't effect.

Will the code keep responding to commands as intended, as long as you don't leave it idle for >= 10 sec?


text:
How to delete first voltage reading?
I'm trying out a new ADC, ADS1262, below is the code. I want to discard the first voltage reading.
*/
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 1                     // Programmable Gain = 1
#define VREF 2.50                 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262;                     // class

float volt_V=0;
float volt_mV=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup()
{
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT);                  //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT);                   //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);               // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT);                // Power down output

  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init();                      // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");

 }

void loop()
{
  volatile int i,data;

 if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data   ready(DRDY pin)
  {
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes conversion register
    Responsebyte = true ;
  }

  if(Responsebyte == true)
  {
    for(i = 0; i <5; i++)
    {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }

  if(SPI_RX_Buff_Count >= 5)
  {

    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

     uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|      ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
     sads1262Count = (signed long) (uads1262Count);      // get signed value
     resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
// Serial.print(resolution,15);
     volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
     Serial.print(volt_V,8);

   }

  SPI_RX_Buff_Count = 0;

}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

Why not just read the voltage reading once in setup()?   Right after the init. A dummy read there, and then no extra variables or logic in the loop() code.   Simple enough.    Or even make the 'get a reading' code into a function/subroutine.  Call it once at the end of the setup() function, first reading is eaten and call 'get a reading' function in loop() as desired.  Again, no extra variables or logic required.

@lornix: Simplest solution so far! As a matter of practice in any project using an A/D, I read it couple of times as part of its setup and again after any configuration change.

Here is what the code shown in the other answer will do.
int read_first = 0;

That allocates read_first and sets it to zero.
if (read_first ) {
    volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
    Serial.print(volt_V,8);
}
else {
   // discarded first result, now we've read the first one
   read_first = 1;
}

First time in, read_first evaluates false, so the else branch will be taken, and read_first set to 1.  Note that no reading has been taken yet, so the  “// discarded first result, now we've read the first one” comment is incorrect and irrelevant.  Second and later times in, read_first evaluates  true, so volt_V readings will be taken and printed.
To correct the problems with that code, use an approach like the following.
int useReading = 0;
...
volt_V = resolution*(float)sads1262Count;
if (useReading ) {
    Serial.print(volt_V,8);
    // and otherwise use the reading as desired
}
useReading = 1;

After this takes a first reading, it doesn't use that reading because useReading evaluates false.  Subsequent readings get used because useReading is turned on after the first reading.

Simplest way is to have a flag to specify whether you've read the first reading or not.  Default to zero:
int read_first = 0;

Then you can say:
if (read_first ) {
    volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
    Serial.print(volt_V,8);
}
else {
   // discarded first result, now we've read the first one
   read_first = 1;
}


text:
Reading/Writing salvaged EEPROM
Recently I stumbled myself on a fairly old blood sugar test strips canisters. Inside them, I found this what they called "Code Card" which inside, an EEPROM Microchip 93LC46B a 1K Microwire compatible serial EEPROM. I want to salvage them for my Arduino project. Is possible to read/write data to them? and how to determine the capacity? I only see 16 bit word size on the datasheet and 1K on the title.

Page 1 of the datasheet: The Microchip Technology Inc. 93XX46A/B/C devices are 1Kbit low-voltage serial Electrically Erasable PROMs (EEPROM).  - in what way is that vague?

Yes you can use it with Arduino. You just have to read the datasheet.

@Majenko Didn't notice that but thanks

BTW, MicroWire is almost like SPI, but CS is active high not active low.


text:
"port" is greyed out in 1.6.13, running win 10 for an Uno R3
I am new to this, and my kid got an Elegoo smart robot car kit v2.0 for Christmas. We assembled the car, but after downloading the software, the program always states:

Arduino: 1.6.13 (Windows Store 1.6.13.0) (Windows 10), Board: "Arduino/Genuino Uno"
Sketch uses 2,242 bytes (6%) of program storage space. Maximum is 32,256 bytes.
Global variables use 210 bytes (10%) of dynamic memory, leaving 1,838 bytes for local variables. Maximum is 2,048 bytes.
  avrdude: ser_open(): can't open device "\.\COM1": The system cannot find the file specified.
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
This report would have more information with
  "Show verbose output during compilation"
  option enabled in File -> Preferences.

I don't know what other information is important. Can somebody please help me?
Thank you.

When the port is greyed out its not available (I know you had worked that out) so you have a problem with you serial to USB drivers.
Looking at the kit I think you are connecting the UNO to a USB port on your PC/laptop using a blue cable.
 1. Please can you check that the cable is connected properly.
 2. Can you try a different USB port on the PC (don't use a USB hub - some don't work).
 3. Does Windows recognise a device has been plugged?
 4. Are you running it as administrator, you will need to be to install the drivers.
 5. Can you try connecting it to a different PC?
If these don't fix it then, please comment and well go through looking at the device manager.
Hope it works, it looks like fun.

Matt, thanks for answering.  yes, i've conected the blue USB cable, the device manager sees it as an arduinu Uno.  i changed the com port in device manager to com1. (took me a minute to figure out that the com ports were hidden)   And yes i an running it as administrator.

Why did you change the com port in device manager?  Normally mine show up as 3, 4 and 22.  It's possible you already have something on com1 and this is preventing the ide using it.  Also it's worth rebooting, because this can free a com port that has been locked by a process that's crashed.

it was originally 3 and didn't work.  i changed it to 1 because that is what the error said it was set on.  and since i can't change the port in the arduino IDE, i figured it was worth  shot.  and i definately tried rebooting as well including rebooting with the uno hooked up.

Is it an original uno or a clone? Clones can sometimes be awkward. Have you got a spare cable?  You might want to try uninstalling the drivers, reboot and then try again (I had to do that for one board).  It's possible the cable is dead, the board could be fried (unlikely) or your PC could be being awkward.  The setup you have should work, so it sounds like a fault rather than attempting the impossible.

it is an original board i believe.  i'm going to try to find another cable.  if my computer is identifying the board in device manager then the cable should be working though right?  i'll try a new cable tonight.  i really do appreciate your time.

Yes, the cable is fine, my brain isn't, slight glitch there.


text:
NodeMCU sensor values to web page
I post NodeMCU sensor values to a web page. But how can I pass those values to a database using PHP?
Here is the code to post sensor values to a web page:
#include <ESP8266WiFi.h>

const char* ssid = "CDS_ARDUINO";
const char* password = "arduinotest@wifi";

WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  // Start the server
  server.begin();
  Serial.println("Server started");
  // Print the IP address
  Serial.print("Use this URL : ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("Connnection: close");
  client.println();
  client.println("<!DOCTYPE HTML>");
  client.println("");
  client.println("<meta http-equiv=\"refresh\" content=\"3\">");
  client.println("
Getting NodeMCU Analog values
");
  int sensorReading = Serial.read();
  client.println("");
  client.println("");
  client.println("
");
  client.println("");
  client.println("");
  client.print("
");
  client.println("");
  client.print("&nbsp &nbsp &nbsp &nbsp &nbsp");
  client.print(" Analog input value is ");
  client.println("");
  client.print(sensorReading);
  client.print("
");
  client.println("");
  delay(100);
  Serial.println("Client disconnected");
}

Before your question gets closed, since it's only merely related to Arduino, I'd like to post this answer to give you more of an clue on how to set up the system.

Connect PHP and the database of your choice.
Connect the Arduino to PHP (probably with TCP/IP or HTTP), to send the values to the database.
Use PHP (+ webserver) to generate and serve webpages.

Only point 2 is somewhat related to Arduino.SE, so I'll try to give you some "handles" to get started.
https://www.arduino.cc/en/Tutorial/WebClient
https://www.arduino.cc/en/Tutorial/HttpClient
You can issue a GET request with variables to a webpage using Arduino.
In PHP you can read out these variables.
And using PHP you can connect and send variables to your database.
You shouldn't connect the Arduino directly to the database, because exposing your database to the world wide web is a security risk.
After this, it will be relatively easy to generate a page with the contents from your database.