message:
Combining code for multiple sensors in one program

I need to operate 2 different sensors (gas and temp) simultaneously.
I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together. My background in coding is basic and I'm not the one who wrote these codes.

Here are the sketches:

Thermistor code:

    void setup() {
      //This function gets called when the Arduino starts
      Serial.begin(9600);
      //This code sets up the Serial port at 9600 baud rate
    }

    void loop() {
      //This function loops while the arduino is powered
      int val; //Create an integer variable
      val=analogRead(0);
      //Read the analog port 0 and store the value in val
      Serial.println(val);
      //Print the value to the serial port
      delay(1000);
      //Wait one second before we do it again
    }

This is the gas detector code:

    /* GAS Sensor MQ-2
    This sensor detects flammable gasses
    the board has four pins
    connect AO to Arduino pin A0
    connect DO to Arduino pin 2
    connect Gnd to Arduino Gnd
    connect Vcc to Arduino 5 volts
    */

    int sensorPin = A0;
    // select the input pin for the potentiometer
    int DOPin = 2;
    // select the pin for the LED
    int sensorValue = 0;
    // variable to store the value coming from the sensor
    int ledPin =13;

    void setup() {
      // declare the ledPin as an OUTPUT:
      pinMode(DOPin, INPUT);
      pinMode(ledPin, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      // read the value from the sensor:
      sensorValue = analogRead(sensorPin);
      Serial.print("Analog Output = ");
      Serial.println(sensorValue);
      // turn the ledPin on if triggered
      if (digitalRead(DOPin) ==HIGH) {
        digitalWrite(ledPin, LOW);
        Serial.println("Digital Output = OFF");
      } else {
        digitalWrite(ledPin, HIGH);
        Serial.println("Digital Output = ON");
      }
      delay(1000);
    }

body:
You just need to assign the sensors different pins.

    /* GAS Sensor MQ-2
    This sensor detects flammable gasses
    the board has four pins
    connect AO to Arduino pin A0
    connect DO to Arduino pin 2
    connect Gnd to Arduino Gnd
    connect Vcc to Arduino 5 volts
    */

    int gasSensorPin= A0; // GAS sensor pin
    int DOpin= 2; // select the pin for the LED
    int gasSensorValue= 0; // variable to store the value coming from the sensor
    int ledPin = 13;

    int tempSensorPin = A1;  //Temperature sensor pin
    int tempSensorValue;

    void setup() {
     // declare the ledPin as an OUTPUT:
     pinMode(DOPin, INPUT);
     pinMode(ledPin, OUTPUT);
     Serial.begin(9600);
     }

    void loop() {
     // read the value from the sensor:
     gasSensorValue= analogRead(gasSensorPin);
     Serial.print("Analog Output = ");
     Serial.println(gasSensorValue);
     // turn the ledPin on if triggered
     //
     if (digitalRead(DOpin) == HIGH){
     digitalWrite(ledPin, LOW);
     Serial.println("Digital Output = OFF");
     }
       else {
         digitalWrite(ledPin, HIGH);
         Serial.println("Digital Output = ON");
      }

    Serial.print("Temperture: ");
    tempSensorValue = analogRead(tempSensorPin));
    Serial.println(tempSensorPin);  //Print the value of pin A4

    delay(1000);
    }

This is your combined sketch.


sender: user

message:
Difference between data type int and long on Arduino

I was learning to program for a *void obstacle robot* but when I looked at the code I saw two data types long and int.

Int are datatypes that holds  -2,147,483,648 to 2,147,483,647.
Long are also datatypes that holds -2,147,483,648 to 2,147,483,647.

Int and long are like same but I came up with the code where two types of datatype is used as seen below:

    int trigPin = 2;
    int echoPin = 4;
    long duration, cm, inches;

But how can you know when to use which datatype? I searched a lot in the web but I didn't understand so can someone explain this to me please.

sender: assistant

body: `int` in AVR GCC is **16** bits, *not* 32.


body:
On the Arduino (AVR models) an `int` is 16 bits, not 32 bits. Thus it goes from -32768 to +32767.

That is **different** from `long` which is 32 bits.


body:
According to the C language specification, `int` must be at least 16 bits or longer and `long` must be at least 32 bits or longer.

It is OK for a compiler to implement `int` as 32 bits or even 64 bits. It is OK for a compiler to implement `long` as 64 bits or longer. But it is not allowed for a compiler to implement `long` as 16 bits.

So when to use which type?

If the values you will be working with can be represented within 16 bits then it's OK to use `int`. If you need more than 16 bits use `long`. If you need more than 32 bits use `long long`.

Do not be caught up with compiler and/or CPU specifics. As mentioned by others, even within the same product range, Arduinos, there are 16 and 32 bit CPUs available. Instead, only trust what the standard guarantees.

The full specification of types in C are:

- `char` must be at least 8 bits
- `int` must be at least 16 bits
- `long` must be at least 32 bits
- `long long` must be at least 64 bits

Note: It is perfectly legal for compilers to implement char, int, long and long long as 64 bits. This is in fact not uncommon among DSPs.


body:
I like to use types from `stdint.h`.

While they do have minor drawbacks, the benefit they provide is you know exactly the size your are handling, even when compiling on other architectures.

    #include <stdint.h>

    uint8_t  my_byte = 0xf0;
    int16_t  trig_pin = 2;
    int16_t  echo_pin = 4;
    uint32_t duration, cm , blah;
    uint64_t big_int;

    // etc.

But obviously you don't want to be moving around a bunch of int32_t when your data only needs int16_t.


body:
It's the same reasoning as in C: the size of the `int` type is expected to be *the natural word size that your system handles most efficiently*. It must also be at least 16 bits wide, no smaller than a `short`, and no larger than a `long`.

So an `int` may be 16-, 32-, or 64-bits, based on the whatever your system handles best, and so is most likely to be 16 bits wide on an 8- or 16-bit CPU, 32 on a 32-bit CPU etc.

I use `int` when I want the best performance, whilst taking care to guard when I need more range than offered by 16 bits. These days, you tend to know when you are writing application code for 16-bit systems, although that's not so true for "library" code where portability may be of greater concern.

In your example, assuming the author had chosen their types carefully, the `int` variables probably require a small range and could afford to be word-size, leading to potentially shorter or faster code (or both). The `long` ones presumably required more than 16-bit range (they are guaranteed to be at least 32 bits wide). On the processor you'd selected as a compilation target, it looks like `int` and `long` were both implemented as 32-bit; this would be different (or *should* be) if you selected a 16-bit target CPU.


body:
if you are using Esp32 boards in Arduino IDE:
[![enter image description here][1]][1]

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


message:
"tamper" circuit of a reed switch: can I connect the two wires to an INPUT and an OUTPUT pin?

While working for the automation side of my new house, I'm currently in the process of installing several reed switches on top of external doors and windows.

Even if this could be used as a "security" infrastructure, I'm more interested, at the moment, at the "automation" side (*checking the status of door and windows without the need to physically watch them*) and as such, I'm going to extend the arduino-based infrastructure I've already planned and prototyped [*more details [here][1]*].

This is the reed-switch I've installed (1€ coin added for size reference):

[![reed switch photo][2]][2]

and this is the related circuits:

[![reed switch circuits][3]][3]

As you can see, it comes with two circuits: one related to the "switch" funcionality; another one as a safety-measure to catch some "cuts" along the wires.

To check its status, currently, I've configured:

 - "contact circuit":
   - one end to an Arduino GROUND_PIN;
   - the other end to Digital PIN 52 (REED1_SW_Pin);

 - "tamper circuit":
   - one end to an Arduino GROUND_PIN (same GND pin as above);
   - the other end to Digital PIN 50 (REED1_AT_Pin);

 - Arduino setup:
   - `pinMode(REED1_SW_Pin, INPUT_PULLUP)`
   - `pinMode(REED1_AT_Pin, INPUT_PULLUP)`

 - Arduino code:
   - the main code-block handling REED events is reported below

Even tough everything is working fine, I wonder if there are better approaches, expecially inchecking the status of door and windows without the need to physically watch them terms of POWER-CONSUMPTION. So, here are my questions:

 1. **TAMPER-Circuit**: due to its nature, it will always be a "closed" circuit, with current flowing inside, from REED1_AT_Pin to GND. Currently I'm checking its state every 1 second (`#define REED_AT_CHECKDELAY   1000`) but a frequency of once every 5 seconds, or even 10 seconds would be acceptable (for me). So I would like to have the current flowing _ONLY_ during the "checking-timeframe". Something like:
      - every 5 seconds...
      - power-up something, getting the current flowing along the circuit;
      - check if the current flows;
      - if yes => OK
      - if no => set/keep the ALARM state
      - power-down the "something"

Is it feasible? If yes, how? Also: is it worth the effort?

2. **REED-switch circuit**: same as above. Polling approach is still acceptable (for me) but frequency need to be relatively high (5 seconds max), in order to keep of sort of "near-real-time feedback" when opening/closing windows. Best would be 2 secs polling-interval.
With such a timing, does the polling-approach make sense?

3. from an "electronic" point of view, what is the "to-be-preferred-scenario" for the Arduino board:
    - having a small, fixed, steady current, flowing out from a PIN, for _YEARS_ on a 24/7/365 basis or...
    - having a continuosly transition from LOW->HIGH->LOW for a Digital PIN, say once every 5 seconds, again, for YEARS?

Every comment, sidenotes, hints, critics, whatever... is **REALLY** welcomed/appreciated.

----------

## Arduino code-block handling REED events ##

