text:
Array of strings - how to determine the number of elements present
I would like to use an array of strings which I define as follows:
char* CommandQueue[]={"FirstCommend", "SecondCommend", "ThirdCommand", "Cmd4", "Cmd5"};

The purpose of this array is to hold commands ("strings of various lengths") that the Arduino will receive through a serial port. Those commands will be interpreted by calling appropriate callback functions to act on them. The CommandQueue is supposed to line up the commands in a sort of "buffer".
Initially the "CommandQueue" array does not contain any elements and gets populated during the runtime of the project. The  array will continuously be interrogated and once a command is interpreted (and the corresponding function executed) the command will be eliminated from the queue.
How can I determine how many elements (i.e. strings) or commands are present in the array? The sizeof() function will not be helpful because the individual elements can be of different lengths.
Thanks in advance for your help or comments.

Just use a variable to store it... Which is the correct way to handle a buffer, i think...

You can't know how many items are in an array simply because an array has a fixed size, and there is no such thing as "not an entry".
The closest you can have is a fixed size array and only some entries in it are valid - those that aren't valid have a special value to say "this is not a valid entry". For char pointers it's normal to use NULL as the "not a valid entry" value.
The drawback of this approach though is that you can never store more items than there are slots for, and finding out how many valid or invalid entries there are and shuffling them around when you remove the first entry is both a tedious and time consuming task.
Better in this situation to use a circular buffer which is a fixed size array but you remove the concept of a "first" entry. Instead you have a "head" and a "tail" value which is the locations in the array where you read from (remove the oldest) and write to (add after the newest).  It's how the serial port on the Arduino deals with incoming and outgoing data - as data arrives it is added to a circular buffer and you then read from that buffer.
To help work with circular buffers I wrote a small template class:

https://github.com/MajenkoLibraries/CircularBuffer

A very useful macro is membersof().
#define membersof(x) (sizeof(x) / sizeof(x[0]))

You will find in defined in large libraries and frameworks for C/C++. For your example above the number of elements is:
const int COMMAND_QUEUE_MAX = membersof(CommandQueue);
...
for (int i = 0; i < COMMAND_QUEUE_MAX; i++) ...

A dynamic set would require a max length and null terminated or simply a counter.
const int COMMAND_QUEUE_MAX = ...;
char* CommandQueue[COMMAND_QUEUE_MAX] = { ....., NULL };

for (char** cpp = CommandQueue; *cpp != NULL; cpp++) {
  char* name = *cp;
  ...
}

Or even better use a Queue data type:
Queue<char*, COMMAND_QUEUE_MAX> CommandQueue;
...
char* cp;
while (CommandQueue.dequeue(&cp)) ...

Cheers!

Do you need to know how long the command queue is, or just if there are still elements in it? This seems like a case where you might be better off using a different data structure – a linked list seems like an obvious possibility. If you're not familiar with linked lists, this article may be helpful. Otherwise, I think you'll need to keep track of the number of elements in the queue for yourself.
If you do use an array, it will need to be declared with a fixed length, something like:
 char * CommandQueue[MAX_QUEUE_LENGTH];

The sizeof operator would tell you the length of the array, but not the number of items in it (the length of the array is the number of character pointers defined by MAX_QUEUE_LENGTH). The code to manage the command queue as an array could get pretty messy, especially if you need to execute the commands in order.
If instead you use a linked list then each command is added to the list at the end as it comes in, and when you execute commands they are pulled from the head of the list. If you need to know the length of the queue you could either update it as you add and remove commands, or you could iterate over the list and count the number of items in the list.


text:
Where are the Arduino Due registers?
Having most of my experience on ATmega chips, and just starting up with Arduino (to reduce hardware development time) I'm happy to see that the usual registers such as TIMSK0, PCICR, TCNT1H and others can be used from the Arduino IDE just as they appear in the Atmel datasheet.
Migrating to the Arduino Due, however, came with a shock: the registers specified in the datasheet of the Cortex-M3 are not recognized by the Arduino IDE (although I downloaded the extension necessary for being able to select the Due). I wanted to do something very simple, like configuring a timer. I found TC_CMR0 in the datasheet, but the Arduino IDE doesn't recognize it. I found an example using the Arduino Due with timers in an obscure forum, and they used REG_PWM_CMR0. I tried it in the Arduino IDE, and it was accepted by the compiler.
I searched the Arduino and other forums, and couldn't find any hint whatsoever about the naming of the registers. Why are the names of the registers different? And can I find a conclusive documentation about the register names, or am I doomed to research each and every one of the hundreds of registers individually?

When I read the title I thought "like all the microcontrollers, they are just there, inside the package"

There are a few files in the Arduino Due core that you should have a look at. They give great insight into the SAM register set up; variant.h, variant.cpp and chip.h
After that you can dive into the libsam and the many components (include/source).
The SAM code has a very different structure and style compared to AVR.
Cheers!

I found almost everything I needed to know from the CPUs datasheet here.  I got the link from the Due page on the Arduino website.
For all the registers I was interested in, in my case the Parallel IO registers, it seems to be the case that the Arduino library names them the same as the datasheet, but prepended with "REG_" so PIOC_OWDR (Output Write Disable Reg for PIO port C) becomes REG_PIOC_OWDR.
In addition to finding the register names, the datasheet obviously contains a lot more useful information about how the CPU works and how to get the most out of it.
I also found the header files in the Arduino library (arduino\hardware\sam\1.6.4\system\CMSIS\Device\ATMEL\sam3xa\include\instance\instance_pioc.h for the example above) to be good places to look up what the registers are called.

i used the same datasheet you linked, and I also realized that the Arduino names are usually prepended with "REG_", but that's not always the case. For example, the TC_CMR didn't become REG_TC_CMR

I'd suggest looking in the folder I mentioned then to find the include file relevant to the timers to get clues for what you are looking for.

This is where a recursive grep -R of the arduino installation directory can be really handy...

The Arduino Due files you are after are located here on a Windows PC:
 C:\Users\name\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\component

source: Stack Exchange

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

sort: votes


text:
How to use the native USB of the Arduino Due for high-speed communication?
All the Arduino examples involving communication via USB I could find use a virtual COM Port.
On the Arduino part it's
Serial.begin(baudrate);
Serial.write(byte);

