text:
Efficient way to store array with repeating values?
So I have about 2000+ X and Y values where I will look up the Y value for a given X value. If I store the values naively they won’t fit in memory, however there are a lot of repeating values and the X values are arranged in numerical order so I don’t really need to store them explicitly.
So my plan is to use the 3 most common Y values and have an array for all the Y values with only 4 possible values (So using only 2 bits with a bitfield), where 0,1 and 2 corresponds to the most common Y values and 3 tells the program to go fetch the value somewhere else, and here I am thinking a hash table/tree.
Before implementing all this stuff I thought I would ask here if anyone has a better way of doing this, such as if it’s possible/recommended to use the flash memory on the arduino for this or if there’s some better way to store the data. The Y data consists of analog read values which hover around a specific value (say 800) and vary +- 20 or so. I think a histogram of the Y data follows a normal distribution, but I currently do not have enough data to tell.

Could you give an example of how the data would look? How fast would lookup need to be?

Without a better understanding of what the data is or how you intend to use it it's impossible to give you real recommendations.
However it is simple enough to store your data in flash memory.
Since X is just a sequential value it can, as you have noted, be ignored.
For the rest, a simple array in flash which you then read with pgm_read_<X>() where <X> is the data size that you are using.
All this can be read on the Arduino PROGMEM Reference Page although the documentation is not great.
So here's a little example:
const int values[] PROGMEM = {
   100, 399, 2847, 1, -497, 32, 4370
};

void setup() {
    Serial.begin(115200);
    for (int i = 0; i < 7; i++) {
        Serial.println((int)pgm_read_word(&values[i]));
    }
}

void loop() {
}

The casting of the return from pgm_read_word as an int is needed to interpret the sign bit properly (it returns unsigned by default).

Nice, that would completely solve the memory issue :D What’s the speed penalty for storing the data in flash memory? I need to read relatively fast, I’m running the ADC at around 30 kHz and need to read data inbetween reads. From my understanding of flash memory it reads chunks at a time, right? So I could load parts of the array and store that in RAM while using that part of the array?

@BeaconofWierd At the time scales you are talking about the speed is negligible. No, flash does not read in chunks. It erases in pages, and writes in rows, but reads in bytes. It's just part of the instruction memory address space. Yes, it's slower than reading RAM, but only very slightly slower.

Ah, that makes it even simpler :) I updated the question with a more detailed explanation of how the data looks like. Even though I can store it in flash memory I probably still want to store it efficiently and you seem like the type of person who likes to think about how to store data efficiently ;)

@BeaconofWierd You would have to analyse the data more deeply to come up with some suitable storage system. And then you have to consider the increased time taken to decode your compressed data. If all your values are a small amount varying around an offset you can reduce your storage size by half by using a signed byte to store just the offset (±127). If you could reduce your values to just a selection of 16 discrete values you could store them in nibbles as 0-15 (2 values per byte). Or you could pack 3 values into 2 bytes for 5-bit (0-31) values (with 1 bit wasted per 2 bytes).

@BeaconofWierd: On AVR, reading from RAM takes 2 CPU cycles per byte. Reading from flash takes 3 cycles/byte. If you store 16-bit values, flash vs RAM is only 2 cycles difference. If you store an 8-bit offset, it's one cycle difference. Negligible in both cases if you only read one value every 33 µs.


text:
How to set an array size to a variable which might change later into the code?
I'm trying to initialize an array globally which could be of different sizes according to future code in Arduino.
int n=0;
int val[n];
This says that the array bound is not an integer constant before ']' token. This also says that the val variable wasn't declared.
I have browsed other forms and have been told to use dynamic storage usage which I don't know how to use.
I'm trying to store different weight values respective to time in a variable. I first tried to store the weight in one variable but couldn't find the total weight etc.

Please edit your question and add the code in "text format". There is a "button" on the Edit window tool bar that looks like this {}. Highlight all of your code then click it.

This looks like an XY problem to me. The array of variable size is not the real goal, and is most likely a bad idea in the first place. What is your real purpose? What are you trying to accomplish?

why not use int val[10] or int val[50]?

As others have suggested, dynamically allocated memory is often problematic on a memory-starved device like an Arduino. As you create and release memory, the "heap" (a pool of memory to be used for that purpose) gets broken up into "islands" of free memory with still-used blocks of memory peppered throughout.
In fairly short order you wind up with your available memory pretty much unusable, your app runs out of available memory, and your app crashes.
This is known as "heap fragmentation". When you only have a couple of K of RAM to work with, it quickly becomes fatal.
If you can be sure that you allocate a dynamic buffer in a function call sequence, don't do any other dynamic memory allocation, and then free it before returning, you can probably get away with it without fragmentation, but you really have to be careful.
If you instead dynamically allocate a block of memory very early in your app's life and then keep it for the entire run that can be okay too. That block takes a chunk of your heap and just stays there.
A third alternative is to allocate a statically sized array at compile time that's big enough for your largest use, and treat that as a buffer. You can save contents there as needed, then when you're done with those contents, use the buffer for something else.

The Arduino platform uses a C / C++ compiler.  In C++ one can use features such as Vectors to create what appear as arrays of varying sizes.  However, it is likely memory is wasted when trying to abstract the memory usage from the application in this way.  In an embedded environment, memory is likely at a premium.  Consequently, it is almost always better to handle array sizes in embedded situations by allocating the expected amount manually at the beginning of the program.
Tip: If the size of the array depends on the situation the application is used in and there are advantages of smaller verses larger arrays depending on the application, try using Conditional Compiling to create different versions of the application.

In general arrays declared like
int array[n];

needs a constant size n, so that the correct memory size can be allocated at the time of declaration. Otherwise the compiler doesn't know what to do with that variable. You cannot change the size of an array, especially not by simply assigning values to non-existent elements. To create a new array with a size unknown at compile time, you would need to use dynamic allocation:
int *array = new int[n];

The variable array is actually not the array itself, but a pointer to an integer array. The compiler will create the pointer variable, which will only hold an address, where the new dynamically created array is stored. With the new keyword we are allocating a new memory space. With int[n] we are telling the program to allocate space for n integers. You can create arrays with sizes unknown at compile time, but you cannot change the size of an array. You would need to create a new one to change size. Dynamically allocated storage, that is not needed anymore should be freed. (You can google more about this)
BUT: On an Arduino you should not use dynamic allocation. If you use the dynamic allocation too much (over and over again) in a program, you will get memory fragmentation. As you allocate and free memory of different sizes, you will get many small memory spaces, which are too small to hold your new arrays. So this memory is now useless and Arduinos only have very little RAM to use for dynamic memory. When your RAM is full, your program will crash. Real computers - in contrast - have loads of memory, so that is not a problem there.
It is better to allocate your memory statically, with enough space to handle your biggest expected amount of data. So you should really think about, if you really need dynamic allocation. I would say no.

There are also other problems with your code.

You use the following for loop:
for(n = 0; isFinished = true; n++)

A single = marks an assignment. So at the start of every for loop iteration you are assigning true to isFinished. And every assignment will evaluate as true. So you have an infinite loop there. If you want to check for equality, you need to use == (double equal sign). Also in that for loop isFinished newer changes. You initialize it with false, so the loop will not run once. If you instead check for it to be false the loop  will be infinite, since there is no possibility, that this variable changes inside the loop. Instead use n for the loop condition and run the loop as many times as you have elements in your array.
Generally your logic seems not well thought through. You are already using a for loop to measure multiple values, so why don't you just directly measure as many values, as you want to measure, by using the for loop as described above. Then you don't need all the isFinished stuff, because you will always have all the needed values, when you exit the for loop. So you also don't need to check, if there are enough values measured. And it is not clear, what the threshold check should do.

source: Stack Exchange

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

sort: votes


text:
Failure to recognize the Arduino Mega2560 R2 board by the computer
I am using an Arduino mega2560 R3 My Arduino port is not recognized by the computer.led on is green,leds Tx and Rx are yellow and led L is blinking constantly(According to the figure).I used an Arduino Uno to upgrade the Arduino Mega bootloader(According to the figure)  but the problem with the Arduino Mega board was not resolved.What do you think is the solution? Is the mega board burnt?m
I tested the communication cable, there was no problem.I also tested a UNO board that had no problems and was programmed by computer.

If the PC isn't recognising it then the problem is anywhere between the PC and the ATMega16U2 USB interface chip (the small square one by the LEDs).

I tested the communication cable, there was no problem.I also tested a UNO board that had no problems and was programmed by computer.

Did you test a different PC?

Then you should consider re-burning the firmware on the USB chip.

The "L" LED is controlled by the main MCU. This is blinking because the bootloader is running fine. There is nothing (superficially) wrong with the main MCU.
The TX ad RX LEDs are controlled by the ATMega16U2 (or 8U2 or 32U2 depending on the board version) chip which forms the USB interface bridge. These being solidly on are a bad sign. Normally they would be off until some form of communication between the PC and the main MCU (via the 16U2) takes place. This is not happening. If it were a faulty cable then the LEDs would be off. If the PC were not configuring the port the LEDs would be off. But they're on. Therefore the fault is most likely with the 16U2 itself.
Either the chip has been physically damaged (maybe through overvoltage or other misuse) or it has "forgotten" its firmware, either again through misuse or having the firmware overwritten with something else (which can only happen if you specifically perform such an action through the programming header for that chip).
The first step of diagnosis is to try and communicate with that chip through the 6 pin header adjacent to it. You can do this in the same way as you do for programming the bootloader on the main MCU, but instead of programming a bootloader you program the 16U2's firmware (IIRC it's included with the IDE or the AVR core somewhere).
If that is successful and the LEDs start working correctly and the board starts to function again then it's cured. If not, then chances are the chip is dead.
If the chip is dead does that mean the board is dead? Not necessarily, no. It depends on how the board died. If only the 16U2 is dead and the main MCU is fine you can still use it, just not through the USB connection.  You could either use the TX/RX pins and your own external USB to UART interface to replace the 16U2 or program it through the ICSP (SPI) header using another Arduino or a dedicated USB programming dongle. It's less convenient, but means you can still use the board.

Insightful answer, great example of problem solving bit by bit. Thank you for taking the time.

