body:
      import processing.serial.*;
    import java.io.*;
    Serial myPort;
    int mySwitch;
    String transmitter[] = new String[1280000]; //initialize array

    void setup(){
             mySwitch=1;
             //Open the serial port for communication with the Arduino
             //Make sure the COM port is correct
             myPort = new Serial(this, "COM6", 9600);
             myPort.bufferUntil('\n');
    }

    void draw() {
            if(mySwitch == 1)
            {
               readData("input.txt");
               int index = 0;
               while(index < 128000)
               {
                 myPort.write(transmitter[index++]);
                 if(index8 == 0)
                   delay(100);
               }
            }

             mySwitch = 0;
    }

    void readData(String myFileName){

             File file=new File(myFileName);
             BufferedReader br=null;

             try{
               br=new BufferedReader(new FileReader(file));

               String transmit=null;
               int i = 0;
               /* keep reading each line until you get to the end of the file */
                    while((transmit = br.readLine()) != null)
                       transmitter[i++] = transmit;

             }catch(FileNotFoundException e){ e.printStackTrace(); }

             catch(IOException e){ e.printStackTrace(); }

             finally{
                     try {
                       if (br != null) br.close();
                     }
                     catch (IOException e) { e.printStackTrace(); }
             }
    }
In the above code, I have an String array and I'm reading lines from a file and saving them as strings. How would I save them as byte/char inside an array of byte/char?

Basically, I have a file of integers on each line, each integer in the range [0, 255]. And I want to read this integer and send it to the Arduino. The Arduino serial.read() function reads a byte at a time. This is the issue I am trying to solve.

title: Using Processing to send data to Arduino

Answers: 1

body:
I believe I have actually found a very efficient solution to this problem by re-writing the code the following way by using the "Scanner" class and not the "BufferedReader" class. Any input on making this more efficient is welcome!

    import processing.serial.*;
 import java.io.*;
 import java.util.*;
 Serial myPort;
 int mySwitch;
 Scanner file;
 byte transmitter[] = new byte[1280000]; //initialize array

 void setup(){
     mySwitch=1;
     //Open the serial port for communication with the Arduino
     //Make sure the COM port is correct
     myPort = new Serial(this, "COM6", 9600);
     myPort.bufferUntil('\n');
 }

 void draw() {
     if(mySwitch == 1)
     {
         readData("input.txt");
         int index = 0;
         while(index < 128000)
         {
             myPort.write(transmitter[index++]);
             if(index8 == 0)
                 delay(100);
         }
     }

     mySwitch = 0;
 }

 void readData(String myFileName){
     try{
       file = new Scanner(new File(myFileName));
     }
     catch(Exception e){System.out.println("NOT FOUND!");}

     int i = 0;
     while(file.hasNextByte())
       transmitter[i++] = file.nextByte();

     file.close();
 }


body:
This is basically an off-shoot from [https://arduino.stackexchange.com/questions/20569/unexpected-output-pin-behavior-was-relay-on-off-doesnt-loop][1]. It's the same schematics and so on, however, I'm now wondering what the output voltage and current is.

I've a 9V battery and the MOSFET transistor from the arduino starterpack (doesn't say the specs) connected to the 5V pin on the board. I need the following output current/voltage for it to activate a solenoid:

 - 6V: 160 mA
 - 7V: 190 mA
 - 8V: 220 mA
 - 9V 240 mA
 - 10V :270 mA
 - 11V :300 mA
 - 12V :320 mA

and I'm just not sure how to calculate it since I'm not sure about the output from the transistor and all the way to the solenoid.

The solenoid: http://www.electrokit.com/en/plastic-water-solenoid-valve-1-2-12v.51108

[![It should be solenoid instead of relay in the schematics][2]][2]

  [1]: https://arduino.stackexchange.com/questions/20569/unexpected-output-pin-behavior-was-relay-on-off-doesnt-loop
  [2]: https://i.stack.imgur.com/ElqV9.png

title: Regarding the output voltage and current in arduino

Answers: 1

body:
You don't need to "calculate" anything with a MOSFET.  You will be using it in the *saturation* zone. That means it is fully turned on and will allow through the current you need.

However, the gate of a MOSFET looks, to all intents and purposes, like a small capacitor. That means there will be a certain amount of *inrush* current to the gate when you turn it on. To limit that inrush current you need a small resistor (say 100-220Ω) on the gate.

