text:
Arduino (Or Raspberry Pi) As HID Device
I have an Arduino Uno and A Raspberry Pi B+. I was wandering how I could use either as a Programbel HID Device (EX: https://srlabs.de/badusb/). The Reason I ask under the arduino section is I want to preferably use it. If not I can use either.

The Arduino question has already been asked and answered.  As for the pi, it is theoretically possible with a model A or zero to operate the USB as a device rather than host, though I'm not sure anyone has ever done so.  But with models such as the B+ having multiple USB connectors, an onboard USB hub gets in the way of operating in device mode.

The Uno cannot be used as a HID device through the on board USB. You might be able to use the V-USB Library to be a HID device using the digital IO pins. See this tutorial.
There are several arduino compatible boards that do can act as a HID device natively. Most boards built around the ATMega32u4 can be a HID device.  For example the Arduino Micro
See this question about the Raspberry Pi.

I would share our experience with V-USB. For educational purposes, we had the opportunity to use like 15+ Arduinos with V-USB (Adafruit Trinket). At the moment, only two of them works well. There are various issues with newer motherboards, Windows 10, and mystic enumeration problems. I strongly recommend going for 32u4, such as Arduuno Leonardo or Arduino Micro (or any similar product with 32u4)

This answer is not correct in saying that it is not possible with the stock hardware.  The Uno's USB interface is provided by a reprogrammable ATmega8u2 or 16u2, and there are writeups online of how to program that to be an HID device.  Granted, there is the subsequent difficulty of the USB-serial channel not then being available to program the Arduino, though a dual-mode firmware is conceivably possible, if perhaps challenging to use with OSX hosts.

http://arduino.stackexchange.com/questions/484/arduino-as-usb-hid


text:
Streaming audio from PC to Arduino over WiFi
Say I wanted to, purely hypothetically, set up a pirate radio station by connecting an Arduino to a WiFi network away from home, streaming music to the Arduino, decoding it, and broadcasting it with an FM transmitter.
Given an Arduino (Genuino) Uno, a Sparkfun ESP8266 Thing Dev breakout board for WiFi connectivity, and an Adafruit Si4713 Stereo FM Transmitter breakout board, how would I go about the actual streaming of music (in MP3 or WAV format) from a (Windows) computer to the Arduino over WiFi? Would an Arduino Uno be powerful enough for this? Which components would I need to decode the audio?

The limitations of the serial out of the ESP8266 and into the Arduino would be one big constraint--115200 baud doesn't leave much time for processing.  Doing stereo D/A conversion with Arduino PWM would be an even more severe constraint.

Well, a sort of... You can stream 64kbps MP3, get it via wifi from esp8266. Then for all the rest, forget the Arduino.
You need a dedicated MP3 decoder chip (many out there, sta013 was one of the oldest beasts) which can take the digital mp3 stream and convert it to analog output.
You can feed the line level analog output to the FM Transmitter, and then you're golden.
Note that you shall develop some application on the PC to actually stream out the MP3 - an off the shelf solution such as a Shoutcast server may not work, as the usual web-radio stations inject station data and currently played track metadata into the mp3 stream what you have to remove from the MP3 decoder chip.
Since the actual wifi bandwidth with ESP is limited (as well as the processing power of the Arduino), you may switch to a more efficient compression format. For example, a 64kbps WMA sounds far better than a 64kbps MP3, and at 64kbps AAC is superior to any of the other formats. Ensure that your decoder chip can work well with a modern codec comperssion format.

Great in-depth answer, thanks! For the encoding, would something newer like the VS1053B do?

Could - but you do have a full PC for encoding, no? If you wish, you can encode real time the microphone plus some music playback on the PC (called "stereo mix") and stream out via internet to your Wifi module in the wild.

source: Stack Exchange

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

sort: votes


text:
Critical sections in Arduino, interrupt consuming data
We all know the interrupts, but how do they really work?
The problem:
In my sketch an interrupt method (invoked when pin goes high) is consuming data from a buffer and the main loop() is filling the buffer at random speeds (from Internet - I'm using ESP8266, not the Arduino). Although I think there shouldn't be any threading problems with this buffer - I might be wrong - the program hangs up after random number of seconds (about half a minute average - and then the built-in watchdog resets it after few seconds). When I detached the interrupt method and merged it into the main loop() code, the problem disappeared (but I can't leave it like that). So it's probably either that I'm doing something illegal in the interrupt method (maybe it's just taking too long - how much time can an interrupt method take?) - or the second possibility - it is a threading problem.
The questions:
The main question is: how to correctly synchronize the interrupt method? How to create a critical section if the interrupt method cannot wait (for a semaphore) and if I leave it, it won't be invoked again because the pin is already high? And the detailed questions:

How to create a thread-safe variable (a bool flag), so that interrupt method can skip the critical section if the main loop has entered it? (I understand the interrupt method is "safe" - it won't be interrupted - but how to secure the regular code?)
If I detach an interrupt method that is triggered when a pin goes high when it is low (for just a few fast instructions), the pin gets high in that time, and then I'll re-attach the method to this pin again, will it be invoked? The same question for noInterrupts(); How to make sure it will be invoked, if I can't check the pin and invoke (or not) the method manually in an atomic transaction with re-attaching the method?
If I detach this method (in main loop), is it possible that it will be invoked before the control is back from the detachInterrupt() method? (because the pin got high from external device in this very moment) And the same question for noInterrupts();
I've read that noInterrupts(); causes some things, like reading incoming serial data, to be skipped. Can this method be even used if I don't want that? Or can I have guaranteed that it won't happen if the method is fast enough? (if so, please define the "fast enough"!)

So, is there a common template for creating a critical section between an interrupt method and the regular code? Or at least synchronizing a variable access? And if not, how to make sure the detached/blocked pin method will be invoked after re-attaching/re-enabling it?
The common buffer code:
(if you want to check whether this can cause any "threading" problems)
class Buffer
{
  protected:
    byte *buf;
    int len, readpos, writepos;
    bool wasFull, wasEmpty;
    long ratioSum, ratioCount;

  public:
    Buffer(int length)
    {
      len = length;
      buf = new byte[len];
      readpos = writepos = 0;
    }

    bool isFull()
    {
      bool full = writepos - readpos >= len;
      wasFull &= full;
      return full;
    }

    bool isEmpty()
    {
      bool empty = readpos >= writepos;
      wasEmpty &= empty;
      return empty;
    }

    void write(byte b)
    {
      if (isFull()) { if (!wasFull) { wasFull = true; Serial.println("Error: Buffer overflow!"); } return; }
      int pos = (writepos++) % len;
      buf[pos] = b;
      if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
    }

    byte read()
    {
      if (isEmpty()) { if (!wasEmpty) { wasEmpty = true; Serial.println("Error: Buffer underflow!"); } return 0; }
      int pos = (readpos++) % len;
      if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
      return buf[pos];
    }

    int available()
    {
      return writepos - readpos;
    }

    void measureRatio()
    {
      ratioSum += available();
      ratioCount++;
    }

    int getRatio()
    {
      int ratio;
      if (ratioCount > 0)
        ratio = 100 * ((float)(ratioSum / ratioCount) / (float)len);
      else
        ratio = 100 * ((float)available() / (float)len);
      ratioSum = 0;
      ratioCount = 0;
      return ratio;
    }
};

PS:
I have discovered that printing to Serial in the interrupt method (even without a flush() is causing my program to crash after max half a second. Is it just a duration of printing or is it something else? Also if you're thinking that the warning printing in my Buffer code can cause the crashes, then I assure you that they're not because I always check isEmpty() and isFull() before each read and write operation, so they just can't occur.

For people looking for a really good interrupts tutorial and detailed deep info how they work, I have found this great article by Nick Gammon:
http://gammon.com.au/interrupts

Warning: I am not familiar with the ESP8266 hardware, and some of my
answers below may be only valid on the AVR architecture.
The simplest way to synchronize your main code with your interrupt
service routine is to define a critical section in your loop() that
wraps access to the shared data, and to make sure this critical section
cannot be interrupted:
noInterrupts();
buffer.write(data);
interrupts();

This should be fine as long as you make the critical section as short as
possible. Majenko's recommendation, to inspect the write() method with
“a fine toothed comb” in order to minimize the critical section, is
definitively good advice.
To understand the relevance of the “as short as possible” requirement,
think about what could happen if the interrupt triggering event (the pin
going high) happens while interrupts are disabled. If this happens
once, it's not a problem: the interrupt is put on hold (technically,
an interrupt flag is raised), and then it's serviced as soon as
interrupts are enabled again. However, if the pin goes high twice
while interrupts are blocked, then, when you enable interrupts again,
the interrupt handler will be called only once. Whether this is a
problem or not I cannot say, it all depends on what job the handler is
supposed to do.
Now, to the specific sub-questions:

How to create a thread-safe variable (a bool flag)

Chances are the boolean can be read and set atomically, so it's
inherently thread-safe. On an 8-bit CPU, like the AVR, access to a
multi-byte variable has to be protected inside a critical section. But
since you have a 32-bit CPU, I bet you have atomic access to variables
up to 32-bit wide.

If I detach an interrupt method that is triggered when a pin goes high
  when it is low (for just a few fast instructions), the pin gets high
  in that time, and then I'll re-attach the method to this pin again,
  will it be invoked?

Hard to say without reading both the datasheet of the hardware and the
source code of attachInterrupt(). It may be safer to keep the handler
attached and start its code with something like
if (doNotRunInterruptHandler) return;.

The same question for noInterrupts();

Yes, it will be invoked, but at most once.

If I detach this method (in main loop), is it possible that it will be
  invoked before the control is back from the detachInterrupt() method?

Yes, the interrupt can fire while detachInterrupt() is checking to see
whether you gave it valid parameters.

same question for noInterrupts();

Check the implementation. On the AVR, noInterrupts() is atomic.

I've read that noInterrupts(); causes some things, like reading
  incoming serial data, to be skipped.

Nothing like this will happen if your critical section is fast enough.

please define the "fast enough"!

It depends on how long you can afford to delay the interrupt service
routine. For example, if you are reading serial data at 115200 bps
and the UART has only a one-byte buffer, then a 86 µs critical
section can make you loose one byte.
Then, there is the risk that several interrupts of the same kind fire
during the same same critical section. As said before, the interrupt
will only be serviced once. If this is a problem, then you should not
block interrupts for longer than the minimum possible period of the
triggering event.
Also, there is always the risk that several, unrelated interrupts fire
during the same critical section. Then, the one with the lowest priority
will have to wait for the critical section to finish and then for the
higher priority interrupt to be serviced.

"Chances are the boolean can be read and set atomically, so it's inherently thread-safe." - if that's even true, it doesn't solve the problem of reading a flag, and if it's false then setting it to true (a flag that acts like semaphore for critical section). The interrupt can happen between reading and writing the flag, so both "threads" can enter and "think" that they're alone. There should be an atomic exchange instruction that inverts values between two variables (registers) - this is the only way to make it safe as far as I know. Is something like that in Arduino/ESP?

Firing the delayed interrupt only once is not a problem in my case because it's a "ready for more data" signal. So, if I understand correctly, the only safe way for me is the noInterrupts() and wrapping write() with it, because after this line I can be sure that the interrupt won't be fired and it won't be skipped if the pin got high during critical section. Knowing that, I've wrapped the write() in it, removed substracting positions from read() method (write() is now safe) and also blocked the Serial printing (just to make sure) - and it is still crashing... How is it possible?

@P.W.: There is no support for atomic exchange in the Arduino library: you may need to look low level, at the instruction set. The AVR architecture only supports this in the XMega cores, and I know no Arduino using these cores. As for why your program is still crashing, I do not know.

Ok, so knowing that the program works fine when the interrupt method is just called from loop() instead attaching it to the interrupt, knowing what I just did (the comment above) and looking at the "critical" buffer code - are you sure that there are no "threading" errors left? The code should work and there is nothing left that can be done? (The interrupt method just reads the buffer and forwards it through SPI in very small portions and at high speed). PS: Thank you for the useful facts in your answer.

Man! You gave me the answer but even you didn't realize that! See my own answer for details - thank you!

The trick here is not to make your interrupt routine, or your main routine "thread safe" - instead you need to make the single item that is shared by the two "thread safe". That means your Buffer class.
You need to go through that with a fine toothed comb and work out which bits could possibly be accessed by the two contexts at once and protect them.
The bits that jump out at me immediately are the calculations and manipulations of writepos and readpos. Accesses to those variables need to be made as atomic as possible.  One of the best ways of doing that is to massively restrict the actual access to those variables and wrap those accesses in critical sections (disable / enable interrupts). That keeps the critical sections as short as possible.
For instance, instead of directly manipulating the variables, as you enter the function you first create "cached" copies of the variables you will modify that could be modified at the same time (such as writepos being written to in the ISR):
cli();
int cachedWritePos = writepos;
sei();

Then you do your manipulations and calculations on those cached variables. Finally, just before you exit the function, you write your now safely changed cached variable values back to the member variables:
cli();
writepos = cachedWritePos;
sei();

The critical sections are then as brief as possible, and any heavy calculations (I count the modulus operator % as a heavy calculation) don't block the interrupt from firing.
Of course that is not a foolproof method and doesn't protect against two contexts changing the same variable and it getting out of step. To counter that you will have to use a mutex. There's no getting around that, other than ensuring that your program never changes the same variables from two different contexts. The only mutex you really have access to is a manually implemented spinlock.
On that note, I am having some trouble following the logical flow of how your buffer works. There are bits that don't look quite right to me, such as this bit:
if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }

According to my way of thinking both readpos and writepos have to have reached (or exceeded) the end of the buffer for them to wrap around to the start again.  That can't really happen properly in a function that is only writing, or a function that is only reading. I think you want to only be checking writepos and wrapping that in the write function, and only checking readpos and wrapping that around in the read function, not both in both functions.
As far as using Serial in an interrupt goes, the general rule is: don't do it.  I don't know about the ESP8266's serial code, but certainly on the Arduino it relies on interrupts being used to take each character from the TX buffer and transmitting it through the UART interface. If you are in an interrupt routine and your (64 byte) serial TX buffer fills up any attempts to write to that buffer (Serial.print) will block until the interrupt that sends the characters has made some room for you - and of course that interrupt will never happen while you're blocking because you are in an interrupt at the time.
On systems with multiple priority levels of interrupt (such as a PIC32) the same holds true if you are in an interrupt routine that is at a higher priority than the Serial interrupt. If you are in a lower priority one the serial interrupt can still interrupt your current interrupt routine and function correctly.

“I count the modulus operator % as a heavy calculation”. Modulus is cheap if the compiler can optimize it to a bitwise AND, i.e. if the dividend is unsigned and the divisor is both a power of two and a compile-time constant. This is not the case in the OP's code, but that could probably be fixed.

Regarding to the line if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; } - it's logically OK. It's just for preventing readpos and writepos from exceeding the range of an int and becoming negative. And they should be checked and modified together, because if you would substract only the writepos (which first crosses the line) then it would become less than the readpos, meaning that there were more bytes read than written. It doesn't matter when this substraction is done, as long as it is done together and is thread-safe (and it isn't!). Thanks for tips!