And on the PC part it's just using a virtual COM Port.
However, the Arduino Due includes a native USB port, without all that UART+FTDI chip. I couldn't find any examples using the native interface, it seems everyone is content with communicating using the simple but slow way of Serial.write();.
How can I make full use of the native USB port, besides directly accessing the registers of the Cortex-M3, which seems to be a very tedious and complicated process? The data I would like to transmit is both large and time-critical, so I need to take care of buffer sizes, transfer types, etc., so writing characters one at a time to a general-purpose serial interface is not enough. The PC endpoint (I'm considering using libusb) should also see a proper USB device instead of a virtual COM port.

Sounds like it's time to move up to Atmel Studio.

Sounds like you need to use a HID interface.  I believe the Arduino core includes generic HID code, though I haven't used it, and I'm not sure it's actually enabled by default.

@IgnacioVazquez-Abrams Atmel studio Requires an ISCP, right?

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


text:
How to read the serial data from a ATMEGA8 on a PC using Arduino?
I want to check if a device is working or not. It is a custom made PCB with a Atmega8. It was given to me along with the AVR code. How do I read the data that it sends on my laptop using a arduino, preferably a Arduino Uno?
I tried connecting the output UART pin to the Rx of the arduino, and then provided the common ground. Then I opened serial monitor on my laptop but I a m not getting anything. Is it because the PCB is damaged or am I doing it wrong?
I have the AVR code which was burned on the IC, so I can provide you with more information if you need.

Connecting to the RX pin on the Arduino will let the AVR chip receive the data, but not the PC. Try connecting to the TX pin, and making sure the Arduino isn't running anything that would initialize its own UART.

@NickJohnson Thanx, would Serial.begin() be what would initialize it's own UART.

That's right. Best option is to load an empty sketch, or the 'blink' sketch.

@NickJohnson Thank you, and it works perfectly. Can you convert it into an answer so that I can accept it?

If you connect the TX pin on your device to the 'TX' pin on the Arduino, then load a sketch such as 'blink' that won't initialize the Arduino's own UART, you can use the Arduino's onboard USB-UART adapter to talk to your device.

Or just tie the reset pin low so that the serial pins go high-impedance.

You can download this example code to your Arduino UNO...
https://www.arduino.cc/en/Tutorial/SoftwareSerialExample
Make sure the baud rate on the line mySerial.begin(4800) to match the baud rate your device is sending.
Then run "Serial Terminal" from the Arduino IDE and connect the output of your device to pin 10 on the Arduino.
If the baud rate is correct, you should see the Serial output from your device in the serial terminal window.
Why you might not want to direct connect
Here is the schematic of the serial port section of the Arduino UNO...

The TX pin on the header is connected directly connected to the TXD/PD1 pin on the ATMEGA chip as highlighted in red. This pin will be actively driven if any of the following happen...

There is a sketch running on the Arduino than enables the serial port (i.e. includes Serial.begin()).
There is a sketch running on the Arduino that enables pin 1 as output (i.e. includes pinMode(1,OUTPUT);).
The Arduino reboots and runs the bootloader, which always briefly enables the serial port on startup.

There are some devices that can be permanently damaged by having their serial output tied to an actively driven signal, especially a +5 volt one like we have here. The BBB is one of them (I know from experience!).
One response suggested downloading the BlinkMe sketch into the Arduino, presumably to make sure there is not another sketch running that could enable the serial port. This is the right idea, but you have to keep in mind that the UNO will reboot anytime the RTS line is toggled. Here is a not-so-far-fetched scenario...

You load BlinkMe into the UNO.
You connect the device to the TX pin on the UNO.
You launch Tools-Serial Monitor from the Arduino IDE to see the serial data.
The Serial Monitor window opens and toggles the RTS line (does this every time you launch it).
The UNO reboots.
The bootloader runs and enables the serial port on the ATMEGA.
The connected device is cooked.

Also keep in mind that even if the attached device can tolerate being connected to an actively driven signal, once you connect another signal to the Arduino TX pin then you loose the ability to communicate with the Arduino.
Loading the Softserial sketch takes the same number of steps as loading the BlinkMe sketch, reduces the chance of of damaging the connected device, and also allows you to keep access to the Arduino while you are doing all this.

That really isn't necessary, when he could just hook his UART up to the pins used by the Arduino for hardware serial.


text:
Arduino Due - wireless programming via Xbee
I would like to integrate an Arduino Due into a project, which probably will evolve over time and will need some re-programming. Instead of having to disconnect and pull out the Arduino Due out from the enclosure, I was wondering whether it can be set up for wireless programming via an Xbee in a similar way as for the Arduino Fio (like described here: http://arduino.cc/en/Main/ArduinoBoardFioProgramming).
Has anyone tried that already or succeeded doing that?

Theoretically, it is possible I have not tried to do it on an Arduino but I did work something similar with a pic controller. Usually, when we program the board with the firmware file we break the firmware file and send it as multiple packets over the serial com port to be written to on a certain flash memory location on the controller.
In your case, you can try an experiment by using 2 XBee modules that are connected together with the appropriate channel and network ID settings wirelessly. connect one XBee to your computer using a serial to USB cable. On the Arduino side, you have to connect to power it and use the second XBee to connect to it on the UART port. This way the XBee acts as a simple wireless data transfer channel to send and receive data wirelessly (if I am right this should be achievable in the transparent mode on XBee).
One thing to note is to check the Arduino schematic to see how exactly the data over USB is sent to the controller. If it is on UART then this should work straightforward if not then you may have to figure out something else for it.

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


text:
SerialEvent handling when using multiple serial ports
I would like to use multiple (three) serial ports on an Arduino Due. Instead of polling the ports continuously, I would like to use a Serial.Event function for each of the ports. These handler functions will read out the incoming string from the port and parse the string (i.e. check for a pre-defined command and call a corresponding sub-routine).
I was wondering what is going to happen when serial data arrives at the same time at two different ports? For example, if the program is in the process of handling/parsing the first serial message, will it interrupt/abandon this process as soon as another SerialEvent on another port is triggered? Or will it complete the first SerialEvent routine before going to the second one?

The built in serialEvent() function on arduino only responds to serial port 0, called just "Serial" in the code. To respond to messages on "Serial1", use serialEvent1() on the Arduino Due there also exists serialEvent2() and so on.
EDIT: the serialEvent() handlers are not on interrupts; they run sequentially in-between loops. If the loop is blocking they do not get run, and they do not interrupt eachother.

I am aware of that. I meant that I intend to monitor the different serial ports with their respective SerialEventX instruction. But the same question remains: what is going to happen when, say, the SerialEvent1 function is being handled while on Serial2 a message arrives and SerialEvent2 is triggered?

They are not on interrupts, so nothing special happens.

That should be fairly simple to implement.
Each serial port has TX and RX interrupts. You just need to tie into the various interrupts.
Here is an example for a mbed, but it should be similar (both use ARM NVIC interrupt controllers).
To be clear, this wouldn't involve touching the serialEvent() function stuff at all, but rather implementing what it does using your own code.

If you set up your own interrupt handlers, you also get the benefit of being able to control interrupt priority yourself. The ATSAM3X has 16 interrupt priority levels, and a interrupt of a higher priority can pre-empt a lower-level interrupt.
I Strongly suggest you read the ATSAM3X datasheet. It describes the interrupt controller, as well as the rest of the processor peripherals.


text:
Using an Arduino as an LED controller for an arcade stick
I'm attempting what seemed to be a rather simple problem at first glance, but due to my limited knowledge of Arduino workings I need some help. I'm trying to use button outputs from a PS360+ arcade controller. Each of the button terminals output +5V, and is meant to be connected through a button to the grounds on the PS360+.
  What I want to do is have an Arduino somewhere in between the button output and ground on the PS360+, to control and animate LEDs. What I've done so far is connect the VCC of the PS360+ to the Arduino's VIN and the ground of the Arduino to the PS360+'s button ground, which powers the Arduino. I then have a button output from the PS360+ going into the button, and the button's ground is connected to an Arduino pin. That Arduino pin's mode is set to INPUT. I then have another pin with an LED which is set to the value of the input pin.
  For some reason, the Arduino seems to get random input from the button(Though it does seem to react somewhat to buttons presses), and the PS360+ does not recognize the button press. Setting the input pin to pullup mode has even less result, and never reads low.
Anybody got any ideas? Here's my current circuit diagram. 1P is a +5V output. I think that it's an internal pull-up pin like the Arduino's, but I am not certain.
And my current code:
int buttonlisten = 22;
int led = 53;
int val = 0;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(buttonlisten, INPUT);
}

void loop() {
  val = digitalRead(buttonlisten);
  digitalWrite(led, val);
}

Thanks!

Are the two grounds on the board connected internally?

Yes, All grounds on the PS360+ board are connected internally.

You should connect the vcc of the PS360 directly to 5v on the arduino. Not to Vin. Vin will make the voltage go through the voltage regulator first. Supplying a 5v regulator with 5v will result in a voltage lower than 5 volt. Putting 5volt on a input pin while the atmega runs at a lower voltage could damage the chip.

Oh, scary. I will definitely do that. Thanks for the advice.

I think the idea of putting the arduino between the button and ground is the problem here — 1P appears to be the input for the controller button, and you can't expect to take an 'input' from the button on both pins at once.
Try connecting one lead of the button back to its ground, and the other to 1P (as it would be originally I assume). Then solder/connect another lead from the button's non-grounded pin to an arduino pin designated as INPUT_PULLUP.
This way you have two pulled-up input pins connected to the same button pin, which are both pulled low (since Arduino & PS360+ share GND) when the button is pressed.

Perfect! This works quite well, and does not seem to interrupt any inputs on either board. Thanks a lot!


text:
Embedded-c, schedule a function?
Simple question, of course if you do this
FunctionA();
Delay(1000);
FunctionB();
FunctionC();

it will call A, then wait a second, then call B, then call C.
How does one do this? ...
FunctionA();
.. Invoke FunctionX one second from now ..
FunctionB();
FunctionC();

So, I want it to do A, then without stopping continue to B and then C.  Later (one second later) it will do X.
Of course, in c# you'd just use a coroutine, in Android you'd use a Handler or whatever.
Surely there's a command along the lines of .. invoke in .. 2000 .. method.
Really sorry for the basic question, experts, I am damned if I can find this anywhere. Thanks!

Surely there's a command along the lines of .. invoke in .. 2000 .. method.

Not "a command" but you can make up something like that easily enough. Example:
// Function scheduler demo
// Author: Nick Gammon
// Date: 11 July 2015

typedef void (*GeneralFunction) (); // function pointer type

GeneralFunction wantedFunction = NULL;  // function to call
unsigned long functionTimerStarted;     // when the timer started
unsigned long delayPeriod;              // how long to wait (ms)

void functionA ()
  {
  Serial.println ("Function A");
  }  // end of functionA

void functionB ()
  {
  Serial.println ("Function B");
  }  // end of functionB

void functionC ()
  {
  Serial.println ("Function C");
  }  // end of functionC

void functionX ()
  {
  Serial.println ("Function X");
  }  // end of functionX

void scheduleFunction (GeneralFunction f, unsigned long when);  // prototype
void scheduleFunction (GeneralFunction f, unsigned long when)
  {
  wantedFunction = f;
  functionTimerStarted = millis ();
  delayPeriod = when;
  }  // end of scheduleFunction

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

  functionA ();  // call this now
  scheduleFunction (functionX, 2000);  // call this later
  functionB ();  // call this now
  functionC ();  // call this now

  }  // end of setup

void loop ()
  {
  // see if time to call the delayed function
  if (wantedFunction && millis () - functionTimerStarted >= delayPeriod)
    {
    wantedFunction ();
    wantedFunction = NULL;  // don't call it again
    }  // end of if time up

  // do other wanted stuff here

  }  // end of loop

This uses:

A function pointer to remember which function to call in the future.
A global variable to remember when you wanted this timing interval to start.
A global variable to remember how long to wait.

In setup() I called a function to save this information for future use:
  scheduleFunction (functionX, 2000);  // call this later

Then in loop() we see if the time is up, and then call the function.
This example just calls functions with no arguments, things will get more complex if you want to call a function with an argument. It would even be possible to remember the argument, but it may be unnecessarily complicated to explain how to do that, since your example did not ask for it.
You could also even schedule multiple functions, but again, showing all that adds to the complexity of the explanation.
For more information about function pointers, see Function pointers / function callbacks / function variables.

Hi Nick. Thanks for that detailed code sample!  Thanks for letting me know there is indeed no "schedule" or "invoke" like function .. interesting. It's interesting you really have to "roll your own" just using the main run loop. Of course, this is a "one shot" solution, if you send another scheduleFunction it will walk over the previous one right!  I'm wondering is there a trivial way to say start a new thread or some such? perhaps that would allow for a more flexible solution.  Again it's priceless info there is NO schedule or invoke -like command, thanks!!!!

There is no pre-emptive multi-tasking because the (AVR) hardware does not support it. The Unix-based boards probably do. The best you can manage is co-operative multi-tasking, where you give other functions a chance to run at some suitable point. If you wanted to have multiple functions scheduled you would have to expand what I wrote a bit, for example to have an array of outstanding functions. However you may want to design your project with a different paradigm, people have done quite complex projects without scheduling functions to run in the future.

@JoeBlow: No, there is no trivial way to start a new thread. You would need to install some sort of scheduler, which you don't have in the standard Arduino environment. You can take a look to the ArduinoThread library though. It is not threads, it's rather a generalization of Nick Gammon's approach.

Hi Nick ... fascinating.  Brilliant, thanks.  Hi Edgar, that's awesome - again thanks for the definitive information.  You guys are the best.  Yes I will just write my own threadesque, blocker, etc.  Thanks!!!!!

@NickGammon: Preemptive multitasking is possible on the AVR. See Atomthreads for example. I never tried, and it's likely to be expensive in RAM, as you need a per-thread call stack.

Hmmm, OK. That appears to use a timer to "pre-empt" whatever-it-is that is executing. No doubt that can work after a fashion, but of course you need the timer interrupt, which you may not want to give up, and you have to, of course, have interrupts enabled. Joe: You are probably best off designing differently. For example, in my code I tested in the main loop if it was time to call a scheduled function. You could, of course, simply have flags for things that need doing (eg. turn the tank pump off) and check directly.