Thanks for your full explanation

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


text:
USB FT232 driver on M1 mini
I've scored a couple Nanos with FT232RL chips but can't see them on my brand new M1 mini. Can someone point me at how to determine whether v11.1 supports this USB chip?
It appears that the device is being instantiated but the Arduino IDE gets no response to the Get Board Info.
FT232R USB UART:

  Product ID:   0x6001
  Vendor ID:    0x0403  (Future Technology Devices International Limited)
  Version:  6.00
  Serial Number:    AR0JT9YB
  Speed:    Up to 12 Mb/s
  Manufacturer: FTDI
  Location ID:  0x02214000 / 20
  Current Available (mA):   500
  Current Required (mA):    90
  Extra Operating Current (mA): 0

Executing the ioreg mentioned by @st2000 gives;
+-o Root  <class IORegistryEntry, id 0x100000100, retain 31>
  +-o AppleT8103USBXHCI@00000000  <class AppleT8103USBXHCI, id 0x100000291, registered, matched, active, busy 0 (1676 ms), retain 328>
  | +-o Extreme SSD@00200000  <class IOUSBHostDevice, id 0x10000081d, registered, matched, active, busy 0 (219 ms), retain 132>
  +-o AppleT8103USBXHCI@01000000  <class AppleT8103USBXHCI, id 0x100000295, registered, matched, active, busy 0 (4 ms), retain 39>
  +-o AppleT8103USBXHCIFL1100@02000000  <class AppleT8103USBXHCIFL1100, id 0x1000006eb, registered, matched, active, busy 0 (1220 ms), retain 494>
    +-o Keyboard Hub@02100000  <class IOUSBHostDevice, id 0x10000071c, registered, matched, active, busy 0 (164 ms), retain 30>
    | +-o Apple Keyboard@02120000  <class IOUSBHostDevice, id 0x100000805, registered, matched, active, busy 0 (162 ms), retain 32>
    +-o 4-Port USB 2.0 Hub@02200000  <class IOUSBHostDevice, id 0x100000730, registered, matched, active, busy 0 (826 ms), retain 46>
    | +-o 4-Port USB 2.0 Hub@02230000  <class IOUSBHostDevice, id 0x100000785, registered, matched, active, busy 0 (11 ms), retain 42>
    | +-o 4-Port USB 2.0 Hub@02220000  <class IOUSBHostDevice, id 0x100000791, registered, matched, active, busy 0 (16 ms), retain 43>
    | | +-o Backup+ Hub@02223000  <class IOUSBHostDevice, id 0x1000007dc, registered, matched, active, busy 0 (6 ms), retain 41>
    | +-o 4-Port USB 2.0 Hub@02210000  <class IOUSBHostDevice, id 0x10000079d, registered, matched, active, busy 0 (776 ms), retain 43>
    | | +-o FT232R USB UART@02214000  <class IOUSBHostDevice, id 0x100007622, registered, matched, active, busy 0 (75 ms), retain 23>
    | +-o 4-Port USB 2.0 Hub@02240000  <class IOUSBHostDevice, id 0x1000007b6, registered, matched, active, busy 0 (12 ms), retain 42>
    +-o 4-Port USB 3.0 Hub@02600000  <class IOUSBHostDevice, id 0x100000749, registered, matched, active, busy 0 (231 ms), retain 46>
      +-o 4-Port USB 3.0 Hub@02620000  <class IOUSBHostDevice, id 0x10000075e, registered, matched, active, busy 0 (170 ms), retain 43>
      | +-o Backup+ Hub@02623000  <class IOUSBHostDevice, id 0x1000007c3, registered, matched, active, busy 0 (155 ms), retain 41>
      |   +-o Backup+ Hub BK@02623100  <class IOUSBHostDevice, id 0x1000007ee, registered, matched, active, busy 0 (147 ms), retain 131>
      +-o 4-Port USB 3.0 Hub@02640000  <class IOUSBHostDevice, id 0x100000763, registered, matched, active, busy 0 (15 ms), retain 42>
      +-o 4-Port USB 3.0 Hub@02630000  <class IOUSBHostDevice, id 0x100000775, registered, matched, active, busy 0 (15 ms), retain 42>
      +-o 4-Port USB 3.0 Hub@02610000  <class IOUSBHostDevice, id 0x1000007a9, registered, matched, active, busy 0 (16 ms), retain 42>

Which does not appear to contain the device afai can see. Any know if this means a new device for Big Sur is indicated as per Majenko♦ ?

@Majenko - You've just added the answer to the edit which I did, which had already added, and formatted, the answer. I suggest rolling back to edit #2 :-) Also, w.r.t. my two declined flags, now RowanP's comments, on the (now deleted) answer, can't be seen. They should be moved to this question.

I run macOS Big Sur on M1 silicon (a new machine installed in the last month) and also  FT232RL interfaces (e.g., cheap HW-417-V1.2 unit). I just went back through my downloads used in setting up the machine, as far as I can recall I did not have to download the FTDI driver which I used to on the previous older machine. This supports @Majenko's answer regarding a built in driver. I read a little more about this here. If anyone can point to more information about the built in driver that would be awesome.
I use ls /dev/cu.* in a terminal window to check which USB devices are plugged in. Mine shows up as /dev/cu.usbserial-A5XK3RJT
On the macOS desktop, the [Apple Icon]\About this Mac\System Report\USB information (which I think is a GUI representation of the ioreg mentioned above?) shows the device as:
FT232R USB UART:

  Product ID:   0x6001
  Vendor ID:    0x0403  (Future Technology Devices International Limited)
  Version:  6.00
  Serial Number:    A5XK3RJT
  Speed:    Up to 12 Mb/s
  Manufacturer: FTDI
  Location ID:  0x02240000 / 17
  Current Available (mA):   500
  Current Required (mA):    90
  Extra Operating Current (mA): 0

If non-standard PIDs or VIDs are causing devices to be blocked, then a possibility (which I have not tested) might be just to reflash the config on the FTDI device see: dangerousprototypes - how to get a nicely named serial device.
Use ls /dev/cu.* in a terminal window to see if the device is showing as a call-up USB device. Then in Arduino IDE rather than using "Get Board Info", just set Tools/Port to that USB port and try to upload a sketch. The port should show up as /dev/cu.usbserial-AR0JT9YB or similar.
The FTDR device is in the ioreg output you posted, I believe it's hiding there as:
FT232R USB UART@02214000 <class IOUSBHostDevice, id 0x100007622, registered, matched, active, busy 0 (75 ms), retain 23>