You might want to consider a circular buffer (unless that is what you are attempting, I am not sure with your code).

Yes, I think that a circular buffer is what I just did here - but what do you mean by that? Are you thinking about some specific class? (I'm not very good at C++ so I may not know some obvious common classes).

The logic of your system looks like an attempt at a circular buffer but hasn't quite got it right. I have a CircularBuffer library you are welcome to pull apart and see how it should work: https://github.com/MajenkoLibraries/CircularBuffer

Thanks, but do you see any logical errors in this code? Because it works just fine (if not invoked from an interrupt!). Worked for almost 1.5h and didn't crash (while on interrupt it's about 30 seconds).

I am still concerned about how you think the circular buffer is meant to work with that code I highlighted in my answer. Despite your explanation it still makes absolutely no sense to me. The write function should never have any need to change the read pointer, nor the read function the write pointer. Ever. Full stop. Reading and writing are completely separate things.

@Majenko I agree it's not a good idea and unnecessary (and maybe I'll even change that later) but it makes perfect sense: writepos - readpos means how many bytes is writing ahead of reading. When any of them reaches the size of buffer, it is wrapped around (by modulo) so the buffer is written/read from start again. If both of them are greater than the length of the buffer and you substract a buffer size from both of them at once then both data positions (calculated by modulo) and writepos - readpos value does not change. It's for preventing overflow (size of int) only.

That still makes no sense at all. When you write you should wrap the write pointer. It won't overflow. When you read you wrap the read pointer. It won't overflow. If the write pointer would equal the read pointer after a write then the buffer must be full so you block waiting to write or discard data depending on what you are doing.

@Majenko You don't understand, the writepos and readpos are not wrapped - they are just incremented (and that's why I have to worry about int range). The modulo is calculated only at the moment when accessing the byte of data. If you don't believe me this code ok then create some unit tests and check it out. This is for 100% not the cause of the problem.

It's no wonder it isn't working then, and no wonder I cannot understand the logic of your program. That is certainly not how you create a circular buffer!

Let us continue this discussion in chat.

My problem with crashing is fixed! :) I will share here what was wrong - maybe someone will have similar problem in the future.
But first...
I have marked Edgar Bonet's answer because he answered most of the difficult questions that were bothering me and for pointing me out that reading a 16-bit variable on 8-bit processor is not atomic (it was the most significant clue) and for helping me to understand that noInterrupts() is the safe and only way to synchronize with the interrupt method in my case. Thanks Edgar! But credits also go to Majenko because I wouldn't have guessed it without him. He pushed me into the right direction in our chat discussion - that I have to secure all the methods accessing readpos and writepos. Thanks Majenko. I agree with him that my Buffer code is ugly and it's not a good way to implement a circular buffer, but it was still logically OK - it just needed one more thing...
The solution
You probably know it already. The key is the non-atomic reading of readpos and writepos. For example: the code from loop() starts to read readpos, reads the first byte of it, then the interrupt happens, readpos changes there and the loop() continues reading the other (changed) half, which is then glued with the old (out of date) half - so - a random value. Or another one: the loop writes first byte of writepos (as it fills the buffer) and then interrupt fires and reads the first (changed) byte with the old (out of date) second byte. So the solution is to just wrap all access to those variables with noInterrupts() - and the whole code works perfect! :) Thank you guys! Not only for helping me to fix it, but for helping me to understand it.
Here is how it looks like now (non-crashing version):
class Buffer
{
  protected:
    byte *buf;
    const int len;
    int readpos, writepos;
    bool wasFull, wasEmpty;
    long ratioSum, ratioCount;

  public:
    Buffer(const int length)
      : len(length)
    {
      buf = new byte[len];
      readpos = writepos = 0;
    }

    bool isFull()
    {
      noInterrupts();
      bool full = writepos - readpos >= len;
      wasFull &= full;
      interrupts();
      return full;
    }

    bool isEmpty()
    {
      noInterrupts();
      bool empty = readpos >= writepos;
      wasEmpty &= empty;
      interrupts();
      return empty;
    }

    void write(byte b)
    {
      if (isFull()) return;//{ if (!wasFull) { wasFull = true; Serial.println("Error: Buffer overflow!"); } return; }
      int pos = (writepos++) % len;
      buf[pos] = b;
      if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
    }

    byte read()
    {
      if (isEmpty()) return 0;// { if (!wasEmpty) { wasEmpty = true; Serial.println("Error: Buffer underflow!"); } return 0; }
      int pos = (readpos++) % len;
      //if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
      return buf[pos];
    }

    int available()
    {
      noInterrupts();
      int result = writepos - readpos;
      interrupts();
      return result;
    }

    int free()
    {
      noInterrupts();
      int result = len - available();
      interrupts();
      return result;
    }

    void MeasureRatio()
    {
      ratioSum += available();
      ratioCount++;
    }