The other thing is that RAM is generally one of the most precious things on these processors, as many problems I have seen with crashes are when people use up all their RAM. So maintaining multiple call-stacks is going to make that problem somewhat worse.


text:
Is there an equivalent to Grbl for Excellon PCB drilling?
For CNC milling we have code such as Grbl Controller in the PC, and Grbl itself in an Arduino, and these handle the appropriate G-code files. Is there an equivalent package to handle Excellon files and drive a 3-axis drilling machine?

Most PCB software will export to Gerber-files. There is already software that does pcb milling, including hole-drilling. I'm not into this stuff, but a google search for "gerber cnc" might give you better results.

Thanks Gerben. I will look into the pcb milling packages. If there is one that will talk to Grbl and if it has a sub-menu that will handle a drill file as a separate operation, then that could be the easiest way to go.

No, there is no existing Arduino library to parse Excellon format drill files in order to control a drilling machine. Looking at the specification it looks to be very similar to G Code, and some brief googling shows that there are various utilities for converting it to G Code that could be run from something like grbl.

Thanks Jake. See my comment to Gerben. If there isn't a direct pcb package, then yes, I guess I'll have to do an Excellon --> Gcode then through say, Grbl Controller --> Grbl.


text:
Arduino Bluetooth connection with Android
I am wondering why my Arduino program won't start its sketch to connect a bluesmirf to an android device and send data to the android whenever I use an external power supply. The sketch starts whenever i open the serial monitor, but using the power supply, it wont work.

What type of arduino do you have?

You'll probably find that you are not supplying enough power to operate the Arduino and the components attached to the Arduino. Your current (Amps) draw is most likely higher than your external power supply can output.
I had this problem when using a 9v battery to power an Arduino with an XBee chip and some LEDs attached. The 9v would be able to power the kit for a while but would then not output enough current to power the Arduino. In the end I had to scrap a few LEDs.
You need to find out how much current your Arduino and its components are using and use a suitable power supply that can output enough current to power your Arduino.
Also remember when you send and receive a packet out of a Bluetooth radio - more current is required than when the Bluetooth radio is idle.


text:
Why is my variable not getting updated?
I have the following snippet of code:
const unsigned long fiveMinutes = 5 * 60 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

The doStuff() routine is getting called on every loop() iteration, because the value of lastCheck isn't getting updated. I thought Icould update global variables inside subroutines, but the behavior I'm seeing says otherwise. What am I doing wrong? (doStuff() is defined and works correctly, I'm not posting it here for brevity.)

"unsigned long lastCheck = 0 - fiveMinutes;" Are you sure you meant that?

Yes. It works with that line, the line of concern is lastCheck = now; inside loop(). That line doesn't update the lastCheck variable correctly.

Post the disassembly of loop().

It really would be useful if we could see what doStuff() is doing. Maybe it resets the Arduino and it is constantly rebooting itself. Does the program have the same side effect if doStuff is simplified to just a println()?

I have the following snippet of code: - Unfortunately snippets don't cut it as I try to explain at  Snippets R Us! - you need to post a  Minimal, Complete, and Verifiable example. That is, code that actually demonstrates your point.

I modified your code to produce a working example:
const unsigned long fiveMinutes = 20 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println ("Starting.");
  Serial.println (fiveMinutes);
  }  // end of setup

void doStuff ()
  {
  Serial.println ("Doing stuff");
  }

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

I reduced the interval to 20 seconds, and Ignacio Vazquez-Abrams is correct about the initial test, however apart from that, I see "Doing stuff" every 20 seconds.

I thought I could update global variables inside subroutines ...

You can.

Are you sure you didn't have:
void loop() {
  unsigned long lastCheck;
...


text:
Arduino Due Serial garbage
I have made a custom board based on the Arduino Due but have some problems with the Serial communication with the 16u2 chip.
i have usb connection with the 16u2 chip and was able to load the arduino-due usb serial hex over the usb port. the usb now shows up as arduino com port. now when i try to load a sketch it says No device found on COM12. the SAM chip is erased but it can't load the new sketch.
now when i load a sketch with a simple serial print at 115200 over the native port. the SAM chip is programmed correctly. when i open the serial monitor i receive data but it is garbage! the garbage is always different. the sketch is at 115200 and the monitor also at 115200.
this would explain why it can't upload a sketch with the 16u2.
the same sketch on a original arduino due works fine.
the transmit an receive led are blinking.
What would cause this garbage in the connection where do i start looking?

SAM chip not running at the speed you expect it to run at?

Tip: Output a constant stream of "U" through the serial port. Measure the resultant frequency on the TX pin (before it gets to the 16U2). Double the frequency. That is the actual baud rate it's transmitting at. Compare that to what you expect it to be (115200). Any difference can indicate a difference in source clock speed.

You mean the serial speed or the actual chip speed?

The actual chip speed determines the serial speed. If that is wrong the serial will be wrong. By analysing the serial speed you can back-track that to the chip clock speed.

Alright thank you for the tip! will try to messure the frequency of the TX.

What could cause the chip to run at a wrong speed?
and is there a way to test te speed at what speed a chip is running?

Incorrect crystal or incorrect fuse settings. Testing the TX is a good way of measuring the clock speed. You get a ratio of what you want and what you measure, then apply that ratio to the clock speed you want - the result is the actual clock speed.

was not able to get a frequency test but did a speed test sketch on a original Due and 2 of my own builds.
The Due runs at 6745 Millis
and my own at 6281 Millis so it seems to be running slower then the original Due.
the crystal used is:
link.
i don't have any knowledge of fuse settings so will have to read into this.
if i have a different crystal would this need different fuse settings than a original Due?

Umm, well according to the schematics the Due has a 12MHz crystal. Yours is 16MHz. And you numbers suggest it's running faster than the original not slower, which would make sense. So yes, you will need to change the fuse settings to get the correct speed from a 16MHz crystal. At the moment you are most likely overclocking it.

sorry that was the 16U2 crystal it is a 12MHz crystal:
link
Yes you are correct its the other way it is running faster.

Have you adjusted the crystal's capacitors to suit the crystal you have chosen?

I have checked and it seems that they are 12pF and the datasheet for the crystal says it needs a 8pF.
Could this be the solution so my problem?

The crystal has a load capacitance of 8pf - that means it needs around 16pf load capacitors.

Oke so replace them with 16pF or is the 12pF close enough?


text:
I need a simple, low power, low cost wireless switch to transmit to Arduino
I'm looking for a very simple wireless, low-power, low-cost switch that can transmit a signal to an Arduino. Ideally, each transmitter would have a signature. For instance, let's say I had 4 different transmitters that are attached to a sensor. When the sensor is tripped, I want to wirelessly send a signal to the Arduino. I've looked at these 433 MHz modules, but it seems like they would also need a microcontroller to send the data, while that's a possible solution, I'm wondering if there is a even smaller, simpler solution.

... ESP8266 ... ?

modify a wireless garagedoor remote.

There is no such thing as a transmitter that can attach direct to a sensor, since no two sensors in the world work the same way. You need something intelligent between the sensor (to read the sensor value) and the transmitter (to tell it what to transmit).
There are "all in one" modules, like the ESP8266, which have an MCU and WiFi combined in one chip which are closer to what you want, but it is still down to you to program those modules to work how you need them to work for your sensors.

You could use an infrared led and an infrared sensor combined with a simple circuit to send a series of flashes that only your arduino can read. The only downside to this is that infrared can only be used indoors and they don't work if you don't have a direct line of sight.


text:
How do I call functions sequentially without using the Delay function?
I've been messing with the Adafruit Neopixel lib, and I'm trying to replace some of the delay functions with mills ( so that I don't block the serial port ). So far I have the following code;
void loop() {
  currentMillis = millis();

  colorWipe(strip.Color(255, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 255, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 255), 50); // Blue
  colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
}

void colorWipe(uint32_t c, uint8_t wait) {
  if (currentMillis - previousMillis >= 200) {
    for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      //delay(wait);
      Serial.println("Light");
      previousMillis = currentMillis;
    }
   Serial.println("Done");
  }
}

The issue I'm running into ( and I do understand this is fundamental concept in Arduino programming ) is how to run sequential functions, like the ones in loop, while still not blocking the main loop. The way this currently functions, it runs through the first colorWhipe loop and then just keeps iterating.

Assuming the commented out delay in colorWipe should still happen then you need to nest the state machines:
void loop()
{
    static bool waiting=false;
    static int state = 0;
    static unsigned long previousMillis = 0;
    unsigned long currentMillis = millis();
    if(waiting){
        if(currentMillis - previousMillis >= 200){
            waiting = false;
        }
    }

    if(!waiting  && currentMillis - previousMillis >= 50) {
        previousMillis = currentMillis;

        switch(state) {
        case 0 :
            if(colorWipe(strip.Color(255, 0, 0))){ // Red
                state++;
                waiting = true;
            }
            break;

        case 1 :
            if(colorWipe(strip.Color(0, 255, 0))){ // Green
                state++;
                waiting = true;
            }
            break;

        case 2 :
            if(colorWipe(strip.Color(0, 0, 255))){ // Blue
                state++;
                waiting = true;
            }
            break;

        case 3 :
            if(colorWipe(strip.Color(0, 0, 0, 255))){ // White RGBW
                state++;
                state = 0;
            }
            break;
        }
    }
}

int wipeState = 0;
bool colorWipe(uint32_t c)
{

    strip.setPixelColor(wipeState , c);
    strip.show();

    Serial.println("Light");
    wipeState++;
    if(wipeState == strip.numPixels()){
        wipeState = 0;
        return true;
    }
    return false;
}

Here's an OOP solution. (It seems a lot of Arduino programmers shy away from C++ classes, but I use them all the time).
Since you don't want to block loop(), you need to create a function that will set the pixel (if time has expired) and return immediately. I would create a class to encapsulate the pixel strip.
The way this works is the class has a loop() function that needs to be called every time in the main program's loop() function. The class's loop() will either return (almost) immediately or it will update the pixel. Which will also be very quick. This allows you to do other things in the main loop().
Disclaimer: I just whipped this up, there may be bugs.
// A class to encapsulate the neo pixel strip.
class color_strip {
    protected:
    Adafruit_NeoPixel pixels;
    uint32_t last_ms;
    uint32_t color;
    uint32_t duration = 0;
    int current_pixel;
    bool first_time;

    public:
    // Constructor
    color_strip(int num_pixels, int pin) {
        strip = Adafruit_NeoPixel(num_pixels, pin, NEO_GRB + NEO_KHZ800);
    }

    // Call this from setup()
    void setup() {
       strip.begin();
    }

    // Call this to start a wipe
    // param duration_ms is how long the entire wipe should take
    void wipe(RGB color, uint32_t duration_ms) {
        // Calculate how long to light each pixel
        duration = duration_ms / strip.numPixels()
        // Initialize this data for loop()
        last_ms = millis();
        first_time = true;
        this->color = strip.Color(color.red, color.green, color.blue);
        current_pixel = 0;
    }

    void loop() {
        // Is there something to do? Only if duration != 0
        if (0 != duration) {
            // Time to change pixel?
            uint32_t current_ms = millis();
            if (current_ms - last_ms >= duration || first_time) {
                first_time = false;
                // Finished the entire wipe?
                if (current_pixel == strip.numPixels()) {
                    duration = 0;
                }
                else {
                    // Set the pixel
                    strip.setPixelColor(current_pixel++, color);
                    strip.show();
                    // Save
                    last_ms = ms;
                }
            }
        }
    }

    // Returns true if doing a wipe, else false
    bool working() {return duration != 0;}
};

Usage: you can create an array of colors. You then cycle through all these colors. If you want to add more colors, simply add to the array.
// Helper struct to store rgb
struct RGB {
    byte red, green, blue;
};
RGB all_colors[] = {
    {255, 0, 0},
    {0, 255, 0},
    {0, 0, 255},
    {0, 0, 0}
    // Add more colors here, if needed
};
// Need to keep track of the current color being displayed
byte current_color = 0;
const byte num_colors = sizeof(all_colors) / sizeof(all_colors[0]);

// Here's the actual object
// Change the parameters to whatever they need to be in your setup
color_strip strip(number_of_pixels, pin_number);

void setup()
    // Call the class setup function
    strip.setup();
}