When using a BJT, though, you need to ensure that you allow enough current through the base to allow enough current through the collector.  Divide the current you need through the collector by the *Hfe* (typically 100 for a small signal transistor) and that is the *minimum* current you need to allow through the base. Subtract a silicon junction voltage (0.6V) from the voltage of the IO pin (5V). Divide it by your base current calculated above, and that is the *maximum* resistor you can use on the base.

And also your transistor symbol in your schematic is backwards.


body:
The Arduino SW, under Tools, identifies my Uno as COM Port 3. However, COM Port 3 on my computer is in use by a chip set. My computer assigned COM Port 4 to my Arduino Uno.

Can I reassign my Uno to COM Port 4?

Edit: This question also applies to people who don't have administrative privileges. They do not have privileges to change the port via Windows Device Manager.

title: Can I reassign my Arduino Uno COM Port?

Answers: 2

body: If the Arduino IDE identified your Uno as COM Port 3, your computer most likely has already assigned COM Port 3 to your Uno. You can double check the port assignment in Device manager > Ports.

body:
You can change your COM Port number for a device by following these instructions:

 http://plugable.com/2011/07/04/how-to-change-the-com-port-for-a-usb-serial-adapter-on-windows-7


body: I want to use a string of Neopixels attached to a Digispark hanging off of a RasPi3 as indicators for various situations.  For example: a motor (connected to a driver hat on the I2C bus of the RasPi) turns on or reverses direction.  Can I use Firmata, or is there something like it for the Digispark that I can use with Python?

title: How can I control neopixels attached to a Digispark?

Answers: 2

body:
You need a dedicated microcontroller since you need very precise timing for controlling the neopixels. It works well on an ATTiny85, we are using Adafruit Trinket boards to control Neopixels and work well. So far up to 12 pixels :)

You can download a Trinket Neopixel library, which is modded for an internal osc ATTiny85 from Adafruit.

Then your Raspi can talk to the microcontroller. It is a little problematic, though, since the software serial port handling consumes too much memory on ATTiny, and the ATTiny will ignore all serial input while refreshing the neopixels. Therefore you may get it easier by using an Arduino UNO, or Leonardo or Micro which is powerful enough for many pixels, and have a built-in hardware serial port.

As a matter of fact, you can talk to these Arduino boards as if it would be a serial port, so just plug in a Leonardo over USB and you'll get a new serial port in Rpi to talk to.

body: A circuit can be made using two 74HC121s and an OR gate that would be connected to the SPI peripheral in the microcontroller. The timing would be accomplished by the multi-vibrators while each byte would be output through the serial port.


body: 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.

title: Arduino (Or Raspberry Pi) As HID Device

Answers: 1

body:
The Uno cannot be used as a HID device through the on board USB. You might be able to use the [V-USB Library](https://www.obdev.at/products/vusb/index.html) to be a HID device using the digital IO pins. See [this tutorial](http://blog.petrockblock.com/2012/05/19/usb-keyboard-with-arduino-and-v-usb-library-an-example/).

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](https://www.arduino.cc/en/Main/ArduinoBoardMicro)

See [this question](https://raspberrypi.stackexchange.com/questions/32197/can-the-pi-emulate-an-hid-device-with-via-usb) about the Raspberry Pi.


body:
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?

title: Streaming audio from PC to Arduino over WiFi

Answers: 1

body:
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.


body:
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:

 1. 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?)
 2. 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?
 3. 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();`
 4. 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.

title: Critical sections in Arduino, interrupt consuming data

Answers: 3

body:
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](https://en.wikipedia.org/wiki/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.

body:
**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.

body:
**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;
        }
    };


body:
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?

title: Resend data traffic from an Arduino

Answers: 0


body:
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!

title: Disable other buttons while one of buttons is pressed

Answers: 1

body:
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


body:
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

 [i]: https://github.com/Sackhorn/HC-05-Pro-Micro-Hookup/raw/master/HC-05 Layout_bb.png "pro micro hookup"

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;
      }
    }

title: Arduino Pro Micro and HC-05 Bluetooth module

Answers: 0


body:
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'.

title: code to force a gentle servo power up

Answers: 2

body:
I would recommend an [S curve][1] for the angular positioning of the door.

That should guarantee a smooth start and stop.

  [1]: https://en.wikipedia.org/wiki/Sigmoid_function

body:
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:

1. 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.

2. Use a special type of servo known as a [feedback
   servo](https://learn.adafruit.com/analog-feedback-servos/about-servos-and-feedback),
   or [convert a regular
   servo](http://www.instructables.com/id/Servo-Feedback-Hack-free/) 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.


body:
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!

title: MatLab connection to Arduino using Bluetooth

Answers: 1

body:
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.*


body:
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 [![enter image description here][1]][1]so the flow control pin stays high during whole packet transmit. Please help. Thank you.

  [1]: https://i.stack.imgur.com/36NbZ.png

title: Arduino serial non-blocking

Answers: 1

body:
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()`.


body: 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...

title: ESP8266 module cutting connection with PC via USB

Answers: 1

body:
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.


body:
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, "d/d/d ", d.month(), d.day(), d.year());
       Serial.print(sz);
        }

        if (!t.isValid())
        {
        Serial.print(F("******** "));
        }
        else
        {
        char sz[32];
        sprintf(sz, "d:d:d ", 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);
        }