    int getRatio()
    {
      int ratio;
      if (ratioCount > 0)
        ratio = 100 * ((float)(ratioSum / ratioCount) / (float)len);
      else
        ratio = 100 * ((float)available() / (float)len);
      ratioSum = 0;
      ratioCount = 0;
      return ratio;
    }
};

I'm glad it's working now. Thank you for sharing this final summary.

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


text:
Resend data traffic from an Arduino
I have an Arduino with an Ethernet shield and I want to capture all Ethernet data traffic that connects to the Arduino via [as?] a router. This is because I want to use the Arduino like a honeypot and at the same time resend the Ethernet traffic to the Raspberry, but only specific TCP traffic instead of UDP.
In other words, I want to resend all of the traffic data from an Arduino to a Raspberry Pi, but I need to only resend all of the TCP traffic because the Raspberry reads and parses this. However, I only see examples of UDP traffic but nothing related to TCP. It doesn't matter what kind of port the Arduino listens on, I just need the data out of the other side, can you help me?

I am sorry, I am having a hard time understanding what you are asking here (I am guessing a language barrier). Can you clarify what it is you are trying to achieve? What traffic are you referring to - how does the arduino receive it? What form does it take?

Your question statement doesn't make a lot of sense, but I have to wonder at your design.  Given that a conventional Arduino has no network interface, and is terribly short on resources to deal with network traffic at all, it really makes little sense to connect a network to the Arduino, rather than directly to the pi.

Sorry, my english is not as well as I want, I am spanish user...well, I have an arduino with its ethernetshield, I want to capture all ethernet data traffic that connects to arduino since a router because I want to use the arduino like honeypot and at the same time resend the ethernet traffic to raspberry, but specific TCP traffic instead of UDP, I don't now If your are understand me, sorry.

I have tried to reword your question, although a few points remain unclear: when you say since a router ("desde un router"?) do you mean that you have the Pi and the Arduino both connected to a router? Or are you using the Arduino as a router/filter to filter the traffic and only resending TCP traffic on to the Pi? To do the latter, you would need two Ethernet shields, one for the incoming UDP and TCP packets and one for the outgoing TCP packets that will go to the Pi. You would also need to use a hub, and not a switch or router as otherwise the Arduino will only see traffic intended for it.

Also, can you post your sketch that you are using with the Arduino, to filter the packets, and also a network diagram to clarify how you have the Pi and the Arduino (and the router (if there is one) and the rest of the network) connected? As it stands your question is rather unclear and is likely to be closed, unless your provide clearer information and the sketch and the network diagram to illustrate what you actually mean.


text:
Disable other buttons while one of buttons is pressed
I'm making a project with three buttons. What I'm trying to do is to disable other buttons (make them not respond to a click event) when one of three buttons is pressed.
For now I have this code:
    const int button1=3;
    const int button2=4;
    const int button3=5;

    int button1State=0;
    int button2State=0;
    int button3State=0;

    void setup() {
    pinMode(button1, INPUT);
    pinMode(button2, INPUT);
    pinMode(button3, INPUT);
    }

   void loop() {
   button1State=digitalRead(button1);
   button2State=digitalRead(button2);
   button3State=digitalRead(button3);

   if( button1State == HIGH){
   // do some stuff
   }

    if( button2State == HIGH){
    // do some stuff
    }

    if( button3State == HIGH){
    // do some stuff
    }

    }

Do you have any ideas how I could do it?
Thanks is advance for any suggestions!

what code do you have so far?

I've added a code to the post question

Yea, definitely use an FSM as per my suggestion below.