void loop()
{
    // If the strip has completed its wipe, set it to next color
    if (!strip.working()) {
        current_color = (current_color + 1) % num_colors;
        strip.wipe(all_colors[current_color], 1000);
    }
    // Call the class loop(). It will return quickly so won't block
    // the rest of the program
    strip.loop();

    // Do other stuff here...
}

By adding duration to millis, you introduce the rollover problem.

@LookAlterno Not sure if that's a joke or not....Anyway, OP needs to be able to handle classes. Adafruit_NeoPixel is a C++ class.

@Jot Rollover should not be an issue with unsigned variables. See the answer here: https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover

@JohnnyMopp As far as I know, calculating a time in the future has the rollover problem. I mean this line "last_ms = millis() + duration;". Suppose duration is 10 and millis is 0xFFFFFFFA. Then last_ms will become 4. The next millis() - last_me will return 0xFFFFFFF6, which is larger than duration, but millis() has not even counted to the next millisecond.

@Jot Ok. I thought you were referring to the main loop. I just through that in there to force an update the first time. I've replaced it with a flag. Thanks.


text:
Implement a discrete controller /transfer function with arduino uno
i want to implement a discrete transfer function at z domain with arduino UNO.I  know that i must do the inverse z transform and find the difference equation.Afterwards i must use PWM because arduino UNO has not DAC.
Is there anyone who knows about this ?and can help me.... i want a code as an example  .Thank you.

At the very least your question should include the nature of the inputs, and it would be helpful if you included the equation in the form to be implemented - ie, document every part of the problem except the Arduino.

the reference input is a unit step signal 1 volt.i should use pwm and filters for DAC.Have you got any idea ?

authors: Νίκος-Μάριος Κοκολάκης


text:
Wired serial connection between two Arduinos - do they need a common Ground (GND)?
I would like to connect two Arduinos by a serial connection. Is it sufficient to connect TX1<-->RX2 and RX1<-->TX2 or do I also need to connect the GND of the two Arduinos?

Short answer: Yes.
Rx/Tx is referenced with a logic ground. Without ground being common, there is no way to determine what is high or low.
(Sorry I don't have a more technical explanation)
Edit: I thought I would add, if you are using the same power source, then they probably have a common ground. In this case, a common power source doesn't mean the wall side of a wall adapter, but the SAME wall adapter.


text:
Operating / pin voltages ATTiny chips
I would like to set up a project with an ATtiny chip, such as the ATtiny84 or ATtiny85, in which I interface the microcontroller directly with an XBee for both wireless serial communication, as well as monitoring a digital signal from the Xbee (digital input to the ATtiny). As the Xbee chips can handle only 3.3V and will be damaged at higher voltages (such as 5V), I was wondering whether I can simply power the entire project at 3.3V so that all digital inputs and outputs will be at that voltage?

Yes.  As given in the datasheets, normal ATtinyX4/X5 chips can run with a supply between 2.7 and 5.5V inclusive, whereas the low-power versions can run between 1.8V and 5.5V. Mind the speed restrictions when running at lower voltages though; see the "Electrical Characteristics" section of each datasheet to determine the maximum characterized speed for a given voltage.

Won't less speed affect serial communication? Isn't there an option in the bootloader or somewhere to fix this?

Sure it will, which is why you adjust your timing mechanism appropriately.

Thanks for the comments. Does that mean that when I use 3.3V as the supply voltage that the pin voltages, e.g. the HIGH signal of a digital output will be the same 3.3V?

It will be very close. See the datasheets for details.

Specifically, table 21-1 says that V_OH is going to be at least 2.5V for a 3V power supply, so maybe 2.7V for a 3.3V supply. That should provide a sufficient safety margin for the input stage of 3.3V logic.


text:
What are some "must-have" sensors or shields for an Arduino robot or motor?
I am starting to learn Arduino and wanna make some projects.which components will  I have to buy?please help me.

Depends on the task of your robot :)
But in general: motors, wheels/chassis, motor shield, battery pack (and charger), bluetooth or other wireless communication, Arduino (nano?), LED's and probably soldering stuff, there you have the basics.

This seems interesting: http://litbimg1.rightinthebox.com/images/384x384/201412/lwxxyp1418874401020.jpg Try searching Arduino Robot Kit, you could even order the items seperatly off e-bay (to check if that's cheaper).

Make sure to pick a motor shield with an FET bridge on it - the L293/L298 and compatible bipolar bridges have horrible losses.