As an addendum to @st2000's answer, it's worth noting that OS X comes with a basic driver for FTDI built in. However if your device uses a non-standard VID or PID it will not work.  At the time of writing this, according to this forum thread, FTDI have not yet written an updated driver for Big Sur, and seem to be struggling to do so (they have been writing one for the past year and still haven't managed it).
This should not apply to an Arduino that uses an FTDI with default settings, but worth noting for some custom devices.

A MAC is usually (unless it is really old) running a derivative of Unix. I would open a console install and use "lsusb" to list out all the USB connected devices.
A (Linux) example of lsusb:
$ lsusb
Bus 001 Device 004: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port

I would do this with and with out the Arduino FTDI chip connected and look for the difference. This stackexchange question/answer contains how to do this on a MAC or use other MAC commands to do the same.  As pointed out in the comments the more native MAC command is:
ioreg -p IOUSB

Note, if you have fake FTDI chips there was a time when the FTDI driver that Windows ran would brick the fake FTDI chip. I think it would assign the vendor and device IDs both to zero. You should be able to see this with the "lsusb" command.

On OSX the equivalent command is ioreg -p IOUSB

Thanks @Majenko.


text:
Newbie Arduino DC motor problem
So I am new to Arduino and new to electronics in general. I've looked up a few tutorials and they all have a simple early tutorial that turns on a DC motor and turns it off again. Something like this:

(source: cloudfront.net)
The transistor I am using is a 2N2222 and the motor is a little 3V DC toy motor.
The problem is that the when I use this circuit, the motor barely turns (I need to give it a little help to get it it moving). I know my code is right (motor is on for 5 seconds, off for 1). i can tell this is working but clearly something is not right.
I am powering the Arduino off the USB port.
As a test, I swapped out the 2.2K Ohm resistor for a 560 Ohm resistor and the motor seems to run fine. However, it creeps during the "off" time (the motor is not under any load). Also, the transistor gets very hot after about a minute of running this loop.
So my questions are:

Why does the motor not work when I use the 2.2K Ohm resistor when I see that 2.2K Ohm resistor in different circuit diagrams that demonstrate this type of circuit?

Why does changing to the 560 Ohm have the effect that it does

Why does the motor creep during the off cycle when using the 560 Ohm?

Why does the transistor get so hot using the 560 Ohm resistor?

Finally, sometimes as a test, to simple try to turn turn the motor on, I will just reroute to pin 9 wire directly to the Arduino 5V on my breadboard (bypassing Arduino control altogether). Is there any reason this is a bad idea?

I am anticipating questions about current draw but my multimeter maxes out at 200mA; I am getting a new one that goes to 10A and will help me see how much I am drawing.
Thanks in advance of any help. I have tried to be clear and concise so hopefully this does not elicit any snark. If there are any resources to point me to, I would be happy to hear them.
Thank you!
Jim

Are you using external power source? USB is not strong enough for driving DC motor.

Are you sure you have wired the transistor the right way round?

The transistor is a current driven device. When it is saturated the CE voltage should be around 0.7V, if more as you will see with the 2.2K you are not driving it hard enough, something in the 200 Ohm range should work nicely although the 560 might depending on the transistor gain. Try using a voltage driven device with the same circuit with a Logic Level avalanche rated N-Channel MOSFET (C-D, E=S, B=G) rated at a few amp. With the avalanche rated MOSFET you can leave the diode off. Expect much better performanced and a lot cooler part. The MOSFET will be cold  it is not burning power as heat.

I see a couple of issues here, which are related to your questions. I will use numbers here, but these do not necessarily correspond to the numbers you have used when asking.

The first thing you need to do when controlling a motor is to know it maximum stall current. The stall current is the current that will circulate through the motor (and through the transistor) when you apply an external force to stop the motor's shaft. But it's also the same current needed for the motor to start when it's completely stopped. So, for dimentioning a transistor, you typically will select one that has, as a rule of thumb, a collector current two times bigger than the motor's stall current.
The 2N2222 has a maximum Ic of 800 mA (best case, since there are 600 mA versions as far as I know). Although you are not specifying much about your particular motor, a typical 3V DC motor may easily be asking for 500+ mA. Some small motors (specially bad quality ones) may have stall currents bigger than 1 A.
If your motor is asking for, let's say 300 mA when continuously running, then, you are near enough of the maximum current of the 2N2222.
But there is something more important here: dropout voltage in the transistor. The 2N2222 is a bipolar one, so it will have a Vce superior to 1V (probably around 2V), which means that you are dissipating a non trivial amount of power in the transistor. That power is not useful for your motor, nor for your transistor. Here, if the motor has a 3V nominal voltage, the 2V dropout in the transistor is even desirable, but I don't see your calculations about the real dropout in your description. So I assume that you are just counting that there will be an approximate 2V dropout. That means that, if your motor is taking 0.5A to work, you are dissipating 2V x 0.5A = 1W (Watt) in the transistor. But the poor 2N2222 is a 0.5W transistor! But even if your motor is using much less current, let's say 0.25 A, you are sill using it at its limits. That will explain why it's getting hot.
So, my advice is to go for a bigger transistor, if you want to count on its dropout to do not apply a voltage bigger than 3V to the motor (which can really reduce it lifespan a lot), AND do some calculations to be sure that at the currents you are using, you will have the Vce that you want.
Another option, probably better, is to replace that bipolar old transistor by a MOSFET, but you will need to provide the apropiate voltage for supplying the motor, since if not you will get nearly all the 5V to the motor (due to the very low Ron on Mosfets, and thus very low dropout voltage), and that will be very bad.
Also, please note that the 500mA of the USB port are probably not enough for your setup. But even if you are powering your Arduino from an external power supply through its power jack, you will find a good idea to use common grounds but different Vcc sources for logic and for the motor.
Finally a short advice: be sure that the diode protecting the back EMF (the diode connected with its cathode to Vcc in your circuit) is a fast diode. A slow, 1Nxxxx diode is usually to slow for effectively protecting your transistor. If you are using for example an 1N4007, you can switch to a UF4007 (Ultra Fast).
Regarding your 560R vs 2K2 resistor, this exceeds the answer a bit, so my advice is to read something about base resistors in transistors, like this. Also something about open collector configurations may help.
Finally, the practice of connecting the base resistor to Vcc in this kind of circuit to test the transistor should be fine. But DO NOT CONNECT the transistor's base directly, use always the resistor.

The links to the evilmadscientist alone is worth a +1, but very nice answer. I have the same issue with a sample Arduino kit and a motor that stalls at start so now I know how to approach it.

***ERROR CORRECTION: Sorry all, I did have one error in my code that explains the creep. I thought I was running a loop to simply turn the motor on and off but actually it was running full on for 5 sec (255) and partial speed (120) of 1 sec, thus the creep. When resetting the code to on on for 5 sec, fully off for 1 sec, with a 560 Ohm resistor, things work as expected. (I still have the problem with the 2.2K Ohm though so most of my question stands.
nbloqs, Thank you ; I will review your answer in detail.
What would so many tutorials show this basic schematic if to has so many issues?
Thanks again!

Some of the tutorials are designed for kits that come with motors where they know the currents involved. Also, usually they are pretty basic and most of them will not deal with base resistor values, or proper transistor selection. I was not saying that the 2N2222 will not work, but it will probably operate at its limits and thus will be heating (specially if the motor is kind of unknown). Regarding your resistor, I added point 9 to my answer.

Also added point 10 about your "test with Vcc" question.

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


text:
Arrays, and for loops... faster to use together, or not to use?
I'm a 4th year EE undergrad, so I'm more of a hardware guy than software. But concerning best programming techniques, is it "better" (more efficient/and/or equally effective) to use for loops when trying to change several items in an array by the same mathematical operation?
--OR--
Is it best to list each item out and have each operation performed by the rate at which the primary "void loop" cycles?
I'm using a Teensy 3.2 board and trying to get a DSP reverb effect working. I have an array of 8 delay tap lines, each with a different time multiplier. I'm trying to determine if it will take more time to process a for loop for each delay-tap line, versus multiplying each element in my array without the additional loop. I need to minimize processing time at all costs to avoid additional system lag.
Sample code:
  //Set delay times
  for(int i = 0; i < 8; i++)
  {
    delay1.delay(i, pot1*pauses[i]);
  }

versus
  delay1.delay(0, pot1*pauses[0]);
  delay1.delay(1, pot1*pauses[1]);
  delay1.delay(2, pot1*pauses[2]);
  .
  .
  .

EDIT
Added sample code.

can you give some pseudo-code for each method?

Sure, I updated the original post. It likely seems like a trivial question since any dummy wouldn't want to write out 10 lines of repetitive code--most applications that aren't time-sensitive. But I recall trying to do something similar with my Uno board (8MHz) and drawing lines to an OLED. Using "For" loops significantly increased the drawing time.

is it "better" (more efficient/and/or equally effective)

depends on your definition of "better", or "efficient", ...
for example unrolling a loop is typically more efficient speed-wise, but less so space-wise. or vice versa.
on top of that, you have other potential definitions for "efficiency", like readability, etc.

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


text:
Download and print data from Thingspeak
I opted to try doing this with Thingspeak Library instead, which @gre_gor suggested early on. Worked much easier!
Here's working code for anyone else trying to do this. I used the MKR1000.
#include "ThingSpeak.h"
#include <SPI.h>
#include <WiFi101.h>
#include "DHT.h"

char ssid[] = "XXXXXX";    //  your network SSID (name)
    char pass[] = "XXXXXXX";   // your network password
    int status = WL_IDLE_STATUS;
    WiFiClient  client;

unsigned long myChannel = CHANNEL;
const char * myReadAPIKey = "READKEY";
const char * myWriteAPIKey = "WRITEKEY";

#define DHTPIN 1
#define DHTTYPE DHT11
DHT dht(DHTPIN,DHTTYPE);

void setup() {
  // put your setup code here, to run once:
 Serial.begin(9600);
WiFi.begin(ssid, pass);
 ThingSpeak.begin(client);
  delay(10000);

}

void loop() {
 printWifiStatus();
    Serial.println("Reading Sensor Data... ");

  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
    float water = ThingSpeak.readFloatField(myChannel, 4);

   delay(100);

    Serial.print("Writing to ThingSpeak... ");
    ThingSpeak.setField(1, (float)h);
    ThingSpeak.setField(2, (float)t);
    ThingSpeak.setField(3, (float)f);
    Serial.print("... ");
    ThingSpeak.writeFields(myChannel, myWriteAPIKey);
     delay(5000);

  Serial.print("Current temp is: ");
  Serial.print(f);
  Serial.print(" *F and ");
  Serial.print(t);
  Serial.println(" *C");
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.println("% ");
  Serial.print("Water Signal: ");
  Serial.print(water);
  Serial.println(" seconds");

  Serial.println("Function complete, time to rest.");
  delay(10000); // Hibernate [To Do]

}

void printWifiStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

------------ ORIGINAL MESSAGE ------------------------------------------------
I've been banging my head against this for a week now and I have made no progress.
I'm trying to convert this code to also read a field on Thingspeak and print to serial (as well as run a pump based on the output). I've tried a handful of guides and recreating it from other projects to no avail. Is there a straightforward method?
#include <SPI.h> //you don't need this as we arn't using the shiled just chip
#include <WiFi101.h>
#include "DHT.h"

#define DHTPIN 1    // what pin we're connected to, pin1 is 5th pin from end
#define floatswitch 7 // float switch
// soil moisture sensor
int soilPin = 2;
int soilPower = 6; //Variable for Soil moisture Power

// light sensor

// Uncomment whatever DHT sensor type you're using!
#define DHTTYPE DHT11  // DHT 11
//#define DHTTYPE DHT21  // DHT 21
//#define DHTTYPE DHT22  // DHT 22

DHT dht(DHTPIN,DHTTYPE);

String apiKey ="XXXXXXX"; // api from ThingSpeak

char ssid[] = "XXXXX"; //  your network SSID (name)
char pass[] = "XXXXX";    //your network password
int keyIndex = 0;     // your network key Index number (needed only for WEP)

//#define WEBSITE "api.thingspeak.com"

//int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "api.thingspeak.com";    // name address for Google (using DNS)

// this function powers and reads the moisture sensor to avoid sensor corrosion.
//int readSoil()
//{
  //  digitalWrite(soilPower, HIGH);//turn D7 "On"
    //int val = analogRead(soilPin);//Read the SIG value form sensor
   // return val;//send current moisture value
   // digitalWrite(soilPower, LOW);//turn D7 "Off"
//}

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

void setup() {
  pinMode(floatswitch,INPUT_PULLUP);

  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }

}

void loop() {

pinMode(soilPower, OUTPUT);//Set D7 as an OUTPUT
 // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);
//Connect to WPA/WPA2 network.Change this line if using open/WEP network
WiFi.begin(ssid, pass);
digitalWrite(soilPower, HIGH);//turn D7 "On"
    // wait 5 seconds for connection:
    delay(5000);
  Serial.println("Connected to wifi");
  printWifiStatus();

// READ STUFF

String url = "/channels/358435/field/6/last.txt";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
        "Host: " + server + "\r\n" +
        "Connection: close\r\n\r\n");
    String channelData = client.readStringUntil('\n');
// READ STUFF

  int h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  int t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  int f = dht.readTemperature(true);
  int x = digitalRead(floatswitch);
//This is a function used to get the soil moisture content
  int s = analogRead(soilPin);
  int w = 5;

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f))
  {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Soil Moisture: ");
  Serial.print(s);
  Serial.print(" *F ");
  Serial.print("Float Switch: ");
  Serial.print(x);
  Serial.print("channelData");
  Serial.println();

Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {

    Serial.println("connected to server");

          client.print(F("POST "));
          client.print("/update?key=apiKey&field1="
          +               (String) h
          +  "&field2=" +(String) t
          +  "&field3=" +(String) f
          +  "&field4=" +(String) s
          +  "&field5=" +(String) x
          +  "&field6=" +(String) w
                                   );

          String tsData = "field1="   //need the length to give to ThingSpeak
          +             (String)  h
          +  "&field2=" +(String) t
          +  "&field3=" +(String) f
          +  "&field4=" +(String) s
          +  "&field5=" +(String) x
          +  "&field6=" +(String) w
        ;

          client.print("POST /update HTTP/1.1\n");
          client.print("Host: api.thingspeak.com\n");
          client.print("Connection: close\n");
          client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
          client.print("Content-Type: application/x-www-form-urlencoded\n");
          client.print("Content-Length: ");
          client.print(tsData.length());  //send out data string legth to ts
          client.print("\n\n");
          client.print(tsData);
          client.stop();
          digitalWrite(soilPower, LOW);//turn D7 "Off"
          delay(200);
          Serial.println("Function complete, time to rest");
          WiFi.disconnect();

//This is where to put the sleep and hibernate stuff

          delay(20000);

//hibernate stuff ^^^^
    }

}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