title: Measuring The Distance Using GPS programmed with Arduino

Answers: 2

body:
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.

[![enter image description here][1]][1]

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:

[![enter image description here][2]][2]

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);

  [1]: https://i.stack.imgur.com/SodLK.png
  [2]: https://i.stack.imgur.com/jd1QN.png

body:
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


body:
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
        }

title: Drop alpha character from serial input

Answers: 1

body:
If you just want to remove the letters:

<!-- language-all: lang-c++ -->

    #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>](http://www.nongnu.org/avr-libc/user-manual/group__ctype.html).


body:
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!

title: Breaking a switch case from an ISR

Answers: 3

body:
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 `delay`s. 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;
    }

body:
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](http://www.nongnu.org/avr-libc/user-manual/group__setjmp.html).
Then, in the ISR, you restore that context with `longjmp()`. This is
kind of like a goto statement that works across functions:

<!-- language: lang-c++ -->

    #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, <s>we
have to enable them explicitly upon return from `setjmp()`</s>
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:

 1. Carefully examine the generated assembly to convince myself it does
    the right thing.
 2. 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](https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/)
and [here](https://www.sparkfun.com/news/1801)). 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.

body:
<!-- language-all: lang-C++ -->

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.


body:
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.

title: Arduino Nano USB Serial Bypass

Answers: 1

body:
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.


body: 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??

title: Motor shield and sensors

Answers: 0


body:
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](https://github.com/don/NDEF/blob/master/examples/ReadTagExtended/ReadTagExtended.ino) 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.)

title: Defining an NFC tag as NDEF using the Arduino Uno and the PN532 NFC module

Answers: 1

body:
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.


body:
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][1]

  [1]: http://www.driver-motor.com/UploadFile/ProductImage/1/5/20090328230757_照片-005.jpg

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);

    }

title: Controlling Enable Function on MicroStepper Driver

Answers: 1

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

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

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

3. 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.

4. 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.

5. 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.

  [1]: http://www.arduino.cc/en/Reference/StepperBipolarCircuit


body:
I have a [linear actuator][1] 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.

<!-- language: c -->

    //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);
    }

  [1]: http://www.firgelli.com/Firgelli_Technologies_PQ12_R_p/pq12-r.htm

title: Control speed of linear actuator servo

Answers: 1

body:
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.


body:
Sorry if this has been asked before, but I've read tons of threads and it seems the answer is only implied on a couple of occasions.

I'm an electrical noob, but I understand that a 9v battery plugged into a wall wort with a diode would serve as a battery backup if the power was cut from the wall wort.  I also understand that Vin on an arduino already has a diode to do this.

I'm currently powering a temp/humidity that is dumping data into MySQL using a standard A-B USB cable and 5V DC USB power supply.  I'd like to incorporate a 9V battery plugged into Vin and ground, so that if DC power turns off, I can dump the data onto the SD card instead (since my MySQL server may or not be running during an outage).

title: Can a 9V battery be used as a backup power supply (to Arduino Uno) while plugged directly into Vin and ground?

Answers: 2

body:
My problem with that is that the other side of the diode on the Arduino is normally powered up. So for example if you have a 12V supply in the power jack you'll have 11.3V at Vin (because of the diode drop). Thus you are pumping 11.3V into your 9V battery which won't be designed to handle it. It will probably get hot and explode.

You would need *another* diode specifically between the battery and Vin. And make sure that Vin is at least 10V so that the normal mains power does not charge the battery.