It largely depends on your interests but since you've mentioned robotics, a motor shield, motor power supply, and one or a couple of hobby servos or DC motors will get you started on learning about controlling mechanical motion. You may be able salvage a DC motor from something else, like the vibrator motor from a dead cell phone.
If you want to start inexpensively, a few LEDs and a ~200 Ohm resistor for each one, and a couple of light or temperature sensors will give you plenty to play with. It's amazing how much real-world data you can collect and infer from a couple of well placed temperature sensors.
LM34 and LM35 are inexpensive and easy to use analog thermo-sensors that read directly in 0.01 Volts / degree (Fahrenheit and Celsius respectively), so only minimal arithmetic conversion is required (because along the way, you'll learn about Analog to Digital conversion, too).
Get some experience with those simple parts, and the coding to make them useful, and you'll have a much better idea of what you want to do next and what you'll need to acquire to do it.


text:
What is the necessity of “Prototyping Shield” for an arduino UNO R3?
I just want to learn arduino and make some small projects.But in beginner starter kit there's a part named Prototyping Shield .Is it necessary or will it help me?

The prototyping shield can be used to build your own circuits up in a more permanent form which can be plugged direct into the Arduino.
You can think of it as a blank canvass on which you can paint your own shield design.


text:
motor hard stop vs coasting
I'm using this motor driver with 2 of these motors to control a skid steer robot. To get the robot to coast to a stop, I use this code:
  analogWrite(MotLPWM, 0);  //coast to stop
  analogWrite(MotRPWM, 0);
  digitalWrite(MotL1, HIGH);
  digitalWrite(MotL2, HIGH);
  digitalWrite(MotR1, HIGH);
  digitalWrite(MotR2, HIGH);

to get the robot to hard stop, I use this code:
analogWrite(M1PWM, 0);
analogWrite(M2PWM, 0);
digitalWrite(M1INA, LOW);
digitalWrite(M2INA, LOW);
digitalWrite(M1INB, LOW);
digitalWrite(M2INB, LOW);

I would like for the robot to stop and/or brake with something in between so it isn't so hard on the gears. The following snippet of the whole sketch is supposed to let the motors coast for 1/4 second then hard stop. Unfortunately, it doesn't coast and goes straight to the hard stop. Any ideas how to fix it?
    void allStop () {
//COAST
  analogWrite(MotLPWM, 0);  //coast for 1/4 second before fast stop
  analogWrite(MotRPWM, 0);
  digitalWrite(MotL1, HIGH);
  digitalWrite(MotL2, HIGH);
  digitalWrite(MotR1, HIGH);
  digitalWrite(MotR2, HIGH);
//HARD STOP
  if ((millis() - previousCoastMillis) > 250) {
  analogWrite(MotLPWM, 0);
  analogWrite(MotRPWM, 0);
  digitalWrite(MotL1, LOW);
  digitalWrite(MotL2, LOW);
  digitalWrite(MotR1, LOW);
  digitalWrite(MotR2, LOW);
    previousCoastMillis = millis();
  }
}

The full sketch is here:
int ledB = 5;

int MotL1 = 8;
int MotL2 = 7;
int MotLPWM = 9;

int MotR1 = 11;
int MotR2 = 12;
int MotRPWM = 10;

unsigned long previousCoastMillis = 0;
const int coastInterval = 500;

void setup() {
  pinMode(MotL1, OUTPUT);
  pinMode(MotL2, OUTPUT);
  pinMode(MotLPWM, OUTPUT);
  pinMode(MotR1, OUTPUT);
  pinMode(MotR2, OUTPUT);
  pinMode(MotRPWM, OUTPUT);
  pinMode(ledB, OUTPUT);
}

void loop() {
  go();
  allStop();
}

void allStop () {
//COAST
  analogWrite(MotLPWM, 0);  //coast for 1/4 second before fast stop
  analogWrite(MotRPWM, 0);
  digitalWrite(MotL1, HIGH);
  digitalWrite(MotL2, HIGH);
  digitalWrite(MotR1, HIGH);
  digitalWrite(MotR2, HIGH);
//HARD STOP
  if ((millis() - previousCoastMillis) > 250) {
  analogWrite(MotLPWM, 0);
  analogWrite(MotRPWM, 0);
  digitalWrite(MotL1, LOW);
  digitalWrite(MotL2, LOW);
  digitalWrite(MotR1, LOW);
  digitalWrite(MotR2, LOW);
    previousCoastMillis = millis();
  }
}

void go () {
  analogWrite(MotLPWM, 150);
  analogWrite(MotRPWM, 150);
  digitalWrite(MotL1, HIGH);
  digitalWrite(MotL2, LOW);
  digitalWrite(MotR1, HIGH);
  digitalWrite(MotR2, LOW);
  digitalWrite(ledB, HIGH);
  delay(1000);

}

You are trying to use a mix of delay and  millis
Instead you will want a proper state machine:
void loop(){

    switch (state){
    case GOING: go();
       state = WAIT_FOR_COAST;
       transition = millis();break;

    case WAIT_FOR_COAST: if(millis()-transition > 1000){
            allStop(false);
            state = WAIT_FOR_STOP; transition = millis();
        }
        break;
    case WAIT_FOR_STOP: if(millis()-transition > 250){
            allStop(true);
            state = WAIT_FOR_GO; transition = millis();
        }
        break;
    case WAIT_FOR_GO: if(millis()-transition > 1000){
            allStop(true);
            state = WAIT_FOR_GO; transition = millis();
        }
        break;

    }

}

Remove the delay in go and use a simple if-else in the allStop where parameter == true means hard stop and false means coast.
Another option is to use a extra mosfet to put a resistor across the motor instead of shorting it out (which is what the hard stop will do). That will reduce the breaking torque but defeats the isolation of the board.

I forgot to comment out the delay in the go function when I was transferring the code to this forum. Clerical error.

This works. When allStop gets called, previousCoastMillis is reset. Then the motor coasts while it's stuck in the while loop for 150ms. Then it hard stops.
void allStop () {
  previousCoastMillis = millis();
  while (millis() - previousCoastMillis < 150) {
    analogWrite(enA, 0);
    analogWrite(enB, 0);
    digitalWrite(in1, HIGH);
    digitalWrite(in2, HIGH);
    digitalWrite(in3, HIGH);
    digitalWrite(in4, HIGH);
  }

  analogWrite(enA, 0);
  analogWrite(enB, 0);
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}


text:
SD card initialization failed
i use the example sketch of SD card presented in Arduino IDE.
It runs well, but when i reboot my Adruino Mega by the reset button, the SD card initialization fails.
To fix it, i need to remove the SD card, insert it in his socket and reboot the board again. Then, SD card initialization is OK.
How can i update my code to try initialize the SD card until initialization is OK?
Also, can you explain me where come this bug ?
See the example SD card setup on the Arduino Mega:
Serial.print("Initializing SD card...");

  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

It is probably not a bug, not all sd cards are compatible with the sd library. Are you resetting the arduino while the sd card is busy? Perhaps the socket on its module is not suitable for 5v. Perhaps you use a breadboard. Perhaps the wires are too long Perhaps the arduino mega has not enough voltage due to a cheap usb cable. There are many more things that can be wrong.

is some other SPI device attached?

No other SPI device attached. I use usb cable and 20cm wires to link sd card to the arduino. I will try the work with an external 9V power supply and maybe see you soon...

After using an external power supply, initialization works well after 10 reboots !!! You're write Jot, using only the usb cable, voltage on the CS pin of SD card device is about 4.5V. With an external voltage high 5V for the arduino, CS pin of SD card device is 4.99V. I think that the problem came from here. Thanks !

A sd card is 3.3v (or at least compatible with 3.3v). Can you show a photo of the module with the socket? Is there a chip on the module to convert the 3.3v signals from the sd card to the 5v signals of the arduino?

I don't known how to post pictures here, but there is a regulator on the device. I can measure 4.99V on one of pins and 3.29V on the other on.

The spi signals for the sd card should be converted to 3.3v signals. On this module is a hc4050 to convert the signals: https://www.adafruit.com/product/254

My board is equipped with the SN74LVC125A, a 3.3V buffer. Find the board model here: https://www.amazon.fr/SKYNET-Lecteur-Reader-ARDUINO-RASPBERRY/dp/B01DNXWVES

I just add an external 9V power supply to my Arduino Mega. The SD device is power by arduino 5V pinout.

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


text:
ESP8266 library: 2 requests received instead of 1
I have a strange issue with my sketch using WiFiEsp.h library from https://github.com/bportaluri/WiFiEsp
When i send 1 request to my ESP8266 from my browser as http://192.168.0.25
, it seems that my ESP8266 receives 2 requests and run 2 times. See the sketch here and Serial Termninal:
void loop()
{
  // listen for incoming clients
  WiFiEspClient client = server.available();
  if (client) {
    Serial.println("New client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          Serial.println("Sending response");

          // send a standard http response header
          // use \r\n instead of many println statements to speedup data send
          client.print(
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: text/html\r\n"
            "Connection: close\r\n"  // the connection will be closed after completion of the response
            "\r\n");
          client.print("<!DOCTYPE HTML>\r\n");
          client.print("\r\n");
          client.print("Hello World!\r\n");
          client.print("\r\n");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(10);

    // close the connection:
    client.stop();
    Serial.println("Client disconnected");
  }
}

Serial temrinal:
[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 2.0.0
Attempting to connect to WPA SSID: Numericable-6010
[WiFiEsp] Connected to Numericable-6010
You're connected to the network
SSID: Numericable-6010
IP Address: 192.168.0.25

To see this page in action, open a browser to http://192.168.0.25

[WiFiEsp] Server started on port 80
[WiFiEsp] New client 0
New client
GET / HTTP/1.1
Host: 192.168.0.25
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Referer: http://192.168.0.25/
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7

Sending response
[WiFiEsp] Disconnecting  0
Client disconnected
[WiFiEsp] New client 1
New client
GET /favicon.ico HTTP/1.1
Host: 192.168.0.25
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
Accept: image/webp,image/apng,image/*,*/*;q=0.8
Referer: http://192.168.0.25/
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7

Sending response
[WiFiEsp] Disconnecting  1
Client disconnected

Please, could you explain why 2 clients connected ? How can i disconnect just after the first one ?

browsers automaticaly request /favicon.ico for sites

https://stackoverflow.com/questions/1321878/how-to-prevent-favicon-ico-requests

Thanks for information, but how should i code my url request ?

Could you explain the 'href' parameters ?

instead of pointing to a server, the icon is encoded in the href parameter as base64 string

Browsers automaticaly request /favicon.ico for sites. Add this to  section of your HTML to eliminate the 'favicon' request:
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
client.println("HTTP/1.1 200 OK\r\n" "Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("");
client.println("<link rel='icon' href='data:;base64,iVBORw0KGgo='>");
client.println("");
client.println("Hello World!");
client.println("");

based on this SO answer, instead of pointing to a server, the icon is encoded in the href parameter as base64 string

I changed the <link> to the last edit of the SO answer

Adding head part with hortcut icon link in html response fix the issue. Thanks !!!
            client.print(
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: text/html\r\n"
            "Connection: close\r\n"  // the connection will be closed after completion of the response
            "\r\n");
          client.print("<!DOCTYPE HTML>\r\n");
          client.print("\r\n");
          client.print("<link rel='shortcut icon' href='data:image/x-icon;,' type='image/x-icon'> \r\n");
          client.print("\r\n");
          client.print("\r\n");
          client.print("Hello World!\r\n");
          client.print("\r\n");


text:
code to force a gentle servo power up
So I am new to the board and looking for a source to answer an Arduino servo project's rough power up.  The project uses a pair of servos operating together to swing a small door.  I have been working with intro level sketches over the last few weeks. I have powered and re-powered my Arduino Uno several times with different codes and each time the unit is powered the two servo motors move to their last position at what appears to be full speed resulting in a rather jerky and jumpy power up.
What can you suggest in the code that would force the servo motors to gently move toward their new code starting position?  Like a 'warm up cycle'.

You cannot do that with ordinary servos. This is because of the way the
communication protocol is built: the only thing a servo understands is a
command which in effect means “go to that position as fast as you can”.
You can achieve smooth movements by updating the requested position (the
so called “set point”) many times by tiny steps, but you still have the
problem at startup.
I see two possible solutions to your problem:

Make sure you know the position at which the servo was left when you
powered down your Arduino. You can either arrange to leave it always
at the same position, or you can store the last position in EEPROM
before powering down. Then, at startup, you initialize the servo with
that last known set point.
Use a special type of servo known as a feedback
servo,
or convert a regular
servo to
get a feedback. A feedback servo is a type of servo that tells you
its actual position, so you can arrange for the initial set point to
match that position.

Thank you for your reply.  You are correct, I was specifically and exclusively inquiring about the ability to control the servo's rotational speed at program initialization.  I'm "learning" about the control methods for servo control post initialization... still learning.  Based upon your comment it looks like I should add EEPROM to my list of things to learn.  I will need to educate myself a little more with on line resources.

I would recommend an S curve for the angular positioning of the door.
That should guarantee a smooth start and stop.

Just to be clear, I'm not saying that you should use the S curve simply to represent absolute min and max. No. You should use it to assign the current and target position to begin and end of the curve, then split the space in between. This requires fairly accurate timing, so it might not fit well with the rest of the program you have written.

This is irrelevant to the actual problem of the question.  It might be worth contemplating later on (such as for commanded movement between positions while the system is running), but it provides no help for the present start-up difficulty.

@ChrisStratton I see the question as composed by 2 parts: a) handle the initial offset, which yes, I have not addressed, and b) "gently move", which is what I was addressing and you refer to as "later on".

No, both references are to the startup problem - see the question title "gentle servo power up" and the "warm up cycle" in what you are calling part 2 if there is any doubt.

I was referring to "What can you suggest in the code that would force the servo motors to gently move toward their new code starting position?" Doesn't that mean that there is a new target set?


text:
Receiving serial data in acsii, how to split it.
Hello I want to know how to split an incoming serial message that comes in this format CxxxLxxx, x=number, so i can take the 3 numbers after the C and save them and then take the 3 numbers after the L and also save it, i have a code for this but it doesn't always work, can anyone tell me where I´m wrong or is the approach I´m taking is not the right one. Thanks.
int value = 0;
int channel;
int x;
String str;
int y;
String str1;
int le;

void loop()
{
if (Serial.read() == le)
{ }
  else
       {
        str = Serial.readStringUntil('C');
        str1 = Serial.readStringUntil('L');
        channel = Serial.parseInt();
        value = Serial.parseInt();
      DmxSimple.write(channel, value);
      le = Serial.read();
      Serial.println();

       }
}

This:
if (Serial.read() == le)
{ }

looks very suspicious - sometimes it can read the C or L and therefore render the rest of your code useless.
Also Serial.parseInt shall be avoided - it returns the first thing which looks like a number, and will not wait for all three numbers.
However, your problem is likely the DMX write speed. While the DmxSimple.write is getting executed, no new incoming message can be processed. Depending on your actual Arduino board and chip, there is some buffer, but the solution is not rocket-proof at all.
You can:

make a solid protocol between the PC and the Arduino, i.e. the PC sends one command, arduino sends it out over the DMX, and Arduino answers an OK to the PC. The PC will not send out any new command unless it has received an OK first.
avoid these ad-hoc mess, i.e. serial-reads and serial.printlns here-and there.

For example, if you change the protocol so: CxxxLxxxE (E stands for end) you can utilize readStringUntil to read the input until a separator, and then use the toInt method to actually convert the read data to integer:
void loop() {
    strDummy = Serial.readStringUntil('C');
    strC = Serial.readStringUntil('L'); // xxx from CxxxL
    strL = Serial.readStringUntil('E'); // xxx from LxxxE
    channel = strC.toInt();
    value = strL.toInt();
    DmxSimple.write(channel, value);
}

After learning that it is not possible to change the protocol, here is a new plan
int channel;
int value;
void loop() {
    if (Serial.read()=='C') { // wait for a C
        channel=Serial.parseInt(); // parse till first non-number
        value=Serial.parseInt(); // parse till first non-number
        DmxSimple.write(channel, value);
    }
}

See https://www.arduino.cc/en/Tutorial/ReadASCIIString for a tutorial. Note that Arduino Serial commands are pretty confusing sometimes :) for example, parseInt will actually consume one non-number character implicitly after parsing a number.
Also note that this solution works well if the command is sent as one batch. If you are trying to send the command manually, e.g. from a terminal window, character by character, parseInt may time out. Consider increasing the timeout to 10 seconds or more by https://www.arduino.cc/en/Serial/SetTimeout

Thanks for the quick answer, the problem is that I get data from a program called Freestyler DMX, with the help of a program called Serialmon i saw that the protocol that the program uses is CxxxLxxx, and that why a cant add en 'E' to the protocol, I tried using Serial.readStringUntil, but cant get it to work the right way.

Ok, then do this: read and discard anything until you get a C. Then read three characters and concatenate them to a string. Then read and discard anything until you get an L. Then read three characters and concatenate them to a string. The two strings now contains the two numbers.

Ok, I tried this but it has some problem, also i dont know how to post in code again in the comment section sorry...
C = Serial.read();
Serial.print(C);
String channel_str = String(C);
String value_str = String(C);
channel_str.remove(4);   // Remove from from index=4 leaving only Cxxx
channel_str.remove(0,1);   // Remove 1 character starting at index=0 leaving only xxx
value_str.remove(0,5);   // Remove 5 characters starting at index=0 leaving only xxx
int channel = channel_str.toInt();
int value = value_str.toInt();
DmxSimple.write(channel, value);

Unfortunately, code formatting does not work in comments. I am unsure what is the reason for printing out things what you read? and what is in C - that is one character only, it makes no sense to remove anything? Anyhow I have improved my answer with an example.

Thanks for the help, i just made some changes and its ready to connect to the software FreeStyler, just having some minor problems with the processing speed but I can deal with that, thanks a lot. Should I post the code or leave it like that?

I am happy it worked! Feel free to post your code, there is always something which can help someone in any code :)
Processing speed can be a burden, try to reduce how many DMX channels you have in use in FreeStyler. One channel is 8 byte in your protocol, that is 80 bits, which makes 4 ms at 19200 bps speed. On the DMX side things go at 250kbps, and one byte (10 bits) is needed for one channel, making a full refresh cycle 20ms. Doing that over your protocol and say, 19200bps will take a bit more than 2 seconds :) (1 byte is 8 data bits, plus a start bit plus a stop bit on the uart.)