Why not use a library and check the examples?

Sorry, I should have mentioned that. Trying not to get stuck with the Thingspeak library as I've read it gets buggy when other libraries update. Also trying to remain platform agnostic so I can plug this into Adafruit.io, AWS or whatever other data platforms come along down the road.

https://www.mathworks.com/help/thingspeak/get-channel-field-feed.html

Thanks @Juraj I ddi try working through that and another question on SE here, but it came down to basically the following, but still didn't work.
String data = "GET /channels/344468/fields/1/last";

Serial.println(data);

post the code of modified sketch

Tried updating based on iohans answer.

@gre_gor I decided to try using the Thingspeak library. And it worked so much better. Updated the question. Thanks!

You need to construct a client object and pass in a URL. Then, wait for a response and read data in from the client. Here is the main concept.
const char host[] = "api.thingspeak.com";

WiFiClient client;

const int httpPort = 80;

if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
}

String url = "/channels/1417/field/1/last.txt";

client.print(String("GET ") + url + " HTTP/1.1\r\n" +
        "Host: " + host + "\r\n" +
        "Connection: close\r\n\r\n");

while(client.available()) {
    String channelData = client.readStringUntil('\n');
    // do something with the data

}
Make sure to include a Read API key if your channel is not public. Also, check out CheerLights project examples for more ideas on how to do this. Many CheerLights projects read data from a a ThingSpeak channel.

Thanks iohans! Tried dropping it in betweet brackets of // READ STUFF still working on it though, but first time it has still sent data while trying to do a GET request.

There is a lot to tighten up in your code. Move these lines to set up

pinMode(soilPower, OUTPUT);//Set D7 as an OUTPUT
// attempt to connect to Wifi network:
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
//Connect to WPA/WPA2 network.Change this line if using open/WEP network
WiFi.begin(ssid, pass);
digitalWrite(soilPower, HIGH);//turn D7 "On"
// wait 5 seconds for connection:
delay(5000);
Serial.println("Connected to wifi");
printWifiStatus();

Also, you need the while client available to read the data into your string variable. The get is asynchronous, so the data is not ready immediately. You should separate read from write, and clear the client for each connection.

You've given me a lot of homework, thank you! Going to dig in tonight. One question about getting that into Setup, I want this to hibernate for several hours and turn off the wifi et all. Should I still move that to setup or put it in a separate loop like the printwifi status if I'm thinking about power saving.


text:
2D Tracking of an object - which sensor?
I'm currently working on a project for which I require a sensor. I've made a quick and simplified drawing of what the result is supposed to do:

Basically, I want one LED of a LED-Strip to light up dependent on the location of a moving object. If the object in above image (say a slow rolling ball) were to move from bottom to top, then the LED strip should also light up from bottom to top. I have no problem getting the LED strip to light up adequately, however I'm not sure which sensor actually can pick up objects as required in this case.
As I've understood regular IR sensors can only detect if there is an object and how far it is away, however they can't pick up said object's relative position on the y-axis. Is there any way to do this rather easily, perhaps with triangulation? I've looked into Bluetooth and RFID but haven't found anything particularly useful.

Why not just infra-red beams going to detectors. As the object travels it breaks different beams and triggers different LEDs. You don't even need an Arduino to do it.

How small can the IR beams become? I was under the impression that they would always scatter and thus interfere with each other.

Depends on how good your lenses are. If you want ultra-narrow then use lasers.

I feel that an array of IR transmitters and receivers could work for you.
If you put the transmitters/receivers in an recessed tube with (black, non-ir reflectant) separations, you can avoid crosstalk.
You should be wary that it may require some tweaking to find the right sensitivity.

Here is a video (and here) that shows this in practice. I like the fact that you don't need sensors on either side of the object.
You may also consider video-processing, but that's out of scope for Arduino.
Or use a Lidar.

There are many solutions to the problem.  For a free moving ball confined to a square flat surface with sides:

Choose IR LEDs mounted at such a height and distribution to be
blocked by the rolling ball.  Make sure at least 1 IR LED is blocked by the ball no matter where it is located.
Line two adjacent sides with strips of these IR LEDs.
Use the Arduino to light each LED one at a time at a frequency of about 40KHz.  Scan all LEDs within a second.  This should be adequate to locate a slow moving ball in 2D space.
On the two opposite sides mount a ASK Remote Control receiver.  A common device easily harvested from old entertainment equipment or bought from electronics part supply houses.
Use the Arduino to sense when the ASK Remote Control receiver detected or did not detect the flashing IR LED.
When the Arduino finds an IR LED that is not detected, the ball can be assumed to be between the IR LED and the ASK Remote Control receiver.

Note, the patter of intersecting lines will look more like two sets of bicycle tire wheal spokes.  Not like a checker board.  It may be better to confine the ball to a smaller square then that of the square where the transmitting IR LEDs and ASK Remote Control receiver are mounted on.


text:
Is there any way I can stop the Arduino Mega 2560 from resetting all variables after losing and reconnecting power?
I am using an Arduino Mega 2560 board. I have tried connecting a 115 Ω resistor from 5V to Reset, and 10 µf capacitor form reset to GND (to disable autoreset), and the variables still seem to reset themselves when I unplug and replug-in the Arduino. Any way to stop this from happening?
Basically I am making a device that is sensitive to time, and must run for about 2 months, but if it is unplugged, it can't lose its place in time and reset the whole program.
I think one alternative would be for me to have it actually write how long it has been running into a .txt file on the microSD card and then verify that in the start-up...
Any ideas?

You have a power supply other than the USB connection, right?

Save the variables you need to EEPROM.

If you can't give the MCU enough warning of a power-down to save its critical variables, you'll have to keep it alive with batteries, sleeping if necessary, until the power comes back.
Tying Reset high won't help. The chip resets at power-up - that's built in. In fact, a power-up reset and a grounded-Reset-pin reset behave a bit differently - see the datasheet. Even if it didn't reset on power-up, the RAM needs power to maintain its contents, so it loses them when it drops.

Arduino Mega board has RESET-EN "jumper". If you cut the trace, it won't reset MCU by DTR from USB-to-Serial chip. If you have to upload new sketch, you'll have to short it by piece of metal.
There is also possibility to use .noinit section for storing variables, so if you don't loose power, it won't get overwritten by automatic init. However, bootloader could be messing with that memory too. So it might not help without erasing this bootloader and using ISP(SPI) interface to program it.
Or you can use for example RTC (if you already have one) and it's battery backed RAM.

Take power from UPS (uninterruptable power supply).

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Not all questions have direct answer. Variables are stored in volatile memory that doesn't work without power and upon power reset variables are reset. There is no way to stop it from happening due to Arduino (and most other uC) design restrictions. But workaround solutions are possible, as almost always ;-)   SD card, duplicate power supply, UPS, car accumulator of big capacity, Ethernet shield are just several examples.

The question is not on how to prevent power shortage but on restoring state after power shortage, hence I don't consider this answer relevant to the question. Also I guess the OP knows about UPS and did not need anyone to mention it.


text:
Write PWM with only 8 bit? (Timer2)
I have a problem with the Servo library.
I need to read a PPM signal and create a PWM signal of each channel. The problem is that PPM has a higher resolution than PWM so I want to use the 16 bit Timer1 for reading PPM. However the Servo library that writes the PWM signal also uses Timer1.
Is it possible to generate a PWM signal with 8 bit / Timer2? And has someone made an example, or an explanation about, how to do that?

Yes, there is example in this Tutorial

Maybe use the servo library as is, and do the PPM counting with timer2 with some overflow handling.

Yes, Arduino Servo library uses Timer1 (and other ones, depending on Arduino boards) to manage FastPWM via software interrupts. Timer2 is used by tone() function: be careful if you are using that function.
A good example using Timer2 to generate PWM is the Infrared remote library for Arduino. If IR_USE_TIMER2 is defined it will use Timer2. The key code is at IRremote.cpp where the ISR is managed.

Here is a simple example from my page about timers of using Timer 2 to output a square wave of 50 kHz:
const byte LED = 3;  // Timer 2 "B" output: OC2B

const long frequency = 50000L;  // Hz

void setup()
 {
  pinMode (LED, OUTPUT);

  TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1); // fast PWM, clear OC2B on compare
  TCCR2B = bit (WGM22) | bit (CS21);         // fast PWM, prescaler of 8
  OCR2A =  ((F_CPU / 8) / frequency) - 1;    // zero relative
  OCR2B = ((OCR2A + 1) / 2) - 1;             // 50% duty cycle
  }  // end of setup

void loop()
  {
  // do other stuff here
  }

Is it possible to generate a PWM signal with 8 bit / Timer2?

yes. I implemented multiple approaches, some on avrs and some on pics but the basic principles are the same: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/
that post provided a list of links to other implementations - one of them off a timer 2 on avr.