Bear in mind a 9V battery doesn't have much capacity. With the power LED on,  taking sensor readings, and sending data via Ethernet (if that is what you are doing) you may have only bought yourself 15 minutes.

I have a post about a [temperature and humidity sensor](http://www.gammon.com.au/forum/?id=12106) which runs all the time from 3 x AA batteries. I think the batteries need replacing about every two years. The data is written to an SD card which you remove and plug into your computer when you want to.

---

> when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery

Looks like I misread the question. @mwwalk is quite right. If you supply more than 6.6V through Vin then the circuitry switches the USB off. See here:

[![Uno power switching][1]][1]

Vin is provided by the power jack (after a diode which drops it by 0.7V) - see blue ellipse. In any case (power jack or not) Vin goes through a voltage divider (two 10k resistors to the left of the red circle). This is compared to the output of the 3.3V voltage regulator. Therefore `GATE_CMD` is HIGH if Vin exceeds 6.6V. This turns **off** the MOSFET (green circle) and disconnects the USB power.

  [1]: https://i.stack.imgur.com/KyoOl.png

body: No, when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery, not usb and the battery will quickly be depleted.


body:
I'd like to connect Arduino with bluetooth shield to multiple bluetooth devices (TV & baby monitor), plug a corded headset into the contraption, sprinkle LEDs on top, and do the following:

If there is a signal above certain threshold coming from the baby monitor listen to a mix of TV and baby monitor audio with LEDs blinking; otherwise listen only to TV audio.

Thus the questions:

Can bluetooth connect with multiple devices simultaneously?

What do I need to implement that?

title: Can I turn a headset with a cord into a bluetooth headset with multiple connections?

Answers: 0


body:
I bought a light sensor (**LDR**), but he got **stained**, what it means? It is used? Or is **residuum** of time?

I must give back? I have to clean up or something?

I bought as new, so I tested one of the LEDs will not turn on.

I bought the (Mercado Livre in BRAZIL).

The product is:
http://www.gbkrobotics.com.br/exemplo-produto/p7-sensor-de-luz-com-leds.pdf

I pay R$8 BRL (equivalent aprox. $2 dollars) but, i just wanted to know if he had something I could do, because only shipping was R$ 13 BRL ($4 dollars)

* I'm starting with Arduino, thx

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/cgS8u.jpg

title: Arduino LDR sensor stained

Answers: 1

body:
I've read you post a couple of times and I get the impression you would like this board to work, so here are some quick check to try and find the fault.

 - You need a bread board
 - An arduino
 - A 200-300 ohm resistor.
 - Some wires. About 6 hands :)

Connect the board ground to the breadboard.  Then connect the to the resistor.  Then connect that to the power supply ground.

Take the positive off the power supply and touch it to the LED1 pin and check LED1 lights up.  Repeat with 2 and 3.

Switch every thing off

Connect the Positive to the Vcc connection of the board.
Connect a wire between Arduino A0 and "Sinal Analog"

Load this sketch

       void setup() {
           Serial.begin(9600);
        }
       void loop() {
           Serial.println(analogRead(A0));
           delay(250);
       }

When you cover the LDR it should read a lower number when you shine a light on it should read a higher number.

Turn everything off again, and if you have a multi meter test the resistance of the resistor on the board it should be 300 ohms, but I can't remember which way to read the bands and it might be 10K ohms, which would be a problem.

If anything doesn't work then they can all be fixed for a few cents and you don't need to worry about the discolouration.

Hope that helps you.


body:
I have a Teensy set up as a keyboard, joystick, and I'm giving keyboard commands. Letter and number keys are going fine. But when I try sending ENTER, I get some extra code in my Linux terminal:

<!-- language: lang-none -->

    $ 16424
    16424: command not found

the code I have to give the ENTER key goes like this:

<!-- language: lang-cpp -->

    void setup() {
      pinMode(0, INPUT_PULLUP);
      pinMode(1, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop() {
      // read the digital inputs and set the buttons
      Joystick.button(1, digitalRead(0));
      Serial.println(digitalRead(0));
      if(digitalRead(0)==0){
        Keyboard.println(KEY_ENTER);
      }
      delay(50);
    }

where is this  "16424" coming from, and how do I send an ENTER keypress?
I am using a Teensy 2.0, on Linux, with Arduino IDE 1.6.7.

title: How do I give the ENTER keypress?

Answers: 1

body:
You can't just "print" a key like that. You use `print` for sending text.

When you use `println` it sends an enter key along with your text, so you can do :

    Keyboard.println("ls -al");

and it will send the text `ls -al` and press enter for you.

If you want to do it in the 'raw' way you will need to press and then release the key:

    Keyboard.press(KEY_ENTER);
    Keyboard.release(KEY_ENTER);


body:
I have an ATmega328P Arduino and am trying to make the LED blink using assembly without any additional includes. The goal is to have it blink for 1 second on, then 1 second off, however, it blinks incredibly quickly and is barely perceptible. Am I doing something incorrectly?

    ; DDRB     = 0x04
    ; PORTB    = 0x05
    ; TCCROB   = 0x25
    ; TCNT0    = 0x26
    ; 0b00000000 = OFF
    ; 0b00100000 = ON

    setup:
        ldi r16, 0b00100000  ; Set r16 to LED ON value
        out 0x04, r16   ; Set DDRB to output
        out 0x05, r16   ; Set PORTB to ON
        ldi r16, 0b00000101     ; Set r16 with prescaler 1024 value
        out 0x25, r16   ; Set the TCCROB to 1024
     ldi r20, 0     ; Reset r20
     ldi r21, 1    ; Hold value 1 to increment r20
    loop:
        in r17, 0x26   ; Read the timer
        cpi r17, 128   ; Check to see if the timer is halfway done (1/2 second, max 255 value)
        brbc 0, increment  ; If r17 <= 128 (max 255 val before resets to 0), invert current LED state
     rjmp loop
    increment:
     adc r20, r21   ; Add r21 (1) to r20 (with carry)
     brbs 0, reset   ; If the carry branch is set, reset the register
     rjmp loop    ; Otherwise, run the clock
    reset:
     ldi r20, 0    ; Reset the delay register
     cpi r16, 0b00000000  ; Check if r16 is set to LED OFF
     brbs 1, switchon  ; If it is, change it to ON
     ldi r16, 0b00000000  ; Otherwise, change it to OFF
     out 0x05, r16   ; Set the LED to the new state
     rjmp loop    ; Run the clock
    switchon:
     ldi r16, 0b00100000  ; Set r16 to LED ON value
     out 0x05, r16   ; Set the LED to the new state
     rjmp loop    ; Run the clock

title: Make LED blink using AVR assembly

Answers: 2

body:
It appears that your intent is to set TCCROB up with a 1024x prescale, and each time it counts up to 128, increment r20, and toggle the LED each time r20 overflows to zero.

That sequence ought to take 1024/16M · 128 · 256 seconds, or about 2.1 seconds, a fairly leisurely toggle rate.  If instead it's flashing a hundred or more times too fast, probably one of the comparisons is backwards.

Some of the following items might make it easier to debug the problem:

• Instead of `brbc 0,...`, say `brcc ...`
• Instead of `brbs 0,...`, say `brcs ...`
• Instead of `brbs 1,...`, say `breq ...`

That is, use proper mnemonic branch instruction names, rather than referencing SREG bits.

• If my arithmetic was correct and your branch tests were fixed, your rate would be off by a factor of two.  To fix this problem, you could replace one of the more problematic tests (testing for carry clear after `cpi r17, 128`) with `cpi r17, 0` followed by a `breq`, and change the prescale factor to 256 instead of 1024, which gives 256/16M · 256 · 256 seconds, or about 1.05 seconds.

• Use named constants for register names instead of 0x04, 0x05, 0x25, and 0x26.

 • Instead of your lengthy toggle sequence use EOR to toggle the value.  That is, replace

        cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
        brbs 1, switchon        ; If it is, change it to ON
        ldi r16, 0b00000000     ; Otherwise, change it to OFF
        out 0x05, r16           ; Set the LED to the new state
        rjmp loop               ; Run the clock
    switchon:
        ldi r16, 0b00100000     ; Set r16 to LED ON value
        out 0x05, r16           ; Set the LED to the new state
        rjmp loop               ; Run the clock

with

        eor   r18, r16          ; Toggle LED bit
        out   PORTB, r18        ; Set the LED to the new state
        rjmp  loop              ; Go run the clock

where r16 and r18 are initialized as follows in setup:

        ldi r16, 0b00100000     ; bit mask for LED pin
        mov r18, r16

body:
There is a bug with the logic of your program: once TCNT0 gets larger
than 128, it will continue to be larger than 128 for quite some time...
during which time you are continuously incrementing your r20 counter.
The simplest fix would be to reset TCNT0 right after the `increment`
label, with something like `out TCNT0, zero_reg`. Then you may want to
compare TCNT0 with 61 instead of 128, in order to get closer to the
desired blink frequency of 0.5 Hz.

Other than that, there are quite a few problems in the way you write
your code. jwpat7 has already pointed out some of them, and here are
more:

* You should not increment a register with `adc`, but with plain `add`.
  Both instructions update the carry bit, but `adc` also adds the
  previous value of the carry bit to the target register.
* Better yet, increment with `inc`, as it's purpose is more obvious. But
  then you should test the zero bit, as `inc` does not update the carry
  bit.
* There is little point in resetting r20 once it has overflowed, as it
  is zero at this point.

There are also quite a few ways the program could me made simpler. The
simplest would probably be to configure timer 1 to deliver an interrupt
every second, and toggle the LED in the ISR. If you do not want
interrupts, you can configure counter 1 in much the same way, only
without the “interrupt enable” bit, and check the interrupt flag in a
busy loop.

Below is a slightly simplified version of your program. I tried to keep
it as close as possible to yours, without using timer 1, nor interrupts,
and not even the interrupt flag. The code checks for timer 0 overflowing
by comparing its current value with the previous one.

    .set PINB,     0x03
    .set DDRB,     0x04
    .set TCCR0B,   0x25
    .set TCNT0,    0x26
    .set LED_MASK, 0b00100000
    .set PS_1024,  0b00000101

    setup:
        ldi r16, PS_1024    ; Set r16 with prescaler 1024 value
        out TCCR0B, r16     ; Set the TCCROB to 1024
        ldi r16, LED_MASK   ; Set r16 to the LED bit
        out DDRB, r16       ; Set LED pin to output
        clr r18             ; Clear the saved timer
    loop:
        ldi r20, 61         ; Initialize our software counter
    check_timer:
        in r17, TCNT0       ; Read the timer
        cp r17, r18         ; Compare with previous value
        mov r18, r17        ; Save current value
        brsh check_timer    ; unless the timer has decreased, repeat
    decrement:
        dec r20             ; decrement the software counter
        brne check_timer    ; if not zero, go back to checking the timer
    toggle:
        out PINB, r16       ; toggle the LED
        rjmp loop

If we can use the timer overflow interrupt flag, then the test is
simpler, and we do not need to store the previous and current values of
the timer in registers:

    check_timer:
        sbis TIFR0, TOV0    ; unless the timer has overflowed
        rjmp check_timer    ; check again for overflow
        sbi TIFR0, TOV0     ; otherwise clear the overflow flag


body:
I made simple sketch that generates three random numbers and then calculates the average of these three random numbers.

It divides the total by 3 and then displays that average number with `serial.println`.

Sometimes the generated average number can be decimal (for example 261,333333 or 124,33333).

Interestingly, the serial print doesn't print in decimal format **124,33333**
it prints just integer **124**.

How do I print the value in decimal?

title: Printing decimal numbers

Answers: 2

body:
In the C family of languages, if you divide an integer by another
integer, the compiler interprets the division operator (`/`) as an
_integer division_, i.e. you get the integer part of the quotient. Thus,

<!-- language: lang-c -->

    (first_int + second_int + third_int) / 3

is an integer.

If either operand is a floating point number, then the other one is
implicitly converted to floating point, and you get a floating point
division. Thus

    (first_int + second_int + third_int) / 3.0

is a floating point number, and the result you expect.

body:
In languages such as C or C++ there is a distinction between integer types and floating-point types. You see, computers work using **bits**. A bit is either **0** or **1**. A bit obviously lack in both range and precision, so we combine multiple bits in order to improve.

# Integral Types

A **byte** is a group of 8 bits. In C, the type used is either

    uint8_t x; // Values from 0 to 255.
    int8_t  x; // Values from -128 to 127
    char    x; // Values from the ASCII character set (still -128 to 127)

On Ardiuno Uno, an **int** is a group of 16 bits:

    uint16_t c; // Values from 0 to 2^16-1 = 65535, synonym: unsigned int (Arduino)
    int16_t  c; // Values from -32768 to 32767,     synonym: int (Arduino)

A **long** is a group of 32 bits:

    uint32_t v; // Values from 0 to 2^32-1 = 4,294,967,295 = 4 GiB (unsigned long)
    int32_t  v; // Values from -2,147,483,648 to 2,147,483,647 (long)

There is also usually support for 64-bit numbers, but we try not to use them in Arduino code. The reason is that most Arduino MCUs use **8-bit** registers, so 64-bit operations such as "add", "sub", etc. would be very slow.

**Note**: Different architectures use different numbers of bits for these types. In order to be compatible with other architectures, use `int32_t` etc. to be sure.

## Literals and Casts

Oftentimes, the compiler can not see what type a literal value is supposed to be. In C, the compiler picks a default which is usually larger than you would like. For this reason, it is useful to know how to specify a literal exactly with the type:

     ((uint8_t)200)   // Casting 200 to an unsigned 8-bit integer
     ((char)65)       // Making the ASCII letter 'A'
     ((int32_t)42)    // Force 32 as a signed 32-bit integer (long)
     42L              // The 'L' suffix does the same as above

## Division and Remainder

A common cause of problems when programming in C is the division operator `/`. If the operands are both integer types, the result will also be an integer. So `1/3` is in fact `0`. You can get the remainder of the division using the modulus operation `%`. For instance:

    void show_division(int n, int d)
    {
        Serial.print("The division: ");
        Serial.print(n);
        Serial.print(" / ");
        Serial.print(d);
        Serial.print(" equals ");
        Serial.print(n / d);
        Serial.print(" with a remainder ");
        Serial.println(n % d);
    }

# Floating-point Types

All of the above types are integrals, so they do not support any fractional value. Therefore C defines **two** different floating-point types: **float** and **double**. The former is a 32-bit value and the latter is a 64-bit value. The way it works is that the bits are split in 3:

* A single bit is used for the **sign**.
* A certain number of bits represent the fractional part, the **mantissa**.
* The rest of the bits are used for the **exponent**.

As an example, the 32-bit float value representation for 1.25 is

    seeeeeee_emmmmmmm_mmmmmmmm_mmmmmmmm = s * 2^(e-127) * (1.m...)_2
    00111111_10100000_00000000_00000000 = (+1) * 2^(127-127) * (1.0100)_2
    // Note: Binary 1.01 equals 1.25 in decimal

## For performance, use the `f` suffix

Although 64-bit doubles are very accurate, the resulting code will run much slower. I, therefore, recommend using 32-bit floats instead. It is useful to know that you can tack on an `f` after the floating-point literal:

    (a + b + c) / 3.0f; // Make sure to divide using 32-bit operations.

If `a`, `b` and `c` above are integer types, the additions will also be integer additions. When the compiler sees an `int` divided by a `float`, it will convert the `int` to a `float`, and then perform a float division. This is slow, but certainly faster than a double division.

The compiler is smart, but it doesn't hurt to help it. There is only a very small precision loss in converting this to a float multiplication:

    (a + b + c) * (1.0f / 3.0f);

The compiler will pre-calculate `(1.0f / 3.0f)`, so you get a much faster floating-point multiplication (in addition to the `int` to `float` cast).

**Note**: Arduino Uno defaults all floating point literals to 32-bit, and `double` is the same as `float`. Therefore, the `f` suffix is strictly not needed. It is still good practice to add these for compatibility with other architectures.


body:
So I have been messing around with the Arduino Capsense library with the immensely helpful guide; http://www.instructables.com/id/How-To-Use-Touch-Sensors-With-Arduino/  (many thanks to DangerousTim!)   using the code provided, i managed to get a relay to operate with a sensor.  It worked great and I was able to adjust the distance and sensitivity.  But when i tried adding another sensor and relay, it stopped working.  I've been trying to isolate the problem for a while now and have gotten nowhere.  I'm hoping someone can help me, here's the original code for the single sensor and relay;

<!-- language-all: lang-c++ -->

    #include <CapacitiveSensor.h>
    #include <CapacitiveSensor.h> //change '42' to any desired pin...

    long time = 0;
    int state = HIGH;
    boolean yes;
    boolean previous = false;
    int debounce = 200;
    CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
    // To add more sensors...
    //CapacitiveSensor   cs_4_6 = CapacitiveSensor(4,6);        // 10M resistor       between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
    //CapacitiveSensor   cs_4_8 = CapacitiveSensor(4,8);        // 10M resistor  between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil

    void setup()
    {
        cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
        pinMode(13, OUTPUT);
    }

    void loop()
    {
        long total1 =  cs_4_2.capacitiveSensor(30);

        if (total1 > 60){yes = true;}
        else {yes = false;}

        // to toggle the state of state
        if(yes == true && previous  == false && millis() - time>debounce){
            if(state == LOW){
                state = HIGH; }
            else state = LOW;
            time = millis();
        }

        digitalWrite(13, state);
        previous = yes;
        delay(10);
    }

and here's the code for the two sensors and relays

    #include <CapacitiveSensor.h>

    int led = 13;
    int led2 = 12;
    long time = 0;
    int state = HIGH;
    long time2 = 0;
    int state2 = HIGH;
    boolean yes;
    boolean previous = false;
    boolean yes2;
    boolean previous2 = false;
    int debounce = 200;

    CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        // 10M resistor  between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
    CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

    void setup()
    {
        cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
        cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);  //Calibrate the sensor...
        pinMode(led, OUTPUT);
        pinMode(led2, OUTPUT);
    }

    void loop()
    {
        int total1 =  cs_4_2.capacitiveSensor(30);
        Serial.println(total1);
        int total2 =  cs_5_7.capacitiveSensor(30);

        if (total1 > 60){yes = true;}
        else {yes = false;}
        if (total2 > 60){yes2 = true;}
        else {yes2 = false;}

        // to toggle the state of state
        if(yes == true && previous  == false && millis() - time>debounce){
            if(state == LOW){
                state = HIGH;
            }
            else
                state = LOW;
            time = millis();
        }

        if(yes2 == true && previous2  == false && millis() - time2>debounce){
            if(state2 == LOW){
                state2 = HIGH;
            }
            else
                state2 = LOW;
            time2 = millis();
        }

        digitalWrite(led, state);
        previous = yes;
        digitalWrite(led2, state2);
        previous2 = yes2;
        delay(10);
    }

title: Arduino capacitive touch sensor help

Answers: 1

body:
I think you are making a mistake initializing **cs_5_7**.

    CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
    CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

You are using same pin 4 for both Capacitive sensors. Try using different pins. I am quite sure that, this would help.


body:
Does there exist (any user developed etc.) version of the Hardware UART serial library that has support for RTS/CTS based flow control?
More interested in the Tx side (Arduino sends data, while the peripheral can back-pressure). The library should enable the Arduino to stop transmitting within 1 character of seeing a 'not ready' indication from the peripheral.

Thank you.

title: Arduino Hardware serial library with rts/cts flow control support

Answers: 3

body:
I believe that CTS would be fairly easy to implement:

    void loop() {
      uint8_t clear_to_send = digitalRead(CTS);
      volatile char data;
      if (clear_to_send) {
        Serial.write(data);
      }
    }

I'm not sure about RTS.

body: I have I discovered that RTS/CTS may be implemented in genuine Arduinos, but is not supported by Arduinos that use the CH340 USB to serial chip. I found this when my JAVA program could talk with a genuine Uno ok, but didn't send any data to several Arduino compatibles that use the CH340 chip (but did receive from them). I had RTS/CTS set on the JAVA program. When I changed it to FLOWCONTROL_NONE it started working just fine.

body:
I am not aware of any such library. You could try to implement one
yourself, and maybe share it with the community. :-)