text:
exchanging data between two hc05 bluetooth modules
Iam working with gyroscope and Iam trying to send its values from one bluetooth(HC-05) module to another bluetooth module but the data exchange is not happening and I have used 2 arduino boards to do it.
Is there a simple way to do it?

You will get your required details here.

I think there is no simple answer for that. First you have to pair 2 HC-05 modules. To do so, you have to configure one HC-05 as slave, and other HC-05 as master.
Steps for SLAVE:

Be sure to select correct Baudrate in your Terminal Emulator (Arduino IDE or Terraterm etc.) for your module. There is no default baudrate... Different manufacturers set the baudrate on their HC-05's differently... 9600 and 38400 are good starting points.
Enter AT mode, by providing high level(3.3V or 5V) signal on KEY pin(PIO11)
Note the values of AT+PSWD?, AT+NAME? and AT+ADDR?(let's say 1111:22:123456) commands. You might set the password to 1234 for easy remembering. Issue AT+PSWD=0000...
Be sure to set the module to slave mode by issuing AT+ROLE=0 command.

Steps for MASTER:

Be sure to select correct Baudrate in your Terminal Emulator (Arduino IDE or Terraterm etc.) for your module. There is no default baudrate... Different manufacturers set the baudrate on their HC-05's differently... 9600 and 38400 are good starting points.
Enter AT mode, by providing high level(3.3V or 5V) signal on KEY pin(PIO11)
Reset the module to its original state by issuing AT+ORGL command.
Remove the previous parings(if any) by issuing AT+RMAAD command.
Set same password as slave by issuing AT+PASSWD=0000 command.
Change the role to master; AT+ROLE=1
Set connecting mode to any address it sees; AT+CMODE=1
Initialize the SPP profile lib ; AT+INIT
Be sure that you see the slave HC-05 module, AT+INQ command will list the modules you see.
Be sure that you see address of the slave module(1111:22:123456).
Last of all enter AT+LINK=1111,22,123456(note the commas).

With these steps you should exchange data...

Sure @szahin will try to do it


text:
Arduino Ethernet Shield on Arduino Mega Pin Usage!
I currently have an Arduino Ethernet Shield which is Mega Compatible. I've found on the Arduino Ethernet Library https://www.arduino.cc/en/Reference/Ethernet that the Shield uses different Pins on the Arduino Uno and Arduino Mega. How is this possible? The Ethernet shield isn't connected to those pins mentioned.
Arduino Uno:
Pin: 13 - SCK
Pin: 12 - MISO
Pin: 11 - MOSI
Pin: 10 - SS for Ethernet Controller
Pin: 4 - SS for SD Card
Arduino Mega:
Pin: 52 - SCK
Pin: 50 - MISO
Pin: 51 - MOSI
Pin: 53 - SS for Ethernet Controller
Pin: 4 - SS for SD Card

Those 4 pins D50 to D53 are the ICSP pins which appear twice on the MEGA; the Ethernet Shield uses the second set of connections located in the middle of the Mega board.
The header files gets told (by the Arduino IDE) that the board is a MEGA so the compiler uses those pin numbers to connect.

The SS pin is not on the ICSP header. It needs to come from one of the headers on the side still.

Firstly, I am assuming you are using an Ethernet Shield similar to the Arduino Ethernet Shield.
Secondly, I assume that you are referring to the following quote on the Ethernet Library page:

The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.

This communication interface is called SPI.
The Ethernet Shield connects to the SPI interface (ie MISO, MOSI, SCK) using the in-circuit Serial Programming (ICSP) pins which are also connected to the SPI interface pins (ie. pins 50, 51, and 52)

As noted in the above quote, pin 53 is not used as the SS pin (but needs to be kept as an output pin and not used). Pin 10 is used instead for the ethernet SS pin on both the Uno and Mega.


text:
Arduino ethernet shield not getting correct IP
I have a very simple sketch which I'm using to (try to) prove out an ethernet shield. The complete sketch is below. When I upload the sketch, the IP address that the shield gets is 0.140.140.140, which is incorrect. I just received the shield today from SparkFun, it is this one. Am I doing something wrong, or is my shield  and/or Arduino broken? The Arduino is an Uno R3. The sketch works otherwise (the LED blinks as expected).
Sketch:
#include <SPI.h>
#include <Ethernet.h>

// Network information
byte mac[] = {0xDE, 0xAD, 0xBE, 0xCF, 0xFE, 0xEE };
byte ip[] = { 172, 31, 42, 201 };

void setup() {
  pinMode(4,OUTPUT);
  digitalWrite(4, HIGH);
  delay(1);

  // initialize serial:
  Serial.begin(9600);
  Serial.println("Starting sketch...");
  Ethernet.begin(mac,ip);
  delay(1000);
  Serial.println(Ethernet.localIP());
  Serial.println("Setup done.");
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13,HIGH);
  delay(1000);
  digitalWrite(13,LOW);
  delay(1000);
  Serial.println(Ethernet.localIP());
}

The sketch you have written works perfectly with a cheap Ethernet Shield clone from eBay.  Those (and the older Arduino Ethernet Shields) use the Wiznet W5100 chip.
The new shields, of which you have one, use the newer, more powerful, Wiznet W5500 chip.
You can't use the old Ethernet library with the new Wiznet W5500 chip.  It doesn't work.
You have to use the "Ethernet 2" library as described here:

http://labs.arduino.org/Ethernet+2+Library

Note: this library is used to work with the new Ethernet shield (version 2) and Leonardo Eth that uses a new Controller W5500.

That page is linked from the product page you link to above.  If you had read the product page you would already know this.

Ok, my bad for not knowing to use the Ethernet 2 library... unfortunately,the page you linked to doesn't have a download link, and my IDE doesn't have the Ethernet2.h file available, so the sketch won't even verify with Ethernet2.h.

This is all a product of the fallout between the two superegos in Arduino.  The library (AFAIK) is bundled with the Arduino IDE that you can download from Arduino.org but not with the IDE That you can download from Arduino.cc.  These days you need both IDEs and you have to lick your finger and hold it up to see which way the wind is blowing to know which to use at that particular time.  The whole situation is getting incredibly childish and idiotic.