text:
esp8266- how to use GPIO0 as an input?
First, my setup:
I have an Arduino Uno with an Adafruit Audio Shield.  I have a Wemos D1 Mini controlling the project.
I need for the D1 to know when a file is playing.
I have a GPIO pin on the Uno programmed to be high when a file is playing.  Low otherwise.  I have two GPIO pins on the Wemos that are unused, D3 and D4 (GPIO0 and GPIO2).  (I use a divider circuit of a 10K over a 20K resistor to bring the 5V from the Uno down to 3v3 for the Wemos). D4 is already a problem because it has to be high to boot and the GPIO from the Uno is normally low. D3 (GPIO0) has to be high to boot and has an internal pullup.
Here's my problem.  How do I turn off the pullup on GPIO0? Even when the Uno GPIO is low (0V), the GPIO0 measures 2.4V, which my sketch sees as a logical 1.
Any tips would be appreciated.  (I thought of reversing the polarity on the Uno so that low=true, but even when the Uno is driving the pin low, the Wemos GPIO0 pin is still at 2.4V, so low-true logic won't work either.).

Don't use the voltage divider and never set the Uno pin HIGH.
Pull io 0 of esp8266 LOW with pinMode of the Uno pin.
pinMode(TO_ESP_IO0, OUTPUT); // sets the pin LOW

pinMode(TO_ESP_IO0, INPUT); // let it to the io0 pull-up resistor


text:
Press one button then another?
Let's say we have two buttons - button 1 and button 2. What I need to do is to do something (like turn LED on) when button 1 is press, then button 2 is pressed. I can do it realy simple by just using two boolean variables, but how can we tell button 1 was the first pressed button?

Look up what a "finite state machine" is.  Use interrupts or digitalRead to check status of the buttons.

A nice solution is to use a state variable. In C/C++ (thus Arduino) you can use an enum variable for that.
enum EState
{
  // Button 1 and 2 are not pressed
  NoButtonsPressed,

  // Button 1 is pressed, button 2 is not pressed
  FirstButtonPressed,

  // Both buttons are pressed
  BothButtonsPressed
};

EState _state;

void setup() {
  // put your setup code here, to run once:
  _state = NoButtonsPressed;
}

void loop() {
  // put your main code here, to run repeatedly:
  switch (_state)
  {
  case NoButtonsPressed:
    if (digitalRead(1) == HIGH)
    {
      _state = FirstButtonPressed;
    }
    break;

  case FirstButtonPressed:
    if (digitalRead(1) == HIGH)
    {
      // Button 1 is still pressed, ignore second button.
    }
    else if (digitalRead(2) == HIGH)
    {
      // Button 1 is not pressed, button 2 is pressed.
      _state = BothButtonsPressed;
    }
    break;

 case BothButtonsPressed:
   // Switch on LED
   digitalWrite(2, HIGH);

   // Reset state.
   _state = NoButtonsPressed;
   break;

 default:
   // Other state, illegal.
   break;
  }
}

In every state you can define exactly what needs to be done. Because of the loop function being ran continuously, you just need to handle one state (change) at a time.
Additional notes:

Your requirements are not fully complete (like when to switch off the LED), probably when button 2 is released (which I don't check for), you can add a new state for this.
I did not take debouncing of buttons into account; you might need to do this especially if you check for releasing buttons. On the official Arduino website there is a good article about it.
I haven't tested the sketch.

Thank you! This solution is great! :)

Nice clean answer. (Voted)

It looks like this code should not have button bounce problems because it ignores button presses unless it's in the state waiting for that button press, and then it advances to a new state where it will ignore that button press and wait for the next one. As you say, if you get more elaborate, like responding to button releases, it will need debouncing.

@DuncanC Thanks for the upvote and comment. In the example above debouncing is not strictly needed, although I can imagine the user wants to have the LED off after the second button has been released, without debouncing, the LED will stay on a ms or less after the second button has been pressed because the second button will be pressed (LED on) and bounces back (switching off the LED). If the requirements are that the LED should be on until the first button is pressed, than debouncing is not strictly needed.


text:
confirming this will blink LED at given frequency
I want to blink an LED at an specific frequency, ie: 7Hz
here what Im doing
int ledPin = 4;
float freq = 7;

void setup() {
  pinMode(ledPin, OUTPUT);
}

float periodo() {
  float peri = 1/freq;
  float halfer = peri/2;
  float millisec = halfer*1000;
  return millisec;
  //return ((1/freq)/2)*1000;
}

void loop() {
  digitalWrite(ledPin, HIGH);
  delay(periodo());
  digitalWrite(ledPin, LOW);
  delay(periodo());
}

Is this correct? is that the best way to do it?
thanks in advance!

In addition to the answer: I would not call  periodo in the loop if the freq does not change. Use a global int actPeriod variable and only initialize it in the setup function with  actPeriod=periodo(freq); and every time the preq variable might change (in comming revisions ;-)). Then use the new variable in the delay. With the actual code there would be no problems, but you asked for optimal code and if you add time criutial functionallity, it could matter.

You can check if it is correct by timing it for one minute and check if it is (approximately) ok.
However, I see a few improvements:

First is that you always return 1/7/2*1000 = 71.429, which is rounded down to 71. 71 * 14 = 994 ms so you get a bit faster speed than 7 Hz. if this is a problem you have to compensate for this.
Another small problem is that you delay, but the digitalWrite commands also take some time which is not included for the delays. So you need also to take this into account when using a precise delay.
When using floats I always use float constant numbers, like 1.0 and 7.0 instead of 1 and 7. This can especially be useful when you divide two integers (e.g. 1/7), which results in 0.14 this is rounded down to 0 as it is an int.