The best solution for this is a finite state machine. There are lots of tutorials on state machines, just google.
Finite state machines are a very important concept in coding. You will find the need for them everywhere. Do yourself a favour, and read up about them, practice them, understand them, love them. Understand when they will be useful, and when they are not. If you do not, you will be back here shortly, with another question, which could also be solved by a finite state machine.
I strongly recommend you use this task as a practice task for learning about finite state machines.
Note also that, in electrical circuits, you frequently get bounce - when you push a button, your arduino will see many "button presses" (from off, to on, back to off), until it settles down. See http://blog.kennyrasschaert.be/images/20140401/Bouncy_Switch.png for example. A state machine can also help you with this.
If you don't want to learn about FSMs, read on:
initialise last_button_pressed to 0 (meaning no button pressed)
if last_button_pressed>0
   if not(is_button_pressed(last_button_pressed) then
      last_button_pressed=0
else (no button is pressed)
   for each button_to_check (1,2,3)
      if last_button_pressed=0 and is_button_pressed(button_to_check) then
         last_button_pressed=button_to_check

Thanks a lot for your suggestion. I'll surely learn about finite state machine and hope it will work for me

The principle of FSMs are not that difficult. Have a go, and post your state diagram here, and I will give you some more pointers. Then you can try implementing it, and I can give you more pointers.


text:
Arduino Pro Micro and HC-05 Bluetooth module
I am using Sparkfun Arduino Pro Micro with an ATmega32u4(3.3v, 8MHz) on it (https://www.sparkfun.com/products/12587) and a HC-05 Bluetooth Module. I also running this on Windows 10.
I've made these connections: (same as this tutorial) with some additional for leds
Arduino Pro Micro TxD (Pin 0) -> HC-05 RxD
HC-05 TxD -> Arduino Pro Micro RxD (Pin 1)
I am following this tutorial: http://playground.arduino.cc/Learning/Tutorial01
I have two Serial ports available for the HC-05 COM30(incoming) and COM31(Outgoing). When I try to send letter 'H' in Serial monitor on COM31 the arduino ide freezes and the HC-05 flashes rapidly. When I try to send letter 'H' in Serial monitor on COM30 it sends but nothing happens as H should ideally turn on the led. The arduino pro works with a button but I would like to send the command externally as in the tutorial. I also try in processing but the same thing happens as when using the arduino serial monitor. I have been trying for a couple of days now with no idea why it is not working, I have tried adjusting baud rates and changing to Serial1 with no change.
I uploaded this to the Arduino to test the Bluetooth module:
#include <SoftwareSerial.h>

char val; // variable to receive data from the serial port
int ledpin = 6; // LED connected to pin 48 (on-board LED)
int ledpin2 = 5;
void setup() {
  pinMode(ledpin, OUTPUT);  // pin 48 (on-board LED) as OUTPUT
  pinMode(ledpin2, OUTPUT);  // pin 48 (on-board LED) as OUTPUT
  Serial.begin(9600);
  Serial1.begin(9600);       // start serial communication at 9600bps
}

void loop() {
  if( Serial1.available() )       // if data is available to read
  {
    digitalWrite(ledpin2, LOW);
    val = Serial1.read();         // read it and store it in 'val'
  } else {
    digitalWrite(ledpin2, HIGH);
  }
  if( val == 'H' )               // if 'H' was received
  {
    digitalWrite(ledpin, HIGH);  // turn ON the LED
  } else {
    digitalWrite(ledpin, LOW);   // otherwise turn it OFF
  }

  delay(100);                    // wait 100ms for next reading
}

Processing code:
//import class to set up serial connection with wiring board
import processing.serial.*;
Serial port;
//button setup
color currentcolor;
RectButton rect1, rect2;
boolean locked = false;
void setup() {
  //set up window
  size(200, 200);
  color baseColor = color(102, 102, 102);
  currentcolor = baseColor;
  // List all the available serial ports in the output pane.
  // You will need to choose the port that the Wiring board is
  // connected to from this list. The first port in the list is
  // port #0 and the third port in the list is port #2.
  println(Serial.list());
  // Open the port that the Wiring board is connected to (in this case 1
  // which is the second open port in the array)
  // Make sure to open the port at the same speed Wiring is using (9600bps)
  port = new Serial(this, Serial.list()[2], 9600);
  // Define and create rectangle button #1
  int x = 30;
  int y = 100;
  int size = 50;
  color buttoncolor = color(153, 102, 102);
  color highlight = color(102, 51, 51);
  rect1 = new RectButton(x, y, size, buttoncolor, highlight);
  // Define and create rectangle button #2
  x = 90;
  y = 100;
  size = 50;
  buttoncolor = color(153, 153, 153);
  highlight = color(102, 102, 102);
  rect2 = new RectButton(x, y, size, buttoncolor, highlight);
}
void draw() {
  background(currentcolor);
  stroke(255);
  update(mouseX, mouseY);
  rect1.display();
  rect2.display();
}
void update(int x, int y) {
  if(locked == false) {
    rect1.update();
    rect2.update();
  } else {
    locked = false;
  }
  //Turn LED on and off if buttons pressed where
  //H = on (high) and L = off (low)
  if(mousePressed) {
    if(rect1.pressed()) {            //ON button
      currentcolor = rect1.basecolor;
      port.write('H');
    } else if(rect2.pressed()) {    //OFF button
      currentcolor = rect2.basecolor;
      port.write('L');
    }
  }
}
class Button {
  int x, y;
  int size;
  color basecolor, highlightcolor;
  color currentcolor;
  boolean over = false;
  boolean pressed = false;
  void update()
  {
    if(over()) {
      currentcolor = highlightcolor;
    } else {
      currentcolor = basecolor;
    }
  }
  boolean pressed()
  {
    if(over) {
      locked = true;
      return true;
    } else {
      locked = false;
      return false;
    }
  }
  boolean over()
  {
    return true;
  }
  void display()
  {
  }
}
class RectButton extends Button {
  RectButton(int ix, int iy, int isize, color icolor, color ihighlight)
  {
    x = ix;
    y = iy;
    size = isize;
    basecolor = icolor;
    highlightcolor = ihighlight;
    currentcolor = basecolor;
  }
  boolean over()
  {
    if( overRect(x, y, size, size) ) {
      over = true;
      return true;
    } else {
      over = false;
      return false;
    }
  }
  void display()
  {
    stroke(255);
    fill(currentcolor);
    rect(x, y, size, size);
  }
}
boolean overRect(int x, int y, int width, int height) {
  if (mouseX >= x && mouseX <= x+width &&
      mouseY >= y && mouseY <= y+height) {
    return true;
  } else {
    return false;
  }
}


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:
MatLab connection to Arduino using Bluetooth
I am attempting to send some information from MatLab to an Arduino Uno via Bluetooth with the following
MatLab program:
b=Bluetooth('HC-06',1);
fopen(b);
for i=1:1:15
  fprintf(b,i);
  out(i) = fscanf(b,'%d');
end
fclose(b)

and Arduino program
int matlabval=0;

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

void loop() {
  if (Serial.available() > 0) {
    matlabval = Serial.read();
    Serial.println(matlabval);
  }
}

the output  of arduino is
1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
10
10
10
11
10
12
10
13
10
14
10
15
10
The number 10 appears after each number. Why is that so?
Thanks in advance!

http://www.asciitable.com/
Decimal 10 is the ASCII code for a "New Line" so it appears your Matlab send code will add a "New-line" after each sent value.

As discussed in the comments, the "problem" seemed to be Matlab adding a "New Line" which is a decimal 10 in ASCII.

asciitable.com Decimal 10 is the ASCII code for a "New Line" so it appears your Matlab send code will add a "New-line" after each sent value. – Paul Apr 14 at 8:15

thank you very match the problem is solved – abbas hussien 5 hours ago

You might want to accept this answer so that this question gets "closed" and the site's statistics will be more accurate.
It will also avoid this question being bumped up by the system and people reading into something that has already been solved.


text:
Arduino serial non-blocking
I'm writing an Arduino program to communicate with another module using RS485, so I need to control data flow with one pin. But when I set the pin to HIGH (line 88) it almost instantly falls (as you can see in the image, line 70). So my guess is that Arduino Serial.write() function is non-blocking, but I need it to be blocking so the flow control pin stays high during whole packet transmit. Please help. Thank you.

Please post the code as text rather than image. And indent it by selecting it and clicking the {} button. It makes things easier for those who want to help you.

You are right: Serial.write() is non blocking: it puts the data in a
buffer and waits for an interrupt routine to send it through the UART.
If you want to wait for the transmission to complete, you can call
Serial.flush().


text:
ESP8266 module cutting connection with PC via USB
My Arduino UNO is connected directly to the ESP8266 (01) WiFi module. The Red and Blue LED flashes and it seems to work properly. But when I connect the UNO to my computer, the module refreshes at irregular intervals and the PC produces sounds as that of ejecting and inserting a USB. I don't know whether this is caused due to low voltage supplied from the USB or some other reason. Please help me out...

At which pins you connected the ESP8266?
The pins pin 0 (RX) an 1 (TX) are connectet internaly to the FTDI USB-to-TTL Serial chip.
If you using Serial.begin() to communicate with the ESP8266, you can't communicate with the pc at the same time.
Use SoftwareSerial to communicate with the ESP8266 an Serial to PC.
It is also recommed to feed the ESP8266 with an external 3.3V power supply and stabilize with an capacitor. This could  produces the sounds of ejecting and inserting a USB.

I've used pin 0 and 1. Since I'm a newbie to Arduino can you please provide a link for using SoftwareSerial.

A tutorial for using SoftwareSerial can be found here. For the code you can read this. Also this blog post could be helpful.


text:
Measuring The Distance Using GPS programmed with Arduino
Who among here have tried measuring the before and after distance traveled using gps? I'm going to use the code from TinyGPS library's distance_between command without constant value of latitude and longitude,
like this:
static const float LONDON_LAT = 51.508131, LONDON_LON = -0.128002

I want to see that the first GPS latitude and longitude results is used as reference point.
How will I apply it on my code so that I could be able to get the distance I traveled? Please help me.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
 /*
   This sample code demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
 */
 static const int RXPin = 4, TXPin = 3;
 static const uint32_t GPSBaud = 4800;

  // The TinyGPS++ object
TinyGPSPlus gps;

 // The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup()
{
 Serial.begin(115200);
 ss.begin(GPSBaud);

     Serial.println(F("FullExample.ino"));
     Serial.println(F("An extensive example of many interesting     TinyGPS++ features"));
  Serial.print(F("Testing TinyGPS++ library v. "));                    Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
  Serial.println(F("Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars     Sentences Checksum"));
     Serial.println(F("          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
           Serial.println(F("---------------------------------------------------------------------------------------------------------------------------------------"));
}

void loop()
{
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
  printInt(gps.hdop.value(), gps.hdop.isValid(), 5);
  printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
  printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
  printInt(gps.location.age(), gps.location.isValid(), 5);
  printDateTime(gps.date, gps.time);
  printFloat(gps.altitude.meters(), gps.altitude.isValid(), 7, 2);
  printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
  printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
  printStr(gps.course.isValid() ?        TinyGPSPlus::cardinal(gps.course.value()) : "*** ", 6);

  unsigned long distanceKmToLondon =
   (unsigned long)TinyGPSPlus::distanceBetween(
     gps.location.lat(),
     gps.location.lng(),
     LONDON_LAT,
     LONDON_LON) / 1000;
     printInt(distanceKmToLondon, gps.location.isValid(), 9);

     double courseToLondon =
    TinyGPSPlus::courseTo(
     gps.location.lat(),
     gps.location.lng(),
     LONDON_LAT,
     LONDON_LON);

   printFloat(courseToLondon, gps.location.isValid(), 7, 2);

   const char *cardinalToLondon = TinyGPSPlus::cardinal(courseToLondon);

   printStr(gps.location.isValid() ? cardinalToLondon : "*** ", 6);

   printInt(gps.charsProcessed(), true, 6);
   printInt(gps.sentencesWithFix(), true, 10);
   printInt(gps.failedChecksum(), true, 9);
   Serial.println();

   smartDelay(1000);

   if (millis() > 5000 && gps.charsProcessed() < 10)
    Serial.println(F("No GPS data received: check wiring"));
   }

  // This custom version of delay() ensures that the gps object
  // is being "fed".
  static void smartDelay(unsigned long ms)
  {
  unsigned long start = millis();
  do
  {
   while (ss.available())
    gps.encode(ss.read());
    } while (millis() - start < ms);
    }

    static void printFloat(float val, bool valid, int len, int prec)
     {
   if (!valid)
   {
    while (len-- > 1)
    Serial.print('*');
    Serial.print(' ');
    }
    else
    {
   Serial.print(val, prec);
   int vi = abs((int)val);
   int flen = prec + (val < 0.0 ? 2 : 1); // . and -
   flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
   for (int i=flen; i<len; ++i)
   Serial.print(' ');
   }
   smartDelay(0);
  }

 static void printInt(unsigned long val, bool valid, int len)
 {
  char sz[32] = "*****************";
  if (valid)
  sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
   sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartDelay(0);
  }

  static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
  {
  if (!d.isValid())
   {
   Serial.print(F("********** "));
   }
   else
   {
   char sz[32];
   sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
   Serial.print(sz);
    }

    if (!t.isValid())
    {
    Serial.print(F("******** "));
    }
    else
    {
    char sz[32];
    sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
    Serial.print(sz);
    }

    printInt(d.age(), d.isValid(), 5);
    smartDelay(0);
    }

    static void printStr(const char *str, int len)
    {
    int slen = strlen(str);
    for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
    smartDelay(0);
    }

This is where those dreaded maths classes come in.
You know - the ones where no one paid attention because you thought "Where in the real world would I ever want to know this stuff?" Well, right here is were you would want to know this stuff.
The distance between two points on a 2D plane (i.e., a map) can be looked at as two vertices of a right-angled triangle.

Going from Start to Finish you travel X degrees across the globe and Y degrees up or down it.  So you can calculate the number of degrees between the two points with simple pythagoras' theorem:

In C it's quite easy to do those calculations.  You can find X and Y by subtracting the two longitudes and scaling it for the logitudinal circumference of the Earth where you are. You can do the latitudes in a similar way:
float X = ((long2 - long1) * 24901 * cos(lat1)) / 360.0
float Y = ((lat2 - lat1) * 24860) / 360.0

24901 is the circumference of the Earth at the equator, and 24860 is the circumference of the Earth going through both poles. Both are in miles, so the result will also be in miles. The numbers are different for the two directions because the Earth is not a perfect sphere. It is somewhat flattened at the poles, and is called an oblate sphere.
It doesn't matter which one you subtract from which since, when you square them, they will become positive anyway:
float X2 = X * X;
float Y2 = Y * Y;

Then you can get the square root:
float Distance = sqrt(X2 + Y2);

So now you know how to calculate it without relying on some function in some library. It only takes a couple of lines of C code and you don't have to then know just how to use this unknown function provided by a library, and the theory will stand you in good stead for future similar projects.
Oh, and the code in full, in case you want it:
float X = ((long2 - long1) * 24901 * cos(lat1)) / 360.0
float Y = ((lat2 - lat1) * 24860) / 360.0
float X2 = X * X;
float Y2 = Y * Y;
float Distance = sqrt(X2 + Y2);

This is good but along different lines of latitude, the distance isnt the same for a given angle, even for a perfect sphere. 15 degrees near the poles is shorter than 15 degrees near the equator. I think he should calculate arc length to get X using ((long2 - long1)*2*pi*Earth radius*cos (lat1)) / 360 and Y can be gotten similarly, except the cosine shouldnt be present

@Majenko Thanks for sharing your brilliant idea, but I already tried doing it, and unfortunately that won't work since we knew Earth is not perfectly spherical. What I am trying to know is how can I find the distance following the technical form of the Earth. Please see stated above.

D'oh, you're quite right. I had totally overlooked that. I will update the answer in the morning.

If you're going to use the circumference, then 2*pi shouldnt be present in the equation; its already a part of the circumference

@TisteAndii It's early yet and I haven't had my first sip of coffee.  Again, quite right.

Ah, unfortunately coffee isnt a thing here :(

I have been always frustrated from the missing double (64bit) type in Arduino world and hence the problem with properly calculating GPS distance, bearing and destination point.
The following library uses Float64 & Math64 libs and also adds some fast and very fast implementations of trigonometric functions and fast and regular versions of GPS GPS distance, bearing and destination point.
Feel free to use it - and any help in improving it is welcome !
https://github.com/vtomanov/Gps64


text:
Drop alpha character from serial input
I receive strings over the serial port like so:
VLT=53.0, AMP=-30.2, AHR=-10, SOC=98, TMP=136, STS=192
I want to reduce the use of string functions with the idea of dropping all non-digits, keeping numbers dot and comma, to get this:
53.0,-30.2,-10,98,136,192
in an array and simple read [0], [1], etc.
Regular expressions would be idea, but do not exist like in PERL.
Any hint would be much appreciated.
Relevant code used:
    char inByte = SerialPortOne.read(); // read byte
    strRecordIn.concat(inByte);         // add byte to receive buffer
    for (int i = 0; i <= 3; i++) {    // VLT, AMP, AHR, SOC
    strWord = getValue(strRecordIn, ',', i);  // get data item from RecordIn array
      strWord.remove(0, 4);           // remove field identifier (1st 3 char plus =)
      strRecordOut += ',';            // add delimiter
      strRecordOut += strWord;        // add value
      strWord = "";                   // reset strWord
    }

Ideally:
    char inByte = SerialPortOne.read(); // read byte
    if (inByte = [%d.,]+) {
      strRecordIn.concat(inByte);       // add byte to receive buffer
    }

If you just want to remove the letters:
#include <ctype.h>

char inByte = SerialPortOne.read();  // read byte
if (!isalpha(inByte)) {              // not letter
    strRecordIn.concat(inByte);      // add byte to receive buffer
}

Or you may test it for isdigit() and explicitly compare to ',' and
'.':
if (isdigit(inByte) || inByte == '.' || inByte == ',') {
    strRecordIn.concat(inByte);      // add byte to receive buffer
}

C.f. the documentation of
<ctype.h>.

Brilliant! I got lots to learn in this Arduino environment. Thank you!

@MaxG: Well, in this case it's standard C, not specific to Arduino.


text:
Breaking a switch case from an ISR
I'm struggling with something. My CPU sits in a switch case state machine like this:
switch(expression) {

   case constant-expression_1  :
      statement(s);
      break; /* optional */

   case constant-expression_2  :
      statement(s);
      break; /* optional */

   /* you can have any number of case statements */
   default : /* Optional */
   statement(s);
}

I have an interrupt that occurs on a button press. In the interrupt, I change the switch expression to the case I want to go next, like this:
void ISR(void){
   expression = constant-expression_2;
}

After the interrupt has been handled, I want the CPU to return directly to the case being switched to, and to not continue where it left off.
Does anyone have any good ideas on how to implement this, if it's possible? I'd prefer to not have to wait for the code to finish what was happening in the previous case before going to the one being switched to.
Thanks in advance!

A rather drastic, solutions would be be to reset the chip in the ISR.

It is certainly possible, although I do not think there is any clean
way of doing it...
Here is an idea that may work: right before the switch statement,
you save the current context with the setjmp()
function.
Then, in the ISR, you restore that context with longjmp(). This is
kind of like a goto statement that works across functions:
#include <setjmp.h>

jmp_buf env;

ISR(FOO_vect) {
    expression = ...;
    longjmp(env, 1);  // go to start of loop
}

void loop() {
    setjmp(env);  // landing point from ISR exit
    switch (expression) {
        ...
    }
}

Notice that the normal exit sequence of an ISR (the reti instruction)
re-enables the interrupts. Since we are skipping this exit sequence, we
have to enable them explicitly upon return from setjmp()
interrupts are re-enabled not by the reti instruction but by longjmp()
restoring the CPU's status register.
Warning: This is a (very dirty) hack that I have not tested. If I
were to use this trick, I would first:

Carefully examine the generated assembly to convince myself it does
the right thing.
Test, test, test...

In case of problems, debugging this may be harder than just testing the
expression inside every slow function you have.
Addendum: Although I am saying that there is no clean way of doing
what you intend, there certainly is a clean way of achieving the same
end result: just make sure your switch statements return fast. My
preferred way of doing this would be to make sure no function ever
waits. For example:

A routine reading sensors would not wait for them to respond. Instead,
it would return immediately if no reading is available. If a reading
is available, it would retrieve it, send a query to the next sensor
in the list, then return.
A communication routine would not wait for complete messages. Instead,
it would return immediately if no byte is available. If a byte is
available, it would buffer it and return. Unless it's the last byte of
a complete message, in which case it would process the message.

Obviously this could require a heavy refactoring of your code, probably
using finite state machines (see for example the tutorials
here
and here). It may be easier to
just test whether the expression has changed inside every busy-wait loop
you have, as recommended by Gerben's and Nick's answers.

I think longjmp() may return to the mainline but with the ISR's context; I'd expect some surprising behavior. But if you call setjmp() prior to the switch statement (or higher, if appropriate), and the ISR sets a (volatile!) flag to indicate it has been called, then each case could do if( flag ) longjmp(); as frequently as it is appropriate to do without leaving some operation partially completed. ...

... You'll probably want to abstract away as much of the case code as possible into small functions where the actual work and the flag-testing will be done. This way, both setjmp() and longjmp() will have (had) the same context.

@JRobert: “longjmp() may return to the mainline but with the ISR's context” I don't understand what you mean by “ISR context”. setjmp() and longjmp() save and restore quite a bit of context, including all the call-saved registers and the stack pointer.

Longjmp restores the context as it was at the setjmp call. It may be; I just don't know. It sounds like you had similar concerns in your caveat to inspect the assembly code and to test carefully. It's quite possible it will work as expected/desired. On the other hand, allowing the ISR to return first gives me a lot more confidence in the outcome.

@JRobert: I fully agree with you. I posted this because I think it's a fun hack worth sharing. I already stated in the answer I do not consider this a clean programming technique. I just expanded on that consideration, just in case it was not already extra clear.

Most of the time this isn't a problem, because code normally runs pretty fast. The problem, most of the time, is the use of delays. What I did was use my own delay function that checks if the expression has changed, and if so, immediately returns.
Below is my code. I had to modify it a bit, so it might not work out of the box, but will give you the idea as to how.
volatile byte expression;
volatile boolean expressionChanged = false;

switch(expression) {

   case constant-expression_1  :
      statement(s);
      myDelay(1000);
      statement(s);
      break; /* optional */

   case constant-expression_2  :
      statement(s);
      myDelay(500);
      statement(s);
      break; /* optional */

   /* you can have any number of case statements */
   default : /* Optional */
      statement(s);
}

void myDelay(int ms)
{
    uint32_t start = micros();
    while (ms > 0 && !expressionChanged)
    {
        //yield();not implemented in arduino
        if ( (micros() - start) >= 1000)
        {
            ms--;
            start += 1000;
        }
    }
}

void ISR(void){
   expression = constant-expression_2;
   expressionChanged = true;
}

Thanks for the answer! My problem is, one of my cases includes a communication transceiver method, which can take a lot of time to get through, and another case does sensor acquisition from about 30 sensors. I would prefer to not have to check in every "slow" piece of code if the case has changed, but if this is unavoidable, it will have to do. Any ideas?

In case of the 30 sensors, you could rewrite the code, so it only check a single sensor at a time, and then in the next cycle checks the next sensor. Your communication transceiver description is to vague for me to make any suggestions. Other that sprinkeling if(expressionChanged)break; around. This is probably unavoidable, since breaking at certain locations in the code, could cause some bad side-effects.

First, put your major processing into functions. That looks better anyway. eg.
switch(expression) {

   case constant-expression_1  :
      function1 ();
      break; /* optional */

   case constant-expression_2  :
      function2 ();
      break; /* optional */

   /* you can have any number of case statements */
   default : /* Optional */
      function_default ();
}

Now inside your functions do a return if you notice the expression has changed. This will get you out of any number of nested loops. For your 30 sensors, for example, you can now have a loop.
void function1 ()
  {
  for (int i = 0; i < 30; i++)
    {
    if (expression_changed)
       return;
    // take sensor reading
    }
  }  // end of function1

Also, as Gerben suggested, replace any delay calls with a function that does the delay, however which ends early if the expression changes. It can return a boolean to let you know this happened. eg.
boolean myDelay(int ms)
  {
    uint32_t start = micros();
    while (ms > 0)
    {
        if (expression_changed)
           return true;   // early return
        if ( (micros() - start) >= 1000)
        {
            ms--;
            start += 1000;
        }
    }
  return false;   // normal return
  }

Now any function that needs delays can use that, like this:
void function2 ()
  {
  do_something ();
  if (myDelay (1000))
     return;   // bail out
  do_something_else ();
  }  // end of function1

My problem is, one of my cases includes a communication transceiver method, which can take a lot of time to get through

There must be logical spots where you can just test the expression and do a return (preferably cleaning up anything that needs it) when required.


text:
Arduino Nano USB Serial Bypass
I have a Nano clone here, that sporadically fails to get detected by my banana pi. This is annoying, because it works for days and hours, but fails to work randomly.
The Nano gets it's own power via VIN and thus should have enough power.
I thought of bypassing the FTDI and make a Serial connection via 2 Wires. Alternatively: Is there a way to force the arduino to use external Power over USB. I have the feeling, the the arduino wrongly decides, that USB is the better power source and uses it, causing the errors ( device not accepting address 21, error -62 )
P.S.: There is also a touch-screen connected to the banana pi via USB. Whatever port I use, It works and never failed. Just the Nano fails from time to time.

Many arduino type boards have a resistor between the USB-serial function and the main ATmega, potentially allowing an external "strong" driver to take over.  But the Banana pi may not (?) support 5v I/O.  Your best bet is probably to locate and remove that resistor, then build a level shifter with resistors.  For safety you could put one on both transmit and receive, since the the receive pin could potentially be misprogrammed as a 5v output.  As for the USB, is your "arduino" and especially its USB-serial chip real, or fake?

One could lower the 5V line from arduino to the banan pi with 2 resistors (voltage divider)/. That would be it.

Minimal recommended voltage for Vin is 7 Volt!

@ansi_lumen It's probably easier to just remove the 5v wire from the USB entirely, or remove the diode D1 from the board (the black two pin component on the bottom)

Is it truly an FT232 on it, or the el-cheapo Chinese CHwhatever it is?

@Gerben. Shure? Think there is no voltage regulator for Xto5V on the Nano. The chip takes 5V. I think 7V would kill it.

@Majenko Package looks okay. Flashed it with ftdi_eeprom and it still works.

@Gerben To remove the 5V line from the USB is also a good idea. But I think, I'll be faster with soldering a serial connection cable with voltage divider. This way I would get a free port for other stuff.

Assuming that USB-power was the actual problem here.

I can't comment so have to post this as an answer, but perhaps connect the GNDs together? But I also see that someone else mentioned the whole el-cheapo concept, too. I have noticed differences between boards sometimes, and exchanging them with one from a known supplier sometimes fixes my problems.

@ansi_lumen did you ever solve your problem. If so, could you post the answer here please?

To answer this question
The arduino in question was broken. Shortly after asking I was not even able to connect it to my PC successfully. I replaced it with a new one and everything runs smoothly now for months.
Since this unit survived a whole product development-process I am not surprised at all. In fact I had three and expected one to get killed in action.


text:
Motor shield and sensors
While making a Arduino programmed maze runner Will bipolar motor shield be more beneficial than using tb6612fng motor shield???? Also which type of sensors will be better??

No. Especially with battery power you want to use a low-loss FET bridge rather than a bipolar one.  Sensors choices depend a lot on the maze pathway size, rules such as if you can see over the walls, etc.


text:
Defining an NFC tag as NDEF using the Arduino Uno and the PN532 NFC module
I bought a bunch of blank Mifare Classic NFC cards and I'd like to write NDEF records to them using my Arduino Uno. When I read them using my Uno and a PN532 NFC module using Don's NDEF library however, it tells me they're not NDEF formatted.
Is there any way to define my NFC tags as NDEF using just the PN532 module and an Arduino Uno? (My Android phone doesn't support NFC.)

I found the answer to my own question right after posting it, while going through the examples included in the library above:
The library contains an example named "FormatTag" which does exactly what I was looking for.


text:
Controlling Enable Function on MicroStepper Driver
I'm having trouble using the ENABLE pin on my microstepper driver, I'm not sure of the exact model but it looks exactly like the one pictured here
Microstepper Driver
Here's my code:
#define MAX_LEN 8
#define MIN_INCREMENT 0.5
#define LIMIT_SWITCH 3
#define ENABLE 10
float buoyancymass = 4401.425;
float centrebuoyancy = 14.164;
float mainarm = 14.3;
float nosearm = 1.8;
float adc = 11.4;
float meanadc = 22.65;
volatile byte enable_state = LOW;

#include <Stepper.h>

const int stepsPerRevolution = 1600;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;         // number of steps the motor has taken
float stepinch = 0.00524; // 1 step = x"

void setup() {
  // initialize the serial port:
  Serial.begin(9600);
  pinMode(LIMIT_SWITCH, INPUT_PULLUP);
  pinMode(ENABLE, OUTPUT);
  //enable motor
  digitalWrite(ENABLE, enable_state);
  //interrupt
  attachInterrupt(digitalPinToInterrupt(LIMIT_SWITCH), limitbrake, FALLING);
  // set the speed
  myStepper.setSpeed(30);
}

void limitbrake() {
  digitalWrite(ENABLE, !enable_state);
}

The problem I'm noticing is that when I set the pinMode(ENABLE,OUTPUT); my stepper doesn't draw current and therefor, doesn't drive. This occurs regardless of whether I set my enable_state to HIGH or LOW.
Funny enough, when I set it to pinMode(ENABLE,INPUT); it does draw current and drive the motor, but unfortunately my limit switch which I've attached an interrupt to doesn't disable the motor when its pressed.
Before you ask, I've tested the enable pin on my driver and my limit switch circuitry in other programs and they both work. I'm just having trouble with putting it together.
Here is the rest of my code if you were wondering.
float calc_margin(float pos, float mass) {
  // calculate margin
  Serial.print("Distance: ");Serial.println(pos);
  float batterymoment = mass*pos;
  Serial.println(batterymoment);
  float totalmass = mass + 12404;
  Serial.println(totalmass);
  float totalmoment = 149650+batterymoment;
  Serial.println(totalmoment);
  float buoyancymoment = buoyancymass*centrebuoyancy;
  Serial.println(buoyancymoment);
  float wheelmoment = totalmoment - buoyancymoment;
  Serial.println(wheelmoment);
  float wheelweight = totalmass - buoyancymass;
  Serial.println(wheelweight);
  float cgwheels = wheelmoment/wheelweight;
  Serial.println(cgwheels);
  float maindistance = mainarm - cgwheels;
  Serial.println(maindistance);
  float nosedistance = cgwheels - nosearm;
  Serial.println(nosedistance);
  float mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  Serial.println(mainmass);
  float nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  Serial.println(nosemass);
  float mainmoment = mainmass*mainarm;
  Serial.println(mainmoment);
  float nosemoment = nosemass*nosearm;
  Serial.println(nosemoment);
  float netmoment = buoyancymoment+(mainmoment*2)+(nosemoment*2);
  Serial.println(netmoment);
  float netcg = netmoment/totalmass;
  Serial.println(netcg);
  float staticmargin = adc - netcg;
  Serial.println(staticmargin);
  float answer = staticmargin/meanadc;
  Serial.println(answer);
  float percentage = answer*100;
  Serial.print(percentage); Serial.println("%");
  float result = answer;
  return result;
}

boolean check_margin(float test_margin) {
  if (test_margin > -0.04 && test_margin < -0.02)
    return true;
  return false;
}

float armcalc(float mass) {
  for(float x=0;x<MAX_LEN;x+=MIN_INCREMENT) {
    // calculate margin
    float margin = calc_margin(x,mass);
    if (check_margin(margin)) {
      return x;
    }
  }
  return -1;
}

float stepcalc(float arm){
  int arminch = arm*12;
  float numberofsteps = arminch/stepinch;
  int result = numberofsteps;
  Serial.print("Calculated steps: "); Serial.println(result);
  return result;
}

void loop() {
  // read input
  Serial.println("Enter mass: ");
  while (!Serial.available());
  float mass = Serial.parseFloat();
  float arm = armcalc(mass);
  if (arm < 0) {
    // Error message
    Serial.println("Error!");
    return;
  }
  Serial.print("Arm distance is "); Serial.println(arm);
  // step
  const int steplength = (int) stepcalc(arm);
  Serial.print("Number of steps is "); Serial.println(steplength);
  myStepper.step(-steplength);

  while(1);

}

An interrupt service routine which toggles state sounds like you are just asking for trouble. Even if it is not the cause of your problem, you would likely be better off with logic to assertively set the correct level. Are you aware of the issue of "contact bounce"? That could see you toggle the motor state a somewhat random number of times, with the result depending if that is even or odd...

I drive those with 12 Volts from a printer port. I remember mine should be also 5V-compatible. Plus, I have the feeling, that you don't exactly know, how these drivers work...

These drivers differ from the H-Bridge-design described here. You don't need to generate pulses for the coils, as you would do with a classic H-Bridge.

Connect your motor to A+, A-, B+, B- (a is one coil, b the other)

Connect Power (guess 12+ volts, mine take up to 48V) to GND and V+

Either connect 5V to ENA+(+5V) or a free arduino Pin and ENA-(ENA) to GND. This pin enables/disables the driver. If no input is present at this pin, the driver will not work.

Connect DIR+(+5V) to a free arduino pin and DIR-(DIR) to GND. This pin controls the direction. HIGH makes the motor turn right, while LOW on this pin makes the motor turn left.

Connect PUL+(+5V) to a free arduino pin and PUL-(PUL) to GND. This pin controls the speed. The more pulses/second one applies, the faster the motor turns. (Up to a limit, of course).

Sketch should be easy.
Plus: You could turn around the control connections, by hardwiring all +5V pins to 5V and use INPUT_PULLUP to switch the current flow on the negative lines. I know that these drivers are optical isolated and draw as little as 10 mA from a pin, if at all. So you should be safe.

I fixed the enable function and I'm able to control the motor, but I'm still unable to use my limit switch to set the enable pin on or off. Would you have any idea as to why that is?

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


text:
Control speed of linear actuator servo
I have a linear actuator that I want to be able to slow down. Right now, the shaft moves too quickly. I'm not sure how to do this. I was looking into varSpeedServo.h library but couldn't implement it.
//Includes
#include <Servo.h>

//Defines
#define LINEARACTUATORPIN 9        //Linear Actuator Digital Pin

const int button1Pin = 4;     // the number of the pushbutton pin

// variables will change:
int button1State = 0;         // variable for reading the pushbutton status

Servo LINEARACTUATOR;  // create servo objects to control the linear actuator

int linearValue = 10000;   //current positional value being sent to the linear actuator.

void setup()
{
  //initialize servo/linear actuator objects
  LINEARACTUATOR.attach(LINEARACTUATORPIN, 1050, 2000);      // attaches/activates the linear actuator as a servo object

  // initialize the pushbutton pin as an input:
  pinMode(button1Pin, INPUT);

  //use the writeMicroseconds to set the linear actuators to their default positions
  LINEARACTUATOR.writeMicroseconds(linearValue);

}

void loop()
{

  // if the pushbutton is pressed set the linear value
  button1State = digitalRead(button1Pin);
  if (button1State == HIGH) {
    // set the position value
    delay(2000);
    linearValue = 1050;

  }

    if (button1State == LOW) {
    // set the position value
    linearValue = 2000;
  }

  //use the writeMicroseconds to set the actuator to the new position
  LINEARACTUATOR.writeMicroseconds(linearValue);
delay(3000);
}

Also see  Change Servo Speed With RedBearLabs BLE Shield

Have you tried something like the following?
#define STEP 50

void loop()
{

  // if the pushbutton is pressed set the linear value
  button1State = digitalRead(button1Pin);
  if (button1State == HIGH) {
    // set the position value
    if (linearValue > 1050)
       linearValue = max(linearValue-STEP,1050) ;

  }

    if (button1State == LOW) {
    // set the position value
    if (linearValue < 2000)
       linearValue = min(linearValue+50,2000) ;
  }

  //use the writeMicroseconds to set the actuator to the new position
  LINEARACTUATOR.writeMicroseconds(linearValue);
  delay(100);
}

By changing the STEP value (or the delay in the next-to-last line) you can change the speed of the servo.


text:
Port Manipulation - fastest implementation
I'm working on an Arduino program but am getting bogged down on what is the 'correct' implementation. I understand that multiple versions may work, so for my needs the 'correct' version will be the fastest (i.e. executing in the fewest clock cycles)
I need to set three analog input pins on my Mega 2560 - let's call them PF2-0.

I could use pinMode() - but that performs some extra checks that I want to leave out.
I could use _BV() in the process, but that's another function call I wish to avoid.

So, using port manipulation, I can write:
DDRF = 0x07; //PF2, PF1, PF0 as input
PORTF = 0x07; // Disable pullups

This should configure my three pins as inputs - and reduce any extraneous function calls. This should even be faster than writing:
DDRF = (1 << PF2) | (1 << PF1) | (1 << PF0)

Is this the fastest implementation?
*To be honest, I'm not sure how to profile this to know for sure.

Fastest way is to write nothing: all the pins start as inputs by default.

I could use _BV() in the process, but that's another function call I wish to avoid. - it isn't a function, it's a macro. And the compiler optimizes the results. As Edgar Bonet points out, using it three times in one line and ORing the results together, gives you a single machine instruction which executes in one cycle (plus another to write to the register). You can't improve on that.

DDRF = 0x07; //PF2, PF1, PF0 as input - surely that makes them outputs?

@NickGammon, you're correct of course - I was confused.

The standard Arduino way of doing this is to use pinMode(). It's not
fast, but it's easy to understand, especially for beginners. And it's
portable across architectures.
If you want to go fast, then you should skip the Arduino functions and
use port manipulation, and avr-libc. The standard avr-libc way of doing
what you want is:
DDRF = _BV(PF2)   // set PF2 as output
     | _BV(PF1)   // also PF1
     | _BV(PF0);  // and PF0

This compiles to two assembly instructions: one for loading a CPU
register with the constant, and the other to copy the register to the
DDRF IO port. Notice that you set the bits for the pins you want to set
as outputs, and you clear the bits for the inputs. By default, all the
pins start as inputs.
The _BV() here is not a function call: it's a macro that expands to
(1 << (x)). The way you write the expression to the right of the =
sign is irrelevant as long as it is recognised to be a compile-time
constant. If you want to see for yourself, you can disassemble the
generated binary with the command
avr-objdump -S -C my_prog.elf > my_prog.lst

You get an assembly listing interspersed with your source. Doing this on
the example above yields:
    DDRF = _BV(PF2)   // set PF2 as output
         | _BV(PF1)   // also PF1
         | _BV(PF0);  // and PF0
100:    87 e0           ldi r24, 0x07   ; 7
102:    80 bb           out 0x10, r24   ; 16

Here, the ldi instruction means “load immediate”, i.e. load a register
(r24) with a constant value (0x07). The “out” instruction copies that
register into port 0x10 (namely DDRF). Both are single cycle
instructions, so the whole sequence takes two CPU cycles.

AFAIK the compiler should be smart enough to use bit manipulation instructions when in presence of _BV().
When unsure, you can always add -save-temps to the gcc options, to see what the compiler actually does. It will not give you profiling information, but you can see in detail how your C gets turned into assembly.
Remember to pay attention to what level of optimization you use. You should use the same that will be employed in the final version of your code (probably O2).

Probably -Os...


text:
Sampling Rate of Arduino Uno
It might be a stupid question but, I am currently using Arduino Uno with the 16MHz processor, what is maximum sampling rate of data available to me if I want to read data of a sensors such as accelerometer?

It depends how the accelerometer is read. Is it I2C? SPI? Serial? Can you provide a part number or link? Please read How do I ask a good question?

I m sorry for incomplete information,i am using MPU6050 with I2C .

I have a page about I2C. The speed of I2C depends on a number of things, such as the I2C clock (which you can change) and also how many data bytes are in a "packet". There is a fixed overhead of the device address in each packet.
A broad rule-of-thumb would be around 4700 bytes per second for a single-byte payload at the default clock rate. You may also need to spend time asking for a reading. I haven't read the datasheet (which you didn't link).
The datasheet for the MPU6050 may give you more information about how fast it can respond.


text:
Arduino Nano - Unknown USB device
I just bought an Arduino Nano v3.0 (compatible? +- 5$) and I cannot connect it to my computer (Windows 8.1 64bit, Arduino IDE 1.6.8 installed).
The Arduino was bought as a clone but shows GRAVITECH.US on the front.
It has a FTDI FT232RL chip (1412-G B8908572) on the back.
When connecting the Arduino the power leds burns the TX and RX led flash a few times (really shortly) and then die. Then the yellow L leds blinks once per second continiously.(power to the Arduino comes from the USB cable, not from external power)
In the system tray I get a message saying
"The last USB device you connected to this computer malfunctioned,
and Windows does not recognize it."

In the device manager I get a node under Universal Serial Bus Controllers:
Unknown USB Device (Device Descriptor Request Failed).

When examining the properties of the device, the device-status is:
Windows has stopped this device because it has reported problems. (Code 43)
A request for the USB device descriptor failed.

I tried to reset the device
I tried different USB cables
I used another Windows 8.1 PC without Arduino IDE installed
I used an old XP computer

All give same error.
I read about the bricking of clones by the recent FTDI drivers...
I downloaded the FT_Prog tool V3.0.60 to check the PID, but the tool simply does not find the Arduino...
I'm out of ideas... does anyone have some left?
Thanks in advance!
Michiel

I found the issue!
There is a bug in the Arduino hardware:
https://ketturi.kapsi.fi/2014/04/how-to-fix-moody-arduino-nano/
You need to bridge pins 25 and 26 of the FTDI chip (located at the back of the Arduino) to ground the pin 26 TEST signal.
If I connect these pins then it works just fine!

It would be good to summarize the key point - bridging pins 25 and 26 of the FTDI to ground the pin 26 TEST signal, rather than relying on a link for the key element of your answer.

Thanks for the advice, I added the comment to my solution.

I've had this issue before. You can try reuploading the bootloader. If that doesn't work, maybe try re-installing the drivers.


text:
What is the best way to attach TMP36 sensor to the copper coil?
I am very new to this site and this question may not be strictly related to Arduino, but I do small Arduino project which needs to measure the temperature of the copper coil using TMP36GZ sensor.
What is the best way to glue it to the coil for best measurements?
Shoul I use silikone or epoxy?
Should I take extra steps to ensure proper readings from the coil surface (f.ex.: using thermal paste)?

If you don't have to worry about conductivity from the electrical standpoint, you could use a thermal epoxy such as Arctic Silver which uses "microfine" particles of silver to conduct heat. It's a two part (redundant when using the term epoxy, I think) adhesive that is engineered to transfer heat, but may also short conductors. I've used the stuff and unless subject to intentional separating force, it holds well.

The datasheet devotes a whole page to mounting and thermal conductivity (though not to specific adhesives), particularly with respect to the plastic, through-hole devices, as the leads provide more a direct conductivity path to the sensing junction than the plastic bead does. If the surrounding air is at a different temperature from the coil surface you'll either need to insulate the leads from the air, or better, epoxy them to the coil with a thermally conductive but electrically insulating epoxy.
Here's an excerpt:

Caution should be exercised, especially with T-3 packages, because the > leads and any wiring to the device can act as heat pipes, introducing errors if the surrounding air-surface interface is not isothermal. Avoiding this condition is easily achieved by dabbing the leads of the temper-ature sensor and the hookup wires with a bead of thermally conductive epoxy. This ensures that the TMP35/TMP36/ TMP37 die temperature is not affected by the surrounding air temperature. Because plastic IC packaging technology is used, excessive mechanical stress should be avoided when fastening the device with a clamp or a screw-on heat tab. Thermally conductive epoxy or glue, which must be electrically nonconductive, is recommended under typical mounting conditions.

Update:
I also noticed they didn't specify an epoxy, which I take to mean the feel it isn't critical. You'll need one compatible with "most" plastics and with copper. I'd probably use a big "wad" (that's a technical term :) of any off-the-shelf non-electrically conductive epoxy over the whole sensor and its leads, getting the sensor face as close to the copper as possible. I might even wrap some thermal insulation around the connecting wires for a foot or so, or even wrap that much of them around the coil and tape them to it, just to keep the sensor and the wires at as close to the coil temperature as possible. My guess is that will be more than sufficient to get temperature readings of the coil to within the sensor's limits of accuracy.

Data sheet is a bit too technical for me (a newcomer). F.ex.: it does not specify clearly what type of plastic the enclosure is made of and what type of thermally conductive epoxy need to be chosen. Is any good or does it require special epoxy, suitable for copper, etc..


text:
Maximum potentiometer resistance
I want to hook up a potentiometer to my arduino (Leonardo) as a voltage divider with the middle pin to an analog pin. I want to use the highest resistance to save power. I looked on the datasheet and it said the maximum output impedance is 10kOhm (§24.7.1 on Atmega32u4 datasheet). I also found another question that said I should use a 10kOhm potentiometer. What doesn't make sense is if the knob was turned towards the middle so that there is 5k on both sides, it's not the maximum capable resistance. So should I use a 20kOhm potentiometer?

Aren't you more interested in input impedance?

Oh yeah. But the datasheet said output impedance... I'm confused. I'm ensentially asking what is the maximum potentiometer resistance for analog input without the chip stuffing up.

The voltage divider is Thévenin equivalent to a voltage source having no more than 1/4 the resistance of the pot. You could then use a 40 kΩ pot and still be within spec.

If you are sequentially reading various analog inputs and your resistance is too high, you might get some cross-talk. If this is the only analog input you are reading, there should be no issue. If you really care about sub-mA consumption, you should probably use a barebones ATmega instead of your Leonardo.

I'm actually using two pots for two analog input pins. I also kinda get with your meaning of cross talk as I heard the analog pins are multiplexed into one capacitor. Also I am planning to use barebones Atmega but I'm using a Leonardo as my prototype. I want to know how changing the pot resistance affects the chip.

Take a look at the block diagram in the datasheet. The nature of multiplexing is you make a choice. You choose input 0 or input 1. They aren't somehow combined into a single input at the same time.

There is a lengthy discussion about this on the Arduino Forum. As I understand it, the input impedance is only important if you are sampling a rapidly varying signal, as it takes a finite time to charge the sample/hold capacitor. However your potentiometer would not vary rapidly (certainly not in the order of thousands of herz). Thus I don't think the potentiometer resistance will be particularly important, particularly if you are not changing the analog inputs (eg. from one channel to another). The continuous current through the 10k pot would be 0.5 mA.
If you are worried about power, then rather than connecting the +5V side directly to 5V, connect it to an output pin, which you can bring high when you want to take a measurement, and make low at other times. That reduces the power through the pot, since there won't be a voltage potential. You might allow a few microseconds for the reading to stabilize when you need to take one.

So the lower the pot resistance, the faster response time? Also I will constantly always be taking a measurement

No, I don't think this is an issue. The "response time" is really the time taken to do the ADC calculation (nominally 104 µs if you don't fiddle with the registers).
See ADC conversion on the Arduino (analogRead). As mentioned on that page you can speed up the measurement by changing the ADC prescaler. However even with a prescaler of 128 you get 9615 conversions per second. I doubt you can turn the pot fast enough for this to be a meaningful issue.
Regardless of the response time, the issue here is accuracy. Will a lower pot value give more accurate results? Well, I doubt it. The ADC effectively copies the analog input into a 14 pF capacitor (the "sample and hold" capacitor) which it then tests against the reference voltage divided up in various ways.
The input impedance would be relevant if you were sampling a high-frequency input. On the page I linked I sampled a 4 kHz sine wave and got good results. You just won't be turning the pot that fast (4000 times a second).

I'm still unsure with how potentiometer resistance affects the data ...

If you keep sampling the same ADC input (eg. A0) then I think the sample and hold capacitor can be charging in the background (while your code is doing other things).
But even if that were not the case, the datasheet says the sample and hold operation takes place 1.5 ADC cycles after the conversion starts. So at 16 MHz clock rate, and a prescaler of 128 for the ADC clock, this means we have:
128 * 62.5 ns * 1.5 = 12 µs

Now since the datasheet says the sample-and-hold capacitor is 14 pF, and the time taken to (almost fully) charge a capacitor is reckoned to be:
5 * R * C

Given R = 110k and C = 14e-12 (14 pF) then it will take:
5 * 110000 * 14e-12 = 7.7 µs

I quoted 110k because the datasheet mentions a resistance of 1 to 100k in series with the capacitor, plus the 10k impedance they recommend.
This means the capacitor will charge within the 12 µs it has available. Bump R up to 1e6 (1 megohm) and the calculation now gives:
5 * (100e3 + 1e6) * 14e-12 = 77 µs

This exceeds the 12 µs quoted for the sample-and-hold.
This is why, I suggest, that for fast-changing signals they recommend a lower input impedance.
However if I am correct that the sample-and-hold capacitor is normally connected to the ADC input, then that 77 µs can be spread over the time you deal with the calculation. Still, that is quite a few clock cycles. :)

My recommendation is to stick with 10k or so potentiometer (as recommended by the datasheet) and use my earlier suggestion of connecting the 5V side of the pot to an output pin instead of continually having it connected to the +5V signal. That way you only need to "power" the pot when you actually need to take a reading. However you can see that a 20k pot (or even 50k) will probably still be in an acceptable range for an accurate conversion.
For example, a 50k pot could charge the capacitor in:
5 * 150000 * 14e-12 = 10.5 µs

I would also be cautious about a 1 megohm pot because then slight variances in other things (eg. heat on the wire, nearby noise) could swamp the reading from it.

Wait, sorry do I need to half my potentiometers' resistance if I'm using two analog inputs?

No, because the multiplexer chooses one input at a time (the others are effectively out of circuit).
However if you are choosing between two pots (to measure two) then the resistance becomes more relevant. As I showed, with a high value pot it takes longer to charge the capacitor, so if you read A0 and then immediately afterwards A1, you don't want a lengthy charging time for the capacitor, because that would give erroneous readings.

So the lower the pot resistance, the faster response time? Also I will constantly always be taking a measurement

See amended reply.

So in conclusion, resistance doesn't matter, and I could use a potentiometer in the mega ohms? And this is because I'm twisting a potentiometer, right?

I can't tick your answer because I'm still unsure with how potentiometer resistance affects the data even though you said it doesn't matter that much.

See more details in reply about timings.

Ah math formulas now I get it thanks! Wait, sorry do I need to half my potentiometers' resistance if I'm using two analog inputs? Cuz don't all analog inputs have to share one capacitor?

You have two pots? The multiplexer (see the datasheet) chooses one port or the other. You don't have to second-guess that part. - See further amendments to the answer.

Sorry halving is not correct. Im using both ports at the same time so would it take double the time to sample both?

These chips only have one ADC. It is impossible to sample them both at the same time. You have to do one after the other. For example: foo = analogRead (0); bar = analogRead (1); - that's two reads. That takes twice as long as one read.

A 50 K pot has a maximum Thévenin resistance of 12.5 kΩ.

Wait, you mean 40k pot is actually the 10k impedance recommendation?

Sounds like it. :)


text:
nrf24l01 (8pin) + adapter board (10pin) oops?
I just got my first arduino boards and have been learning the basics (so I know very little). I got the 2.4GHz NRF24L01+ (this one: NRF24L01+) and along with it a breakout board (this one: NRF24L01+ board) which I didn't realize was 10pin (nor that there is an 8pin version) vs the wireless board's 8pin. So my question is, is it safe to connect the module to this adapter board in some way? From the pinout of both I would assume not, since for example the bottom two pins on the board are ground (and therefore connected together) and the ground pin on the NRF24L01+ is next to the VCC (NRF24L01+ pinout) and the top two on the board are both VCC 3.3 and from what I can tell by looking at the etched lines, it seems it leads to the resistors (not sure if they are resistors or what, like I said, I know very little still). There seems to be an LED on this board as well, connected to the AMS1117 chip (that's a voltage regulator, correct?).
So, I am guessing I cannot just connect the NRF24L01+ to the adapter board straight in, right? But, can it with some wires? Would that even make sense? Also, is this board even necessary for anything? I bought it having read something somewhere (been reading too much to keep track of where exactly) that recommended it, but a tutorial I saw today didn't make use of it, instead just soldering a capacitor to two of the pins saying some other place recommended it to reduce noise.

To be honest, I don't see much added value for this breakout board.
First, as you mentioned, you won't be able to plug your NRF24 directly into it because the pinout is not compatible; hence, you will have to use wires for that. But you could as well use wires directly from your Arduino to the NRF24 module.
Second, regarding power (you are right, AMS1117 is a voltage regulator), the Arduino 3.3V pin is enough (50mA for UNO) to power your NRF24 as its current consumption is low (max 13.5mA as per the datasheet):

Please note these are specifications for the chip itself not for the board, which may need a bit more current, but not much more according to my own experiments.
As a side note, I have created my own very simple breakout for the NRF24 board, with just a tiny piece of stripboard, that's something you can easily do by yourself if you have the right tools (saw, cutter, soldering iron), a few pin headers and some stripboard scrap:

Last, the only utility I see with your breakout board is to be used as 3.3V supply for higher currents in future experiments.
EDIT:
as commented by @Hans-Neve, a capacitor would be useful between 3.3V and GND pins, as near the NRF24L01 board as possible, so that short consumption peaks do not impact correct function of the board. The breakout board has one (or more exactly 2: 100nF and 10uF) It is advised you add those two (at least the large 10uF cap) in your circuit. I saw some people directly soldering one cap on the pins of the NRF24 board, but if you use short enough wires to connect it, you can perfectly put this cap on a breadboard during your experiments.

The 3v3 supply from arduino should be OK for this module yes, only that some burst transmission might benefit a capacitor close to the power pins on the module. The higher power modules will work with power from arduino but will under perform due to drawing too much, here the capacitor is needed as it will smooth out the current bursts.

@HansNeve thanks I have edited my answer accordingly.

So does the breakout board have that capacitor already in the right spot? say if I use wires from the NRF to the board, will that have the correct effect?

@insaner from the breakout picture, I'd say yes, but as soon as you use wires to connect to your NRF24, it won't be as good. At least, you'll need to use short wires (10cm should be the maximum, those are easy to find with the right M/F connectors). Note that it is not possible to provide a "mathematical" rule to this, the only rules that prevail are "the nearer the cap the better" and "if it fails, try to shorten distance further (and possibly change cap values)". This is often a "trial and error" approach here.

It's also worth mentioning that Megas tend to have especially crappy 3.3V regulators and you should really use a capacitor (fairly large one 100+uF electrolytic) to ensure smooth operation.

OK, I will have all those things in mind. Thanks everyone!


text:
Keyboard input arduino speed
I have an Arduino clone of a Leonardo and I was just wondering how many keyboard commands I can send to the computer per second via USB. I'm not talking about the delay between send and receive (because that could vary between computer), I'm talking about the minimum possible time between something like stimulating a key press down and key press up as fast as possible.

From my tests, it has been at least 1 millisecond, however, it can depend on what is running simultaneously on the Arduino.

Well what if you were doing key up and key down of a single character, with that only being in the void loop?


text:
Funduino Uno with 5V 1A power supply?
Can I use a "Funduino Uno" arduino with power from a power bank with DC 5V 1A output?

Yes. As long as it connects the the arduino clone via USB and can maintain a stable power output then it's suitable.