If you take this route, you will have to copy the file
[HardwareSerial.cpp from the Arduino core][HardwareSerial], make your
changes there, and have your version replace the one from the core. Here
are some ideas that may help to get you started:

- Wire the 'ready' signal from the device to an interrupt-capable pin of
  the Arduino.
- Inside the interrupt handler:
  - when 'ready' is deasserted, disable the UDRE interrupt by issuing
    `cbi(*_ucsrb, UDRIE0)`
  - when ready is asserted, enable it again, but only if the output
    buffer is not empty:
    `if (_tx_buffer_head != _tx_buffer_tail) sbi(*_ucsrb, UDRIE0);`
- Patch `HardwareSerial::write()` to enable the interrupt only if
  'ready' is asserted.
- Note that the UDRE IRQ can be explicitly called
  [by `HardwareSerial::flush()`][flush]
  and [by `HardwareSerial::write()`][write] if interrupts are globally
  disabled. You will have to condition this on the 'ready' signal.
- Note also that [`HardwareSerial::write()` can write directly to the
  UART][direct write] if the buffer is empty. This also has to be
  conditioned on the 'ready' signal.

[HardwareSerial]: https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/HardwareSerial.cpp
[flush]: https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/HardwareSerial.cpp#L219
[write]: https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/HardwareSerial.cpp#L262
[direct write]: https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/HardwareSerial.cpp#L242