The best you can do is using the millis command. You keep a timer and compare it to the current millis value. If it is too high, do a state change. This will take into account every other method you do meanwhile the digitalWrites.
Something like: (code fixed due to EdgarBonet's remarks)
const float FREQ = 7.0; // Hz
const int PIN_NR = 4;

unsigned long _startTime;
unsigned long _counter;

int _currentState = LOW;

void setup()
{
  _startTime = millis();
  _counter = 0;
  _currentState = LOW;
  digitalWrite(PIN_NR, _currentState);
}

void loop()
{
  if (_startTime + _counter * 1000.0 / FREQ / 2.0 >= millis())
  {
    _counter++;
    _currentState = ~_currentState;
    digitalWrite(PIN_NR, _currentState);
  }
}

Some small notes:

_currentState is the current state of the LED, with ~ you can flip it (it's called the not operator).
_startTime is the (close to zero) value of the millis value at startup.
Take in mind there is a limit how long this app can run or precise. millis works with ms, meaning you cannot get beyond 500 Hz, and you get 'approximations' with frequencies below in some cases. E.g. when Freq = 80 Hz, you get 1000 * 1 / 80 / 2 = 1000 / 160 = 6.25 => 6, which is actually 1000/6/2=83.3 Hz.
Also the counter is added once per state change, and because of 1000 * _counter ... an overflow exists when _counter >= 256 * 256 * 256 * 256 / 1000 = about 4 million. With 1000 state changes per second, this happens after 4000 seconds, which is 66 minutes. For 7 Hz it will not occur fast.

This will make each interval 71 ms longer than the previous one, which means the frequency is modulated down towards zero. 2. This is prone to a rollover bug. Avoiding the bug is as easy as following the Blink Without Delay tutorial, so there is no good reason to keep the bug. 3. If you call millis() twice in a single loop iteration, you could very well get different results, in which case your timing calculations are off. Call millis() once and record the value if you need it twice. 4. Why these irritating underscores in front of every single variable name?

@EdgarBonet Thanks for your comments. 1 was indeed a stupid bug. 2. The Blink without delay tutorial is not exactly precise as the interval is a fixed value. It could be improved with some compensation though without having my 1000 multiplication resulting in a rollover. 3. Good point, I changed it in my code. 4 Not in every variable name, only 'global/class' variables, to make clear these are not local variables.


text:
Turn RGB blinker via serial
I have a BLUno bluetooth arduino based on uno.
the logic kind of works, I am connecting ok to the phone, getting and sending messages via blue tooth
but with the serial data, Im having problems using it, and with the logic.
I want to have the option to turn ON/OFF some RGB LEDs, the problem is that the state is sometimes erratic.
here the code
int redLED = 2;
int greenLED = 4;
int blueLED = 3;

static bool redRunning;
static bool greenRunning;
static bool blueRunning;
static bool freq = 34;

void setup() {
  Serial.begin(115200);               //initial the Serial
  Serial.write("started");

  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(blueLED, OUTPUT);

  digitalWrite(redLED, HIGH);
  digitalWrite(greenLED, HIGH);
  digitalWrite(blueLED, HIGH);

  redRunning = false;
  greenRunning = false;
  blueRunning = false;
  freq = false;
}

void loop()
{

  if (Serial.available() > 0)
  f{
String s = Serial.readStringUntil('\n');

//    String s = Serial.readStringUntil("#");   // Until CR (Carriage Return)
//    s.replace("#", "");
    Serial.println("s:" + s);

if (s == "red_ON")
{
  redRunning = true;
}

if (s == "red_OFF")
{
  redRunning = false;

}  if (s == "green_ON")
{
  greenRunning = true;

}  if (s == "green_OFF")
{
  greenRunning = false;

}  if (s == "blue_ON")
{
  blueRunning = true;

}  if (s == "blue_OFF")
{
  blueRunning = false;

}

 }

 //

  if (redRunning) {
//    Serial.println("redRunning");

digitalWrite(redLED, LOW);
delay(125);
digitalWrite(redLED, HIGH);
delay(125);
  }

  if (greenRunning) {
//    Serial.println("greenRunning");

digitalWrite(greenLED, LOW);
delay(125);
digitalWrite(greenLED, HIGH);
delay(125);
  }

  if (blueRunning) {
    //    Serial.println("blueRunning");

    digitalWrite(blueLED, LOW);
    delay(125);
      digitalWrite(blueLED, HIGH);
    delay(125);
  }

  if (!redRunning && !greenRunning && !blueRunning) {
    digitalWrite(redLED, HIGH);
    digitalWrite(greenLED, HIGH);
    digitalWrite(blueLED, HIGH);
  }

   }

So what is the proper way to handle state? so the LED stay blinking? but also can turn off all LEDs
also if I can turn LEDs combined, at the moment, I'm turning on one, then the other,
All these problems come from not understanding how to handle state internally, and manage changes that come via serial.

use blueRunning = HIGH;  to store the LED state directly .... then set all three colors at the same time withhout using an if statement ... digitalWrite(blueLED, blueRunning); delay(125); digitalWrite(blueLED, LOW);

@jsotola what a great way to do it! thanks! please make it an answer

I think you are handling the state quite well, but if you spend some time to some other topics, I'm sure you get it working:

Instead of delay's everywhere, use just one at the end, and make sure you handle all state before that delay. This means that you set all your states the way you want, that single delay gives a much easier sketch to analyze.
Split your sketch in separate parts (within the loop function):

Read serial input
Adjust states according to your serial input
Adjust states according to time (for blinking purposes)
Set the GPIO pins for the LEDs based on that state
Delay
Regarding the states, you use now 3 'running' states, one for each color, this is good. Probably it's easier to keep these variables attached to the serial input (so if you get "green_ON", greenRunning is always true, else false. So you don't need to always set them to false in the beginning of the loop function, just once during declaration or within setup.

Than you make another (global) variable that defines if (any) LED is in HIGH state (if it WOULD be running) of LOW. This variable you change every 125 ms (or whatever speed you like). You can flip this variable every 125 ms (ledsOn = !ledsOn).
So you get something like (# = pseudo code), for red only, rest is similar:
in global:
bool redRunning = false;
bool ledsOn = false;

in loop:
// Read serial input
# Read input

// Set states
# if serial data Red On is received
   redRunning = true;
# if serial data Red Off is received
   redRunning = false;

ledsOn = !ledsOn;

// Set LEDs
digitalWrite(redLED, redRunning && ledsOn ? HIGH : LOW);

// Delay
delay(125);

Here is some untested code that uses a non-blocking timer to flash the leds.

uint8_t redLED   = 2;
uint8_t greenLED = 4;
uint8_t blueLED  = 3;

static uint8_t redRunning   = HIGH;   // leds off at start
static uint8_t greenRunning = HIGH;
static uint8_t blueRunning  = HIGH;

// static bool freq = 34;             // not sure what this is

void setup() {
  Serial.begin(115200);               // initialize the Serial
  Serial.write("started");

  pinMode(redLED,   OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(blueLED,  OUTPUT);

  digitalWrite(redLED,   HIGH);       // leds off
  digitalWrite(greenLED, HIGH);
  digitalWrite(blueLED,  HIGH);

//freq     = false;
  tick     = false;                   // time interval signal
  ledState = false;                   // state of led display

  static uint32_t ledTicker = millis();
}

void loop() {

  if (millis() - ledTicker >= 125) {             // Once every 125 ms
    ledTicker = millis();
    tick = true;                                 // set the tick flag
    ledState = !ledState;                        // changes state at every tick
  }

  if (Serial.available() > 0) {
    String s = Serial.readStringUntil('\n');

//  String s = Serial.readStringUntil("#");      // Until CR (Carriage Return)
//  s.replace("#", "");
    Serial.println("s:" + s);

    if (s == "red_ON"   )  redRunning   = LOW ;  // sometimes, this format is easier to read
    if (s == "red_OFF"  )  redRunning   = HIGH;

    if (s == "green_ON" )  greenRunning = LOW ;
    if (s == "green_OFF")  greenRunning = HIGH;

    if (s == "blue_ON"  )  blueRunning  = LOW ;
    if (s == "blue_OFF" )  blueRunning  = HIGH;
  }

  //
  if (tick) {                                    // 125 ms passed, so update the leds
    tick = false;                                // reset tick so that leds change only once every tick

    if (ledState) {                              // state of leds at this tick
      digitalWrite(redLED  , redRunning  );
      digitalWrite(greenLED, greenRunning);
      digitalWrite(blueLED , blueRunning );
    }
    else {                                       // all off this time around
      digitalWrite(redLED  , HIGH);
      digitalWrite(greenLED, HIGH);
      digitalWrite(blueLED , HIGH);
    }
  }
}


text:
Merge two 8 bit arrays to one 16 bit array
I am an absolute newbie to Arduino and C++ and try to go through some tutorials to gain a minimal insight. However I stuck already at some tiny Points. What I want to do? Merge two 8 bit integer Arrays in to one 16 bit Array:
int summand_one[8] = {0,0,0,1,1,0,0,0};
int summand_two[8] = {1,0,0,0,0,0,0,1};

int * summand = new int[16];
std::copy(summand_one, summand_one+8, summand);
std::copy(summand_two, summand_two+8, summand+8);

The result should be
{0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1}

However it's not working at all. Constructor/destructor/type errors…
Any helpful idea how to do this?

If you get errors, please include them into your question. They are normally very helpful

It's better to avoid dynamic memory allocation on an Arduino, with only 2 KB of SRAM memory.
Note that your arrays cost 2 (bytes/int) * (8 + 8 + 16) = 64 bytes.
And it seems you are only storing booleans, which could be stored in one bit. So consider another alternative (I will not work that out, since maybe memory consumption is not a problem).
However, an easy solution is to use uint8_t.
Also, I would use a simple memcpy. Very naively it would look like:
uint8_t summand_one[8];
uint8_t summand_two[8];
uint8_t summand[16];

void setup()
{
}

void loop()
{
  memcpy(summand, summand_one, 8);
  memcpy(summand + 8, summand_two, 8);
}

Using some constants for the sizes, you get more flexible/readable and maintainable code:
static const uint8_t SummandOneSize = 8;
static const uint8_t SummandTwoSize = 8;

uint8_t summand_one   [SummandOneSize];
uint8_t summand_two   [SummandTwoSize];
uint8_t summand_merged[SummandOneSize + SummandTwoSize];

void setup()
{
}

void loop()
{
  memcpy(summand_merged                 , summand_one, SummandOneSize);
  memcpy(summand_merged + SummandOneSize, summand_two, SummandTwoSize);
}

Thanks, that did it. Also thanks for the extra explanation on the dynamic memory allocation!

You're welcome.


text:
Trinket Pro 5V red light flashing when battery attached
I am using Trinket Pro 5V to run a simple i/o code. The input from the piezo vibration sensor is read by the Trinket and Translated into a servo position.
It works fine powered through a USB connection, however as soon as I try to power it using a 9V battery (plugged into the Bat+ and G terminals), the code stops running and the red light on the Trinket starts to blink.
Is the power source not sufficient - 9V?
Has anyone faced a similar problem?

@I. Wolfe The red light flashes and the green LED is permanently on when the battery is connected. As soon as I connect it back to a USB it goes back to green light, and red disappears. This does not reset the Trinket, the code is still remembered by the board. I hope this helps with the detailed description. Do you have any thoughts? Do you think  9V has enough juice for the piezo/motor circuit?

Please consider reading the "https://learn.adafruit.com/trinket-gemma-servo-control/wiring" tutorial.
It says

It is suggested you use an external wall or battery supply and not
  power the servo via the regulator. servos can draw up to 500mA and the
  Trinket regulator can only source 150 milliamps (USB power generally
  500 milliamps).

No matter what power supply you hook to the "Bat+" battery pin, if you hook the servo power to the "5V" pin on the trinket, the trinket's on-board 5V regulator will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.
Instead, please hook the servo power directly to the battery.
Alas, a typical partially-drained 9V battery has enough internal resistance that the battery's voltage will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.
Instead, use a better power source.
Many people, even when they intend to eventually run their system on batteries, start out using a wall-wart power supply, so they don't have to keep wondering "Is this glitch because of a bug in my software, or is the battery just going dead?".
The "Adafruit 16-Channel Servo Driver with Arduino" tutorial says:

Good power choices are:

5v 2A switching power supply
5v 10A switching power supply
4xAA Battery Holder - 6v with Alkaline cells.  4.8v with NiMH rechargeable cells.
4.8 or 6v Rechargeable RC battery packs from a hobby store.

You might also want to look at other Battery holders that hold lots of AA batteries in a convenient package.
Related:
"How to get high current from 9 volt batteries"
and
"What is the max current I could draw from a 9V battery?".

Thanks, @david-cary. As soon as I plugged the servo to be powered directly from the battery, it worked like magic! Appreciate your answer:)


text:
Arduino Pro Mini doesn't align nor connect in fritzing
When using fritzing (0.9.6) I notice that the Arduino Pro Mini 3.3 V component doesn't align nor connect to breadboard pins like other components.
Is this a bug or a feature?
I've tried to wiggle the board/component, disable/enable 'Align to Grid', but this doesn't help.
For comparison, a PIC or M1 blue pill aligns/connects fine, even after rotating both the board and components.
Update: To illustrate the issue:

Note on the left how the Arduino Mini Pro doesn't connect and doesn't align, i.e. its pins are between the rows.
For comparison, on the right a blue pill whose pins do align and auto-connect.

Mini has pins on all sides. it fits into breadboard if the pin headers on short sides are not installed or there are on the upper side.

@Juraj, ok, so a sane default would be to just have those pins on the short side disconnected/unaligned?

but in fritzing it doesn't matter if you have it in breadboard or next to it

@Juraj, it's a matter of convenience, with auto-connect you save to make some manual connections.

doesn't it snap to board pins too?

@Juraj No, it doesn't. It snaps (or aligns) them between the rows. I've added a screenshot to illustrate this. Btw, to add to my previous comment - it's not just a matter of convenience, i.e. the breadboard view is mainly about showing how the components are really placed on a real breadboard. And in reality the Mini Pro usually isn't placed besides the bread-board when it has standard headers. Being more abstract is the job of the schematic.

I asked about wire snapping to a board pin. I worked with Fritzing in the past, but I don't have it installed now and the download is not free.

@Juraj FWIW, it's available from the main Fedora repository (under the GPLv3) and likely from other distribution repositories as well. So under Linux it's just a dnf install fritzing or so away.

so the component is just bad. https://forum.fritzing.org/t/pins-not-aligning-with-board/9142/5

To the close voters: this question has been closed two times and was already re-opened one time. See also https://arduino.meta.stackexchange.com/a/2706/13174 for some arguments why it's on-topic. Previous comments arguing it being on-topic here were deleted, unfortunately. See also the help-center which explicitly states: 'Feel free to ask about anything related to Arduino.'

If it were a schematic you would have it finished, no alignment of pins.

There is a mostly corrected part available here:
https://forum.fritzing.org/t/arduino-mino-pro-3-3-v-doesnt-align-connect/15221/2
as noted it needs more corrections before being added to core parts (which will also require obsoleting the current part.)

The Pro Mini component you try to use in Fritzing has a bug in alignment possibly because of position units not specified.
You can fix it by editing the source code of the component as mentioned in this Fritzing forum thread: https://forum.fritzing.org/t/pins-not-aligning-with-board/9142/4

Short Answer...
I’m not an expert on the Fritzing sketch tool, however I’ll guess that the graphical anchor point on the board component shown in your question has been specified incorrectly and that if that bug was corrected, the long edge pins would snap to a breadboard component the same way as your comparative example. Noting that this would almost certainly leave some internal or short edge pins out of alignment with the breadboard grid (depending on the component PCB layout).
More information ...
(I'm pretty sure OP already knows this, but adding for a more generally usable answer)
Arduino Pro-mini was designed for “installations where space is premium and projects are made as permanent set ups”. Some of the design choices can be somewhat incompatible with breadboard which has a 0.1” (2.54mm) pitched square grid either side of a 0.3” (7.6mm) centre notch.
The open-source Pro-mini board has been immensely popular and there are many versions of PCB layout in circulation. Just three examples are shown below. There are many more.

When attaching headers for breadboard use, various configurations of pin headers placed above or below the PCB are used to bring out (predominantly) the long edge connections for the breadboard, while allowing the others to be accessible by leads.

Yes, I think the last assembled variant (i.e. down-facing headers on the long side, 90 degrees side-facing on the short side) is how it's used by most. Fritzing even has 2 revisions of the Arduino Pro Mini: Rev13 and Rev14. Whereas Rev13 does properly align and connect, but is only available as 5 V variant. Rev14 doesn't align/connect but is available in both 3 V/8 MHz and 5 V/16 MHz variants. Modeling it with down-facing headers on the long sides seems to be most flexible, since you still can put it beside the breadboard and connect wires.

Since we've established that this is likely a bug and that there isn't an easy way to change how the headers behave, I'll try to report it upstream such that perhaps the model gets fixed.

My bug report: https://forum.fritzing.org/t/arduino-mino-pro-3-3-v-doesnt-align-connect/15221

Fritzing parts only auto-connect if some pins are declared as male. This can be checked by looking at the part's XML file (search for <connector.*type=) or by opening the part in the 'new parts editor' (i.e. right-click->edit).
Note that it's ok for a part to have heterogeneous connector types. For example, male ones on the long sides and female ones on the short side. Which is what's used commonly with these parts, in reality. This is how for example the M1 Blue Pill or even the Arduino Pro Mini Rev13 (5V) Fritzing parts are defined, which thus auto-connect fine, as expected.
One can only speculate why the Arduino Pro Mini Rev14 (8 MHz/3.3 V and 16 MHz/5 V) parts were defined differently. Might be a bug or a deliberate design choice. However, for being a deliberate choice it would be only consequential to also draw female up-facing headers on the underlying SVG (cf. the Arduino UNO part, where this is done).

To work around this, one can edit the part, change all the connector types on the long sides from female to male and save it as new part - say - using the 'new parts editor', directly inside Fritzing. After that change the new part shows up under the 'MINE' parts category.
After that change the part auto-connects to the bread-board. However, the alignment is still broken, thus, for auto-connection one has to disable View->'Align to Grid'.

So to also fix the alignment some more sophisticated part editing is necessary.


text:
RFduino communication capabilities
Is there any way to connect RFduino's via radio frequency? Or any capability to transmit information between RFduino's for distances up to 200 feet?
I would like to purchase a dev kit (for RF duino) but i'm not sure what parts I will need to transmit info longish (200 feet) distances.

https://blog.adafruit.com/2010/06/11/aprs-radio-shield-for-arduino/
Be warned you need a license to transmit on amateur frequencies at least in the US, you will also need to hook up a transmitter for this shield.
GSMShield would also be great and is something I'm thinking about using for my project, the way the Arduino IDE is setup and the libraries already in place I'm sure it would be easy to turn text messages into commands or readable and usable data between the sender and receiver.
Here are two ways one using a long range radio frequency or the GSM network. We would need to know more exact data of your project on how to implement these two solutions to accomplish what you would like to do.
The first option is most likely going to be the lesser option if you don't have a license to transmit long range frequencies and do not have experience.
The second option is easy and all you would have to do is make sure both sender and receiver are within a GSM network.
Good luck and I'm excited to see what other solutions others may post since I'm in the same boat.


text:
Interfacing arduino with LabVIEW
I have already downloaded the arduino package for LabVIEW, MakerHub LINX, NI-Visa, and I've uploaded LIFA_Base to arduino, and it still does not work :(.
My questions are:
1) Do I need to upload the LIFA_Base to arduino every time I want to interface arduino with LabVIEW, or is once enough? (the order I'm following is: upload LIFA_Base -> upload my arduino code -> run the LabVIEW code)
2) I know my arduino UNO is receiving info by the LabVIEW software because the RX led goes on every time I press the ON/OFF buttons, what could be the problem?
The ideia of this humble project is to turn on/off LED through the LabVIEW. The arduino code follows the LebVIEW code.

String c, string;
int led = 2;

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

void loop() {
   if (Serial.available() > 0) string = "";

   while(Serial.available() > 0)
   {
     c = (byte)Serial.read();
       if (c == ":")
       {
         break;
       }else
       {
         string += c;
       }
     delay(1);
   }

   if (string == "LL")
   {
     digitalWrite(led, HIGH);
   }
   if (string == "DL")
   {
     digitalWrite(led, LOW);
   }
}

From the LabVIEW side of things, I would just go with an event structure and use a single boolean to control the LED - let it go idle when the button state has not changed. No need to poll!

“upload LIFA_Base -> upload my arduino code”. You can only have one program in the Arduino at a time. When you upload your Arduino code, you are overwriting the previously uploaded LIFA_Base.


text:
Trouble reading LM35 with long (?) Ethernet connection
I have a quick question to ask.
I have an Arduino Uno reading 4 temperature sensors (LM35) in 4 different rooms. What happens is that the two nearest rooms give stable values, while the two further ones give very unstable measurements (the temperature keeps floating +-30C around the real values.)
I have connected all the sensors with Ethernet cables with the longest one being about 8-10m.
Is this problem due to noise picked up along the line? There are no strong electromagnetic sources along the way.
I have also measured the voltage values on Arduino end with a multimeter: the values are all stable (and correct) and do not reflect the behaviour detected by Arduino.
Also, I have tried to substitute the LM35 in the farthest room with a photoresistor (the one in the starter kit) and this time the values read by Arduino are perfectly stable. I know that the LM35 works because I have tested it on a breadboard.
Can someone give my some help? Any idea is greatly appreciated.
Edit: I am adding a sketch, although it is a very basic setup:
The only difference with the real layout is that there is also a Ethernet shield.

Can you show a schematic, preferrably with the ethernet wiring explicitly labelled. You might benefit from adding a line driver circuit to either end, or switch to a digital temperature sensor such as a DS18S20. Alternatively you could get some wonderfully cheap NRF24 modules and have everything wireless; that's worked for me.

Thanks, the NRF24 is really nice, but I am afraid that I do not have enough space for its library on Arduino.
But if I switch to a digital temp sensor wouldn't I face the same problem and need a line driver anyway?

I don't know; it depends on how you wire it. When I said "Ethernet wiring explicitly labeled" I meant for you to show the colours of the conductors you used. Not Fritzing's make-believe version: what YOU are actually using.

30C is quite a variation... you're looking at ±300mV variance in your analog signals. Check for loose connections in your wiring. Also check what voltage the LM35 receives on its power pin after the long run of Ethernet cable.

Sorry, I misunderstood your post. I am using the green, orange and white-orange conductors for 5V, ground and signal, respectively.
The voltage received by the LM35 is around 4.2V and with a multimeter I do not see that kind of variance. The problem also remains if I change the analog inputs on Arduino.

At least you're using a twisted pair for signal/ground. I wonder if you'll see an improvement if you connect white-green to ground as well.

The LM35 has trouble driving any kind of capacitive load, so the long runs of cable are generally not a great idea if you are relying on a voltage signal. The datasheet for it (The one I have is from the Texas Instruments website), has a few strategies to reduce this problem somewhat.
The approach that I have used successfully, is to use a current signal, rather than a voltage signal. This has the advantage that you only need a two wire twisted pair cable (I made my own twisted pairs - it is easy for relatively short runs).
The idea is that you connect the LM35 output to the ground pin with a known resistor value (the datasheet example has a 200 Ohm resistor). Since the voltage is 10mv per degree, the current wil be 10/R mA per degree. There will be an additional small current from the LM35 device itself, but this is small, and almost constant. Then connect the supply and ground to one end of your twisted pair.
At the other end, it is necassary to convert the current signal back to a voltage so that your Arduino can read it. Simply put a resistor (again, 200 Ohms is that used in the datasheet example) between the low side of the twisted pair to OV, the high side connected to 5V, and measure the voltage across this resistor.
Figure 17 in the TI datasheet is the one to follow.
Other things that help to get more stable, acurate readings;
Choose a time to take readings when you are not running anything else that might interfere (wireless comms, ultrasonic sensors, motors, solenoids, etc).
Take several readings. Ignore the first two.
Take the median value of the remaining readings (eg take 5 readings, ignore the first two, and sort the others in order. Then take the middle value.).
Hope this helps.

Short answer
Add delay between each reading, 100ms should be enough.
Long answer
The LM35 is an analog device and you are using the internal ATmega328 ADC to read the voltage on the signal pin.
The way the Arduino ADC works is a sample-and-hold process:

open a circuit to an internal capacitor
charge the capacitor
disconnect the circuit
compare capacitor to the reference voltage

Because there is only one of such circuits shared among all the 6 analog pins you need to let the capacitor charge up, which is much slower on long lines having a non negligible resistance and also a non negligible capacitance.
Also other wires and power lines near to your ethernet cable are going to influence your readings, but in that case the ethernet cable shielding is going to help you, if properly used.

Thanks a lot, I will try this as soon as I get back to the setup.


text:
Main Idea of Gyro

I have a L3G4200D (GY-50 model) gyroscope. I have been  trying to learn how a gyro sensor works. The circuit diagram is attached. I want to ask some questions;
a) According to the datasheet of L3G4200D,
    x_lsb and x_msb  (28h and 29h),
    y_lsb ,y_msb     (2Ah and 2Bh),
    z_lsb , z_msb    (2Ch and 2Dh) as  shown in the picture 3.
But according to code that in the picture first, Arduino requests bytes from 168 address of gyro (in the picture, the mark number is 1).
But, 0x28 (hex) stands for b00101000 .
What's wrong with it ?
b) Output of gyro is outputs degrees/second, is it correct?
c) In the picture 2, I did not move it, as it shown its results change, how can the angle change? It must be zero when it does not move.
d) In the picture 1, what I should calculate: highbyte*256+lowbyte ?
e) What does Fs=250,500,2000 dps mean? I know that Dps stands for Degree Per Second. But what would change by FS range, I mean if I pick either 500 or 2000 ?

