body:
I am using an ATTiny85 for the first time and at compile I receive the following errors

    Arduino: 1.6.11 (Windows 10), Board: "Digispark (Default - 16.5mhz)"

    C:\Users\Steve\AppData\Local\Temp\build129e80c0e73568918bca55047472d138.tmp/Smoke_Auto-ATtiny.ino.ino.elf section `.text' will not fit in region `text'

    c:/program files (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld.exe: region `text' overflowed by 562 bytes

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling for board Digispark (Default - 16.5mhz).

The chip is

    Atmel 1344
    Tiny85
    20SF

I think what is happening is that my code is too big for the board.  Am I right?

Assuming so, ignoring any obvious programming errors (I can't debug for this board until I can upload :P ) how can I squeeze code like this onto an ATTiny?  I am not looking for someone to rewrite it for me, I am more interested in learning where there is any obvious bloat - I suspect the IR library (IRremote Version 2.0.1 June, 2015 by Ken Shirriff : 11Kb)

FWIW this is a project to convert a manually operated smoke machine into an automatic one and be able to manipulate the smoke time and delay via a remote. It works on a Mega, proof of concept complete, I want to shrink the board to fit into the mouse-sized controller if that is possible.

    #include <IRremote.h>

    long smokeTimeInit = 5000;  // initial smoke time
    long smokeWaitInit = 60000;  // initial interval between smoke

    long smokeIncrement = 1000; // timer increment value
    long delayIncrement = 5000; // timer increment value

    unsigned long previousMillis = 0; // this is our stored time
    unsigned long currentMillis;  //where we keep count of time

    const int smokeOnPin = 2;  // output to relay
    int smokeStopped = false; // flag to stop smoke
    const int LED = 0;
    const long RECV_PIN = 1;  // input from IR receiver

    IRrecv irrecv(RECV_PIN);

    decode_results results;

    long  smokeTime = smokeTimeInit;
    long  smokeWait = smokeWaitInit;

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

      irrecv.enableIRIn(); // Start the receiver

      digitalWrite(smokeOnPin, LOW);  // start with the smoke on
      digitalWrite(LED, HIGH);

    }

    void loop() {
      if (irrecv.decode(&results)) {

        switch(results.value){
          case 284157975 :
          //more smoke time
            smokeTime = smokeTime + smokeIncrement;
            smokeStopped = false; // smoke on

          break;
          case 284104935 :
          //less smoke time
            if(smokeTime > smokeIncrement){ // don't let the smoke time become less than the increment value i.e. negative
              smokeTime = smokeTime - smokeIncrement;
            }
            else{
              smokeTime = 1000;
            }
            smokeStopped = false;

          break;
          case 284125335 :
          //reduce interval
            if(smokeWait > delayIncrement){
              smokeWait = smokeWait - delayIncrement;
            }
            else{
              smokeWait = 1000;
            }
            smokeStopped = false;  // smoke on

          break;
          case 284141655 :
          // increase interval
            smokeWait = smokeWait + delayIncrement;
            smokeStopped = false;  // smoke on

          break;
          case 284140125 :
          // reset to initial time values
            smokeTime = smokeTimeInit;
            smokeWait = smokeWaitInit;
            smokeStopped = false;  // smoke on

          break;
          case 284148285 :
          // reset but with shorter smoke time
            smokeTime = 1000;
            smokeWait = 60000;
            smokeStopped = false;  // smoke on

          break;
          case 284123805 :
          // reset with short smoke and shorter interval
            smokeTime = 2000;
            smokeWait = 30000;
            smokeStopped = false;  // smoke on

          break;
          case 284131965 :
          // stop
            smokeStopped = true;
          break;

        }

        irrecv.resume();
      }
    currentMillis = millis();

    if(smokeStopped){  // don't even do this if smoke stopped
        if (currentMillis - previousMillis >= smokeTime && digitalRead(smokeOnPin)==0) {
          digitalWrite(smokeOnPin, HIGH); // turn the smoke on
          digitalWrite(LED, LOW);
          previousMillis = currentMillis;
        }
        else if (currentMillis - previousMillis >= smokeWait && digitalRead(smokeOnPin)==1 ) {
          digitalWrite(smokeOnPin, LOW); // turn the smoke off
          digitalWrite(LED, HIGH);
          previousMillis = currentMillis;
        }
    }

    }

title: How do I squeeze code to fit onto an ATTiny

Answers: 2

body:
Yes, the message “... Smoke_Auto-ATtiny.ino.ino.elf section `.text' will not fit in region `text'” suggests the code is too big to fit in the 8K available on the ATtiny85.

[In a .elf file, the TEXT section contains executable code.]

In IRremote.h from  Ken Shirriff et al, some comments at line 28 say to disable protocols you don't need:

    // Supported IR protocols
    // Each protocol you include costs memory and, during decode, costs time
    // Disable (set to 0) all the protocols you do not need/want!

By default, about 13 protocols are enabled and three disabled.  If you only use one or two kinds of remotes, you can  disable a bunch of the protocols.

Here are a couple of minor things for reducing memory, etc.:

• Instead of switching on  `results.value`, a `long`, you could compute an `unsigned int` equal to `results.value-284100000`, since all of your case values start with 2841 and the largest is 284157975.

• Instead of having `smokeStopped = false; // smoke on` seven times within various cases, and `smokeStopped = true;` in one of them, set `smokeStopped` to `false` before the switch, and drop the seven settings-to-false from within the switch.

• Some of your time-related variables would be better as `unsigned long` instead of just `long` variables.

Generally, your code looks clean enough except for those items.  Also, the IRremote code doesn't look bloated; but its tables can take a lot of memory.

*Edit 1–*
Addressing crowie's comment about using `#define` instead of `const int`, one *can* use `#define`'s, but in general the modern thought is that `const int` is preferable for type safety.  Typically there is no difference in generated code – aside from type checking, the compiler treats a `const int` the same way as a `#define`, ie does not allocate memory for it if it isn't used, or if the value is small, may use a load-immediate instead of fetching a value from memory.

My own preference is to use `enum { ... }` to declare integer constants.  For example, instead of

    const int smokeOnPin = 2;  // output to relay
    const long RECV_PIN = 1;  // input from IR receiver

I'd write

    enum { smokeOnPin=2, IRinPin=1 }; // Pin# for smoke on and IR input

body:
The `avr-nm` tool is great for figuring out what is using up all your memory.

You need to get to a command-line in the temporary directory where your program is compiled. You can find this directory by looking at the scrolling bottom window when you compile your program.

You run the tool like this...

```
C:\Users\passp\AppData\Local\Temp\arduino_build_965235>"C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avr-nm" -S --size-sort blink.ino.elf
```

...where in my case...

`C:\Users\passp\AppData\Local\Temp\arduino_build_965235` is  the temporary directory that the Arduino was using

`C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\` and the directory where the Arduino toolchain was installed

`blink.ino.elf` is the output generated from compiling my `blink.ino` sketch.

The `-S` parameter tells the tool to output the sizes of the symbols listed. By looking at these sizes, we can figure out what is using up all the memory and where to focus our reduction efforts.

The `--size-sort` shorts the symbols in size order so we can easily see which are the biggest.

The output of the tool on my program looks like...

```
0080010b 00000001 b click
0080008e 00000001 B datLen
00800088 00000001 b IRcount.1978
00800089 00000001 B msgNum
00800086 00000001 b prevVals.1995
0080008f 00000001 B progDir
00800087 00000001 b sendState.1979
00800109 00000001 b state
0080010a 00000001 b sync
00800092 00000001 B wake
00800066 00000002 D buttonCB
00800068 00000002 D clickCB
0080010c 00000002 B comBuf
00800115 00000002 B datBuf
0000006a 00000002 T emptyCB
00800075 00000002 D holdoff
0080008c 00000002 B ledMode
00800062 00000002 D longButtonCB
0080006f 00000002 d longPressTime
00800090 00000002 b longPressTimer
00000068 00000002 T loop
0080006a 00000002 D mode
00000d00 00000002 T setPort
00800064 00000002 D timerCB
0080008a 00000002 B timerCBcount
00800060 00000002 D timerCBtime
0080007d 00000003 D black
0080007a 00000003 D dark
0080006c 00000003 D outColor
00800077 00000003 D wakeColor
00000da6 00000004 T __mulsidi3
00800093 00000004 b powerDownTimer
00800131 00000004 B prevTimer
00800097 00000004 B sleepTimer
0080009b 00000004 b startTime
00800071 00000004 D timeout
00800105 00000004 b timer
00000a7a 00000006 T disAD
00800080 00000006 b pulseCount.1996
0080009f 00000006 b timeBuf
0080010e 00000007 B blinking
00800117 00000007 B pulsing
00000a80 00000008 T enAD
000000d4 0000000c T setColorRGB
00000a88 0000000e T initTimer
0000005a 0000000e T setup
00000044 00000010 T __do_clear_bss
0080011e 00000013 B fading
0000002e 00000016 T __do_copy_data
00000d66 00000018 T __udivmodqi4
00000a5c 0000001e T initIO
00000ce0 00000020 t sendByte
00000d44 00000022 T __mulhi3
00000822 00000022 T __vector_3
0000006c 00000022 T getTimer
00000d7e 00000028 T __udivmodhi4
00000e18 00000036 T __epilogue_restores__
00000daa 00000036 T __umulsidi3
00000de0 00000038 T __prologue_saves__
000003e8 00000038 T updateLed
0000027c 0000003a T blink
00000d02 00000042 T sendColor
0000008e 00000046 T tileSetup
00000e4e 0000005c T __muldi3
008000a5 00000060 b times
0000035e 0000008a T pulsingUpdate
000002b6 000000a8 T blinkUpdate
00000a96 000000d4 T hsv2rgb
00000b6a 00000176 T main
000000e0 0000019c T fadeUpdate
00000844 00000218 T __vector_2
00000420 00000402 T __vector_9
```
The second column is the amount of space used by the symbol.

So just looking at the bottom of our list, we can see that much of the space is being used by the functions `main`, `fadeUpdate`, `__vector_2` , and `__vector_9`.

`main` and `fadeUpdate` are obvious, but the `__vector_x` functions are actualy interrupt service routines. The actual mapping of numbers to interrupt sources can be different for different chips, so probably the easiest way to figure out what a given vector is would be to comment out the ISR in your code and then do the above process and see which vector evaporates in size.

You will have to look at each function carefully and individually to see how to possible reduce its size, but at least with this procedure  you know where too look!


body:
I am receiving lat and long data from a GPS and want to store these numbers in the middle of a sequence of chars.

E.g. lat = -23.123456

long = 135.123456

I am after something like "Your coordinates are -23.123456,135.123456" as an array of chars.

I have tried:

    float latitude = -23.123456;
    float longitude = 135.123456;

    String one = "Your coordinates are ";
    String two = ","
    String message = one + latitude + two + longitude;

    // Convert String to char array
    int str_len = message.length() + 1;
    char textmessage[str_len];
    message.toCharArray(textmessage,str_len);

    Serial.println(textmessage);

but the result is: Your coordinates are -023.12,0135.12

How can I correct this?

Thanks in advance!

title: Storing latitude and longitude floats as chars with specified precision

Answers: 1

body:
When formatting serial output is a concern, it's worthwhile to download and use the `Streaming.h` [contributed library](https://www.arduino.cc/en/Reference/Libraries) that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like `<<` Serial stream operators to `Serial.print` statements, without increasing code size.  If you don't have `Streaming.h` installed, you can get [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/).

At present, `Streaming.h` doesn't support `setw()` and `setfill()`, which in ordinary C++ set a field width and a fill character.

However, it does support  four base-conversion specifiers, _HEX, _DEC, _OCT, and _BIN; a _FLOAT function with number of decimal places specified; and `endl`.

Thus, to print  “Your coordinates are -23.123456, 135.123456” one would write:

    Serial << "Your coordinates are " << _FLOAT(latitude,6) << ", " << _FLOAT(longitude,6) << endl;

Note that unlike the `String` class, use of `Streaming.h` does not entail any dynamic memory management – everything it does happens at compile time – and it does not increase code size – it translates stream-style operations into ordinary `.print()` and `.println()` calls.  It should result in somewhat smaller, faster, and more-robust code, by avoidance of `String`.  Use of dynamic memory on small-memory embedded systems can be problematic, and this avoids those problems.

---

*Edit 1a:* As Chris Stratton points out, Arduino floats don't support 9-digit precision.  I think Arduino floating-point arithmetic is intended to comply with [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point), which sets out standards to be used on modern computers that support floating-point arithmetic.

In the [binary32 format](https://en.wikipedia.org/wiki/Single-precision_floating-point_format#IEEE_754_single-precision_binary_floating-point_format:_binary32) used to implement IEEE 754 single-precision binary floating-point, significand precision is 24 bits.  That equates to about 7.22 decimal digits (ie, 24*log₁₀(2)), so for simple calculations, 7-digit accuracy is realistic, more than that is not.

---

*[Part of] Edit 1b:*  In the larger scheme of things perhaps there's no need to create and save a formatted string like that.  It is not useful for computing – the float values are better for that.  It is not needed for communication – another streaming write can be done.

---

*Edit 2 [replaces most of 1b]:* Streaming.h  doesn't build any strings, but just delivers the text of its `<<`-arguments character-by-character to a stream.  However, a [PString class at arduiniana](http://arduiniana.org/libraries/pstring/) can build strings from stream inputs, as in the following example code.

    #include <Streaming.h>
    #include <PString.h>

    char buffer[28];
    PString pstr(buffer, sizeof(buffer));

    void setup() {
      Serial.begin(115200);
      pstr.begin();  // Empty the buffer
    }

    void loop() {
      int first=50, second=100;
      pstr.begin();  // Empty the buffer
      pstr << 'X' << first << 'Y' << second << 'T';
      pstr += " hihi ";
      pstr << millis() << endl;
      Serial << pstr;
      delay(1000);
    }

Here's what some of its output to Serial looks like:

    X50Y100T hihi 263198
    X50Y100T hihi 264199
    X50Y100T hihi 265199
    X50Y100T hihi 266201
    X50Y100T hihi 267201
    X50Y100T hihi 268201

What the sample of code does is first initialize a string buffer, then build part of a character string using streaming operator `<<`, then part of it using concatenation, then some more with `<<`, then print the string.  Note that the strings involved here are in fixed buffers, rather than dynamically allocated buffers like the String class uses.


body:
I want to measure the conversion rate of an arduino DUE. I know I could just take it from the datasheet but I need to measure it because I am running the ADC in free running mode.
Hints are welcome, I really don't know where to start.

title: Measuring ADC sample rate - Arduino DUE

Answers: 2

body:
I think using an interrupt controlled measurement might provide the best results for you.

Note: you might get more complete feedback using the Arduino forum.

In general the process would look like this:

 1. Set up an interrupt vector for the ADC peripheral (in this case support for ID37).
 2. Setup ADC registers (res, clock etc)
 2. Set up a timer to time the conversion.
 3. Create Active flag and Timer variables for processing inbound timer values.
 4. Start timer and ADC conversion.
 5. Loop waiting for active flag to set (it gets set in the ISR), when detected do average or store timer values, then clear active flag.

This methodology times each individual conversion using a high speed timer, which could mean a lot of values to process. You could equally not time each conversion, but simply set up say a 1 second timer, and count the total number of conversions in 1 second for your particular ADC configuration.

Peripheral ISR

 1. Waiting for Interrupt.
 5. In peripheral ISR, read and store timer value, reset timer, set active flag
 6. Return from ISR

body:
To expand on [Jack Creasey's answer](https://electronics.stackexchange.com/a/279740/11683), timestamping the samples as they are taken is the most direct way to do it. If you have a block of N samples, the average sample period is simply

$$\frac{Time_{last} - Time_{first}}{N - 1}$$

(Note that there are N-1 time intervals between N samples.)

If you want the sample rate, just invert the expression:

$$\frac{N - 1}{Time_{last} - Time_{first}}$$

---

However, you can also infer the sample rate from a known signal. For example, you can feed a tone signal into the ADC and count the number of samples between some well-defined feature of the waveform, such as rising zero crossings. If you count N samples, then the sample rate is N times the tone frequency. Averaging over multiple cycles of the tone will give you a more precise measurement.


body:
**Short Version**:
Not able to get a servo to move to mapped input from RC remote control PPM signal.

**Detailed Verison**:
I am trying to take an input signal from a hobby RC radio (D4RII receiver ppm stream/one wire) signal and map the values 1000-2000 into 0-180 for a value that is useful for a servo. Initially, I had an issue simply reading the values stored within the array from the [TinyPpmReader.h ](https://github.com/RC-Navy/DigisparkArduinoIntegration/tree/master/libraries/DigisparkTinyPpmReader/)library from [DigisparkArduinoIntegration](https://github.com/RC-Navy/DigisparkArduinoIntegration/tree/master/libraries/DigisparkTinyPpmReader/) on github.

For background, I am using tiny cores. This was the fist issue that was solved:
https://arduino.stackexchange.com/questions/33088/accessing-values-from-array-within-a-library

Second Issue solved:
https://arduino.stackexchange.com/questions/33224/mapping-ppm-signals-to-servo-values

Now, the last part of the battle is to get the servos the actually move. I have successfully (with help)

1.Made the single array values available to be read via serial console (Uno to ATtiny85) like this - **Serial.println(TinyPpmReader.width_us(3));**

2.Successfully mapped the values within the ppm array to 0-180 and validated the values are correctly mapped and printed to the serial console like this - **Serial.println(mappedval0);**

Couple of questions. Is it possible that since the ATtiny 85 only has Timer0 and Timer1 available that pwm wont work? ATtiny 85 datasheet [here](http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf//).  If I understand it correctly, the tinyppmreader library does use an interupt driven process.

I chose to go with the SoftwareSerial library since I don't think it is using any timers (Not really sure).  Or, is this just a simple coding issue? What is my mistake? This will compile and the servo does seem to glitch around but not move according to the mapped ppm stream.

Since my search results are now coming up with my previous questions I am hoping this will help others be able to use ppm / servos with the ATiny 85 since it is so small and perfect for many RC related projects.

CODE:

 #include <TinyPinChange.h>
 #include <TinyPpmReader.h>
 #include <Rcul.h>
 #include <SoftwareServo.h>
 //#include <TinyServo.h>

 int val0;                    // integer to store value
 int mappedval0;
 #define PPM_INPUT_PIN  4

 SoftwareServo myservo;

 const int PPM_max_value = 2000; //put the max value of PPM reading result
 const int PPM_min_value = 980; //put the min value of PPM reading result

 //const byte SERVOS = 1; // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
 //const byte servoPin[SERVOS] = { 1 }; // what pins are your servos on?
 // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

 //#define RIGHTLEGSERVO 0

 void setup()
 {
   Serial.begin(38400);//attiny tx - rx uno does not work at 9600 baud. Set to 38400 @ attiny 1mhz and uno serial console to 38400 baud
   TinyPpmReader.attach(PPM_INPUT_PIN); /* Attach TinyPpmReader to PPM_INPUT_PIN pin */
   //setupServos();
  myservo.attach(0);
 }

 void loop()
 {
    val0 =TinyPpmReader.width_us(3);   //get PPM reading result from index 4
    mappedval0= map(val0, PPM_min_value, PPM_max_value, 0, 180);
    myservo.write(mappedval0);
    //moveServo(RIGHTLEGSERVO, mappedval0);
    //Serial.println(mappedval0);
    SoftwareServo::refresh();
    delay(50);

 }

I have commented out the tinyservo library parts while testing the SoftwareServo library.

title: ATtiny Mapping PPM Inputs to Move Servo Issue

Answers: 0


body:
My idea is to use Arduino to control the TV remote. Not make the Arduino become a TV remote, I want to make an Arduino that can touch button of a remote control.

Any ideas?

title: Control the "TV remote"

Answers: 1

body:
My rather fancy solution would be to make a 3 axis device with x and y controlled by stepper motors and z a simple solenoid to press the buttons.
For extra marks you could add a camera and try to recognise the buttons in software so any remote would work.
How do you plan to control the arduino?  Perhaps with a remote controller?


body:
We are trying to make an app that generates an Arduino sketch (.ino) using Google's Blockly and node.js, and uploads it to Arduino.

Even after searching a lot, I am unable to find how to build and upload the generated code to the board. Is there any tool or API available for node.js to do the same?

Or could I call some binary for this function. Please help.

title: How to programmatically upload an Arduino sketch generated by node.js (electron) or from browser?

Answers: 1

body:
There are two things you need to do:

1. Compile the sketch into a .HEX file
2. Upload the sketch to the board

The first part can be done with `arduino-builder` which is part of the IDE since 1.6.6, or you can use one of various `Makefile` projects on a platform that supports `make`, or you can manually script it yourself calling the correct `avr-gcc` and `avr-g++` commands. You can check the output of the IDE for what those are.

The second part is done, usually, using `avrdude` - again see the output of the IDE for the correct command format.


body:
I made a sample using two of them using Arduino UNO.
So I did that like this:

[![Arduino with 74HC595][1]][1]
(There aren't any resistor on that image, but there are 220ohm resistor on every LEDs.)
And uploaded this code.

    //1.6us+62.5ns
    #include <SPI.h>

    #define sbi(port, bit) (port) |= (1 << (bit))
    #define cbi(port, bit) (port) &= ~(1 << (bit))

    int latchPin = 12;
    int clockPin = 13;
    int dataPin = 11;

    byte data[]={ 0b10101010,0b11001100 };

    void _595_out() {
     cbi(PORTB, 4);
     SPI.transfer(data[0] );
     SPI.transfer( data[1] );
     sbi(PORTB, 4);
    }

    void setup() {
     pinMode(latchPin, OUTPUT);
     pinMode(clockPin, OUTPUT);
     pinMode(dataPin, OUTPUT);

     SPI.setClockDivider(SPI_CLOCK_DIV2);
     SPI.setBitOrder(MSBFIRST);
     SPI.setDataMode(SPI_MODE0);
     SPI.begin();
    }

    void loop() {
     _595_out();
    }

And this worked as I expected. But, when I changed sketch like this,

    //1.6us+62.5ns
    #include <SPI.h>

    #define sbi(port, bit) (port) |= (1 << (bit))
    #define cbi(port, bit) (port) &= ~(1 << (bit))
    #define CHIPNO 2
    int latchPin = 12;
    int clockPin = 13;
    int dataPin = 11;

    byte data[]={ 0b10101010,0b11001100 };

    void _595_out() {
        cbi(PORTB, 4);
        SPI.transfer(data[0]);
        SPI.transfer(data[1]);
        sbi(PORTB, 4);
    }

    void setup() {
        pinMode(latchPin, OUTPUT);
        pinMode(clockPin, OUTPUT);
        pinMode(dataPin, OUTPUT);

        SPI.setClockDivider(SPI_CLOCK_DIV2);
        SPI.setBitOrder(MSBFIRST);
        SPI.setDataMode(SPI_MODE0);
        SPI.begin();
        Serial.begin(9600);
    }

    void loop() {
        for(unsigned int z = 0; z < 65535; z++) {
            data[0] = z & 255;
            data[1] = (z & 65280) >> 8;
            Serial.println("A");
            Serial.print(data[0]);
            Serial.print("/");
            Serial.println(data[1]);
            Serial.println("B");
            _595_out();
            Serial.println("C");
            delay(500);
        }
    }

74HC595s aren't working. Any LEDs aren't on.
Printing Serial works well. Only 74HC595s aren't working.
And Removing all Serial-related thing doesn't solved this problem.
Where did I do wrong?

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

title: shiftOut using SPI isn't working

Answers: 1

body:
    int latchPin = 12;

You use pin 12 as the latch pin. Once you activate SPI the hardware takes over control of the pins MOSI, MISO and SCK. Pin 12 is MISO and thus attempting to change it in your code will have no effect.

You should use some other pin as the latch pin (pin 10 is often used).

---

> And shiftOut using SPI is working when I use first code

`shiftOut` is a software-based method of clocking out bits. It doesn't use hardware and thus it doesn't take control of pin 12.

---

Note: Answered originally on [the Arduino Forum](https://forum.arduino.cc/index.php?topic=448017.0)


body:
I want to count peak of photocell data with serial communication in Arduino.

Here is the question. My problem is when I count one of the peaks it continues the counting and doesn't stop counting. My project is count Michelson Morley fringes with a photocell and Arduino.

If somebody can help me with the coding part I would appreciate it.

Here is the code that I used:

    int count=0;
    int val;
    int data;

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

    void loop() {
      data=analogRead(A0);
      val=map(data,0,1023,1000,0);
      if(val>700) {
       count++;
      }
      Serial.println(count);
      delay(100);
    }

This picture shows what I am trying to achieve:
[![Counting the peaks][1]][1]

Example Michelson Morley fringes:
[![Example Michelson Morley fringes][2]][2]

  [1]: https://i.stack.imgur.com/fRiFh.jpg
  [2]: https://i.stack.imgur.com/mqzq0.jpg

title: Peak counting in serial Arduino

Answers: 1

body:
keep in mind that since you used

    delay(100)

your 'loop' code runs in 10HZ (10 times a second)
So, every time you are lighting on your sensor, if its for longer than 1/10 of a second, you are likely going through several instances of 'loop', in which the condition

    (val>700)

is satisfied.

If you **know** that your peaks are going to take several loops, and only want to count each peak once- a simple way would be to make sure you dropped from the previous peak before incrementing the counter. you can achieve that with something like:

    int count=0;
    int val;
    int data;
    bool inPeak = false;

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

    void loop() {
      data=analogRead(A0);
      val=map(data,0,1023,1000,0);
      if(val>700) {
         if (!inPeak)
         {
            count ++;
            inPeak = true;
         }
      }
      else
      {
          inPeak = false;
      }

      Serial.println(count);
      delay(100);
    }


body:
I need to convert Arduino code to avr-gcc code. This is code:

    #include <Servo.h>

    Servo myservo;

    void setup() {
      myservo.attach(11);
    }

    void loop() {
      myservo.write(67);
    }

I use Arduino Mega.

title: Help: convert Arduino code to avr-gcc code

Answers: 1

body:
Try this:

    #include <Servo.h>

    extern "C" void init(void);

    Servo myservo;

    int main()
    {
        init();
        myservo.attach(11);
        for (;;) {
            myservo.write(67);
        }
    }

Note that this still needs the Arduino core library, as the Servo
library depends on it, which means all this is an exercise in futility.
If you are using the Arduino core, the simplest thing is to use it the
Arduino way. If you do not want to use Arduino core, then you will have
to partially re-implement the Servo library.


body:
Im working on a project where I will be using multiple Arduino (pro mini)'s which emit sensordata through LoRa.

The problem I am currently facing is, when I have multiple sensors, how do I know what data is coming from which Arduino (given they all have exactly the same source-code)?

1. Does the arduino have a UID like some sort of MAC code?
2. What could be a solution to give the Arduino a UID?
3. Do you guys have any other solutions for my issue?

In order to answer #2, I could add a random number calculator to create, but this doesn't feel right to me.

title: Possibility of getting a UID on Arduino

Answers: 1

body:
You could use a small silicon serial chip like the Maxim DS2401 (http://pdfserv.maximintegrated.com/en/ds/DS2401.pdf)

An other method is to use good old dipswitches. That way you set each of your 'transmitter' to different address using the dipswitch. On boot the Arduino reads the switches to know it's address and uses that.


body:
I'm using a `Genuino MKR1000` and I want to use the `SPI` interface, which I've seen that there is no `Slave Select (SS)/Chip Select(CS)` pin usage.

How can I use the `SPI` interface with multiple slaves then?

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

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

title: How to use multiple SPI slaves in MKR1000 if it doesn't have Slave Select (SS/CS) pin?

Answers: 2

body:
The Arduino doesn't care what pin you use for SS since you just use `digitalWrite()` on it anyway. You use any pin you like for one slave, so you can use any other pin you like for another slave.

The ATMega-based boards need pin 10 to be set as an output for SPI to function, but you don't then have to use that for the actual slave select. The only time it becomes a real slave-select pin is when using the Arduino itself as a slave.

body: If the number of slaves is large, consider using a multiplexed arrangement for select lines.  As an example, the 16-pin 74LS138 Decoder/Demultiplexer pulls one of eight lines low depending on the state of its three address lines, while the 24-pin 74LS154 pulls one of sixteen lines low depending on the state of its four address lines.  Both of these chips have two or three enable lines, allowing use of two to four of them together to multiply the number of output lines by two to four via use of one or two more address lines.


body:
I am looking for a graphical programming language for a project of mine, where I am using an Arduino.

It HAS to meet the following conditions:

 - It supports uploaing sketches to ATmega328 (Arduino Uno/Nano)
 - New functions can be defined inside the programming enviroment (I am trying to use a motor connected to an H-bridge with a single command block)
 - The program can run on Windows 7
 - Libraries can be used inside the code
 - C++ can also be used to write the code inside the same program
 - Sketches can be uploaded via Bluetooth 4.0

It would be nice if it met the following condition:

 - The programming enviroment is easy to use
 - The graphical programming language is somewhat similar to Scratch
 - The program can be understood by 10-14 year olds with no programming experience

title: Graphical programing language for Arduino

Answers: 2

body:
The most full featured Scratch-like environment for Arduino, to my knowledge that is close to your listed criteria is http://www.mblock.cc/

It's currently in beta development for enabling bluetooth uploads and supports a range of "extension" plugins.  I believe you can also add functionality by writing your own extensions if you have sufficient programming knowledge.

The software has more features if you use their mblock hardware, while offering a reduced set of commands for other boards such as the Uno.

[![Supported Boards][1]][1]

[![Arduino code with scratch][2]][2]

I'm sure you can add library's to your code but at the expense of the scratch-like interface.  A children's visual design tool being able to provide graphical API to libraries written by an open source community is quite a coding challenge.  You can get a feel for this by trying to use any reverse engineering C++ to UML diagram tools.

I recommend perhaps using one of these scratch tools to build simple firmware as a learning tool with the idea of progressing to an actual programming language soon after.

In any case I hope you find what you're looking for among these options for your project.

 - http://www.mblock.cc/
 - http://s4a.cat/
 - http://blog.minibloq.org/p/documentation.html
 - http://blog.ardublock.com/engetting-started-ardublockzhardublock/
 - https://www.visuino.com/

  [1]: https://i.stack.imgur.com/XxE0x.png
  [2]: https://i.stack.imgur.com/noln2.png

body: Give Visuino a look, they are making noise lately: https://www.visuino.com/


body:
**My question is how to do it (set it up), not if I can do it or with what Arduino.**

I've previously setup OpenCV with Visual Studio 2015. It was a tough one, but I made it through. Now I want to set it up so that it would work with the Arduino and its IDE.

***How should I proceed? Is there any specific things to do?***

My setup:

- Windows 7
- Arduino IDE 1.8.1
- OpenCV 3.1

title: How to setup OpenCV with Arduino?

Answers: 2

body:
If you are thinking of using OpenCV with a "normal" Arduino, such as the Uno or Mega, then think again. OpenCV runs on a computer - be that a desktop computer or an embedded computer. Basically you need an operating system; "normal" Arduinos don't have an operating system.

It may be possible to run OpenCV on an Arduino that runs Linux (some of the strange Intel things that are being marketed as Arduino do, as does the Yún), but in that case you will be writing a Linux application, not working in the Arduino IDE. You would need to treat it as a normal Linux computer and use the normal Linux tools for developing on it (note that OpenWRT that the Yún runs is tricky to develop for - the best way is to cross-compile on a real computer running Linux using the OpenWRT "Buildroot" system).

body:
As some people said before, you just can't run OpenCV on Arduino.
but, you can use Arduino/Raspberry Pi to capture information and send it to a server for analysis. For example, Azure, Bluemix or your main computer.

In your case, I would use Raspberry Pi + camera to capture images/videos.
then, send it through Wi-Fi to a server. Then, on the server, process all images using OpenCV.


body:
I have the following build:

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

And the following code:

    const int buttonPin = 3;
    const int ledPin = 2;
    int buttonState = 0;

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

      pinMode(buttonPin, INPUT);
      pinMode(ledPin, OUTPUT);

    }

    void loop() {
      while (digitalRead(ledPin) != LOW){
        buttonState = digitalRead(buttonPin);

        if (buttonState == LOW){
          digitalWrite(ledPin, LOW);
        }
      }
    }

But it doesn't seem like anything is registered, as my program doesn't respond to the shut down of the LED. What have I done wrong?

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

title: LED doesn't register as LOW after a switch has cut all power to it

Answers: 2

body:
The diagram is open to several different interpretations, depending on what's inside the four-terminal switch.  On many such SPST switches, two adjacent terminals are connected to each other inside it, and the other two likewise.  Which are which in the diagram isn't indicated.

That aside, what is clear from the diagram is that pin 2 is connected by wires to +5V, and will always read in as high.

---

*Edit 1:*
The schematic [posted later] is unclear.  It should be arranged so that solid lines represent wires or pins, with solid lines between things that are connected.  Place items in the drawing to reduce unnecessary and confusing crossing lines.  For example, supposing that the dashed line from pin 2 of R1 represents a wire between pin 2 of R1 and pin 2 of LED1, it is unclear whether the wire bends around the top right pin of S1 (can't read number) or connects with that pin on its way to LED1.  For another example, nothing is shown connecting to pin 1 of R1, and only one long dashed line connects the R1/S1/LED1 group to the Uno.

body:
Looking at your schematic, I get a bit confused.
You should start out with creating the schematic, try to base it on existing schematics on the web/tutorials.

I believe you're trying to read out a button and set an led accordingly?

So start out with the schematic and then try to build a breadboard setup for this. Randomly wiring things up on your breadboard doesn't really make sense, you need a plan.

I've created a shematic of which I believe should work a treat.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/ZGNEY.png)

<!-- End schematic -->

*Using internal pull-ups on the SW1, to avoid the input floating.
Using 220ohms resistor, based on "Basic Red 5mm - Sparkfun LED", 5V source, 2V forward 16mA (http://led.linear1.org/1led.wiz).
Be carefull not to set the SW1 as an output (high) and push the button, this theoretically burns out the I/O pin.
But even then, this is only basic, you may want to consider input protection (http://www.thebox.myzen.co.uk/Tutorial/Protection.html)*

It's very easy to mess something up or do something incorrectly in electrical engineering. To be honest, it may help to watch a lot of tutorials or read books on electronics. It's very usefull to have a basic understanding before wiring things up.

At least base your actions on a (good) tutorial or reference material from Arduino self.

Try to wire up the circuit according to my schematics

Mouseover for example (but please try it yourself before checking!)
>! [![enter image description here][1]][1]

The same actually counts for programming, first try to make it clear what you want to achieve. Maybe even write out the steps that your program should do on a functional level.

I have no idea how you program could actually compile, the while and if statements don't have any closing brackets.

    const int buttonPin = 2;//I switched the LED and button in my design.
    const int ledPin = 3;//So the LED is on a PWM pin, which makes more sense.

    void setup() {
      //Serial.begin(9600); //We're not using serial, so why start serial?
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
       int value = digitalRead(buttonPin);
       digitalWrite(ledPin, value);
       //or digitalWrite(ledPin,digitalRead(buttonPin));//for short
    }

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


body:
I have a project that uses a Telit LE910 4G LTE Modem to allow me some basic monitoring via SMS and HTTP POST to Exosite.

I can connect to a Exosite server with and send a successful HTTP GET request to pull a UNIX timestamp (as a test).

**Problem**

The problem lies with receiving.  The information received cuts off halfway through the HTTP headers, before reaching the body of the information.

This image shows what prints out on the Serial monitor:

[![Serial Monitor][1]][1]

This image shows what the expected result should be:

[![Expected][2]][2]

And this image shows the code the executes to send the request:

[![enter image description here][3]][3]

The result is the same with PrintModemResponse() and with GetModemResponse().  Additionally, I have the same issue with receiving SMS messages.  The data appears to cut off partway through the expected response.  The modem serial (SW_Serial) baud rate is set to 115200.

**Question**

Am I doing something wrong with reading the Serial information from the modem?  Am I hitting a timeout of some sort?

  [1]: https://i.stack.imgur.com/sQiXt.jpg
  [2]: https://i.stack.imgur.com/o3TEx.jpg
  [3]: https://i.stack.imgur.com/e9bd8.jpg

title: Serial Communication Issue with Telit LE910 LTE Modem

Answers: 1

body:
First, please don't post screen images.  Just select the text and paste it into your questions.  You can copy code from the editor or messages from the Serial Monitor window.  Paste into your post, select the section again, and press ctrl-K to format it as a code block in your question (like below).

> Am I doing something wrong with reading the Serial information from the modem?

Yes, you are using delay to "wait" for the response to appear.

> Am I hitting a timeout of some sort?

In a way.  The input buffer only has room for 64 characters.  If you don't read any of them because you're blocked at a `delay` statement, the 65th character (and all others) will be ignored.  **These answer your specific questions.**

<hr>
###Further Suggestions:

To fix the real problem, not just the symptoms, you will have to change your sketch structure.

There are many ways to implement this in a non-blocking way (i.e., without using `delay`).  I prefer [Finite-state Machines](https://en.wikipedia.org/wiki/Finite-state_machine); there are many good tutorials for this  technique (e.g., Nick Gammon's site).

Although it's not as flexible, you could also use your own `while` loop for each response, with a timeout.  Here's a simple example that reads one line.

    char resp[20];
    char resp_Len = 0;
    const uint32_t TIMEOUT_MS = 5000UL; // 5 seconds

    AltSoftSerial modem_port; // pins 8 & 9 ONLY

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

    void loop()
    {
      uint32_t startTime = millis();
      while (millis() - startTime < TIMEOUT_MS) {
        if (modem_port.available()) {
          char c = modem_port.read();
          if (c == '\n') {
            resp[ respLen ] = '\0'; // NUL terminate
            respLen = 0; // reset for another line
            break;

          } else if (respLen < sizeof(resp)-1) { // Room for more?
            resp[ respLen++ ] = c; // accumulate one more character
          }
        }
      }

      Serial.print( F("Response = '") ); // F macro saves RAM
      Serial.print( resp );
      Serial.println( '\'' );
    }

But when the response is long (hundreds of bytes), you may not have sufficient RAM to save the whole response, and then parse it.  You MUST use an FSM to parse the bytes *as they are received*.

For your application, you should skip all the stuff at the front and watch for the "Content-type:" pattern and the two newlines, then save the next line (as above) for parsing:

    enum state_t { SKIP_TO_CONTENT_TYPE, SKIP_TO_EMPTY_LINE, SAVING_TIMESTAMP };
    state_t state = SKIPPING
    uint8_t index = 0;

    const char ContentType[] = "Content_type:";

    bool watchForTimestamp()
    {
      if (modem_port.available()) {
        char c = modem_port.read();

        // Handle this one character, based on our current "state"

        switch (state) {
          case SKIP_TO_CONTENT_TYPE:
            if (c == '\n')
              index = 0;

            else if ((index < sizeof(ContentType) && (c == ContentType[ index ])) {
              // next char matches
              index++;

              if (index == sizeof(ContentType)) {
                // All matched!
                state = SKIP_TO_EMPTY_LINE;
                index = 0;
              }
            }
            break;

          case SKIP_TO_EMPTY_LINE:
            if (c == '\n') {
              index++; // this counts newlines since "Content-type:"

              if (index == 2) {
                state = SAVING_TIMESTAMP;
                index = 0;
              }
            }
            break;

          case SAVING_TIMESTAMP:
                ... Hint: something like the line-saving technique above.
            if (something) {
              return true;
            }
            break;
        }
      }

      return false;
    }

Some part of `loop` will just call `waitForTimestamp` over and over:

    void loop()
    {
        ...

      bool gotResponse = false;
      state = SKIP_TO_CONTENT_TYPE;

      while (millis() - startTime < TIMESTAMP_TIMEOUT) {
        gotResponse = waitForTimeStamp();
        if (gotResponse) {
          // parse the timestamp from the resp array
             ...
          break;
        }
      }

      if (gotResponse) {
        Serial.print( F("Timestamp = ") );
        Serial.print( resp );
        // now you can parse the small response array
           ...

      } else {
        Serial.println( F("Didn't receive timestamp!") );
         ... other error code
      }
    }

This may be a "main" FSM for loop, with a nested FSM for parsing the HTTP response.  The rest is up to you.  :)

BTW, SoftwareSerial is **very** inefficient.  It cannot send and receive at the same time, and it disables interrupts for long periods of time.

If you can use pins 8 & 9, you should use AltSoftSerial instead.  It is very efficient.

If you can't switch to those pins, you could use [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial) if the modem is running at 9600, 19200 or 38400.


body:
The theory is that you can use 3.3v I2C devices from a 5v device as long as the pull ups are only to the 3.3v. I have a 5v pro mini connected to a bmp180 board which has a 3.3v regulator but no level shifters. It is working and giving me data but I am hoping I can get better quality measurements. One observation is the power rail on the BMP board after the 3.3v regulator is being pulled towards 5v. On the scope this looks to happen between i2c messages. I am using the "Adafruit-BMP085-Library" which is in turn using "Wire". In the wire library there is a comment that says that the writedigital() of 1 to the port is setting the pull ups.

Does anyone have any general advice on this issue?

What does the comment about setting the pull-ups mean? How is that function setting the pull ups?

When does the I2C switch back to being an GPIO? Are the lines being pulled high between messages because it is reverting to an GPIO?

title: How do I stop 5v on the I2C port of a pro mini so I can use 3.3v devices?

Answers: 1

body:
Whoever decided it would be a good idea to default to using the Arduino internal pull-up resistors on I2C needs taking out back and giving a good kicking. It is so wrong on so many levels.

Yes, if you disable the internal pull-up resistors you can safely use 3.3v devices. The simplest way to do this is to turn them off again as soon as you have done `Wire.begin();` by writing 0 to the pins with `digitalWrite()`.


body:
I am building a project where I have to store the digital state which is Boolean (either HIGH or LOW) of each I/O port such that after power off the state of I/O ports store in EEPROM and I can retrieve this I/O port's state after power on.

This is my code..

        #include <IRremote.h>
        #include <EEPROM.h>
        int EEPROMaddress = 0;
        int EEPROMaddress1 = 1;
        byte EEPROMbyte = EEPROM.read(EEPROMaddress);
        byte EEPROMbyte1 = EEPROM.read(EEPROMaddress1);
        int RECV_PIN = 11;
        int led = 10;//1FE50AF
        int led1 = 9;//1FED827
        boolean previousState = bitRead(EEPROM.read(EEPROMaddress), led);
        boolean previousState1 = bitRead(EEPROM.read(EEPROMaddress1), led1);
        boolean state;
        boolean state1;
        IRrecv irrecv(RECV_PIN);
        decode_results results;
        void setup()
        {
          Serial.begin(9600);
          pinMode(10,OUTPUT);
          pinMode(9,OUTPUT);
          irrecv.enableIRIn();
        }
        void loop() {
          if (irrecv.decode(&results))
          {
            Serial.println(results.value, HEX);
            switch(results.value)
            {
               case 0x1FE50AF:
               if (previousState == LOW)
               {state = HIGH;
                digitalWrite(led,state);
               previousState=state;
               bitWrite(EEPROMbyte,led,state);
               EEPROM.update(EEPROMaddress,EEPROMbyte);
               delay(50);}
               else
               {state=LOW;
               digitalWrite(led,state);
               previousState=state;
               bitWrite(EEPROMbyte,led, state);
               EEPROM.update(EEPROMaddress,EEPROMbyte);
               delay(50);
               }
               break;
                case 0x1FED827:
               if (previousState1 == LOW)
               {state1=HIGH;
               digitalWrite(led1,state1);
               previousState1=state1;
               bitWrite(EEPROMbyte1,led1, state1);
               delay(50);}
               else
               {state1=LOW;
               digitalWrite(led1,state1);
               previousState1=state1;
               bitWrite(EEPROMbyte1,led1,state1);
               delay(50);}
               break;
    }
            irrecv.resume();
          }
    }

title: How to store 1 bit Boolean data into EEPROM and retrieve this 1 bit data?

Answers: 3

body:
Since this is Arduino SE I'm going to do this with the Arduino functions, there are other ways of course.

Write a bit to EEPROM:

    byte EEPROMbyte = EEPROM.read(EEPROMaddress);
    bitWrite(EEPROMbyte, pinBit, pinState);
    EEPROM.update(EEPROMaddress, EEPROMbyte);

Read a bit from EEPROM:

    boolean pinState = bitRead(EEPROM.read(EEPROMaddress), pinBit);

This is for updating/reading a single bit at a time as asked. If you need to read/write multiple bits at the same time(as I'd assume you are doing after power on) then it's more efficient(and less wear on the EEPROM in the case of the write) to do all the bits at once instead of one EEPROM read/write per bit.

I assume by "I/O ports" you mean Arduino pins. If you're working directly with the PORT registers(e.g. PORTB) then you can just write or read the whole register to the EEPROM, no need to deal with the individual bits.

body:
Note that writing EEPROM is slow - on the order of milliseconds per write - which may limit the performance of your sketch.

A better technique is to provide a limited backup power supply to the MCU; enough to complete a set of EEPROM writes + a safety margin. A capacitor could possibly provide enough run time if doesn't have to power much else. Then, detect and interrupt on a failure of the main supply, immediately write your backup data to EEPROM, and enter an infinite loop to wait for the backup supply to fail. When the system resets, examine the EEPROM to be sure there is valid backup data there, restore what needs to be restored, and resume your task.

Update:

A search for "arduino backup power" finds a number of articles related to switching an Arduino from mains power to battery power when the mains fails. You would only need a very small battery if you're willing to only save necessary information then shut down until the power returns. A capacitor might keep your MCU running long enough to do that. Designing the circuit depends on too much we don't know about your system, though.

In fact, simply switching a backup battery as some of these articles describe, or better, running on a battery which is kept on a mains charger, may make a much simpler system that can surviVe reasonably long power outages without shutting down. Again, we don't know how often or how long your power goes out, and how reliable your system is required to be.

body:
You can store any bits or bytes into eeprom in byte units. The eeprom itself doesn't care whether the data ISS bits or bytes or multi bytes.

Your code only needs to make sure that consistency is maintained in storying and retrieving of eeprom data.


body: I have 12V and 5V power available. Is it better to feed the 5V through the Vcc pin or either the 12V or 5V through the Vraw pin?

title: Is it better to use Vraw or Vcc on Mini Pro?

Answers: 1

body:
Use the 5V connected to the Vcc pin.

If you use the Vraw pin, the voltage goes through a voltage regulator. This voltage regulator will convert the higher voltage down to 5V by converting the extra volts to heat. So in case of using 12V you'd be throwing away around 60% of the power. Which is both wasteful, and will heat up the regulator quite a bit (depending on the load).


body:
I am completely new to programming and I am trying a brute force programming on my garage door opener. I want to use an Arduino for learning purposes. I wrote the following program that finally did what it should and now I am wondering whether there is a shorter code that does the same. Is anyone able to help me in that matter?

I do know that about 2^12 possibilities existed so I ran through all of them. I also knew that some parts of the "pulsetrain" (the set of necessary pulses) start with a particular sequence that is always the same (for all "brute forced" trains) and that the closing sequence is also always identical. I then simply wrote that down in the following, nasty code:

    /*
      Transmitter is connected to Arduino Pin #2
    */

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

    void pulsetrain(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m) {
      PORTD &= ~_BV(PD2);
      //set to LOW, hardwired to make it faster, see http://www.instructables.com/id/Arduino-is-Slow-and-how-to-fix-it/?ALLSTEPS
      delayMicroseconds(283); // (D2)
      PORTD |= _BV(PD2); //set to HIGH
      delayMicroseconds(566);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(283);
      PORTD |= _BV(PD2);
      delayMicroseconds(566);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(a);
      PORTD |= _BV(PD2);
      delayMicroseconds(b);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(c);
      PORTD |= _BV(PD2);
      delayMicroseconds(d);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(e);
      PORTD |= _BV(PD2);
      delayMicroseconds(f);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(g);
      PORTD |= _BV(PD2);
      delayMicroseconds(h);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(i);
      PORTD |= _BV(PD2);
      delayMicroseconds(j);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(k);
      PORTD |= _BV(PD2);
      delayMicroseconds(l);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(m);
      PORTD |= _BV(PD2);
      delayMicroseconds(283);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(566);
      PORTD |= _BV(PD2);
      delayMicroseconds(283);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(566);
      PORTD &= ~_BV(PD2); // last LOW
    }

    void loop() {
      int signals[2] = {283, 566};
      for (int a = 0; a < 2;  a++) {
        for (int b = 0; b < 2;  b++) {
          for (int c = 0; c < 2;  c++) {
            for (int d = 0; d < 2;  d++) {
              for (int e = 0; e < 2;  e++) {
                for (int f = 0; f < 2;  f++) {
                  for (int g = 0; g < 2;  g++) {
                    for (int h = 0; h < 2;  h++) {
                      for (int i = 0; i < 2;  i++) {
                        for (int j = 0; j < 2;  j++) {
                          for (int k = 0; k < 2;  k++) {
                            for (int l = 0; l < 2;  l++) {
                              for (int m = 0; m < 2;  m++) {
                                pulsetrain(signals[a], signals[b], signals[c], signals[d], signals[e], signals[f], signals[g], signals[h], signals[i], signals[j], signals[k], signals[l], signals[m]);
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

title: Huge nested loop in Arduino

Answers: 1

body:
All those variables `a`, `b`, etc. are just the individual bits of a
13-bit number. When you loop through all combinations, you are actually
looping through all the possible _numeric values_ of a 13-bit number.
This can be simplified as this (warning: not tested):

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

    // the bitstream is: 0.101x xxxx.xxxx xxxx.0101
    void pulsetrain(uint16_t code) {
        uint32_t bitstream = (((uint32_t) code) << 4) | 0x0a0005UL;
        for (uint8_t i = 0; i < 21; i++) {
            PIND = _BV(PD2);    // toggle pin
            if (bitstream & 0x100000)
                delayMicroseconds(566);
            else
                delayMicroseconds(283);
            bitstream <<= 1;
        }
        PORTD &= ~_BV(PD2); // last LOW
    }

    void loop() {
        for (uint16_t code = 0; code < 0x2000; code++) {
            pulsetrain(code);
        }
    }


body:
I have heard two theories of grounding: pretty much ground a board at single point, or ground everything in sight.

With the Mini Pro, is it better to provide one source of ground through the Gnd pin next to the Vraw pin, or ground with multiple Gnd pins on the board?

title: Electronically, should single or several ground pins be used?

Answers: 1

body:
There are times when you want a single ground point (*star* grounding), separate grounds with filters (separate analog and digital grounds, for instance), or you just don't care (99% of the time).

Regardless, this is usually a concern when you are laying out a circuit on a PCB. When you already have a PCB the grounds become a moot point because the PCB dictates how they operate.

For a module like an Arduino, unless otherwise stated, all grounds are equal and can be used for whatever whenever.


body:
I've written a simple sketch that adds threshold to an PIR sensor. If the PIR sensor sends 3 `HIGH` ex. `HIGH`...`LOW`...`HIGH`...`LOW`...`HIGH` (The `LOW` == no movement) it will trigger and alarm.

I want to reset the counter of `HIGH`s if there's no movement detected. The problem is the `loop` will get delayed if I put it inline. My code: (Don't mind my code, I'm pretty newbie)

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

    int calibrationTime = 30;
    int pirPin = 5;
    int ledPin = 6;
    int sensorState;
    int stateCount = 0; //How much movement is detected
    int stateThreshold = 3; //THRESHOLD
    bool isSensorHigh;

    void setup() {
      Serial.begin(9600);
      pinMode(pirPin, INPUT);
      pinMode(ledPin, OUTPUT);
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      digitalWrite(pirPin, LOW);
      Serial.print("calibrating sensor ");
      for (calibrationTime; calibrationTime > 0; calibrationTime--) {
        Serial.print(calibrationTime);
        delay(1000);
      }
      Serial.println(" done");
      Serial.println("SENSOR ACTIVE");
      delay(50);
    }
    void loop() {
      sensorState = digitalRead(pirPin);
      //Serial.println(sensorState);
      if (sensorState == 1) {
        isSensorHigh = true;
      }
      if (sensorState == 0 && isSensorHigh == true) {
        isSensorHigh = false;
        stateCount++;
      }
      //Set pins 2,3,4 here to LOW if there's no movement detected over time
      if (stateThreshold == 3) {
        switch (stateCount) {
          case 1:
            digitalWrite(2, HIGH);
            break;
          case 2:
            digitalWrite(3, HIGH);
            break;
          case 3:
            digitalWrite(4, HIGH);
            break;
        }
      }
      if (stateCount == stateThreshold) {
        blinkLeds();
        delay(3000);
        digitalWrite(2, LOW);
        digitalWrite(3, LOW);
        digitalWrite(4, LOW);
        digitalWrite(ledPin, LOW);
        stateCount = 0;
      }
      Serial.println(stateCount);
      delay(150);
    }

    void blinkLeds() {
      for (int x = 4; x > 0; x--) {
        digitalWrite(2, HIGH);
        digitalWrite(3, HIGH);
        digitalWrite(4, HIGH);
        delay(1000);
        digitalWrite(2, LOW);
        digitalWrite(3, LOW);
        digitalWrite(4, LOW);
        delay(1000);
      }
    }

title: Set pins to LOW over time

Answers: 1

body:
Use millis() instead on delay.
Ref: https://www.arduino.cc/en/reference/millis


body:
I'm having a problem with this Arduino code.

So whenever I press the "button" in port 11, which is supposed to either reset the burglar alarm or stop it, the whole program stops (the void loop() function stops). The wiring is most likely not the problem, because I've tested it on multiple occasions with different codes. The button, too, works perfectly well as a button with different codes.

In the Serial port, it keeps printing "78005", which it should before the button is pressed, until when I press the button, at which it randomly breaks off printing (resulting in 78, 780, 7, 7800, or 78005 as the last line printed).

Can anyone explain why the arduino will behave in this way?

Thank you so much.

    int button = 11;
    int receiver = 12;
    int buzzer = 13;
    int frequency = 1000; // frequency of buzzer

    bool keepAlerting = false; // toggles Alarm regardless of detected charge
    int receiverVal = LOW; // value from port 12
    int buttonVal = LOW; // value from button
    int oldButtonVal = LOW;

    int setupTime = 5000; // time the user has to close the box after toggling alarm

    bool alarmOn;
    int buttonMode = 0;
    const int resetButton = 1;
    const int stopButton = 2;
    int buttonModeDecider = 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(buzzer, OUTPUT);
      pinMode(receiver, INPUT);
      pinMode(button, INPUT);
      Serial.begin(9600);

      noTone(buzzer);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.print("7");
      receiverVal = digitalRead(receiver);
      buttonVal = digitalRead(button);
      Serial.print("8");

      if(alarmOn == true){
        Serial.print("6");
        setAlarm();
      }

      Serial.print(buttonVal);
      Serial.print(oldButtonVal);

      if(buttonVal == HIGH && oldButtonVal == LOW){
        buttonModeDecider = 1 - buttonModeDecider;
        Serial.print("Toggled");

        if(buttonModeDecider == 1){
          buttonMode = resetButton;
          Serial.print("1");
        } else {
          buttonMode = stopButton;
          Serial.print("2");
        }

        switch(buttonMode) {
          case resetButton:
          {
            delay(setupTime);
            alarmOn = true;
            break;
            Serial.print("3");
          }
          case stopButton:
          {
            alarmOn = false;
            Serial.print("4");
          }
        }
      }
      Serial.println("5");
      oldButtonVal = buttonVal;
    }

    void setAlarm() {
      if(receiverVal == LOW || keepAlerting == true) {
        tone(buzzer, frequency);
        keepAlerting = true;
      }
    }

title: Arduino stops loop randomly whenever a button is pressed

Answers: 2

body:
A 10 Ohm resistor when switched to ground can cause the power supply to drop below the operating voltage of the Arduino. If you mean to have a pulldown resistor to ground use a 10K value instead.

Note that a 10 Ohm resistor across a 5V supply draws 0.5 Amps of current.

body:
> Arduino stops loop randomly whenever a button is pressed

your button is shorting the supply?


body:
### TL;DR

With regards to the [USB host library][3]:

 - Which is the correct file to modify the Arduino pin used for the USB Host slave select (SS) line?

----

I would like to add USB host functionality, to a particular Arduino setup, whilst, also, being able to use an Ethernet/SD (or just SD) shield.

As both the Ethernet shield and USB Host shield use pin 10 to select the W5500 and MAX3421E respectively1, obviously I can not use a standard USB Host shield. However, I could employ one of the small form factor boards, such as the [USB Host Shield 2.0 Arduino UNO MEGA ADK Compatible Google Android ADK][1] which I found on eBay:

[![USB Host shield][2]][2]

As this board is not in the usual shield "shape", one would not be constrained by which pin to connected to which MAX3421E input/output, in particular the chip select (SS) input. So, one could use a pin (or pins) that is not reserved by the Ethernet shield.

*However*, it does not appear to be possible to simply specify the "select pin" (i.e. the Arduino pin connected to the SS line) when using the [USB Host shield library][3] (or any of the pins used by the library), in `setup()`.

Therefore, I wondered if it was possible to modify the library, so that the pin used to select the USB/MAX3421E could be changed, either by:

 - "Hardcoding" a *different* "select" pin number into a header file;
 - Adding an argument to the `Init()` method, or;
 - Adding a method to the `USB` class, such as `Usb.DefineSelect()`.

The latter two options, I could work through, given the time. However, as a quick and dirty hack, where would I hardcode in a change from pin 10 to a pin of my choosing? Does anyone know? Has anyone had to do this?

-----

### Nitty-gritty

I have had a look through the library to see where pin 10 is defined as the chip select, and [avrpins.h][4] looked like a possible candidate for modification, although it would be rather "rude" (for want of a better word) and probably mess up the other boards.

[usbhost.h][5] seems a much better proposition. Looking at usbhost.h, the [lines 88-91][6]:

    #if defined(__AVR_ATmega1280__) || (__AVR_ATmega2560__) || defined(__AVR_ATmega32U4__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
    typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;
    #elif  defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
    typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;

Looking at the statement

    typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;

the last argument appears to be the pin used for *select*. For the Uno (ATmega328P), in avrpins.h ([line 535][7]) `Pb2` is `P10` (pin 10), so I could substitute `Pb2` for some other pin definition, i.e. `Pd5` for `P5` (pin 5) ([line 529][8] in avrpins.h).

However, what I don't understand is that for the statement

    typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;

which deals with the Mega (ATmega2560), in avrpins.h ([line 512][9]) `Pb0`is `P53` (pin 53). As `Pb4` is actually `P10` (pin 10) ([line 466][10]), why is `Pb0` en lieu of `Pb4` used? That doesn't tie up with the fact that Pin 10 is used for both the Uno and Mega boards. It seems to suggest the pin 10 is used on the Uno and pin 53 is used on the Mega. Unless I have misinterpreted the `typedef`.

------

### Footnote

1 For the USB host shield, from [Arduino USB Host Shield][11]

> Arduino communicates with the MAX3421E using the SPI bus (through the
> ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno
> and pins 10, 50, 51, and 52 on the Mega. On both boards, pin 10 is
> used to select the MAX3421E. Pins 7, 8 and 9 are used for GPX, INT and
> RES pins.

The key piece of information here is that pin 10 is used by *both* the Uno and Mega boards.

For the Ethernet shield, from [Arduino Ethernet Shield V2][12]

> Arduino communicates with both the W5500 and SD card using the SPI bus
> (through the ICSP header). This is on digital pins 10, 11, 12, and 13
> on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10
> is used to select the W5500 and pin 4 for the SD card. These pins
> cannot be used for general I/O. On the Mega, the hardware SS pin, 53,
> is not used to select either the W5500 or the SD card, but it must be
> kept as an output or the SPI interface won't work.
>
> Note that because the W5500 and SD card share the SPI bus, only one at
> a time can be active. If you are using both peripherals in your
> program, this should be taken care of by the corresponding libraries.
> If you're not using one of the peripherals in your program, however,
> you'll need to explicitly deselect it. To do this with the SD card,
> set pin 4 as an output and write a high to it. For the W5500, set
> digital pin 10 as a high output.

Here, yet again, the key piece of information here is that pin 10 is used by *both* the Uno and Mega boards to select the Ethernet.

  [1]: http://www.ebay.co.uk/itm/182052269837
  [2]: https://i.stack.imgur.com/QVuZN.jpg
  [3]: https://github.com/felis/USB_Host_Shield_2.0
  [4]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/avrpins.h
  [5]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/usbhost.h
  [6]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/usbhost.h#L88
  [7]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/avrpins.h#L535
  [8]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/avrpins.h#L529
  [9]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/avrpins.h#L512
  [10]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/avrpins.h#L466
  [11]: https://www.arduino.cc/en/Main/ArduinoUSBHostShield
  [12]: https://www.arduino.cc/en/Main/ArduinoEthernetShield

title: Change select pin of USB Host library

Answers: 1

body:
In order to change the Arduino pin used to select the USB Host board, in order words, where the device's SS line is assigned to an Arduino pin (with the Arduino as the SPI Master and the USB host is the SPI slave), the line to change is at [line 43 in `UsbCore.h`](https://github.com/felis/USB_Host_Shield_2.0/blob/master/UsbCore.h#L43):

    typedef MAX3421e<P10, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x

So to use pin 5, for example, en lieu of pin 10, the line would become:

    typedef MAX3421e<P5, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x

The clue was in the comment on [line 27 in `UsbCore.h`](https://github.com/felis/USB_Host_Shield_2.0/blob/master/UsbCore.h#L27)

    /* shield pins. First parameter - SS pin, second parameter - INT pin */

With this suggested modification to the code, Pin 5 would go to the USB Host SS line and then there would be no conflict with the Ethernet board that uses Pin 10 for its SS line.

-------
This issue, I have subsequently discovered, is covered by the [USB Host Shield Hardware Manual][1], under the **Interface modifications** section. I guess I should have just read the manual first! RTFM...

-------
###Clarification of the issue

I must be honest that my question was somewhat confused. After having read the [SPI library][2], it states that

> **Note about Slave Select (SS) pin on AVR based boards**
>
> All AVR based boards have an SS pin that is useful when they act as a
> slave controlled by an external master. Since this library supports
> only master mode, this pin should be set always as OUTPUT otherwise
> the SPI interface could be put automatically into slave mode by
> hardware, rendering the library inoperative.
>
> It is, however, possible to use any pin as the Slave Select (SS) for
> the devices. For example, the Arduino Ethernet shield uses pin 4 to
> control the SPI connection to the on-board SD card, and pin 10 to
> control the connection to the Ethernet controller.

With respect to the first paragraph, the Uno uses pin 10 and Mega uses pin 53 as the Arduino SS line - so that must be set as an output in order for the Arduino to be the Master. Are realising this as being my source of confusion, it became apparent that the `typedef` statements, in `usbhost.h`, were _not_ where I should have been looking to change the device's Slave Select pin.

With respect to the second paragraph,  I want to use pin 5 (for example) to control the Slave Select (SS) for the USB Host device, instead of the default pin 10.

  [1]: https://www.circuitsathome.com/usb-host-shield-hardware-manual/
  [2]: https://www.arduino.cc/en/reference/SPI


body:
Is it possible to query the **pin-out** and each pin's attributes at *run-time* with Arduino?

If not, can it be done at compile-time?

Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?

I am looking for something like this:

    PinProperties props= getPinProperties(pinNumber);

    props.supportsDigitalInput();
    props.supportsDigitalOutput();
    props.supportsAnalogInput();
    props.supportsAnalogOutput();
    props.supportsPWM();
    props.analogInputBits();
    props.analogOutputBits();
    props.pullupResistance();
    props.pulldownResistance();

etc.

NOTE: [This question][1] is similar and I might use the board model to look up a pre-stored pin-out.

  [1]: https://electronics.stackexchange.com/questions/58386/how-can-i-detect-which-arduino-board-or-which-controller-in-software

title: How to detect pinout at run-time

Answers: 3

body:
There is no strong relation with pin numbering and the hardware as far as I know.

To be more specific, the datasheet tells you what registers can be used for what functions. The microcontroller does not neccesarily know what registers it has or what functionality it's registers have.

You could make your own library or class for a pin.

I would go by something like:

    Pin input1 = new Pin(.....);

    if(input1.isAnalog()){
       input1.setupAnalog();
    }

    if(input1.analogIsReady()){
       input1.readAnalog();
    }

Instead of having a "pinproperties" object for a pin.

You'll have to look how you want to make the class.
You can create one single class that has all functions and just checks if there is an implementation for that pin.

You may go by classes like:

    class pin

    class analogPin extends pin

    class pwmPin extends pin

However, this may fail if your analog pin doesn't support the regular "pin" functions (like I/O).

Theoretically you could use C++'s multiple inheritance to inherit things as I/O, PWM and Analog, but I've heard that it doesn't perform very well on embedded targets.

----------

Alternatively you could make a list of pins that support PWM. And a list of pins that support Analog. And a list of pins that support I/O.

When a person (runtime) tries to set a pin's state, you can check if that pin supports I/O, but I'm not sure what behaviour you'll expect if one tries to set a pin that doesn't support that option.

body:
> Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?

The libraries are designed so that you don't really need to know that. One issue is the relationship between the chip pins and the board pins. Just as an example, pin 19 on the Atmega328P goes to the *board* pin 13 (digital pin 13) on a Uno.

If your program needs a couple of digital inputs and a couple of digital outputs, you could use (say) D2 and D3 as inputs and D4 and D5 as outputs. Then let the underlying libraries work out which chip pin that is, and configure it correctly when you use `digitalRead`, `digitalWrite` and `pinMode`.

You can self-query for the chip type (for example [here](https://www.gammon.com.au/forum/?id=11633&reply=2#reply2)) however that doesn't tell you what board the chip is mounted on.

---

> to avoid completely rewriting my program for each possible Arduino model

What are you envisaging that would require a *complete rewrite*? Many libraries and projects are written to work on multiple boards with only minor changes (if any). You can detect the processor type at compile-time.

I simply don't see where "complete rewrite" comes into it. Use functions to abstract out the parts that interface with pins (as `digitalRead`, `digitalWrite` and `pinMode` **already do**) and a few constants at the start of the code to indicate which pins you have chosen for this particular board.

body:
pins_arduino.h has some standard macros that can be used for some of what you're looking to do. Using the `arduino:standard` variant used by Uno for example:

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L35:

    #define digitalPinHasPWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11)

Or if you want to use your naming scheme:

    #define supportsPWM(p) digitalPinHasPWM(p)

After that it gets a bit more sketchy:

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L28

    #define NUM_DIGITAL_PINS 20

So, assuming that Arduino digital pins will always be numbered consecutively from 0 and any pin that supports digital input also supports digital output(which is the case in any variant I'm familiar with), you could use that to write some macros:

    #define supportsDigitalInput(p) ((p) < NUM_DIGITAL_PINS)
    #define supportsDigitalOutput(p) supportsDigitalInput(p)

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L29

    #define NUM_ANALOG_INPUTS 6

Could be used to write this macro(with numbering assumption):

    #define supportsAnalogInput(p) ((p) < NUM_ANALOG_INPUTS)

Note that this will not work for the `An` analog pin names(e.g. `A0` vs `0`).

As for:

    props.supportsAnalogOutput();
    props.analogInputBits();
    props.analogOutputBits();
    props.pullupResistance();
    props.pulldownResistance();

I'm don't know of pre-existing code for those. There is probably a way to get it for the first three in an architecture specific manner. The last two you'd most likely need to get the information from datasheets for all of your target microcontrollers and define then using processor specific macros.


body:
I have two polystyrene balls wrapped in copper tape. When the balls touch, the tape completes a circuit from a digital pin on an Arduino inside one of the balls to an Arduino inside the other (both powered by 9v batteries). This allows them to send information to each other via the copper tape path.

I was testing the balls out, and they were working too well. Even when the balls weren't quite touching, the signal was getting through! Turns out that's because the signals were travelling via my body. Even if I held one ball in one hand and the other ball in the other hand, digital reads on one Arduino were correctly reading the digital writes from the other.

This is actually great for my project!... unless it's not safe. So I'm looking for two things:

1. A reliable reference on what is and isn't safe in terms of voltage/wattage/amperage travelling from hand to hand.

2. A second opinion on the voltage/wattage/amperage that two Arduinos will actually pump through me (from digital pin to digital pin).

title: How safe is it to use my body as part of a circuit?

Answers: 2

body:
If you are talking about running at 5V, then I doubt there is any safety issue. After all, 9V batteries (the sort you put in your smoke detector) just have bare terminals and no-one tells you not to touch them.

There is quite a bit of related information at [How much voltage is “dangerous”?](https://electronics.stackexchange.com/questions/19103/how-much-voltage-is-dangerous). That link seems to have enough information that there isn't a lot of point of repeating it all here.

There is a reference on that page to someone holding a metal pole connected to a 12V battery wading through water which completed the circuit and he was unable to let go of the pole. But that is **12V** (more than twice 5V) and in circumstances where there was good conduction (his body was wet).

---

In the interests of science I set up a small test. I connected myself to a 5V lab supply via an ammeter. I grasped the terminals firmly (with dry hands) and measured about 3 µA of current. From the page I referenced above there seems to be a consensus that 1 mA would be just noticeable, so this is about 300 times less.

I found if I wet my fingers I got up to about 20 µA of current, still a lot less than 1 mA.

That page mentions that 60V is getting into the range where you might get a shock.

---

Hopefully it goes without saying that if you are going to touch metal balls then you need to be certain that 5V is the maximum, and that some sort of failure in a power supply might not deliver a lot more. But if the balls are battery powered you should be pretty safe.

---

You've added that they are powered by 9V batteries. That doesn't change my answer much. The most that could "escape" due to some malfunction is then 9V. Under normal operation you would have 5V from a digital output pin.

I measured my body resistance as being around 1.5 MΩ, which is consistent with getting 3 µA of current through it.

    I = V / R
    I = 5 / 1500000 = 0.000003 A

body:
In fact the voltage is almost irrelevant. The current is the issue. 30mA is normally considered the limit - this is the value [RCD](https://en.wikipedia.org/wiki/Residual-current_device) are set to trigger at.

Even low voltages applied to intimate places can be fatal. (I have a couple of wires in my heart, these can certainly cause a significant impact).

There is little risk with the low energy available, but if you want to be safe you can use a series resistor. I have (a very early) touch sensor installed on lights in my house. The touch pad is effectively connected to 240V, but is quite safe as the pad is connected through 2 10MΩ resistors. (2 are needed as they are rated at 500V.)


body:
I am having a logical error that I can not figure out with the communication. I am communicating fine with the two boards such that I can send and receive data. Code to my [Transmitter and Receiver][1]. Serial outputs [here][2]. Using library from this site: (Sorry reputation too low to add another link)

*www.instructables.com/ORIG/FV6/0AAE/IBXM5ZIY/FV60AAEIBXM5ZIY.zip*

(**WARNING**: will download with out permission if you visit link above. Use below link if dont want to download)

*www.instructables.com/id/Wireless-Remote-Using-24-Ghz-NRF24L01-Simple-Tutor/?ALLSTEPS*

(Scroll down to step 4, library's are labeled as "library files.zip". Names inside the zip folder are "nRF24L01" and "RF24")

From the Serial outputs I do not understand why on my transmitter it says it sent the time in milliseconds, 5873, but on my receiver output it says it received 241. Also I do not understand how the millis() function on the receiver returned a lesser value than what the transmitter should have sent.

I have novice understanding of c++ and the nRF24L01 radio at best. Any information is appreciated.

Thank you in advance!

  [1]: http://pastebin.com/P6W9UTFN
  [2]: http://pastebin.com/KEENesNq

title: Communication between 2 nRF24l01s and 2 Arduino unos

Answers: 0


body:
I'm using arduino several month now, And i don't understand when i can use the arduino object of String. I'll explain, I read a lot and the it's look like that this object is a good way to read/write and use strings, But everywhere they say that this object take a lot of RAM. So i made some project, And almost in all of them the String object not work as i expected. When i check the RAM in my projects i see that when my usage of RAM is greater then 65% the string object start to do problems. Because of this i stop use the string object and use only char arrays.

So my question is:

 - How can i know when i can use String from the beginning?
 - there is a way to change from char array to string or vase versa easily (i know this is completely different logic)?
 - How can i avoid the memory problems with the String object?

All this questions come from that the String object is very effective and easy to use and i want to use it, But i'm fear from RAM problems so i'm not using it.

Thank you very much for reading all this, Hope you can help me!

title: String use in arduino IDE (this question for understanding)

Answers: 1

body:
String objects are simple to use. There is a trade-off for simplicity. Strings work by using dynamic memory allocation. Something like this for example:

    String foo;
    ...
    foo += 'a';

By adding one character to a string the class has to allocate new memory for the slightly longer string. If you keep doing this you get memory fragmentation.

You are probably better off deciding what your maximum size string is and making that a static array of characters.

---

### So should I use the String objects?

For occasional use they are fine (for example, holding the name of something). They tend to fall down once you start with a small String and keep adding to it, because the code has to dynamically allocate memory, allocating (say) 5 bytes, then 6 bytes, then 7 bytes, and in the process freeing up the original 5 bytes, then 6 bytes and so on. This allocating/freeing process can leave holes in the "heap" causing a thing known as memory fragmentation.

Done to excess you can run out of memory. That is, you might need 100 bytes but have 10 lots of 10 bytes free, with stuff in-between that isn't free.

You don't have lots of memory to start with, so it is probably better, faster and more efficient to decide the largest amount you need for some string, and just make that a character array.


body: I was surprised when I couldn't find an old post where someone asked this question. Seems like a natural beginner, uh excuse me, "newbie" question, but then I'm a throw-back to the days when a home computer came with 3,583 bytes (three-thousand, five-hundred eighty-three). So again, as seen in the title, can I "list" my sketch? I'm pretty sure the answer is NO since if it were a good question someone would have asked it already. It just strikes me as odd that my old VIC-20 could do something this phenomenal techno-marvel can't. Not much of an accomplishment for the dinosaurs, but HEY! We're on the scoreboard now! [nothing's worse than that miserable goose-egg :(   ]

title: Is there a way to "list" (in BASIC, or "cat" in LINUX) the current sketch loaded in my xxxDUINO?

Answers: 1

body:
No. the code burned in an Arduino is compiled not interpreted like Basic.

Basically your C language sketch is compiled into AVR assembly language. The resulting hexadecimal is what is burned to the Arduino.

Yes you could disassemble the hex like we used to do in the good old days, but as before it is highly unpredictable and most of the time not very useful.

Just a quick example. The following simple Arduino sketch that just sets a pin in output and then sets it HIGH:

    void setup() {
      pinMode(13, OUTPUT);
      digitalWrite(13, HIGH);
    }

    void loop() {
    }

The resulting hex file is 3.5Kb.This include various sections of data and code. One would have to analyse the section, convert the hex (op-code) to assembly language and find which part correspond to the C code.

It is possible, and there are probably tools that do a fairly good job. Would the C language generated by the decompilation once recompile perform exactly like the original compiled cole. I doubt it.


body:
I need to program a ATMega328P on a breadboard, running on an external crystal at 8 MHz.

All of the guides I can find either use the arduino environment and describe a 16 MHz config, or using the 8 MHz internal oscillator - which is too inaccurate for this project.

How do I do this?  Configure the chip to run at 8 MHz and upload the program?

title: How to burn bootloader/program an ATMega 328P with an external crystal 8 MHz oscilator?

Answers: 1

body:
myself as of 3 hours ago.

 1. Get an arduino or similar, install the ArduinoISP sketch
 2. Connect the two as described [here][1].
 3. Change the board to Arduino Pro or Pro Mini, Processor to 3.3V, 8Mhz, Programmer: Arduino as ISP
 4. Hit burn bootloader button
 5. Load up the sketch that you want on the device
 6. Without changing anything, use "Upload using programmer"
 7. Remove arduino, fix wiring changes required to use as programmer

Committed to Electronics Stackexchange  for posterity.  Or so I can find it when I forget next time...

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard


body: I'm doing my project on haptic feedback systems. I need a 56bits of data transmitted over wirelessly to a computer to process and send the output to another arduino. I tried ESP8266 using TCP/IP protocol. But it is very slow. Are there any faster modules to do the above task with 100hz speed?

title: Wireless Sensor communication with 100Hz rate

Answers: 1

body:
Make one static tcp connection with a regular check and on error event to restore it in case it drops. Tcp must be able to run data at your rate.
If not, maybe the main arduino loop has delays in it.


body:
I'm using the most recent Arduino IDE to upload a sketch to an Arduino Uno, and the upload seems to succeed, but the final verification step fails with the error:

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f
    avrdude: reading input file ".build_ano/uno/firmware.hex"
    avrdude: writing flash (30908 bytes):

    Writing | ################################################## | 100% 5.01s

    avrdude: 30908 bytes of flash written
    avrdude: verifying flash memory against .build_ano/uno/firmware.hex:
    avrdude: load data flash data from input file .build_ano/uno/firmware.hex:
    avrdude: input file .build_ano/uno/firmware.hex contains 30908 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 3.96s

    avrdude: verifying ...
    avrdude: verification error, first mismatch at byte 0x7800
             0xff != 0xfe
    avrdude: verification error; content mismatch

    avrdude: safemode: Fuses OK (H:00, E:00, L:00)

    avrdude done.  Thank you.

I've re-ran the upload several times, and tried different USB cables, but I get the exact same verification error each time. Does this mean the upload effectively failed (presumably because the flash memory has gone bad), and that my sketch is not running on the Arduino? Is there any way I can fix this?

I tried uploading to a different Arduino Uno, and I received the exact same error.

title: Avrdude fails to verify after upload

Answers: 1

body:
So here is my official answer ;-)

Your sketch goes above the 30k flash available on the Arduino Uno.

Yes the Uno has 32k of flash, but 2k is used for the Arduino bootloader. if you convert 0x7800 in decimal that gives you 30720 which is exactly 30k. And your sketch is 30908 bytes so it's 188 bytes too long.

Try optimizing it.

A second alternative would be to use the Optiboot bootloader replacement (https://github.com/Optiboot/optiboot) which only uses 512 bytes.


body: Are the analog I/O pins on the Arduino still available for sensors when there is an Adafruit Music Maker shield attached to it? I want to play a sound file, but only when a PIR sensor senses motion.

title: Is it possible to have an Adafruit music maker shield and a sensor connected to the same Arduino?

Answers: 1

body:
If you look at the PCB of the Adafruit Music Maker here:

https://learn.adafruit.com/assets/16643

You can see that there are no connections on the analog I/O of the Arduino.


body:
I am using a Python3 GUI on my RPi3 to control my DFRobot Bluno Mega 2560 via USB.  The Mega is hooked up to a breadboard with 4 LED's and I am trying to control each LED with their own toggle switch.  I was able to do this with one LED but for some reason when I try to achieve the same with more than one it doesn't work, I get absolutely no response from the LED's whatsoever.  It is something to do with how the arduino is receiving the ASCII code, or I think it may be a problem with how I am implementing tkinter as I have little experience with it.  If anyone can tell me what I am doing wrong please let me know.

Here is the Python3 GUI code:

    import serial # import the serial library
    import time # import the time library
    from tkinter import * #import Tkinter GUI library

    def toggleRed():
        if redBtn.config('relief')[-1] == 'sunken':
            redBtn.config(relief="raised")
            arduino.write('a'.encode())
        else:
            redBtn.config(relief="sunken")
            arduino.write('b'.encode())

    def toggleGreen():
        if greenBtn.config('relief')[-1] == 'sunken':
            greenBtn.config(relief="raised")
            arduino.write('c'.encode())
        else:
            greenBtn.config(relief="sunken")
            arduino.write('d'.encode())

    def toggleBlue():
        if blueBtn.config('relief')[-1] == 'sunken':
            blueBtn.config(relief="raised")
            arduino.write('e'.encode())
        else:
            blueBtn.config(relief="sunken")
            arduino.write('f'.encode())

    def toggleYellow():
        if yellowBtn.config('relief')[-1] == 'sunken':
            yellowBtn.config(relief="raised")
            arduino.write('g'.encode())
        else:
            yellowBtn.config(relief="sunken")
            arduino.write('h'.encode())

    print ('Connecting...')
    arduino = serial.Serial("/dev/ttyACM0", 9600)
    time.sleep(3)
    print ('Connection established successfully')

    appWindow = Tk() # creates the application window (you can use any name)
    appWindow.wm_title("RGB LED Control") # displays title at the top left
    appWindow.config(bg ="#037481")

    mainFrame = Frame(appWindow, bg="#037481") #define the main frame of the GUI
    mainFrame.grid() #grid the frame into the App Window

    btnFrame = Frame(mainFrame, bg="#037481") #define the frame within the main frame that holds buttons
    btnFrame.grid() #grid the frame into the main frame

    redBtn = Button(btnFrame, text="RED", width=12, bg="red", relief="raised", command=toggleRed)
    redBtn.grid(column=0,row=0,sticky='EW')

    greenBtn = Button(btnFrame, text="GREEN", width=12, bg="green", relief="raised", command=toggleGreen)
    greenBtn.grid(column=0,row=1,sticky='EW')

    blueBtn = Button(btnFrame, text="BLUE", width=12, bg="blue", relief="raised", command=toggleBlue)
    blueBtn.grid(column=0,row=2,sticky='EW')

    yellowBtn = Button(btnFrame, text="YELLOW", width=12, bg="yellow", relief="raised", command=toggleYellow)
    yellowBtn.grid(column=0,row=3,sticky='EW')

    appWindow.mainloop()# begins main loop

Here is the arduino code:

    int ledRed = 13;
    int ledGreen = 11;
    int ledBlue = 9;
    int ledYellow = 7;

    //int ledRedStatus;
    //int ledGreenStatus;
    //int ledBlueStatus;
    //int ledYellowStatus;

    void setup() {
      pinMode(ledRed, OUTPUT);
      pinMode(ledGreen, OUTPUT);
      pinMode(ledBlue, OUTPUT);
      pinMode(ledYellow, OUTPUT);
      Serial.begin(9600);
    }
    void loop() {
      if(Serial.available() == '97') {
        digitalWrite(ledRed, LOW);
      }
      if(Serial.available() == '98') {
        digitalWrite(ledRed, HIGH);
      }
      if(Serial.available() == '99') {
        digitalWrite(ledGreen, LOW);
      }
      if(Serial.available() == '100') {
        digitalWrite(ledGreen, HIGH);
      }
      if(Serial.available() == '101') {
        digitalWrite(ledBlue, LOW);
      }
      if(Serial.available() == '102') {
        digitalWrite(ledBlue, HIGH);
      }
      if(Serial.available() == '103') {
        digitalWrite(ledYellow, LOW);
      }
      if(Serial.available() == '104') {
        digitalWrite(ledYellow, HIGH);
      }
    }

title: Multi-LED Toggle Switch

Answers: 2

body:
Adding comments to your code would help us understand your intentions.

It is assumed you are sending the ASCII values for 'a', 'b', 'c', ... for different buttons and their actions.  And that you want to receive these on an Arduino over the USB using the USB serial port protocol. It is also assumed that your Python script works and the Linux OS is creating a /dev/ttyACM0 or some such serial device when you plug in your Arduino.

Looking at your Arduino code we see you are only checking for the number of bytes in the Arduino's serial port receive buffer by using the [Serial.available()][1] method call.  If your intentions were to read a byte of data you would instead call the [serial.read()][2] method.

It is suggested that you check if there is any data available and if there is you would read it once and save it to a variable. Then you can check this variable many times and decide what action to take based on its value.  If you read the buffer many times you would be pulling a new byte of data from the buffer with each read.  If you run out of data to read you will be supplied with the value of -1 as an indication there is no more data.

  [1]: https://cdn.arduino.cc/reference/en/language/functions/communication/serial/available/
  [2]: https://www.arduino.cc/en/Serial/Read

body:
      if(Serial.available() == '97')

Make sure the comparison is actually valid and Serial.available() does what you think it does. If you wish to read a value from serial port, .available() doesn't seem to be the right function for that.


body:
We are trying to reprogram a remote control car with an Arduino Uno. This car runs the power with a DC motor, and it controls steering using a stepper motor.

We have the Motor Shield R3 attached to the Arduino, but it has just now occurred to us that we can't support both motors with the motor shield (as the motor shield only allows for two DC motors or one stepper motor). Is there a way to somehow work around this? Or is it possible that we would need to replace the stepper motor with DC?

title: Using both a stepper motor and a DC motor with Arduino motor shield R3

Answers: 1

body:
You are right: Motor Shield R3 can drive two DC motors or one step motor.
 So, there are 2 (maybe  3) solutions:

1. Have another shield - now you can drive 2 step motors, or one DC motor(using 'half' of shield, and one step motor using another whole shield.

2. Replace your step motors with DC motor. This option can be more complicated, as no precise position control will be possible when you try to use DC motor for steering. (DC motor are hard to select and hold position, when stepper motors are quite easy to 'go to certain position' AND 'hold'). There is also good mechanical skill needed to remove/place it precisely.

optional option 3. Instead of Motor Shield R3 you can try to use cheap Easy Driver to drive your step motor.