Well isn't that just wonderful. Another project goes to crap because people can't get along. Maybe it's time to look at a Raspberry Pi for this project.

If you're interested I have added Arduino.org (and its associated libraries including Ethernet2) top the beta version of UECIDE


text:
Pin toggle speed
If I use direct port manipulation, what is the average number of clock cycles it takes to flip a pin on the arduino
ie.
void loop(){
  PORTB |=  0b00010000;
  PORTB &= ~0b00010000;
}

So how fast is this generally?

PINB =  0b00010000; or sbi(PINB, 4); will toggle the pin in a single instruction.

If you compile the code and examine the results you can see how many instructions it will take, and thus how many clock cycles.
It's slightly more complex because of what else happens in main() to call loop, but basically you have:
for (;;) {
loop();
  aa:0e 94 49 00 call 0x92; 0x92 <loop>
if (serialEventRun) serialEventRun();
  ae:20 97       sbi wr28, 0x00; 0
  b0:e1 f3       breq.-8      ; 0xaa <main+0x10>

00000092 <loop>:
  92:2c 9a       sbi0x05, 4; 5
  94:2c 98       cbi0x05, 4; 5
  96:08 95       ret

So you can see there is:
Operation                            Cycles
Call loop()                          4
Check if serialEventRun exists       2
Since it doesn't, got start of loop  2

Then in loop:
Set bit                              2
Clear bit                            2
Return                               4

So in total you have 16 clock cycles. At 16MHz that gives you a frequency of 1MHz - however that won't be a square wave of 50% duty cycle since there is much less time between set and clear than between clear and set.  The full 16 cycles, mapped to the state of the IO pin, would look like this:
             _
 _ _ _ _ _ |   | _ _ _ _ _ _ _ _
| call  |sbi|cbi|  ret  |chk|bra|
 . . . . . . . . . . . . . . . .

You can get a much tighter operation by wrapping the pin manipulation in a while (1) loop:
void loop(){
  while(1) {
    PORTB |=  0b00010000;
    PORTB &= ~0b00010000;
  }
}

That reduces down to just:
00000092 <loop>:
  92:2c 9a       sbi 0x05, 4; 5
  94:2c 98       cbi 0x05, 4; 5
  96:fd cf       rjmp .-6      ; 0x92 <loop>

That's sbi (2) cbi (2) and rjmp (2). A total of 6 clock cycles.  At 16MHz that's 2.667MHz. Again, though, not a 50% duty cycle, since the rjmp takes two extra clock cycles:
     _
 _ |   | _ _
|sbi|cbi|jmp|
 . . . . . .

By inserting a pair of 1-cycle NOP instructions you can even out the duty cycle and make it 50%:
void loop(){
  while(1) {
    PORTB |=  0b00010000;
    asm volatile("nop");
    asm volatile("nop");
    PORTB &= ~0b00010000;
  }
}

00000092 <loop>:
  92:2c 9a       sbi 0x05, 4; 5
  94:00 00       nop
  96:00 00       nop
  98:2c 98       cbi 0x05, 4; 5
  9a:fb cf       rjmp.-10     ; 0x92 <loop>

     _ _ _
 _ |       | _ _
|sbi|n|n|cbi|jmp|
 . . . . . . . .

Now, of course, it's 8 clock cycles, so at 16MHz that's 2MHz output, but with 50% duty cycle.
Incidentally, all these instruction timings are available in the Instruction Set Summary chapter of the ATMega328P data sheet.


text:
Speed of reading I2C
How long does it take to read I2C?
I'm reading data from I2C sensor through a 20Hz timer interrupt. The interrupt handler only set the readSensorFlag, and I double checked that it happens at 20Hz through putting a Serial print there.
void TIMER2_Interrupt(void) {
  if (NRF_TIMER2->EVENTS_COMPARE[0] != 0) {
        readSensorFlag = true;
        NRF_TIMER2->EVENTS_COMPARE[0] = 0;
      }
    }

Now in the main loop I perform the reading of sensors.
void loop() {
  // Reading data from sensors to a buffer
  if (readSensorFlag) {
    readSensorFlag = false;

    if (bufferCounter < BUFLEN - 2*SAMPLESIZEINCHAR - 1) {
      epoch = millis();
      proximity = vcnl.readProximity();
      ambientLight = vcnl.readAmbient();

The strange this is that: if I set proximity and ambient light to be some constant and not reading from I2C, then the recorded sampling frequency is 20Hz:
  1988,    7,   10
  2038,    8,   10
  2088,    9,   10
  2188,    1,   10
  2238,    2,   10
  2288,    3,   10

If I revert back reading I2C code (second column is data from sensor), then frequency is only 8Hz!!!
 17637,    8,   33
 17763,    9,   33
 17937,    1,   34
 18067,    2,   35
 18194,    3,   34
 18320,    4,   34

How could reading I2C block the timer interrupt? And how could it be so slow? (I've tried a similar sensor before, and could reach 100Hz with that).

That sensor needs time for a measurement. Are you using the Adafruit library ? https://github.com/adafruit/Adafruit_VCNL4010 That library starts a measurement and waits for it to finish. The code has delays, polling, waiting loops and even wrong use of the Wire library. It was not written to be fast.

Let's take a look at a typical function for reading this sensor. This is from the Adafruit_VCNL4010 library and is for reading the proximity:
uint16_t  Adafruit_VCNL4010::readProximity(void) {
  uint8_t i = read8(VCNL4010_INTSTAT);
  i &= ~0x80;
  write8(VCNL4010_INTSTAT, i);

  write8(VCNL4010_COMMAND, VCNL4010_MEASUREPROXIMITY);
  while (1) {
    //Serial.println(read8(VCNL4010_INTSTAT), HEX);
    uint8_t result = read8(VCNL4010_COMMAND);
    //Serial.print("Ready = 0x"); Serial.println(result, HEX);
    if (result & VCNL4010_PROXIMITYREADY) {
      return read16(VCNL4010_PROXIMITYDATA);
    }
    delay(1);
  }
}

So let's tot up all the I2C transactions in that one function:
read8
write8
write8
{repeated
    read8
    [read16]
    delay(1)
}

So in a best case scenario, assuming it's in a "ready" state, that's the minimum number of transactions, and the delay doesn't occur.  So what is in each of those transactions?

read8:

Begin the transaction, write the address, end transaction, delay 170µs, begin request, read 1 byte, end transaction.  Total 4 bytes plus 170µs

write8:

Begin transaction, write address, write data. Total 3 bytes.

read16:

Begin the transaction, write the address, end transaction, begin request, read 2 bytes, end transaction.  Total 5 bytes (I notice this one has no delay...?)
So now we can see a best case scenario total of bytes transferred:
4 read8 *
3 write8
3 write8
{repeated
    4 read8 *
    5 [read16]
    delay(1)
}

4+3+3+4+5 = 19 bytes, plus 2x170µs delay.

The default clock speed for I2C on the Arduino is 100kHz. We have 19 bytes, plus start/stop/ack bits. So 19 * 8 for the data bytes (152 bits) plus 19 ACK bits (171 bits) and 5 * start + 5 * stop. That's 181 bits in total.
181 bits, at 100kHz, takes 1.81ms to transfer. Add to that the 2*170µs delay, and we are up to a best case scenario of 2.15ms transfer.
Double that up for reading the ambient light as well, and we're up to 4.3ms transfer. That's a theoretical absolute maximum of about 230Hz readings.
Remember: that's a best case scenario.  If the sensor isn't ready to return a reading at the time that there will immediately be a 1ms delay imposed and the number of transactions will increase.
So why would it not be ready to send a reading? The simplest explanation is that it's not set to a suitable sampling rate.
The library doesn't appear to change the sampling rate for the proximity from the default 1.95 samples per second, nor the ambient light sampling rate from the default of 2 samples per second - so unless you are using a different library, or manually changing these settings through your own Wire calls, even at a reduced triggering speed you'll not be getting anywhere near the kind of information you are after.
The fastest you can get for ambient light sampling is 10 samples per second. Proximity caps out at a more respectable 250 samples per second. But only if you tell it to...

Thank you so much, you've always been able to find the root of the problem! I set the sampling frequency to 20Hz (in a register of VCNL4010), and voila, it works!


text:
Avoid overflowing of counter
I have a global uint32_t that keep tracks of used Bytes:
uint32_t usedBytes;
int bytesWritten;

byteWritten = myFile.print(data, FILE_WRITE);

if (byteWritten > 0) {
  usedBytes += bytesWritten;
}

What happen if usedBytes is close to the maximum (0xFFFFFFFF)? Will incrementing it make it 0, or stuck at 0xFFFFFFFF?

It will wrap around though 0.
0xFFFFFFFF + 1 = 0

You can add a higher order word to track more data:
if (byteWritten > 0) {
    uint32_t newUsed = usedBytes + byteWritten;
    if (newUsed < usedBytes) {
        fourGigsUsed ++;
    }
    usedBytes = newUsed;
}

Or you could use uint64_t to automate it - however none of the Arduino print routines cope with the uint64_t variable type.


text:
Millisecond timestamp (13 digits) in Arduino
How can I store a 13 digits int in Arduino?
For example, current timestamp is:
1500666822235
An uint32_t can only hold 10 digits max.
64 bits integer does not seem to be supported on RFduino.

They're timestamps of sensor logging application (accel, gyro). It comes from combining millis (uptime) and RTC (absolute time).

18446744073709551615
That 20 digits. It is the maximum value of a uint64_t. Even the Arduino Uno can use the uint64_t. Perhaps the Serial.print does not support it, but the compiler supports it.
Which processor does your RFduino have ?
Where does the timestamp come from ? Perhaps you are asking the wrong question. Perhaps this is a xy-problem.

How can I store a 13 digits int in Arduino?

create a multi-byte type.
a 40-bit (32+8 bits), or a 96-bit (32+32+32) would hold a ton.
or BCD.


text:
I2C call during Wire.requestFrom
Which I2C command happen during Wire.requestFrom(address, quantity)?
Is it correct that Wire put a Start condition, then 7-bit address appended with read bit? How would that be different from Wire.write(address)?

There is no Wire.write(address) in the Wire library. The function write() takes data and puts it into the library internal write buffer. It does nothing on the I2C bus.
For master write operation (sending from master to slave) the following commands are necessary:
Wire.beginTransmission(address);
Wire.write(data);
Wire.endTransmission();

Only the last of these commands does something on the I2C bus. It generates a Start condition, sends the byte consisting of the address (that we set in the beginTransmission() statement) and the direction bit, which is always 0 here, because these commands are meant for master write operation. Then it sends the data and ends the transmission with a stop condition. You cannot control, which value the direction bit has. The parameter of beginTransmission() is only meant to be 7 bit long. If you provide a bigger address, the function will simply cut the highest bit and issuing a write operation anyway.
For master read operation the action on the I2C bus happens inside the requestFrom() function. It sends a Start condition, followed by the address and the direction bit set to 1 (again you cannot control the value of the direction bit here). Then it reads the bytes, that are coming from the slave until all requested bytes were received. Then you can read the bytes from the library internal buffer with the Wire.read() function. Again this function does nothing on the I2C bus. It only interacts with the libraries buffer.

When the master reads data, you say that the slave can end the transmission with a nack. Check the i2c protocol please.

@Jot  Mhh, seems that you are right. This is not mentioned in the protocol. But I don't understand what happens, when the slave doesn't have enough bytes to send. Are the remaining bytes all read as 0xFF, since the slave doesn't drive the SDA line to low anymore?

Yes, that is what will happen. The master does not receive less bytes but also not more bytes than requested. As long as there is no error on the bus, the master gets the amount of bytes that it wants, regardless how many bytes the slave tries to send.

When you send an address with write(), it is a register address on the device, not the device address on the bus.
The device address is set with beginTransmition() and requestFrom().
If the device requires to set the register before requestFrom(), the register address should be sent with write() wrapped in beginTransmition() and endTransmition().
Example:
Wire.beginTransmission(I2C_ADC121);
Wire.write(REG_ADDR_RESULT); // send register to read, the 'result' register
Wire.endTransmission();
Wire.requestFrom(I2C_ADC121, 2);
byte buff[2];
Wire.readBytes(buff, 2); // read value of the 'result' register


text:
if condition does not work
I'm trying to connect two Arduinos according to the example in Example
I added a bit of debug prints so the code looks like:
#include <Wire.h>

// Include the required Wire library for I2C<br>#include <Wire.h>
int LED = 13;
int x = 0;
void setup() {
  // Define the LED pin as Output
  pinMode (LED, OUTPUT);
  // Start the I2C Bus as Slave on address 9
  Wire.begin(9);
  // Attach a function to trigger when something is received.
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}
void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
  Serial.println(x);
}

void loop() {
  //If value received is 0 blink LED for 200 ms
  Serial.print("x = '");
  Serial.print(x);
  Serial.println("'");
  if (x == '0') {
    Serial.println("Do 0");
    digitalWrite(LED, HIGH);
    delay(200);
    digitalWrite(LED, LOW);
    delay(200);
  }
  //If value received is 3 blink LED for 400 ms
  if (x == '3') {
    Serial.println("Do 3");
    digitalWrite(LED, HIGH);
    delay(400);
    digitalWrite(LED, LOW);
    delay(400);
  }
}

The strange thing is, the terminal gives the following information:
...
x = '2'
x = '2'
x = '2'
x = '2'
x = '2'
x3= '3'
x = '3'
x = '3'
x = '3'
x = '3'
...

However, I never see the expected "Do 3" lines. Why is that? I assume if (x == '3) would return true when x = '3'?
Also I see the x3 = '3'instead of x = '3'... now I print x also while an event is received, but are those in two different threads since the expected text would be "3x = '3'")  or "x = '3'3"

Have you tried if (x == 3)?

@KIIV No ... however it works (that was the main problem)... Ah now I see, it's an integer ... strange the website itself contains an error. I would expect initially strings/characters to be sent but it seems everything can be sent. Thanks!

Maybe the author of that instructable never tested it.

Following code is printing value of integer as string.
int x = 0;
...
Serial.print("x = '");
Serial.print(x);
Serial.println("'");

It prints x = '3' for numeric value 3. But ASCII value for character '3' is actually 51.
And about the second issue - reveiveEvent is called from receive ISR asynchronously, so it's completely random when the main code gets interrupted. Btw printing anything inside of ISR is quite tricky. If the output buffer is full or will be filled up inside of ISR, everything gets deadlocked as it needs ISRs enabled.

I really missed the 'int' indeed.
And thanks about the comment about the ISR ... it was just for testing purposes. I know it's not good to process much things in an ISR (from my regular job).


text:
How to Use Function Code 6 Modbus RTU library
I'm trying to communicate with a temperature controller using Modbus RTU.
I used this Arduino library.
I was able to read PV(current temperature value) using below code. It uses Function code 4.
I want to set SV value(Set Value) using Function code 6
I replaced telegram.u8fct = 0x04; to telegram.u8fct = 0x06; and telegram.u16RegAdd = 0x03E8; to relevant address for SV. But, I couldn't get success.
How can I implement Function Code 6 in this library ?
Code for read PV as below. Its working properly.
    #include <ModbusRtu.h>

    // data array for modbus network sharing
    uint16_t au16data[16];
    uint8_t u8state;

    /**
        Modbus object declaration
        u8id : node id = 0 for master, = 1..247 for slave
        u8serno : serial port (use 0 for Serial)
        u8txenpin : 0 for RS-232 and USB-FTDI
                     or any pin number > 1 for RS-485
    */
    //TRANSMISSION CONTROL PIN - 8
    //HADWARE SERIAL NUMBER - 2
    Modbus master(0, 2, 8); // this is master and RS-232 or USB-FTDI

    /*
       This is an structe which contains a query to an slave device
    */
    modbus_t telegram;

    unsigned long u32wait;

    void setup() {
      Serial.begin(9600);
      master.begin(9600); // baud-rate at 9600
      master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
      u32wait = millis() + 1000;
      u8state = 0;
    }

    void loop() {
      switch ( u8state ) {
        case 0:
          if (millis() > u32wait) u8state++; // wait state
          break;
        case 1:
          telegram.u8id = 0x01; // slave address
          telegram.u8fct = 0x04; // function code (this one is registers read)
          telegram.u16RegAdd = 0x03E8; // start address in slave [CHANNEL 1 PV]
          telegram.u16CoilsNo = 0x01; // number of elements (coils or registers) to read
          telegram.au16reg = au16data; // pointer to a memory array in the Arduino

          master.query( telegram ); // send query (only once)
          u8state++;
          break;
        case 2:
          master.poll(); // check incoming messages
          if (master.getState() == COM_IDLE) {
            u8state = 0;
            u32wait = millis() + 100;
            Serial.println(au16data[0]);//PRINT TEMPARATURE VALUE
          }
          break;
      }
    }

I managed to change SV value.
According to the library, when using function code 6, It get sending data(temperature value) from au16regs[0]as below piece of code of library file.
Need to setup that value before requesting.
(ModbusRtu.h - line number 601)
case MB_FC_WRITE_REGISTER: //if cunction code 6
    au8Buffer[ NB_HI ]      = highByte(au16regs[0]);
    au8Buffer[ NB_LO ]      = lowByte(au16regs[0]);

It's OK to accept you own answer as the solution to the problem.

@VE7JRO yes. Its the ansawer to question. But, you will have to face a problem if you use this code in program with other functions.


text:
SIM900 Shield read only sms headers without text
I enable messages about new SMS
AT+CNMI=2,2,0,0,0

OK

and when received sms, output like this.
+CMT: "+79XXXXXXXXX","1","15/09/23,01:34:03+24"
Test

But when I read message, output only before <CR><LF>
I don't see text of message.
AT+CMGR=1

+CMGR: "REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"

AT+CMGL="ALL"

+CMGL: 1,"REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"
+CMGL: 2,"REC READ","+79XXXXXXXXX","1","15/09/23,01:34:03+24"

I use following  (via SoftwareSerial) code for test this.
SMSGSM.GetSMS and SMSGSM.GetAuthorizedSMS of GSM GPRS GPS Shield Library receive only phone number without sms text.
I use this shield:

AT+GSV

SIMCOM_Ltd
SIMCOM_SIM900
Revision:1137B05SIM900M64_ST_ENHAN

This is most likely a case of overrun SoftwareSerial buffer. You are reading too slowly from the modem, especially with the Serial.print()s in your code. You should look for SoftwareSerial.h in C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial if you're using Win 8 and above. Or just search your PC for it. Look for this line:
    #define _SS_MAX_RX_BUFF 64

Change 64 to 256 and save. If it solves your problem, try reducing 256 to 128 to see if it still works. The greater the size of the buffer, the lesser the amount of memory available to the rest of your program.
You could also try this, to interact with the module:
#include <SoftwareSerial.h>

SoftwareSerial SIM900(7,8);

void setup() {
  Serial.begin(19200);
  SIM900.begin(19200);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (Serial.available() > 0){
    SIM900.write(Serial.read());
  }
  while (SIM900.available() > 0){
    Serial.write(SIM900.read());
  }
}

It does the same thing as your code and doesn't require adjusting buffer size, though I still recommend you make the change if you will use other sketches.

Could you confirm that any of the commands sent over your SoftwareSerial are responding?
You probably need to add a "\n" (new line) at the end of your messages or just use println().
Also, add your code to the question so we can be of better assistance.


text:
Linking Arduino With Twitter
My project is having Arduino with my WiFi shield connect to Twitter and look for any messages that other users have tweeted at me that contain a certain color, (I.E. @myTwitterHandle I want red) and then changes an RGB LED to become that color.
I have been searching online for different methods, and found a few different solutions which I could use as a starting point. However, these apparently call to an old Twitter API that is not supported anymore (support stopped mid 2013).
One solution I came across was to use node-red as well as MQTT.  I am not too familiar with these programs.
Does anyone know how to have Arduino parse a twitter account for mentions containing certain strings and have it print to LED? Any help with be appreciated

The new Twitter 1.1 API requires OAuth authorization over SSL, for which Arduino is under-powered.
You will need to write a proxy application, which would parse the tweets and then send a RGB color value to your Arduino.
You should split your project into three parts.

Retrieving tweets with the Twitter API.
You can get some library to do it for you.
Communicating with your Arduino.
Just try to send an arbitrary color to your Arduino over internet.
And finally joining first two pieces of code together.

And if you get stuck somewhere, you can always ask for help here on StackExchenge.