Have you taken a look at the datasheet for your gyro?

When I used LIS2DH last year, I found address byte has some extra complexity - read the entire datasheet for "gotchas". I think it was a bit to enable consecutive register reads. FS means Full Scale.

According to the datasheet of L3G4200D, x_lsb and x_msb (28h and 29h), y_lsb ,y_msb (2Ah and 2Bh), z_lsb , z_msb (2Ch and 2Dh) as shown in the picture 3. But according to code that in the picture first, arduino requests biytes from 168 adress of gyro(in the pciture ,mark number is 1). But , 0x28 (hex) stands for b00101000 . what's wrong with it ?

168 is, in hex, 0xA8.  That's 0x28 with the MSB set. Why? Well, the datasheet says:

In order to read multiple bytes, it is necessary to assert the most significant bit of the subaddress
  field. In other words, SUB(7) must be equal to 1, while SUB(6-0) represents the
  address of the first register to be read.

So address 0xA8 is the same as address 0x28 plus the instruction "I want to read multiple bytes".

Output of gyro is outputs degrees/second ,is it correct ?

Kind of. The number is actually a representation of the fraction of FS. See below.

in the picture 1,what I should calculate hightbyte*256+lowbyte ?

That is turning two 8-bit values into a single 16-bit value. It's easier to represent it using bit shifts:
(bighbyte << 8) | lowbyte