BTW: the full-code, where the REED switch is handled togheter with pushbuttons and relays, [it's available on GitHub][4]
<pre>
    [...]
    if (reed_sw1_state != reed_sw1_previous_state) {
        // a change occurred. Are we in a "boucing" window?
        if (millis() - last_reed_sw1_debounce > REED_DEBOUNCE) {
          // no. So it's a real change
          // Let's handle the event...
          Serial.print(millis());
          Serial.print("[REED] - SW1 state CHANGED from [");
          Serial.print(reed_sw1_previous_state);
          Serial.print("] to [");
          Serial.print(reed_sw1_state);
          Serial.println("]");
          reed_sw1_previous_state = reed_sw1_state;
          last_reed_sw1_debounce = millis();
        } else {
          // yes. Let's ignore it
        }
      }

      // Let's check REED Switches anti-tamper state
      if (millis()-reed_at1_lastcheck > REED_AT_CHECKDELAY) {
         reed_at1_state = ! digitalRead(REED1_AT_Pin);
         if (reed_at1_state == HIGH ) {
            Serial.print(millis());
            Serial.print("[REED] - AT1 state OK [");
            Serial.print(reed_at1_state);
            Serial.println("]");
         } else {
            Serial.print(millis());
            Serial.print("[REED] - AT1 state ALARM - OnGoing TAMPER!!! [");
            Serial.print(reed_at1_state);
            Serial.println("]");
         }
         reed_at1_lastcheck = millis();
      }
      [...]
</pre>

  [1]: https://arduino.stackexchange.com/questions/15834/how-to-interconnect-multiple-arduinos-with-a-rpi-to-control-home-lights-switches
  [2]: https://i.stack.imgur.com/hFchU.png
  [3]: https://i.stack.imgur.com/Gq0GH.png
  [4]: https://github.com/verzulli/arduino-smart-home/tree/master/TEST_NETWORKED_BUTTON_WITH_REED

body:
>  So I would like to have the current flowing ONLY during the "checking-timeframe".

Turn off the pull-up until just before checking. Allow a few milliseconds for the pull-up to raise the voltage.

> With such a timing, does the polling-approach make sense?

Certainly, if you are trying to save battery power.

---

Bear in mind the voltage drops over long cable runs (and also possibly induced spikes). You might want a more powerful pull-up (eg. 10k) rather than the inbuilt 50k. You can still organize that by having an output pin turn on the voltage to the pull-up. Or, have the pull-up wired in permanently but instead of running the other side to ground, set the "ground" wire to `OUTPUT` and write `LOW` to it - and then set it to `INPUT` when you want it to be inactive.

See my post about [Power saving](http://www.gammon.com.au/power) - you could use a watchdog timer to wake the device at (say) every 4 seconds, to check things.

You may want to add in input-circuit protection (eg. a couple of diodes) to dampen down any incoming spikes. Even something simple like this:

[![Input protection][1]][1]

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


message:
Detaching interrupts

I am using the following code to enable an interrupt for a pin:

    *digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
    PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
    PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the group

But I can't disable it. I am trying with this code:

    if (*digitalPinToPCMSK(pin) == 0)
    *digitalPinToPCICR(pin) &= ~(1<<digitalPinToPCICRbit(pin));

but it isn't working.

body:
Don't you mean:

      PCICR  &= ~bit (digitalPinToPCICRbit(pin));


message:
How can I get my Arduino to recognize a specific object using some kind of sensor?

This is my first question on this site, and I'm relatively new with Arduino. I do have some experience using the board to reprogram a robot that used infrared proximity sensors, servos, and switches.

I would like to add a sensor on to the robot that will allow him to recognize specific "obstacles" that I will put in his environment (not walls!) For instance, when he sees a red card, he needs to spin, but when he sees a green card, he needs to roll in the opposite direction. I do not want to spend much on the cards, but I would be willing to put a small battery and LED in them if I had to. The cards do not necessarily need to be colored, I was just using that as an example.

The robot will be in a well-lit room with noise in the background. He will be controlled by an Arduino Uno, an infrared sensor and a remote control. He can be pretty close to the cards if he has to (3 centimeters or so would be enough). It would be ideal if he could discern different types of cards, but that is not necessary as long as he's able to tell a card from the rest of his environment.

I am simply not sure how to go about implementing this. I have read about using photoresistors to differentiate color, and they're really cheap, but will they be accurate enough from a distance? This is the light sensor I was considering using:

http://www.mouser.com/ProductDetail/Adafruit/161/?qs=GURawfaeGuDpQ5XPTNqKUw==&gclid=Cj0KEQiA6IC2BRDcjPrjm_istoUBEiQASrLz1rQNwZgntUcccnOmrFph-pCbu60R00GNozB_XbZxYz0aAn0j8P8HAQ

I'm willing to pay about 5$ for one if I need to.

If I use the light sensor method, can I just use brightly colored cards or will I need to use LEDs? Is there a better way to accomplish my goal that you are aware of?

Thank you for your time. If there is missing information in my question, please tell me and I will add it.

body:
If you are controlling your robot with a remote control, why do you need it to detect cards, instead you can tell it to do whatever you want right?

If you want to detect specific objects according to their colors, arduino is not a platform i will choose, because it doesn't have processing power to do image processing.

But take a look at this, http://charmedlabs.com/default/pixy-cmucam5/ it can talk to arduino, and you can train it by telling it identify colored objects which i might think is apt for your case.
RFID tags will be a good idea as @Majenko said.


body:
Detecting colour with RGB illumination and an LDR is not particularly accurate in my experience.  The idea is you illuminate the card (or whatever) with red light, take an LDR reading, then with green then blue.

This gives you a set of 3 light levels for the different colour components of the object.  Combining them together gives you an RGB signature for the object.  Ideally, on say a red card, the value from the LDR under red illumination is much stronger, and blue & green much weaker.

RGB LED + LDR colour detection *does work*, but it's not accurate, and it helps to block out ambient lighting.  Maybe if you put a lot of time into calibration, it would for you.  I had a classroom of 14 kids, each made-up one of these circuits, yet only a couple had any moderate success, if at all.
That said, we were using very cheap RGB LEDs and similar quality LDRs.

There's a bunch of stuff you can do to help the accuracy, like subtract readings with only ambient illumination, take multiple readings, etc.

I think you would save yourself a lot of time and frustration buy using a purpose-made colour sensor.

Something like the ADAFruit Colour Sensor -  https://www.adafruit.com/products/1334


body:
You can get an RFID reader for $7 from eBay:

[![RFID reader][1]][1]

Cards are around 30 cents:

[![RFID card][2]][2]

I have example code for an [entry control system](http://www.gammon.com.au/forum/?id=12869) which uses that reader.

The cards tend to activate at around 3 cm to 5 cm, so that sounds about right. Of course they aren't particularly directional, but if you are driving in a certain direction and it detects a card it is probably in front of you (however possibly off to one side).

You could combine card detection with simple range finding using an ultrasonic detector.

  [1]: https://i.stack.imgur.com/iRHQx.jpg
  [2]: https://i.stack.imgur.com/HF3h5.jpg


message:
while compare, something is wrong

I have 5 LDR and Arduino Mega. I connect them and get light level.

    void loop() {
    // print the analog output in milli volts
    int w=analogRead(west);
    Serial.print("west = ");

    Serial.print(w);
    Serial.println(" mv");

    int e=analogRead(east);
    Serial.print("east = ");

    Serial.print(e);
    Serial.println(" mv");

    int n=analogRead(north);
    Serial.print("north = ");

    Serial.print(n);
    Serial.println(" mv");

    int s=analogRead(south);
    Serial.print("south = ");

    Serial.print(s);
    Serial.println(" mv");

    int c=analogRead(control);
    Serial.print("control = ");

    Serial.print(c);
    Serial.println(" mv");

    delay(1000);

    if(e > w)
    Serial.println("west");

    else if(e < w)
    Serial.println("east");

    else if(s > n)
    Serial.println("south");

    else(s < n);
    Serial.println("north");

    Serial.println("\n");
    }

This is my loop and I always see east-north. When west is bigger than east I also see east. What

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

Here:

    else(s < n);
    -----------^

That is wrong. See [Arduino programming traps, tips and style guide](http://www.gammon.com.au/tips#trap13).

---

## Trap #13: Don't put a semicolon at the end of every line

Semicolons end statements. However `if`, `for` and `while` are *compound* statements, so they should *not* have a semicolon after them like this:

**Wrong! ...**

      if (temperature > 40);    // <----- this semicolon is incorrect!
        {
        digitalWrite (furnaceControl, LOW);
        digitalWrite (warningLight, HIGH);
        }

      for (int i = 0; i < 10; i++);   // <----- this semicolon is incorrect!
        digitalWrite (i, HIGH);

The semicolons above (as indicated) terminate the `if` and `for` so they don't do anything useful. The lines following them are just unconditional blocks of code which are always executed, once.

**Correct:**

      if (temperature > 40)
        {
        digitalWrite (furnaceControl, LOW);
        digitalWrite (warningLight, HIGH);
        }

      for (int i = 0; i < 10; i++)
        digitalWrite (i, HIGH);


body:
Nick Gammon correctly points out a problem due to an extra semicolon, but you should also note what the construct `else(s < n)` is doing.  When the `if` condition that this `else` gives an alternative to is false, the statement   `(s < n)` gets executed.  That statement is an expression statement, and its value is the evaluation of `s<n`, either true or false.

If the semicolon after `(s < n)` weren't there, you'd get a compile error because `(s < n) serial.println("north")` is not a valid statement.  You may have meant to say `else if(s < n)` instead of `else(s < n)`.

Note, in the sequence

    if (e > w)
       Serial.println("west");
    else if (e < w)
       Serial.println("east");
    else if (s > n)
       ...

that last `else` typically is reached only rarely, because the only condition to get to it is `e` and `w` being equal.  Due to sensor noise and signal processing noise, the chance of `e` and `w` being equal is probably at most a few percent.

If your north/south test sequence is supposed to be independent of your east/west test sequence, leave out the second `if` and second `else` .  That is, instead say:

    if (e > w)
       Serial.println("west");
    else
       Serial.println("east");
    if (s > n)
       ...


message:
Physical dimensions(size) of the new MKR1000 board?

Anybody here knows the physical dimensions(size) of the new Aduino MKR1000 board?

body: If the diagram on the main page is to scale, then it's approximately 2.2 inches by 1.0 inches.


message:
Do I have a faulty arduino uno, or have I found an Arduino bug?

Lately, we got an old arduino uno donated from a friend and have been trying to get it to work with servos. We have been having very perplexing results. We have tried many different "stock" code and servo combinations with our servos, but here is the behavior:

 - 180 Servos automatically move to right max as soon as power is applied.
 - Sail Winch servo moves a tiny amount and then stops. If power wire is removed and then reapplied, the servo moves another tiny amount.

The code is very simple. First we call the `servo.attach(pin)`, and confirm the pin. We have also tried doing the manual uSec definition: `servo.attach(pin, 600, 2400)`. In our loop() we have tried `servo.write(*value from 0-180*)` and `servo.writeMicroseconds(*value in PWM range*)`

Power is being supplied by a 9v battery, the sensor (yellow) is directly in digital pwm pin, while red (power) is in **+** and black (ground) is in **-**.

**I'm trying to decide whether I should invest in another arduino system.**

servos:

[180 servos][1]

[Sail Winch servo][2]

  [1]: https://www.servocity.com/html/hs-322hd_standard_deluxe.html
  [2]: http://www.hobbyking.com/hobbyking/store/__20853__SW5513_4MA_Sailwinch_Servo_10_63kg_55g_0_9.html

body:
If the Arduino "fails" the moment you apply power to a motor, you can bet that it is a power issue.

Or possibly you are exceeding the output rating of the output pin. You should not draw more than 20 mA from each output pin continuously.

> I'm trying to decide whether I should invest in another arduino system.

Power the motor independently of the Arduino. This is normal advice for all but very small motors. Also make sure that you have a suitable driving transistor / MOSFET if the motor draws more than 20 mA. Take into account any surge startup current.

---

See [Driving motors, lights, etc. from an Arduino output pin](http://www.gammon.com.au/motors) for some design ideas.

For example:

[![MOSFET driver][1]][1]

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


message:
Splitting String from Serial

I am currently working on a program for an Arduino uno and want to, in the program, when it receives a 16 digit number from a serial transmition, it will split the 16 digit number into 4 separate 4 digit numbers.

For Example:
The computer sends the Arduino the number 1100115011001150 and I want the Arduino to break the number so that "Avalue" would equal 1100, "Bvalue" would equal 1150, "Cvalue" would equal 1100 and so on...

Thanks for any help you can provide!

body:
    int nums[] = {0, 0, 0, 0};   // must be always reset to zero if you will repeat this process
    while (Serial.available() < 16);   // wait for 16 chars to come in; easiest way to do this
    for (int i = 0; i < 4; i++){      // for each number
        for (int j = 0; j < 4; j++){    // for each digit in the number
            nums[i] *= 10;
            nums[i] += Serial.read() - '0';

    //while (Serial.available() == 0);
    //Serial.read();  // in case you use an extra character to separate numbers

    A = nums[0];
    B = nums[1];
    C = nums[2];
    D = nums[3];

If you are using a character or characters to delimit the 16-digit numbers being received, make sure to read off those extra characters before running the while loop again.


body:
    char ArrayBuffer[][4] = {};         // holds four characters, must be
declared as global to loop()

in

    loop()
    {
    byte Index = 0;                    // initialize array index
    if(Serial.available())             // have data in Serial buffer
    {
    byte Count = Serial.readBytes(ArrayBuffer[Index],4); // read       //4             //characters     into array buffer , returns actual number //of        characters //read and times out if less than 4 characters are //currently in Serial buffer
     Serial.println(ArrayBuffer[Index]); // print buffer to monitor
    }while(++Index != 4);              // read 4 by 4 characters from incoming stream
    }
...
continue with loop - process ArrayBuffer as required
}

This is one way to get the incoming stream from Serial buffer into for individual buffers, however, it is better, less chance of misdirecting the data into wrong buffer (index)  to read the entire buffer at once instead of using he readBytes four times.
Just my opinion, your mileage will vary.

PS what is the trick to format the code and text correctly ?
This is a mess.
I cannot get the code block to indent, I can get only the first ( four spaces line.


body:
    while (Serial.available() < 16);   // wait for 16 chars to come          easiest way to do this
    for (int i = 0; i < 4; i++){      // for each number
        for (int j = 0; j < 4; j++){    // for each digit in the number
            nums[i] *= 10;
            nums[i] += Serial.read() - '0';

Where did my last post - comment on this code went?
It was suppose to wait for "peers" approval, per note I got after I posted it.

This is not the best way to use "available()", beside what will happen if 16 characters never arrive?


body:
Not tested but should work.

    int nums[] = {0, 0, 0, 0};
    String inString = "";
    while (Serial.available() >= 16) {
      for (int k =0;k<4;k++) {
        for (int i =0;i<4;i++) {
          int inChar = Serial.read();
          if (isDigit(inChar)) {
            inString += (char)inChar;
          }
        }
        nums[k]=inString.toInt();
        inString = "";
      }
      Serial.println(nums[0]);
      Serial.println(nums[1]);
      Serial.println(nums[2]);
      Serial.println(nums[3]);
    }


message:
Defining object

I am trying to hide libraries behind another, for simplicity. But I can't deal with the objects required by the libraries. Basically I want to use the objects both in my .cpp and .ino file, but I am getting errors about double definition, or not declared in this scope.

  *test.ino*

    #include "lib.h"
    #include "obj.cpp"

    void setup() {
      mesh.setNodeID(40);
      mesh.begin();
    }

    void loop() {
      mesh.update();
    }

  *lib.cpp*

    #include "Arduino.h"
    #include "lib.h"

    #include "obj.cpp"

    int message = 1;

    void send() {

      if (!mesh.write(&message, 'C', sizeof(message))) {

        // If a write fails, check connectivity to the mesh network
        if ( ! mesh.checkConnection() ) {
          //refresh the network address
          Serial.println("Renewing Address");
          mesh.renewAddress();
        } else {
          Serial.println("Sending failed, Test OK");
        }
      } else {
        Serial.print("Sent OK");
      }
    }

  lib.h

    #ifndef lib_h
    #define lib_h

    void send();

    #endif

  obj.cpp

    #include "RF24.h"
    #include "RF24Network.h"
    #include "RF24Mesh.h"
    #include <SPI.h>
    #include <EEPROM.h>

    RF24 radio(7, 8);
    RF24Network network(radio);
    RF24Mesh mesh(radio, network);

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

    #include "obj.cpp"

Don't include .cpp files. That gets them compiled twice (or more) and then you get duplicate definitions. Include .h files only.

What you are calling obj.cpp should probably be obj.h, however I haven't actually tried to compile it.

---

> it says that I have multiple definitions of the three objects

I tried compiling but I don't have the RF24 library. Anyway, this is wrong:

**obj.h**

    #include "RF24.h"
    #include "RF24Network.h"
    #include "RF24Mesh.h"
    #include <SPI.h>
    #include <EEPROM.h>

    RF24 radio(7, 8);
    RF24Network network(radio);
    RF24Mesh mesh(radio, network);

You can't *define* things there (like `radio`) which get included in multiple files. `obj.h` or `obj.cpp` it will be the same thing.

These lines need to be in **one** .cpp file:

    RF24 radio(7, 8);
    RF24Network network(radio);
    RF24Mesh mesh(radio, network);

Thus you cannot include that file in another file. However you can refer to them by making them `extern` in a header file, eg.

    extern RF24 radio;
    extern RF24Network network;
    extern RF24Mesh mesh;


message:
Unpacking Arduino binary data on a python sketch

As a follow up to my earlier post: https://arduino.stackexchange.com/questions/20396/simultaneously-reading-data-from-multiple-serial-ports/20642#20642, I am stuck trying to develop a python sketch that can read the incoming serial data from the com port on my Arduino and unpack them from the buffer into two separate cvs files.

One of the csv files would contain the data from the first sensor, while the other would contain the data from the second sensor. I have been able to develop the sketch to a point where on receiving the first header byte the first sensor data is unpacked. I am finding it hard to adjust the sketch to allow for the second byte header to be called to unpack the second sensor data from the data packet. Below is my abbreviated sketch thus far. Thanks all.
<!-- language-all: lang-cpp -->

    def run(self):
        #Creating a csv file to read data from the first sensor
        self.click = open("ball_Data.csv", "wb")
        #Creating a csv file to read data from the second sensor
        self.flick = open("rugby_Data.csv", "wb")
        #creating the serial port object
        self.push = serial.Serial('COM6', 9600)
        while True:
            #If the incoming byte is equivalent to '$'
            if node == b'$':
                # the byte object is equivalent to the available bytes
                node = self.push.read()
                #an array to hold the sensor data
                sensor_array = []
                i = 0
                #This while loop initiates a count from 0 to 9
                #through the sensor array
                while i < 10:
                    #The available byte present
                    malcolm = self.push.read()
                    #The next byte
                    turnbull = self.push.read()
                    #The incoming uint_16 data is unpacked into the variable lingo
                    lingo= (struct.unpack('b', turnbull)[0] << 8) | struct.unpack('B',malcolm)[0]
                    #The variable lingo is then appended to the sensor array
                    sensor_array.append(lingo)
                    #If the length of the sensor array is equivalent to 9
                    #write the data through each count into the sensor array
                    if len(sensor_array) == 9:
                        self.click.write(str(sensor_array[0] ..+ str(sensor_array[9]))
                        #My idea is that this else statement was supposed to trigger
                        #the next header for the second sensor which would be an '#'
                        #sign before unpacking the data
                        else:
                            oldde = self.push.read()
                            sensor_array = []
                            i = 10
                            while i < 20:
                                #The available byte present
                                malcolm = self.push.read()
                                #The next byte
                                turnbull = self.push.read()
                                lingo= (struct.unpack('b', turnbull)[10]<<8)|struct.unpack('B',malcolm)[10]
                                sensor_array.append(lingo)
                                if len(sensor_array) > 19:
                                    self.flick.write(str(sensor_array[10]..+ str(sensor_array[19]))

                                    The Packet data structure for the first and second sensor is:
                                        Packet1 from sensor 1:
                                            data_array[0] = headerbyte('#')
                                            data_array[1] = acceleration_xAxis
                                            data_array[2] = acceleration_yAxis
                                            data_array[3] = acceleration_zAxis
                                            data_array[4] = temperature
                                            data_array[5] = gyro_xAxis
                                            data_array[6] = gyro_yAxis
                                            data_array[7] = gyroz_xAxis
                                            data_array[8] = checksum
                                            Packet2 from sensor 2:
                                                data_array[9] = headerbyte('$')
                                                .
                                                .
                                                .
                                                data_array[17] = checksum

body:
I'm somewhat confused by the flow of your program, so instead I will tell you how I would handle the data.

You have a single-byte header, then 7 bytes of data, followed by a single byte checksum.

PySerial's read is (I believe) blocking by default, so it's simple to read the next serial character - unlike an Arduino.  It also has a "multi-byte" read version where it can read a pre-set number of bytes from the stream for you.

So my methodology would be:

1. Read a byte.  Is it a '#' or a '$'?
2. If it is, remember which stream you are dealing with, then:
3. Read 7 bytes with `this.push.read(7)` into a byte array (or a string in python < 2.6)
4. Read one byte for the checksum. If the checksum is correct (whatever calculation you use for that) then unpack the data in the array.
5. Write the data to the correct file depending on the stream you remembered in step 2.

That way you're not duplicating code for each sensor stream, you are just saying "this packet is stream 2" and using that remembered fact once you have received the packet and verified that it's correct.

A better protocol arrangement, though, which is more reliable, involves both a start byte and an end byte, and your whole packet is wrapped in that pair of bytes.  You then have a "sliding window" arrangement whereby the incoming data bytes scroll past a window of a fixed width, and when the first and last characters in that window match your start and end bytes you then extract the middle section and do what you need to do with it.  That way if you have a $ or a # that is midway through a stream of data it won't trigger reception since the end byte doesn't match. It makes the whole synchronisation of the data more reliable.

For instance, if you have the current data packet that looks like `$ho9*$fup` and you miss the first bit of the data for whatever reason (arduino started transmitting before you were ready to receive, for instance) it might trigger reception on the second `$` which would give you incorrect values.  So instead if you have the start character as `$` and the end character as `#` and include a stream number, so your packet looks like:

    $1ho9*$fup#

Then when you scroll that past the window it would look like:

     $         #
     v         v
    [..........$]
    [.........$1]
    [........$1h]
    [.......$1ho]
    [......$1ho9]
    [.....$1ho9*]
    [....$1ho9*$]
    [...$1ho9*$f]
    [..$1ho9*$fu]
    [.$1ho9*$fup]
    [$1ho9*$fup#]

And the first and last characters match, so you receive the content.

If you were to miss the first $ the second $ wouldn't match - say the extended stream looks like: `$1ho9*$fup#$2hdiw83bf#` and you missed $1, the window would look like:

     $         #
     v         v
    [..........o]
    [.........o9]
    [........o9*]
    [.......o9*$]
    [......o9*$f]
    [.....o9*$fu]
    [....o9*$fup]
    [...o9*$fup#]
    [..o9*$fup#$]
    [.o9*$fup#$2]
    [o9*$fup#$2h]
    [9*$fup#$2hd]
    [*$fup#$2hdi]
    [$fup#$2hdiw] <= Doesn't match even though it starts with $
    [fup#$2hdiw8]
    [up#$2hdiw83]
    [p#$2hdiw83b]
    [#$2hdiw83bf]
    [$2hdiw83bf#] <= Matches - starts with $ and ends with #

As you can see the synchronising of your packet is then much more reliable. It would normally have incorrectly triggered on the first $ it saw.

There is always a chance that there may be a $ and a # in just the right positions within successive packets to fool the system, but the chances of that are somewhat slim.  You can add extra protection against that by "escaping" the start and stop bytes if they appear within your stream. There's many possible ways of handling that if you really need it.


message:
How many bits can an Arduino uno read?

What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

body:
> What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

A digital input is by nature binary (i.e. a single bit). The answer to your question is therefore one bit per digital input.

The total number of digital inputs depends on the board. It ranges from Arduino Micro (which has fewest less with than 10) to Arduino Mega which has the most with more than 60).

Another possible interpretation of your question is the resolution of an analog pin (ADC). The AVR has max 10 bit resolution.

Cheers!


body: Do you mean _simultaneous_ read or write? The AVR processors are 8-bit processors and their I/Os are grouped into 8-bit registers. If you configure all of the bits in a register to the same direction - all inputs or all outputs - then the entire 8 bits could be read/written at once. in C/C++ you would use the `PORTWhich I/Os are assigned to which register is designed into the chip - but the data sheet describes which physical pins are connected to which I/O register. You can take advantage of that to make use of a single register's-worth of pins for up to 8 signals that need to be set or read simultaneously.


message:
PID not working correctly

I'm currently working on a project where I need to use PID to get the correct speed for a motor when it is angled a certain amount.

The problem is that I'm only getting 0.00 and 255.00 as the speed. Nothing in between. The code is supposed to activate when the angle value is more than 1300 and less than -1300. The `ax` variable is from an MPU6050 sensor.

    int16_t ax, ay, az;

    double Setpoint, Input, Output;
    //Specify the links and initial tuning parameters
    double Kp=2, Ki=5, Kd=1;
    PID myPID(&Input, &Output, &Setpoint, Kp,Ki,Kd, DIRECT);

    void setup() {
      Input = analogRead(ax);
      Setpoint = 100;
      //turn the PID on
      myPID.SetMode(AUTOMATIC);
    }

    void loop() {
      accelgyro.getAcceleration(&ax, &ay, &az);
      int a=ax+10900;
      //Here I set the used variable to around 0. ax is actually around -10900
      //This is always true, this won't be in the final code. This is just making it work.
      if(1) {
        int val;
        val = map(a, -1300, 1300, 0, 1023);
        Input = val;
        myPID.Compute();
        Serial.println(Output);
      }
    }

body:
Please respect others by presenting code that is readable. By doing that you may also find obvious errors in your code. Let me clean up the loop() and you will see what I mean.

    void loop() {
        int a = ax + 10900;
        if (1) {
          int val;
          val = map(ax, -1300, 1300, 0, 1023);
          Input = val;
          myPID.Compute();
          Serial.println(Output);
        }
      }
    }

So what is "int a = ax + 10900"? "ax" is not defined but the other use of it is as an analog pin number "Input = analogRead(ax)". And "a" is not used.

There is a condition that is always true "if (1)" and so on.

Cheers!


body:
How fast is your system compared to the loop() sampling time?  Does (100-map((ax+10900),-1300,1300,0,1024)) change appreciably during the sub-millisecond loop()?

With kI=5, an error of only 10 will saturate your 0-255 speed output in 26 iterations of loop(), potentially producing the behavior you see.  If you don't have control of your sampling time, the integral error can wind up (or down) to the process limits very quickly.

From https://www.arduino.cc/en/Reference/Map map() only linearly transforms the input data to the output data, but does not constrain() it to those limits.  If ax=-9000, then val would be greater than 1024.   Still, taking the normal working range of ax+10900 to be (-1300,1300) which is then mapped into  (0,1024), the Kp=2 term with a setpoint of 100 would produce a range of (-200,2048) constrained to the default (0,255) limits.

Working backwards from the setpoint of 100, through the 0-1024 map is 0.0975 along the (-1300 to 1300) range, or val = -949, or ax = -11849.  And the kP=2 times the mapping factor of 1024/2600 would change the output by 2*1024/2600=0.79 points for each step difference of ax from -11849.

The http://playground.arduino.cc/Main/MPU-6050 pages says the acceleration registers are 16 bit with high sensitivity, and suggests that 50 points of noise is a small variation.  If the sensor set for 16 bits for +/-2G into ax, then, each step change 60 micro-G.  If that is the source of your ax, then the small variations could easily saturate your control system, making it bang-bang between its output limits with only milli-G variations at the sensor.

Slow down your sampling time, reduce kI, and think of your Kp, Ki, and Kd as conversions of your measured and translated variable ax errors into output space (0-255 speed).

Also, in choosing a sampling time, consider how often you want the PID to make adjustments to the process.


message:
Maintaining pull down on a relay with a shift register

I currently have an Arduino Mega project that uses a relay to switch some high voltage loads. Currently, I use a scheduler library so that every 250ms I check if certain conditions are met and if so I turn off or on the relay. The relay is active when pulled down.

I'm trying to figure out how to transition this project to using a shift register. If the pin needs to be pulled low to be turned on and I want to keep it on, how do I supply a steady "low" signal using a shift register if the register is clocked to only latch every 8 clock cycles (not to mention I only run this code every 250ms). Even if every bit that gets sent by the shift register is low, do I need to no longer use the scheduling library so that every time through the Arduino loop I am sending the low signal so that the low signal can remain constant? With the standard Arduino pin once I set it to low it stays low until I switch it to high. But with a shift register can I keep it low "until I switch it high?"

body:
You have misunderstood how shift registers work - and one of the main reasons they exist in the first place.

Shift register ICs have a common 'latch' pin which latches the data present at the input of the cell into the cell, thus updating the output. Some ICs also offer an "output enable", which switches the outputs to a high-impedance state irrespective of the values in the cells - this might not be useful in your case, but the feature exists.

With a serial-to-parallel shift register you can shift in as many bits as you want, at whatever rate you choose, and the outputs will never change **until you trigger a rising edge on the LATCH pin**.

----------

**How a (latching) Shift Register works:**

You have eight spaces within the register:

                 ___    ___    ___    ___    ___    ___    ___    ___
    [DATA_IN]-->|___|--|___|--|___|--|___|--|___|--|___|--|___|--|___|-->[DATA_OUT]
                BIT0                                              BIT7

The 'spaces' are chained together; at one end of the chain is the `DATA_IN` pin and at the other end is the `DATA_OUT` pin.

Every time there is a rising edge on the `CLOCK` pin, data is *shifted* down the chain from `DATA_IN` to `DATA_OUT`, one space at a time. For example, if the state of the 'spaces' is as the left hand column, then upon the rising edge of the `CLOCK` pin the spaces will change to the values in the right hand column:

     DATA_IN PIN = 1  ->  C  -> ?
    BIT0 'SPACE' = 0  ->  L  -> 1
    BIT1 'SPACE' = 1  ->  O  -> 0
    BIT2 'SPACE' = 1  ->  C  -> 1
    BIT3 'SPACE' = 0  ->  K  -> 1
    BIT4 'SPACE' = 0  ->  E  -> 0
    BIT5 'SPACE' = 1  ->  D  -> 0
    BIT6 'SPACE' = 1  ->  G  -> 1
    BIT7 'SPACE' = 0  ->  E  -> 1

You will see that `BIT(n)` changes to the value of `BIT(n-1)`, with `BIT0` changing to the value of `DATA_IN`. The `DATA_OUT` pin is used to daisy-chain multiple shift registers together. The important thing to note here is that **the outputs do not change without a rising edge on the `LATCH` pin**. You can pulse `CLOCK` as many times as you want, with whatever values on `DATA_IN`, and the outputs will not change. Ever.

When you finally trigger the `LATCH` pin, the value in each 'space' is latched into a second row of 'spaces' - these represent the outputs. On a latch trigger, the outputs therefore change to the values of the *last eight* bits that were shifted into the `DATA_IN` pin. For example:

    OUTPUT = 11001010
                       SHIFT IN "01101111" (starting with RHS first)
                                   TRIGGER RISING EDGE ON 'LATCH' PIN
    OUTPUT = 01101111
                       SHIFT IN "11110000110011001100"
                                   TRIGGER RISING EDGE ON 'LATCH' PIN
    OUTPUT = 11110000   i.e. the LAST EIGHT BITS that were shifted in
                       SHIFT IN "10"
                                   TRIGGER RISING EDGE ON 'LATCH' PIN
    OUTPUT = 10111100   again the LAST EIGHT BITS that were shifted in

It is generally never the case with a serial-in-parallel-out register that you would ever shift in less that eight bits at a time, so the last example is only there to illustrate the functioning of the IC.


body:
> ... relay ... active when pulled down ... shift register ... latch ... Arduino ...

TPIC6C595

`shiftOut()` and the '595


message:
Arduino compiled sketch on sd card

Hello I have just got my Arduino to read text from a text file and it is running perfectly. I was interested in being able to load a sketch into the Arduino and having it execute it, from and SD card. The Arduino wouldn't be connected to my laptop at all. I researched it and it is possible, with a different boot loader. Which is a bit annoying because I don't want to change the boot loader on my Arduino. I could put it on a standalone atmega chip but lets pretend I don't have those. So I was thinking if you had pre-compiled Arduino code. Which is in hex format and ready to be put on the board, would it be able to be loaded from the SD card? If so how would I go about doing this?

body:
Yes it is possible:

**With a different bootloader**.

You need something which will erase the old sketch from the chip, read the data from the SD card, and write that into the flash of the chip. The only thing that can do that is the bootloader or some external device (another ATMega328p chip which we have to pretend you don't have).

Due to the way the architecture works you can only execute code out of the flash, so you need to program your sketch into the flash somehow. And that is the role of the bootloader.


message:
Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?

**Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?**

I would like to change the operation of a couple of Arduino pins from input to output during execution of the Arduino loop in an event-driven way. Is this possible please?

body:
Yes.

Just call `pinMode([pin], [mode])` whenever you want to change from input to output or output to input.

How to decide when to do that is entirely up to you. You can do it any time you choose using any stimulus you like.


message:
Arduino disecting a string

Hello I have a String that contains the following: "println('hello world')".
I want to be able to remove everything from the String except for the text insie the brackets. Bear in mind that this text will change multiple times as the programme runs. How can I remove everything except for what is in the brackets from the string.

        String line1 = "println('hello world')";

Please help me thx.

body:
> How can I remove everything except for what is in the brackets from the string?

There are a number of [String class][1] member functions that can help with this. First, [indexOf(val)][2] will help locate the character of interest. Second, [substring()][3] will help cut out the part you want. And as a bonus, using [lastIndexOf()][4] will allow brackets within the string.

    String s = "println('hello world')";
    s = s.substring(s.indexOf('(') + 1);
    s = s.substring(0, s.lastIndexOf(')'));

Cheers!

  [1]: https://www.arduino.cc/en/Reference/StringObject
  [2]: https://www.arduino.cc/en/Reference/StringIndexOf
  [3]: https://www.arduino.cc/en/Reference/StringSubstring
  [4]: https://www.arduino.cc/en/Reference/StringLastIndexOf


message:
Trying to run two simultaneous loops that do the same task with different delay cycles

I'm trying to control a pellet stove auger motor in such a way that I can use a toggle switch to do High/Low (H/L) - so the way that I have it now is:

     void setup() {
       // initialize digital pin 13 as an output.
       pinMode(13, OUTPUT);
       pinMode(12, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(12, HIGH);
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(2850);              // wait for a second
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(11250);

Which is just LED on/off but it also controls another relay that controls the blower motor - what I'm trying to set up is a H setting that would be the 2850 delay-ON - and then have say: pin 11 have a delay-OFF of 7000, and have pin 13 still resetting to the delay-ON of 2850.

What I mean is:

 - loop A: pin12 on -delay 2850 pin12 off -delay 11250
 - loop B: pin13 on -delay 2850 pin13 off -delay 7000

I saw and tried the code for 'multi-blink' - as the one I use is pretty much modified 'blink'.

Any assistance would be awesome - I run the one I show above now, on my pellet stove and it was recently -31.4 and worked like a charm, but I'd like to be able to have a high/low option.

PS: I also have a coffee roaster control project as well... help on that one is always appreciated as well.

body:
The Arduino [Simple Timer library][1] (and other similar timer libraries) are made for exactly this kind of application. Your `setup()` routine calls the SimpleTimer library, naming a callback-function and how often it should get called. Your loop function must then call `timer.run()` reasonably frequently (where
reasonably frequently" depends on the timing accuracy and jitter tolerance of your application). `timer.run()` will call each of your callback-functions at its appropriate time. You write the callback-functions to do whatever you need them to do when the timer calls them.

There are one-shot timers and repeating timers - it sounds like your application could one of each per LED: One that fires periodically, to to call a turn-on-LED12 function every (ON_TIME_12+OFF_TIME_12) ms, and a one-shot that calls a turn-off-LED12 function, started by the turn-on-LED_12 function for (ON_TIME_12) msec. Same for LED13, ( ..., etc.)

Your loop function is free to do whatever else, as long as it calls `timer.run()` frequently enough that your application can meet its timing requirements.

  [1]: http://playground.arduino.cc/Code/SimpleTimer


body:
This seems to be the perfect example for [the simple scheduler][1]:

    #include <Scheduler.h>

    const int pinA = 12;
    const int pinB = 13;

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);
      Scheduler.start(setupA, loopA);
      Scheduler.start(setupB, loopB);
    }

    void loop()
    {
      Serial.print(millis());
      Serial.print(F(":pinA="));
      Serial.print(digitalRead(pinA));
      Serial.print(F(",pinB="));
      Serial.println(digitalRead(pinB));
      delay(1000);
    }

    void setupA()
    {
      pinMode(pinA, OUTPUT);
    }

    void loopA()
    {
      digitalWrite(pinA, HIGH);
      delay(2850);
      digitalWrite(pinA, LOW);
      delay(11250);
    }

    void setupB()
    {
      pinMode(pinB, OUTPUT);
    }

    void loopB()
    {
      digitalWrite(pinB, HIGH);
      delay(2850);
      digitalWrite(pinB, LOW);
      delay(7000);
    }

Cheers!

  [1]: https://github.com/mikaelpatel/Arduino-Scheduler


message:
Pro Micro clone worked fine, now RxLED stays on and can't program it

I have burned out a few Pro Micro clones now. Initially I ran them using a 12VDC external raw power supply but two Pro Micro clones burned out pretty quickly this way. Another thread suggested that the Pro Micro clones use regulators that are not very robust. Since then, I've been using just USB power for my 5V/16MHz Pro Micro clones.

The third clone has been working fine on USB power only. I estimate that I uploaded a sketch I was working on about a dozen times. Suddenly the RxLED stayed lit and I can't upload to it anymore.

When I plug it in, Windows assigns a COM port successfully. The Arduino IDE sees the port and I can select it. This tells me the Pro Micro is not entirely dead. When I enable verbose mode for uploading in the Arduino IDE, here's what I get:

    Sketch uses 3,914 bytes (13%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 148 bytes (5%) of dynamic memory, leaving 2,412 bytes for local variables. Maximum is 2,560 bytes.
    Forcing reset using 1200bps open/close on port COM3
    PORTS {COM3, } / {COM3, } => {}
    [repeating 19 more times]
    Uploading using selected port: COM3
    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Bartman\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.2/avrdude.conf -v -patmega32u4 -cavr109 -PCOM3 -b57600 -D -Uflash:w:C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:i

    avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "C:\Users\Bartman\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.2/avrdude.conf"

             Using Port                    : COM3
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .

and after some time:

    avrdude: butterfly_recv(): programmer is not responding
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

On my working Pro Micro clone, I get the following after instead:

    Found programmer: Id = "CATERIN"; type = S
        Software Version = 1.0; No Hardware Version given.
    Programmer supports auto addr increment.
    Programmer supports buffered memory access with buffersize=128 bytes.

    Programmer supports the following devices:
        Device code: 0x44

    avrdude: devcode selected: 0x44
    avrdude: AVR device initialized and ready to accept instructions

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

    avrdude: Device signature = 0x1e9587
    avrdude: reading input file "C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex"
    avrdude: writing flash (3914 bytes):

    Writing | ################################################## | 100% 0.30s

    avrdude: 3914 bytes of flash written
    avrdude: verifying flash memory against C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:
    avrdude: load data flash data from input file C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:
    avrdude: input file C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex contains 3914 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.04s

    avrdude: verifying ...
    avrdude: 3914 bytes of flash verified

    avrdude done.  Thank you.

On the now non-functional one, I tried using a jumper from RST to GND, tapping this twice quickly in succession and uploading from the IDE in an attempt to recover the Pro Micro but this doesn't work.

I don't think it's a bootloader problem since the Pro Micro does get a COM port assigned to it but never-the-less, I tried burning a new bootloader from my working Pro Micro. Here's my Pro Micro to Pro Micro wiring:
[![enter image description here][1]][1]

In the IDE, I've selected:

> Board: SparkFun Pro Micro

> Processor: ATmega32U4 (5V, 16 MHz)

> Port: [current COM port of working Pro Micro]

> Programmer: Arduino as ISP

But when I select `Tools->Burn Bootloader`, I get the following error:

    Arduino: 1.6.7 (Windows 10), Board: "SparkFun Pro Micro, ATmega32U4 (5V, 16 MHz)"

    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Bart_S\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.3/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM6 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xCB:m -Uhfuse:w:0xD8:m -Ulfuse:w:0xFF:m

    avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "C:\Users\Bart_S\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.3/avrdude.conf"

             Using Port                    : COM6
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Is it permanently damaged? What are the next steps to troubleshoot this Pro Micro clone?

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

body:
To make things simpler, try flashing the Pro Micro firmware with another UNO (or compatible) hardware. I prefer an UNO clone with CH340 chip or a pro mini with a FTDI cable. Just to keep things simple.

Flash the UNO with Arduiono as ISP sketch. Use connection guidance from Arduino tutorial:
[Using an Arduino as an AVR ISP][1]

[![connection diagram][2]][2]

Once this is done, AVRDUDE will see the source Arduino as **AVR ISP** and you can flash the firmware on the target Arduino.

You can also use [this post][3] for guidance as well.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [2]: https://i.stack.imgur.com/j6Wh1.png
  [3]: http://blog.bhargavaz.us/2011/08/programming-arduino-bootloader-on-mega8.html


body:
After many hours of unsuccessful bootloader reprogramming attempts, I was able to revive the Pro Micro by trying different timing of double tapping RST while the IDE was compiling/uploading a sketch. After several attempts the Pro Micro suddenly took a sketch and seems to be working now. Not sure how long it will stay this way or how often I will loose it and have to go through these shenanigans again.

Thanks to all for the help.


message:
What does it mean when there are two addresses listed in the data sheet for a particular register?

I have been trying to grasp a better understand of registers and port manipulation. I have been looking through the ATmega 328P datasheet to look at the different registers.

For some of the registers, I see that there are two addresses listed. For example, for PORTB is listed at 0x05 (0x25). Similarly, for its DDRB and PINB, they are listed at 0x04 (0x24), and 0x03 (0x23), respectively. What does this mean for the register? Thank you.

body:
One (the lower number) is the IO port address which is used when using the IN or OUT op-code. The other (higher number) is the memory mapped address.

Different methods of access are more programatically efficient depending on how you are manipulating the values. For instance IN and OUT are more efficient at setting or reading the entire register value, but SBI and CBI on the memory mapped address are more efficient when manipulating individual bits.


message:
Arduino substring not working

Hello  I have an Arduino programme where a string is loaded from an SD card. That all works fine. I want to see if the string that has been loaded contains a certain phrase. I am using substring but it doesn't seem to be working. What am I doing wrong? Here's my code:

    file = SD.open("/classes/basic.txt", FILE_READ);
     Serial.print("Reading, Checking and Compiling \n");
      while(file.available()) {
       character23 = file.read();
       content.concat(character23);
      }
    if (content != "") {
      l1 = content;
      Serial.println(l1 + "\n");
    }

    if(l1.substring(0) == "print"){
      printlnMethod();
    }
    file.close();

it all works until it gets to l1.substring and that doesn't work because the method inside doesn't run. The string that gets loaded into the Arduino from the SD card is : println("hello world");

What am I doing wrong?

body:
Substring takes either one or two arguments.

In the single-argument version that you are using the argument specifies the *start* of the substring. The substring then contines to the end of the string.  So, since you are asking it to start at index 0 the returned value is the entire string - from 0 to the end.

Instead you probably want to use the two-argument version. In that version you provide two numbers - the index in the string to start from, and the index in the string after the last character you want.  So if the string starts with "print" you then want to use `l1.substring(0, 5)` to get the characters 0 to 4 inclusive.


message:
MKR1000 not showing up on OSX

I can't appear to get my MKR1000 to list a port on my mac in the arduino ide, am i missing something obvious or does it need additional drivers?

Also
➜  ~  csrutil status
System Integrity Protection status: disabled.

running OSX 10.11.3

Board appears to be working, default led flashing

body: Double click the reset button on the board. Then it will show in the Port list :-)


message:
Why doesn't my object's method return back to my caller method?

I am creating a miniature computer using an Arduino, and I am creating a full-scale interpreter for it. Everything works, and the code begins to run after calling the runCode method, but once the run is finished it doesn't return to the calling function. I have Serial outputs to tell me where the code reaches.

My code contains an **"Function" object** with a name and a function pointer, an **object to run the code** (with a working Lexer object that splits the inputted code by spaces), and an **in-computer editor** (which completely works except the one function) to input programs to be run.

The function that calls the runCode method for my code-running object (called Joker) **is in the editor**. The problem is, once the runCode finishes, it does not return. **The system halts.** I will post the Function class, runCode Method, and calling method.

P.S. There are Serial prints to determine where the code reaches. It outputs "Function End!", but not "Failed!"/"Succeeded".

P.P.S. It uses a parallax 4x20 Back-lit Single-pin Serial LCD which completely 100% works.

P.P.P.S It uses the QueueList<T> library which is basically a dynamic list that works like a stack.

One more note: The code heavliy uses dynamic lists, function pointers, and lambda expressions, so.... be prepared....

---

Code for Function class (no it does not have any actual functions):

    class Function {
    public:
      String f_name;
      bool (*f_run) (QueueList<float> &stack, SoftwareSerial &lcd);
    };

Code for runCode method:

    bool Joker::runCode(QueueList<String> lineTable, SoftwareSerial &lcd) {
      // Set up lexer
      Lexer lexer;
      // Get all lexer words
      lexer.getWords(lineTable);

      String cur_word = "";
      float num_val = 0.0f;
      bool quit = false;

      while(!quit) {
        cur_word = lexer.nextWord();
        if(cur_word == "")
          quit = true;
        else {
          // Get word in uppercase
          cur_word.toUpperCase();

          Serial.println(cur_word);

          // Parse the first number from it
          num_val = cur_word.toFloat();

          // Check if we have a function
          if(queueListContains(cur_word, dictionary)) {
            Function theFunc = getDictionaryFunction(cur_word, dictionary);
            if(!theFunc.f_run(stack, lcd)) {
              error(F("Unable to process word!!"), lcd);
              return false;
            }
          } else if(num_val != 0) {         // check if the parse was good
            stack.push(num_val);            // if it was: push num to the stack
          } else if(num_val == 0) {         // if zero it could be parsing a zero or it could have failed
            if(cur_word.indexOf("0") != -1) // if it didn't fail:
              stack.push(num_val);          // push to the stack
            else {                          // otherwise:
              error(F("Unknown word!!"), lcd);   // Unknown word error
              return false;
            }
          } else {
            error(F("Unknown word!!"), lcd);
            return false;
          }
        }
      }

      // Test printing the stack
      /*while(!stack.isEmpty()) {
        lcd.print(stack.pop());
        lcd.print(' ');
      }*/

      Serial.print(F("Function end!"));
      return true;
    }

And the caller method:

    void line_editor::RunProgram(SoftwareSerial &lcd) {
      Serial.println("Running program!!");
      // Move to top line
      currentLine = 0;
      while(!lineTableB.isEmpty()) {
        lineTableA.push(lineTableB.pop());
        // Serial.print(lineTableB.peek());
      }

      // Clear the string
      lcd.write(12);
      delay(5);
      lcd.write(128);

      // Joker language object
      Joker joker;

      QueueList<Function> PrintingWords;

      // Create the printing functions
      Function printWord;
      printWord.f_name = "BC"; // print "Beginning Card"
      printWord.f_run = [] (QueueList<float> &stack, SoftwareSerial &lcd) {
        if(stack.isEmpty()) {
          return false;
        }

        float num = stack.pop();
        lcd.print(num);
        lcd.write(13);

        return true;
      };
      PrintingWords.push(printWord);

      // Print the whole stack
      Function printStack;
      printStack.f_name = "AC"; // print "All Cards"
      printStack.f_run = [] (QueueList<float> &stack, SoftwareSerial &lcd) {
        while(!stack.isEmpty()) {
          lcd.print(stack.pop());
          lcd.print(' ');
        }

        lcd.write(13);

        return true;
      };
      PrintingWords.push(printStack);

      // Add all the functions
      joker.addWords(PrintingWords);

      // Run Program here...
      if(joker.runCode(lineTableA, lcd))
        Serial.println("Success!!");
      else
        Serial.println("Failed!!");

      // lineTableA.push(lineTableB.pop());

      Serial.println("Here!!");

      return;
    }

Sorry if I confused anyone. If there are any questions, then leave a comment, and I'll try to clear up the confusion. Any help would be appreciated.

**EDIT::ADDING FULL CODE:**
Here is a [LINK][1] to the rest of the code on github.

  [1]: https://github.com/blueOkiris/TASIC-PC/tree/master

Also, here is the rest of the Joker.cpp:

    void Joker::addWords(QueueList<Function> new_dict) {
      while(!new_dict.isEmpty()) {
        dictionary.push(new_dict.pop());
      }
    }

    bool Joker::queueListContains(String theWord, QueueList<Function> &list) {
      Serial.println("Finding word:");

      QueueList<Function> temp;

      while(!list.isEmpty()) {
        Function r = list.pop();
        temp.push(r);

        Serial.print(">> ");
        Serial.println(theWord);
        Serial.print(">> equals? ");
        Serial.println(r.f_name);
        delay(5);

        if(r.f_name.equals(theWord)) {
          while(!temp.isEmpty())
            list.push(temp.pop());
          return true;
        }
      }

      while(!temp.isEmpty())
        list.push(temp.pop());

      return false;
    }

    Function Joker::getDictionaryFunction(String theWord, QueueList<Function> &list) {
      QueueList<Function> temp;

      while(!list.isEmpty()) {
        Function theFunction = list.pop();
        temp.push(theFunction);

        if(theFunction.f_name.equals(theWord)) {
          while(!temp.isEmpty()) {
            list.push(temp.pop());
          }
          return theFunction;
        }
      }
    }

    void Joker::error(String message, SoftwareSerial &lcd) {
      lcd.write(12);
      delay(5);
      lcd.write(128);

      lcd.print(message);

      delay(2000);
    }

And the header:

    #pragma once

    class Joker {
    private:
      bool queueListContains(String theWord, QueueList<Function> &list);
      Function getDictionaryFunction(String theWord, QueueList<Function> &list);

    public:
      QueueList<float> stack;
      QueueList<Function> dictionary;

      void error(String message, SoftwareSerial &lcd);
      void addWords(QueueList<Function> new_dict);
      bool runCode(QueueList<String> lineTable, SoftwareSerial &lcd);
    };

body:
The short answer here is - It does not return because you have corrupted the stack.
The return address is pushed onto the stack as part of the function call.  If you overwrite (corrupt) that address the program cannot jump back to where it was (return).

So where is the cause of the problem?

Does `getDictionaryFunction(cur_word, dictionary)` ever return NULL or an invalid pointer?  The code tries to execute it anyway.  EDIT: What happens below when *theWord* is not matched or *list* is empty?  Actually I'm surprised this compiles, since there's a few paths where no value is returned.  (I'm no expert on the GCC AVR compiler, but what happens if we don't assign a return value at all?)

    Function Joker::getDictionaryFunction(String theWord, QueueList < Function > &list)
    {
        QueueList < Function > temp;

        while (!list.isEmpty())
        {
            Function theFunction = list.pop();
            temp.push(theFunction);

            if (theFunction.f_name.equals(theWord))
            {
                while (!temp.isEmpty())
                {
                    list.push(temp.pop());
                }
                return theFunction;
            }
        }
        // BAD-JUJU HAPPENS IF WE GET HERE
        assert(false);
    }

Coding style tip: except in trivial cases, it's good to only return from the bottom of your function.  Then the above never happens, and supposedly it's easier for the compiler to optimise.  NOTE: I'm unsure if `assert()` will even do anything on Arduino.  It's left as a marker to mean *Handle Error Here*.

    Function Joker::getDictionaryFunction(String theWord, QueueList < Function > &list)
    {
        Function dict_func = NULL;
        QueueList < Function > temp;

        while (!list.isEmpty())
        {
            Function theFunction = list.pop();
            temp.push(theFunction);

            if (theFunction.f_name.equals(theWord))
            {
                while (!temp.isEmpty())
                    list.push(temp.pop());
                dict_func = theFunction;
                break;
            }
        }
        assert(dict_func != NULL);  // This should never happen
        return dict_func;
    }

Coding style tip: WoRd CasE ~ lower_case, mixedCase, CapitalCase, UPPER_CASE.  I use lower case for all_variable_names, mixed case for functionNames(), capital case for ClassNames and StructureNames, and upper case for MACROS and CONSTANT_DEFINITIONS.  Pick a system, and stick to it absolutely.

Have you run out of memory - the stack could have hit the heap.
What sort of Arduino are you using?

On an Uno, with only 2k of RAM, you might need to make some scope-cuts.
Even on an Arduino Mega, you still only have 8k.

Maybe you can make use of a `freeMemory()` function.  This will give you an indication of the free space between the stack and the heap.  The AdaFruit version is below, but there are others too.

    int freeRam ()
    {
      extern int __heap_start, *__brkval;
      int v;
      return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }

It may be worthwhile reading their [page on Arduino memory usage][1].

So after having a browse through your code, I can't see any obvious problems.  Fix the `getDictionaryFunction()` so you know if it's failing.  Check to see if you're running out of RAM - you are making heavy use of it copying strings around, especially with that template class.

Maybe consider re-compiling the code on a workstation in GCC - it wouldn't take much, just change your serial outputs to printf(), and hard-code your input data (or read from a file).  That will enable easier debugging.

  [1]: https://learn.adafruit.com/memories-of-an-arduino/measuring-free-memory


message:
do digital input pins act as a positive or negative

I've gotten contradicting information on the subject.  Some say that digital input pins send out positive voltage, and if it goes to ground (for example) it reads LOW but if the pin is connected to power, it will read HIGH.  On the other hand, some say that the input pin is receiving voltage from either power (+5V) or ground (0V).  which one is it?

body: It's both, depending on whether or not the internal pullup has been enabled (`INPUT` versus `INPUT_PULLUP`). The pullup ties the input to the positive supply through a moderately large resistance, meaning that it is possible to source a small amount of current from the input pin.


body:
Digital pins sink or source current. They don't provide negative voltages. If the pin is set to `INPUT` then it is high impedance and will not "send out positive voltage".

However if you activate the internal pull-ups, as Ignacio said, then effectively the pin is connected to +5V via (approximately) a 50k resistor.


message:
Arduino to breadboard with LM35 temp sensor

I have moved the MCU of the Arduino to a breadboard using these steps https://www.arduino.cc/en/Main/Standalone then interfaced it with an LM35 temperature sensor to the ADC0. But I can't get proper values from the LM35. I think it's because of the Aref or AVcc. Both are just connected to +5?
Here is my code:

<!-- language: c -->

    float tempC;
    float reading;

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

    void loop()
    {
        reading = analogRead(0);
        tempC = (reading * 0.4882815) + 5;
        Serial.print(tempC);
        delay(1000);
    }

I get hex values and sometime high values. What to do with Aref and AVcc?

**EDIT:** I get values like these
€
Œ

body:
Check the `baud rate` of your serial monitor matches what you have set in your setup() function.  In the above code that is 9600.  If the baud rate is incorrect you typically get rubbish output in the serial monitor.

[![Serial Monitor set at 9600 baud][1]][1]

You may also want to change the Serial.print(tempC) to

    Serial.println(tempC,2);

To get some decimal places.

As for the circuit ~

[![Ricardo Sequeria's example Arduio & LM35][2]][2]

 - You don't need ARef connected.
 - The LM35 VCC should be connected to Arduino 5V
 - The LM35 GND to Arduino Gnd (any of them)
 - Finally LM35 signal (Vout) to Arduino A0.

  [1]: https://i.stack.imgur.com/7oANR.png
  [2]: https://i.stack.imgur.com/vs7wj.png


body:
> clearly it's not flashing every second.

Is it flashing about every .73 seconds? That would be the period you'd expect if you have a 22.000MHz crystal: period = (16/22 * 1.00 sec). (If so, that is a rather high over-clock rate for the chip but suggests just how hardy they really are.)

> I haven't bought any 16 MHz crystal. What will I do?

Buy a 16MHz crystal. That's the right fix. But you might (if I guessed correctly that you have a 22MHz crystal) - *might* - get away with trying a baud rate of (16/22) times your present baud rate, de-rating it to compensate for the clock rate. Be as precise as you can. You'll need to reprogram the chip with your Arduino board because the chip's bootloader expects a 16MHz clock.

Or, if it's not 22MHz, you could time a number of blinks (50 or 100), calculate the clock rate error, and re-calculate a baud rate the way I did above. Use a lower baud rate to start with; it is likely to be less affected by small timing errors.


message:
How to do run time calibration for MPU9250?

Does anyone know how to do the run time calibration for MPU9250 ?

body:
I used [this script][1] to calibrate the MPU6050, which is the same as the MPU9250 minus the digital compass. [This guide][2] explains how to calibrate the MPU9250's magnetometer.

  [1]: http://wired.chillibasket.com/2015/01/calibrating-mpu6050/
  [2]: https://github.com/kriswiner/MPU-6050/wiki/Simple-and-Effective-Magnetometer-Calibration


message:
Arduino Due interrupt is taken but not executed completely

I tried to build a simple l-meter with my arduino due. I programmed a simple frequency meter with one timer and one counter. The timer takes an interrupt each 10s, 100ms, 10ms and 1ms. But ones the interrupt is taken it is stopped and even a short `Serial.println("Hello World");` does not appear in the serial monitor of the arduino IDE. I don't know what I forgot.
Here is my code:

    #define voltage 26

    volatile uint32_t current_range = 10000;               //starts with highest range and decrements. longer measurements produce more precise results. measurements for small l values require 11.111ms
    volatile const double c_1 = 2533029590000000.0;        //constant value for l value calculation
    volatile double correction_value = 0;
    volatile boolean calib = true;
    volatile uint32_t counter_value = 0;

    void initCounter(){
        pmc_enable_periph_clk(ID_TC0);              //enable peripheral clock for TC0

        REG_TC0_CMR0 = TC_CMR_TCCLKS_XC0;           //External clock 0 connected to PB26 (Digital Pin 22)
        REG_TC0_CCR0 = TC_CCR_CLKEN;                //Enable clock
    }

    void initTimer(){
        pmc_enable_periph_clk(ID_TC1);              //enable peripheral clock for TC1

        REG_TC0_CMR1 = TC_CMR_TCCLKS_TIMER_CLOCK1;  //42MHz clock
        REG_TC0_IER1 = TC_IER_CPCS;                 //Enable compare RC interrupt
        REG_TC0_IDR1 = ~TC_IDR_CPCS;                //Enable compare RC interrupt (disbale interrupt = 0)
        REG_TC0_CCR1 = TC_CCR_CLKEN;                //Enable clock

        NVIC_EnableIRQ(TC1_IRQn);                   //Enable interrupt in nested vectored interrupt controller NVIC (IRQN number = TC number * channels + channel number)
    }

    double calc_l(uint32_t CV){
        double freq = (double)CV / ((double)current_range / 1000.0);
        freq = freq * freq;

        return c_1 / freq;
    }

    void calibrate(){
        Serial.println("---Calibrating... shorten inputs then press enter---");
        while(!(Serial.available() == '\n'));
        Serial.print("Start calibration\n");
        initCounter();                              //initialize counter
        initTimer();                                //initialize timer

        REG_TC0_RC1  = 0x1908B100;                  //RC = 420.000.000 to run 10.000ms

        REG_TC0_BCR = TC_BCR_SYNC;                  //reset and start timer and counter simultaneously
    }

    void measure(){
        calib = false;

        //Serial.println("---Measure... connect inductivity then press any key---");
        //while(!(Serial.available() > 0));
        initCounter();                              //initialize counter
        initTimer();                                //initialize timer
        REG_TC0_RC1  = 0x1908B100;                  //RC = 420.000.000 to run 10.000ms

        REG_TC0_BCR = TC_BCR_SYNC;                  //reset and start timer and counter simultaneously
    }

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

        pmc_set_writeprotect(false);                //disable writeprotect for pmc
        pinMode(13, OUTPUT);
        pinMode(voltage, OUTPUT);                   //set digital pin 26 as output
        digitalWrite(voltage, HIGH);                //set digital pin 26 HIGH
        delay(1000);                                //wait 1 second to get circuit working

        calibrate();
    }

    void loop() {
        analogWrite(13, 25);
        delay(100);
        Serial.print(REG_TC0_SR1);
        Serial.print(";");
        Serial.print(REG_TC0_CMR1);
        Serial.print(";");
        Serial.print(REG_TC0_IER1);
        Serial.print(";");
        Serial.print(REG_TC0_IDR1);
        Serial.print(";");
        Serial.print(REG_TC0_CCR1);
        Serial.print("\n");
    }

    void TC1_Handler(){

        uint32_t SR = REG_TC0_SR0;                    //save status register
        uint32_t CV = REG_TC0_CV0;                    //save counter value

        if((SR & TC_SR_CLKSTA) == TC_SR_CLKSTA){      //check whether counter clock is enabled
            if((SR & TC_SR_COVFS) == TC_SR_COVFS){      //check whether counter overflow accured
                switch(current_range){                    //check current range. decrement until smallest range is reached. then print error
                    case 10000: REG_TC0_RC1  = 0x280DE80;                   //RC = 42.000.000 to run 1.000ms
                                current_range = 1000;
                                REG_TC0_BCR  = TC_BCR_SYNC;
                                break;
                    case 1000:  REG_TC0_RC1  = 0x401640;                    //RC = 4.200.000 to run 100ms
                                current_range = 100;
                                REG_TC0_BCR  = TC_BCR_SYNC;
                                break;
                    case 100:   REG_TC0_RC1  = 0x668A0;                     //RC = 420.000 to run 10ms
                                current_range = 10;
                                REG_TC0_BCR  = TC_BCR_SYNC;
                                break;
                    case 10:    REG_TC0_RC1  = 0xA410;                      //RC = 42.000 to run 1ms
                                current_range = 1;
                                REG_TC0_BCR  = TC_BCR_SYNC;
                                break;
                    case 1:     //Serial.println("Error: l value out of range!");
                                REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                                REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                                break;
                }
            } else {
                if(calib){
                    if(CV < 10){
                        //Serial.println("Error: wrong calibration value!");
                        REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                        REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                    } else {
                        //correction_value = calc_l(CV);
                        measure();
                    }
                } else {
                    if(CV < 10){                           //check if counter value is below 10. then l value is to high to get accurate results
                        //Serial.println("Error: l value out of range!");
                        REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                        REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                    } else {                               //l value in nH;
                        counter_value = CV;
                        //Serial.print(calc_l(CV) - correction_value);
                        //Serial.print(" nH; ");
                        //Serial.print(CV);
                        //Serial.print(" ticks in ");
                        //Serial.print(current_range);
                        //Serial.println("ms.");
                        REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                        REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                    }
                }
            }
        } else {
            REG_TC0_CCR0 = TC_CCR_CLKEN;
            REG_TC0_BCR  = TC_BCR_SYNC;
        }
    }

It would be very nice if someone could help me with this.

body:
Maybe I'm dense, but I don't understand why most of the config code is in the ISR.  If the system is getting bound up there, I'd move much of it out and try to simplify it as much as possible, maybe saving only the counter value and the fact that the timer triggered on interrupt, and saving the overflow value if it overflowed.  Then, outside the ISR, on the reporting timescale, I'd check that there was valid data and report or reconfigure as needed.

    int validReading = 0;
    uint32_t measuredCount;
    int overflowed =0;

    void TC1_Handler(){
        measuredCount = REG_TC0_CV0;
        if((SR & TC_SR_COVFS) == TC_SR_COVFS){  //counter overflow occurred
           validMeasurement=0;
           overflow=1;
        else {
           validMeasurement = 1;
           // either reset counter and clock or stop handling interrupts
        }
     }

     loop(){
       ...
       if (validReading) { // report
          ...
       } else {
       if (overflowed ) { // shorten sampling time, calibrate, and initialize
          ...
       }
       if ( measuredCount < 10 ) { // lengthen sampling time?
          ...
       }
       // calibrate and reinitialize
     }


message:
Turn on a light when there is an input

I am using the pin 4 as an OUTPUT and pin 8 as an INPUT to turn on/off the light, but for some reason it is not working. Light is on all the time, but when I try to input something it gets brighter and doesn't turn off when I don't give anything to pin 8.

LED is connected to pin 4 with a 220 R, and the other side to GND. When pin 8 is connected to 5V pin then the light should come on, and off when I disconnect them.

Here is the code:

    void setup()
    {
      Serial.begin(9600);
      pinMode(4, OUTPUT);
      pinMode(8, INPUT);
    }

    void loop()
    {
       bool on = digitalRead(8);
       if(on)
       {
         digitalWrite(4, HIGH);
       }
       else
       {
         digitalWrite(4, LOW);
       }
    }

What am I doing wrong?

body:
Use input with pullup on pin 8 and a button to ground (GND). See below:

    const int ledPin = 4;
    const int buttonPin = 8;

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

    void loop()
    {
       digitalWrite(ledPin, digitalRead(buttonPin));
    }

Using the pin as input and disconnecting is not the same as GND. The pin is floating. By using the internal pullup resistor the pin is HIGH when the button is not connected to GND.


message:
Programming an ATtiny85

Recently I ordered some ATtiny85's from [Jameco][1], and I've been trying to upload code to them through an Arduino Uno, following the instructions from [this video on YouTube][2]. I've been getting a lot of unexpected errors and I am now wondering if the chips I bought are the problem. Here are the specs from the Jameco website:

> Flash (Kbytes): 8 Kbytes
>
> Pin Count: 8
>
> Max. Operating Frequency: 20 MHz
>
> Power Supply: 2.7 - 5.5V
>
> Operational Range: Industrial (A) (-40°C to 85°C)
>
> CPU: 8-bit AVR
>
> Number of Touch Channels: 3
>
> Hardware QTouch Acquisition: No
>
> Max I/O Pins: 6
>
> Ext Interrupts: 6
>
> USB Speed: No
>
> USB Interface: No

Does the "USB Speed: No; USB Interface: No" mean these aren't programmable by my set up? Or is there is anything else I should know about these chips? Do I need to get new ones that are different?

  [1]: http://www.jameco.com/webapp/wcs/stores/servlet/Product_10001_10001_2151312_-1
  [2]: https://www.youtube.com/watch?v=9LjfkjwMqXI

body:
Before you panic (try not to panic) and buy new chips, test the existing ones. See my [page about detecting chip signatures](http://www.gammon.com.au/forum/?id=11633) which has links to [code on Github](https://github.com/nickgammon/arduino_sketches) for a sketch you can run on your Uno, to test the ATtiny85.

[![Chip detector wiring][1]][1]

---

You can also upload code from a .hex file (which the IDE produces) by using a different sketch (same code link) from [this page about a hex uploader](http://www.gammon.com.au/uploader) and wiring like this (you also need an SD card adapter):

[![Chip programmer][2]][2]

---

The first sketch and wiring should at least confirm your chips are OK. The second one is an alternative way of programming them.

  [1]: https://i.stack.imgur.com/OMHlr.jpg
  [2]: https://i.stack.imgur.com/7JMKQ.jpg


message:
ATMega328P-PU not working

I bought some material on the net to start working with Arduino. I didn't want to buy an Arduino, since it costs a bit too much IMHO, so I bought an ATMega328P-PU, and made an Arduino on a breadboard. However, when I use my USBasp to program it it says that he can't set sck period (settings are: Arduino Uno as Board, USBasp as Programmer). It says that it has loaded the bootloader/program anyway, so I tried to go on and ignore it. The blink program can be loaded via programmer, but it doesn't blink (I'm using a small lamp, connecting it directly to 5V and ground works). Here I describe the circuit:

* First Atmega Pin, Arduino Reset -> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -> Ground (not GND pin);

* 1st pin, Arduino Reset -> also to USBasp RST;

* 7th pin, Arduino VCC -> directly to 5V (and USBasp VCC);

* 8th, GND -> directly to Ground (and USBasp GND);

* 9th, XTAL -> to one pin of the 16MHz Crystal Oscillator, and to 22 pF capacitor, which connects to ground (not the pin);

* 10th, XTAL -> exactly as above, but it's connected to the other pin of the same crystal;

* 17th, digital 11 -> USBasp MOSI;

* 18th, dig 12 -> USBasp MISO;

* 19th, dig 13 -> USBasp SCK, and to the lamp whose other pin goes to ground (neither pin nor direct works), but the lamp needs to be disconnected while loading programs to prevent errors (target not responding);

* 20th, AVCC, and 21st, AREF -> directly to 5V;

* 22nd -> directly to ground (not pin).

body:
> The blink program can be loaded via programmer, but it doesn't blink (I'm using a small lamp, connecting it directly to 5V and ground works).
>
> 19th, dig 13 -> USBasp SCK, and to the lamp whose other pin goes to ground (neither pin nor direct works), but the lamp needs to be disconnected while loading programs to prevent errors (target not responding);

The lamp needs to be low power (< 20 mA) to work this way. If it uses more power you will burn the MCU pin.

Use a LED and a resistor instead. Or at least use a voltmeter.

> 21st, AREF -> directly to 5V;

This is not a good idea. Should be capacitor to ground. See for instance [Uno schematics][1].

Cheers!

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf


body:
> First Atmega Pin, Arduino Reset -> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -> Ground (not GND pin);

So it's permanently in RESET mode then? How can it ever do anything if you're holding it in RESET all the time?

RESET should be pulled UP by the resistor, not DOWN.