That is, the high byte is shifted left 8 bits and the low byte is then ORed over the lower (zero) 8 bits.

What does Fs=250,500,2000 dps mean ? I know that Dps stands for Degree Per Second .But what would change by FS range ,I mean if I pick either 500 or 2000 ?

That is the "Full Scale" value. It defines what the raw numbers from the gyro actually mean.  The gyro returns -32768 to +32767. -32768 is -FS, +32767 is +FS. So if the FS is set to 500 degrees per second then:

-32768 is -500 degrees per second
+32767 is +500 degrees per second

The simple formula is (using floating point maths):
DPS = Reading / 32768.0 * FS
The format is more commonly known as Q15 where a 16-bit value is split into 3 parts - a sign bit (bit 15), an integer part (there isn't one in this case), and 15 bits (14-0) of fraction. So the number actually represents, in Q15 format, between -1 and +1 in 65536 steps of 1/65536. That number is then multiplied by the full scale value, just like you would a percentage, to get the real DPS value.

Thank you, These are very precious informations.
I think it will take me long time understand whole part of it.

According to the datasheet, FS seems to be Measurement Range. Also, I think you will find useful information in the following discussions: Understanding the sensitivity of an L3G4200D gyroscope and in How do I get gyro sensor data (L3G4200D) into degrees/sec? Due to the fact that the gyro is 16 bit, the range of values would be 2^16, what makes 65536. So, the values on your screen are between -65536/2 and +65536/2, that's why max. values that you see are around 32000.   There is always very tiny motion that the sensor can detect due to vibrations and etc. So, you should not expect the output of gyro to be a set of constants. Ideally, you should combine the data, lets say for 1 second, and find RMS value(average it) to get the result, don't look just for few instances/samples. Also I should note that if there is ultrasound in the gyro environment, it might also cause wrong results. When outer frequencies coincide with the natural frequency of the gyro system, it leads to resonance and distorted data. This paper has explanation of this phenomenon among with other impacts to the gyroscope.

Thanks for replying.
I have already read that topics you recommend.
Do you suggest calibrating the gryo ? I mean,first I will get 1500-2000 measures and define 0 point, and every time you read values from gyro ,compare it to calibration values , if it does not move value will be 0 .

Yes, something like that. Let's say you average 2000 values, (use RMS instead of mean, because you have negative values), and get 300(x) 400(y) 100(z) values. This would be your 0 point. When you will get a new point, you could compare it to the 0 point to see how much the values has changed and make calculations. I guess there should be ready libraries to make the calculations easy. Just continue to research, there are many projects with reports and ready software done on this topic, I am sure you can find much more.

Yes,I have already found ready-code and its simulation,it works perfectly..But I have to learn how it is written,how it works.The first thing that I should do is to  run  that code step by step .
Thank you for your help.

authors: Дмитрий Петров


text:
Missing character when introducing delay in the code
I am using the following code for reading any incoming message, and doing something after decoding the incoming string. There is a delay of 10sec in the code. When this delay is not introduced in the code, it is working nice. In this case, the output is like below.
+CIEV: "MESSAGE",1

+CMT: "+919080404532",,"2018/02/09,19:30:51+06"
This is an incoming test message

When the delay is introduced, I am unable to see the message on the serial monitor, and subsequent action is not taken by the code. The output is like below.
+CIEV: "MESSAGE",1
+CMT: "+919080404532",,"2018/02/09,1

It is clear that, I am missing some character in serial monitor. If delay is reduced to 400 ms, the output is like below.
+CMT: "+919080404532",,"2018/02/09,19:30:51+06"
This is an incoI am working other job

I checked the following, but did not get any improvement.

Serial.flush and mySerial.flush
Increased both hardware, and software aerial buffer size
used if (!mySerial.available() before delay
Changed baud rate for both
Instead of of Serial.readString(), I used Serial.read() character by    character inside function loop

Without use of the delay, it is working nice. I Think you guys are experienced, and can sort out the problem easily.
//while Introducing any delay in function loop, incoming message cant be read
//working with power failure but with serial monitor
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);  // TX-Pin11, RX-Pin10
String str="";
void updateSerial()
{
  delay(2000);
  while (Serial.available()) {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available()) {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }

}

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

void loop()
{
 Serial.println("I am working other job");
 //delay(10000);            //If you give this delay, then incoming message cant be read
 smstask();
}

void smstask()
{
if(mySerial.available())
{
str=mySerial.readString();
Serial.println(str);
int bra = str.indexOf('@');
int ket = str.indexOf('#');
String str1=str.substring(bra+1,ket);

if(str1=="server")
{
Serial.println(str);
int i=random(1,500);
String str2=(String)i;
String str3="@deviceA#"+str2;
mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
updateSerial();
mySerial.println("AT+CMGS=\"+917602304567\"\r"); // Replace x with mobile number
updateSerial();
mySerial.println(str3);// The SMS text you want to send
updateSerial();
mySerial.println((char)26);// ASCII code of CTRL+Z
updateSerial();
mySerial.println("AT+CMGD=1,4"); // AT Command to receive a live SMS
updateSerial();
}
}

}

void modemsetup()
{
  for(int i=0;i<3;i++)
  {
  mySerial.println("AT");          //Once the handshake test is successful, it will back to OK
  updateSerial();

  mySerial.println("AT+CSQ");      //Signal quality test, value range is 0-31, 31 is the best
  updateSerial();

  mySerial.println("AT+CCID");    //Read SIM information to confirm whether the SIM is plugged
  updateSerial();

  mySerial.println("AT+CREG?");    //Check whether it has registered in the network
  updateSerial();

  mySerial.println("AT+SNFS=0");  //Adjust to earphone mode(AT+SNFS=1 is microphone mode)
  updateSerial();

  mySerial.println("AT+CRSL=2");  //Adjust volume, volume range is 0-15, maximum:15
  updateSerial();

  mySerial.println("AT+CMGF=1");
  updateSerial();

  mySerial.println("AT+CMGD=1,4");
  updateSerial();
  }

  mySerial.println("AT+CMGS=\"+917602304567\"\r");
  updateSerial();

  mySerial.println("I am SMS from GSM Module");
  updateSerial();

  mySerial.println((char)26);// ASCII code of CTRL+Z
  updateSerial();

}

What is the purpose of delay(2000) in updateSerial()?

That is response time of gsm modem. But that delay is not creating any problem.Problem is the delay inside loop

What I was getting at is that sprinkling long delays like you are doing is poor practice, and when you are using the UART like this, you are bound to run into problems. Instead of pausing the entire CPU while you wait for an external device to maybe answer... instead, just check if it has an answer, and if not, check again later. That is, if (Serial.available()) { ... }, rather than delay(20000) and then drain the buffer.

Yes, that is a good practice. But actual problem is , if any message is received when arduino is busy with doing other stuff, character is missing.

This is not true -- the Arduino has a serial buffer which holds bytes until your code can get around to processing them. However, you have to structure your code so that it doesn't use a lot of long delay() calls, otherwise, it will miss characters, as you are experiencing. It's possible for the Arduino to collect characters one or two at a time, and only deal with the string when you get a character that defines the end of a logical command/result (such as a newline or carriage-return).

I  tried reading character by character also, but getting same error. Actually I am using both lora and GSM with same arduino. LoRA code consists of a  a delay of 2 sec inside loop.  Instead of using full loRA code, I just have introduced a delay intentionally.

If serial data is coming in, and your code is doing a delay, the incoming data is stored in a buffer (of 64 bytes). But if you wait too long, the buffer will fill-up. Once it's full, any further incoming serial data isn't stored, and will be lost.
In your third output example, you get exactly 63 characters. Which is the maximum size a 64-byte cyclic buffer can store.

Thank you for your reply. But I increased buffer size to 256 bytes from SoftwareSerial.h