message:
Quadrature Encoder:Interrupts: Reset Count

I'm working on a quadrature encoder(with a 500ppr codewheel) with a Channel A, B and an Index pulse output.  Using an Arduino Mega I'm counting the number of pulses on Channel A on the rising edge. The code for counting pulses on channel A using an interrupt is straight forward enough with plenty of sources and examples out there to work with.

I've used the the code below to the count the pulses(in an increasing manner). What I'm trying to figure out is how I can reset the overall count using a second interrupt. The second interrupt is invoked when the Index channel pulses high.So in another words when the index channel pulses to indicate a full rotation on the code wheel the main count will reset to zero

    #define CHA 2
    #define CHB 3
    #define CHI 19

    volatile int count = 0;
    volatile byte INTFLAG1 = 0;

    void setup()
    {
      pinMode(CHA, INPUT);
      pinMode(CHB, INPUT);
      pinMode(CHI,INPUT);

      Serial.begin(9600);
      Serial.println(count);

      attachInterrupt(0, flag, RISING);

     }

    void loop()
       {

           if (INTFLAG1)
                 {
                   Serial.println(count);
                   INTFLAG1 = 0; // clear flag
                 }

        }

    void flag()
        {
           INTFLAG1 = 1;
           if (digitalRead(CHA) && !digitalRead(CHB))
                   {
                    count++ ;
                   }
         }

Is it possible to implement the reset of the main pulse count with a second interrupt as described?

From what I've read interrupts work at the same level of priority- so I'm thinking there might be a problem here to implement this approach as the interrupts would have to be nested

Any help is appreciated if anyone has done anything like this using interrupts or can point me in  the right direction.

body:
> Is it possible to implement the reset of the main pulse count with a
> second interrupt as described?

Yes, and it's quite straightforward. Your index signal goes to pin 19,
which is interrupt 4 on the Mega, so you can simply

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

    attachInterrupt(4, reset, RISING);

in `setup()`, where `reset()` is a function that resets the counter:

    void reset()
    {
        count = 0;
    }

> I'm thinking there might be a problem here to implement this approach
> as the interrupts would have to be nested

In general you do not want to nest interrupts. If an interrupt is being
serviced when a second interrupt fires, the second one will just wait
for the first one to finish. This approach works fine as long as you do
not have interrupt handlers that take too long to execute.


sender: user

message:
NeoPixel Blink/Glitch

I'm having this weird effect where my NeoPixel will blink/glitch after every cycle of a fading sketch. I'm not certain whether the issue is hardware or in my code. The blinking only occurs during the if statement portion of the code and not during the else statement which blinks red. I have tried multiple sources of power, 5V 2amp, 9V 1 amp, 12V 1amp and a Mac Usb and the problem persists on each power supply.

Any suggestions or ideas would be greatly appreciated.

    #include <Adafruit_NeoPixel.h>
    #include <DistanceGP2Y0A21YK.h>

    #define PIN 6
    #define PIXEL 16

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL, PIN, NEO_GRBW + NEO_KHZ800);

    DistanceGP2Y0A21YK Dist;
    int distance;
    int R = 0;
    int G = 0;
    int B = 0;

    void setup() {
      strip.begin();
      strip.show();
      strip.setBrightness(127);

      Serial.begin(9600);
      Dist.begin(A0);
    }

    void loop() {
      distance = Dist.getDistanceCentimeter();
      Serial.print("\nDistance in centimers: ");
      Serial.print(distance);
      delay(2); //make it readable

      if (distance > 10) {

        for (R && G && B; R < 150 && G < 150 && B < 150; R++ && G++ && B++) {
          for (int i = 0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, strip.Color(R, G, B));
            strip.show();
            delay(1);
          }
          delay(2);
        }

        // fade off
        for (R && G && B; R > -1 && G > -1 && B > -1; R-- && G-- && B--) {
          for (int j = 0; j < strip.numPixels(); j++) {
            strip.setPixelColor(j, strip.Color(R, G, B));
            strip.show();
            delay(1);
          }
          delay(1);
        }

      } else {

        for (int j = 0; j < 256; j++) {
          for (int i = 0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, strip.Color(255, 0, 0));
            strip.show();
          }
          delay (1);

          //blink off
          for (int j = 64; j > 0; j--) {
            for (int i = 0; i < strip.numPixels(); i++) {
              strip.setPixelColor(i, strip.Color(j, 0, 0));
              strip.show();
            }
            delay (2);
          }
        }
      }
    }

sender: assistant

body:
    for (int j = 0; j < 256; j++) {

      ...

      //blink off
      for (int j = 64; j > 0; j--) {
        ...

Notice that you are re-declaring the variable `j`.


message:
Why do I get negative voltages for a PWM waveform?

I used my Arduino Uno's pin 3 to generate a [PWM][1] output. The code is:

    void setup() {
      // Put your setup code here, to run once:
    }

    void loop() {
      analogWrite(3, 180);
    }

I connected the output directly with a oscilloscope.
And the output waveform is shown below:

[![PWM waveform][2]][2]

I found it's weird that the minimum voltage is negative! And with the duty cycle increasing, both the maximum voltage and minimum voltage decrease.
Why does it behave in such a way?

  [1]: http://en.wikipedia.org/wiki/Pulse-width_modulation
  [2]: https://i.stack.imgur.com/5tVdR.jpg

body:
At first you had the scope AC (Alternating Current) coupled.  Then you switched it to DC (Direct Current) coupled.

AC coupling is used to remove the DC component of a signal.  It places a large capacitor between the probe and the internal amplifier.  This is used, for instance, if you want to see a small signal with a large DC offset.  But it can also attenuate and / or alter signals that are low in frequency.

When a PWM signal is AC coupled to an oscilloscope, an interesting phenomenon occurs.  As the duty cycle goes from a minimum (almost always off) to a maximum (almost always on) the DC component of the PWM signal changes.  Since the DC component is blocked by the AC coupling, the PWM signal appears to move lower on the screen as the duty cycle increases.

DC coupling is where there is no coupling capacitor between the probe and the internal amplifier.  Everything comes through.  For digital electronics where the signal travels a small distance from 0 to 5 volts or from 0 to 3.3 volts, this is the best way to use the scope.


message:
How to send data from arduino to Temp Controller for setting temp?

I send data from arduino by method following.
Configure the value : byte message[ ];

    #include <SoftwareSerial.h>
    #define RX 2
    #define TX 3
    int incomingByte = 0;

    SoftwareSerial mySerial(RX, TX);

    void setup()
    {
      pinMode(5, OUTPUT);

      Serial.begin(9600);
      mySerial.begin(9600);
    }

    void loop()
    {
      incomingByte = Serial.read();

      if (incomingByte == 's')
      {
        digitalWrite(5, HIGH);
        byte message[] = {0x01, 0x06, 0x00, 0x01, 0x02, 0x58, 0xD8, 0x90} ;
        mySerial.write(message1, sizeof(message1));
      }
    }

It works. But I want to input from "Serial monitor" to set the temperature.
It does not work when input from "Serial monitor".

body:
You're not writing any data to incomingByte and you're not detecting if data is sent towards the Arduino over serial.

You should change your `void loop()` into this:

    void loop(){

      //Detects if something is sent over serial.
      if(Serial.available() > 0){

        //reads the byte and puts it into the incomingByte variable
        incomingByte = Serial.read();

        //below is your old code
        if (incomingByte == 's') {
          digitalWrite(5, HIGH);
          byte message[] = {0x01, 0x06, 0x00, 0x01, 0x02, 0x58, 0xD8, 0x90} ;
          mySerial.write(message1, sizeof(message1));
        }
      }
    }

When you're using the serial monitor to send data towards the Arduino, also make sure the baudrate you use is the same as the Arduino's. In this case you set your baudrate to 9600 `Serial.begin(9600)`.


message:
Which pins of an Arduino UNO can be used as Tx and Rx pins for connecting to GSM GPRS SIM 900A

I am using Arduino UNO and SIM 900A. Pins 0 and 1 are used as TX and RX. Is it possible to use any other pins?

body:
The best choice for serial communications is obviously the HardwareSerial object, `Serial`, on pins 0 & 1.  However, it is really dedicated to the USB connection (via the onboard Serial-to-USB adapter).  There are ways to connect other devices to these pins, but it is an advanced topic, and should not be attempted by beginners.

The second best choice would be pins 8 & 9, because [AltSoftSerial](https://github.com/PaulStoffregen/AltSoftSerial) requires those pins.  It is very efficient and reliable.

After that, any other pins can be used with one of these two software serial libraries:

[NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial) is less efficient than AltSoftSerial, but *much* more efficient than SoftwareSerial.  It only supports baud rates 9600, 19200 and 38400, but it does support simultaneous TX and RX.  I maintain this library.

If you must use a different baud rate, [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) is the last choice.  It blocks interrupts for long periods of time and can interfere with other libraries.  It cannot transmit and receive at the same time.


message:
I have four servos connected to an arduiono uno and I cannot control them

[![Image of my setup][1]][1]I am making a simple bipedal robot. I have four 9g servos connected to my uno. Whenever I try to even do the simplest command, like move right foot 45 degrees it does not work properly. I have tried on my second Uno and i have the same result.

My program for testing the servos:

    #include <Servo.h>

    Servo myservo;

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

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

Each servo wire is attached to a breadboard where they all share power and ground from the arduino. Each servo wire then has another wire going to pins 3,5,6 and 9.

Does anyone know what the problem is and what I can do? Thanks

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

body: An Arduino is not capable of powering four servos. Power them externally, but make sure the ground of the Arduino and servos is connected.


body:
As others have said, the Arduino cannot drive 4 servos - my experience is that it can have problems powering one if you try to move it too often due to the voltage drop caused by the high current consumption.  When you move a servo the power consumption rises considerably.  A large (220uF or more) capacitor near he servo can help, but even so, by far the best option is to supply the servos from a separate supply.

If the Uno resets when you try to move the servos (especially multiple times per second) then the power supply is most likely your culprit.


message:
Serial communication between arduino and raspberry pi works once, then stops working

I'm using a Arduino Uno Rev 3 connected over usb to a Raspberry Pi Modell B+ running Rasbian.

Here ist the arduino code:

    int input = 0;
    String command = ""; // beinhaltet den aktuellen befehl
    int Action = 1;

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

    void loop() {
      if (Serial.available() > 0)
      {
            input = Serial.read();
        char currentChar = input;

        if(currentChar  == '!') // frage nach trennzeichen
        {
          Serial.println(command);
          //Serial.write(Action);
          Action = command.toInt();

          command = ""; // befehl wieder leeren
        }else
        {
          command = command + currentChar ; // falls noch kein trennzeichen vorhanden, erweitere kommando
        }
        }
    }

Here is the Raspberry Pi code (in python)

    import serial
    from time import sleep as sleep
    ser = serial.Serial('/dev/ttyACM0',9600)
    s = [0]
    while True:
            ser.write(b'2!')
            a =  ser.read(1)
            print a
    sleep(2)

It always works if once after the code was uploaded to the arduino, but if I stop the script on the pi and restart it it stops working. What is the problem here?

body:
"It always works if once after the code was uploaded to the arduino...."
Whenever you you reset the arduino the link between the arduino and the rasperry pi is broken momentarily thus causing the code on the raspberry pi to hang/ffreeze and not responding/ showing any valid results.

Try giving a keyboard interrupt by ( Ctrl + Z ) and restart the python script and that should work just fine!


message:
Atmega8 with Arduino bootloader - wrong serial characters

I recently flashed bootloader of Arduino to Atmega8. Unfortunately I stumbled on a problem I can't solved.

I am testing SerialEvent example on Atmega8. I modified it but started debugging it on my code (I think the same problem stops SerialEvent example from working).

I think the Atmega8 reads the characters sent through serial wrongly. That's why *SerialEvent* 'if' condition doesn't work also. Because it never gets '\n' symbol (it receives it but wrongly interprets it).

    boolean prevState = true;
    boolean OnOff = false;
    boolean stringComplete = false;
    String inputString = "";
    String OnString = "on\n";
    String OffString = "off\n";

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

        while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
        }

        // reserve 200 bytes for the inputString
        inputString.reserve(200);

        DDRD |= 0b00001100;
        PORTD |= _BV(PD2);

        // synchronization info for RPi
        Serial.println("ARD - OK\n");
    }

    void loop() {
        // turn on
        if (OnOff == true && prevState == false){
            PORTD |= _BV(PD2);
            prevState = OnOff;
        }
        // turn off
        if (OnOff == false && prevState == true){
            PORTD &= ~_BV(PD2);
            prevState = OnOff;
        }

        if (stringComplete) {
            Serial.println(inputString);
            // clear the string:
            inputString = "";
            stringComplete = false;
        }
    }

    void serialEvent() {
        while (Serial.available()) {
             // get the new byte:
            char inChar = (char)Serial.read();
            // add it to the inputString:
            inputString += inChar;
            // if the incoming character is a newline, set a flag
            // so the main loop can do something about it:
            Serial.println(inputString);
            if (inChar == '\n') {
                stringComplete = true;
                Serial.println("test\n");
            }

            if (stringComplete && inputString.equals(OnString)){
                OnOff = true;
                Serial.println("Turning on.\n");
            }
            else if (stringComplete && inputString.equals(OffString)){
                OnOff = false;
                Serial.println("Turning off.\n");
            }
        }
    }

I tested a lot of behaviors. Below I attach one of the tests from Realterm:

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

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

First I reset the board - it responded with 'ARD - OK\n' - expected behavior.
Then I sent 'on\n' and it responded with two lines but the characters aren't the same as 'on\n'.
Then I sent 'test123\n' but once again got wrong characters.
It prints multiple lines because it sends the string in which it accumulates the data every time *SerialEvent()* is fired.

Also sending for example variabl *OnString* works ok.

I really don't know why is it acting like that... Help would be appreciated :).

body:
Ok I found a solution (rather workaround).

I uploaded the same program to Arduino Uno. It worked perfectly. I transplanted the Atmega328 from Uno to breadboard. Still worked BUT the Atmega328 is using external 16Mhz crystal (which I added to the breadboard).

So what if I uploaded bootloader for 16Mhz external crystal on Atmega8?
It makes it work properly.

So in short:
Atmega8 with 8Mhz internal oscillator doesn't work properly.
Atmega8 with 16Mhz external oscillator works properly.

Don't know why does it make it work. If anyone can think of a reason I would be glad to know it. Thanks for all your help.


message:
Powering 3.3V Arduino and 12V peripherals from single 12V power supply?

Given:

- I have some home alarm peripherals (motion detectors, glass break sensors) which operate at 12V and draw a nominal current of 20mA when in alarm state.
- I have a Particle Photon (3.3V logic level) which will accept up to 5.6V on its VIN pin.
- I have a 12V @ 2A switching power supply.

Can someone describe to me an efficient circuit which would allow me to power all of the peripherals @ 12V and the Arduino (Particle Photon) at 3.3ishV?

I have on hand an LM7805 linear regulator, which I believe will work, but will be inefficient. I also have on hand a DC-DC step down converter (4.5V-28V IN, 0.8V-20V OUT @ 2A) but I am a novice and don't know how to use it for the scenario described here.

body:
@Majenko remarked:

Put 12V on the IN, connect the OUT to a volt meter, twiddle the knob till it reads 5V. Disconnect the volt meter. Connect it to the VIN of your photon.

@loopforever added:

For the 3.3V Arduino (Photon) current draw will not exceed 500mA. For the 4x 12V peripherals, if all were in an "alarm" state simultaneously, current draw will not exceed 110mA.

@Dampmaskin added:

Dropping 8.7V at 500mA wastes 4.35W so OK you're right, that is inefficient. A buck converter is probably the best approach then

@SDsolar added:

If you use a screw-terminal barrier block you can have both 12V and your lower voltages available at the same time


message:
What is the proper way to implement PID?

I'm having some trouble conceptualizing how to go about implementing PID into my drone. There are a few ways I'm thinking about implementing the pipeline:

* Having one PID Object for each of the six motors.
* Having one PID Object for each axis.

How I would implement PIDs on a per-motor basis?

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

How I would implement PIDs on a per-axis basis?

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

I'm guessing that the second one will be the best course of action, as it can all be put into its own loop, where the PID data will be available on-demand, as opposed to calculating it on the spot. It is object-oriented, and runs in the background.

The first one has its appeals, too. It eliminates some of the calculations needed in order to find the actual value. It is procedural, and very straightforward and performs on the spot.

What do you guys think?

  [1]: https://i.stack.imgur.com/wn221.png
  [2]: https://i.stack.imgur.com/suknF.png

body:
Each unique variable you want control over should have a single pid loop, and each loop should only ever stretch across one "order" of time.

For example, to control the craft's roll rate, you should have one PID loop that takes the target roll rate and outputs the controlled roll torque value, which gets transformed somehow into motor accelerations. The trig weights for that part can be precalculated so it doesn't have to happen at runtime.

To control the craft's roll rotational position, you would need one PID loop that takes the target roll position and outputs the target roll velocity, that target roll velocity then becomes the setpoint for the roll-velocity pid loop.

I don't see why each motor would need its own PID loop unless you are measuring the actual thrust each motor produces. If you did measure each motor's thrust their pid loops would still come after the target torque value were calculated. The target torque PID calculations don't need to know about what motors exist or where they are located.

I may not be understanding the intention of your diagrams or what "order" the PID loops are in, so feel free to comment with clarifications. This is complicated stuff.

Its also worth noting that the actual implementation pid often has some features that don't appear in theoretical pid loops like integral windup prevention. You also need a way to either call them at exactly the same interval each time, or accurately keep track of the time delta since the last update. You may want to take the derivative of the process variable only, not the error, so you don't observe setpoint changes in the D term; you could also "outsource" the derivative term if you IMU has a better calculation of it (like the raw gyroscope values).


body:
I will give a generic C-answer to it:

1) figure out what parameters / variables involved in a PID control loop;
2) structure those parameters / variables into a struct;
3) pass that struct to a common set of PID algorithm.
4) done.

with this approach, the algorithm is only implemented once and the can be used / reused as many times as you want.


message:
problem with bitwise OR

I have this code, in which I try to "glue" four bytes in order to construct an unsigned int. I shift left the bytes and "add" them using the OR operator.

    unsigned long number1;
    unsigned long number2;
    unsigned long number3=0;

    byte byte0 = 1;
    byte byte1 = 40;
    byte byte2 = 107;
    byte byte3 = 238;

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

    void loop(){
      number1 = byte1 <<8 | byte0 ;  //(=10.241 O.K.)

      //(should be 4.000.000.001, it produces 10.241)
      number2 = byte3 <<24 | byte2 <<16 | byte1 <<8 | byte0;

      //(should be 4.000.000.001, it produces 4.016.777.217)
      number3 = number3 | byte3;
      number3 = number3<<8;
      number3 = number3 | byte2;
      number3 = number3<<8;
      number3 = number3 | byte1;
      number3 = number3<<8;
      number3 = number3 | byte0;

      Serial.print("number1 = ");Serial.println(number1);
      Serial.print("number2 = ");Serial.println(number2);
      Serial.print("number3 = ");Serial.println(number3);
      Serial.println(" ");
    }

The problem is that the OR operator applies only to `byte1 <<8 | byte0` and ignores the rest. That is number1 and number2 appear to have the same value *(10241)*.

I also tried "adding" them up separately, as shown with number3, but it also produces a wrong result as well.

I tried the same code in python, and it works fine.

    byte3, byte2, byte1, byte0 = 238, 107, 40, 1
    print byte1 <<8 | byte0
    print byte3 <<24 | byte2 <<16 | byte1 <<8 | byte0

    number3 = 0;
    number3 = number3 | byte3;
    number3 = number3<<8;
    number3 = number3 | byte2;
    number3 = number3<<8;
    number3 = number3 | byte1;
    number3 = number3<<8;
    number3 = number3 | byte0;
    print number3

So, the question is:

Why both number2 and number3 produce a false result?

body:
Correction from another answer for number2:

    number2 = (unsigned long)byte3 <<24 | (unsigned long)byte2 <<16 | byte1 <<8 | byte0; // = 4.000.000.001

And in the first round of loop number3 is correct, all others are wrong as number3 holds a result from previous loop.

      number3 = byte3; // all magic lays here
      number3 <<= 8;
      number3 |= byte2;
      number3 <<= 8;
      number3 |= byte1;
      number3 <<= 8;
      number3 |= byte0;


message:
Record a duration of time as data

I have very little experience with the Arduino and am hoping that you may provide me with some helpful info.

I would like to build a device that records time spent on a project.  I envision the main Uno with a switch, microSD breakout, and an LED to indicate its tracking your time. When setup the user could simply press the switch/button (light up the LED to show you're "working") and while you plug away on your day job the Uno will track the time between switch on and switch off. Then at the time the switch is turned off, have the Uno write a simple data file containing the total time spent on that activity.

I have a basic idea of what I need hardware wise, but am hoping to find insight to the backbone of software programming to make something like this begin to take shape.

body:
There are two ways of doing this:

 1. Using a Real Time Clock (RTC) chip, which you connect to your Arduino.
 2. Using the `millis()` function of the Arduino.

Needless to say, they aren't completely the same in efficiency. An RTC is a dedicated chip for measuring time and is incredibly accurate. The `millis()` is not as accurate, but still pretty accurate.

So, it really depends on how accurate you want it to be. You can make `millis()` more accurate through code, which isn't something difficult. But an RTC always works fine and is always more accurate, if only by milliseconds. In general: need to time long durations, an RCT is probably better.

Regardless of the method you will use, you can convert the data into the desired format so it can be read easily when looking at the files on the SD card. So, for example: you can write code that simply checks how many hours fit in the saved time data, and after that you can check the minutes and even after that you can check for the last seconds. For this you're going to need [modulo](https://www.arduino.cc/en/Reference/modulo).

Here are some resources you might want to check out:

 - An Arduino tutorial for an RTC chip: http://playground.arduino.cc/Main/DS1302
 - Official documentation on `millis()`: https://www.arduino.cc/en/Reference/Millis


body:
> An RTC is a dedicated chip for measuring time and is incredibly accurate.

its accuracy will depend on the crystals used.  a temperature controlled one will be very accurate. But a regular one will just be as accurate as the crystal used, like a mcu.

> The millis() is not as accurate, but still pretty accurate.

stock millis() undercounts. however, that undercounting can be mitigated via code. for long durations, the undercounting can be practically (but not completely) eliminated.


message:
which is the number of bits in a float variable

Since the maximum value of a float variable is 3.4028235E+38, shouldn't it represented with 128 bits instead of 32? *(2^128=3.4028235E+38)*.

body:
No, it is not integer, so you cannot calculate it that way. It have floating point (not in fixed place).

It is stored as

**1.significand x 2 ^ exponent.**

It takes one bit for sign (+/-), 23 for significand (0 is not stored it is implicit) and 8 more for exponent.

Because of this, you have fixed precision (number of significant digits) for very large numbers and also for numbers which are close to zero.

You have it all explained here:
https://en.wikipedia.org/wiki/Single-precision_floating-point_format


body:
No, because IEEE 754 floats use a decimative compressed format. 64-bit floats allocate 1 bit to the sign, 11 bits to the exponent, and 52 bits to the mantissa, 32-bit floats allocate 1, 8, and 23, and so on.

You convert from it by adding an offset to the exponent, multiplying the mantissa by the exponent to the power of 2, and then applying the sign.


body:
Just adding a little piece of information to the previous answers: it's
worth noting that a float can represent _exactly_ all integers from
−224 to +224 (i.e. ±16777216).

The next integer, namely 16777217, is not representable as a float. A
calculation giving this value would suffer a rounding error.


body: Another way of looking at it is that a float variable is actually a list of 4294967296 numbers. That's far less than the possible range of numbers and fractions that a float can represent, so only a subset of the numbers are actually represented. Any number you try and use that's not in that list of numbers is rounded to the nearest one.


message:
Bidirectional communication between Arduino and Raspberry Pi over USB possible?

Is it possible to have bidirectional communication betweeen an Arduino Uno Rev 3 and a Raspberry Pi Modell B+ running Rasbian? They're connected ofer USB, and it would be good if I could use Python on the Pi.

body:
Yes.  The Arduino Uno implements a serial protocol inside the USB signal using hardware.  This is how it is built.  The Linux side is a bit more complex as there are many USB protocols.  Here is a [howto][1] which talks about the Linux side of the Arduino / Linux connection.

To be clear, Rasbian is a derivative of Linux.

  [1]: http://playground.arduino.cc/Interfacing/LinuxTTY


body:
Yes, it is possible to have a USB serial communication between a raspberry pi and an Arduino. And it is  much more easier when using Python on the raspberry pi.

Python has a serial library within it's standard library which you can import on the raspberry pi and then use it to send or receive data to/from the Arduino or the raspberry pi.(Just connected via USB cable).

[Here is the link][1] for a very similar requirement on YouTube.

  [1]: https://www.youtube.com/watch?v=9Pde26llc7s


message:
Is it possible to reprogram an atMega328 chip inside of a pcb?

I have already soldered the atMega chip with instructions onto the perfboard, and I may need to make changes to it. Is it possible to reprogram it without taking it out of the PCB?

body:
I'm assuming you're trying to program using an AVR programmer.

Yes, it's very likely you'll be able to do that. You need to connect the AVR programmer to the correct MCU pins (Sck, Si, So and Rst), including ground and vcc... as you would do with the chip by itself.

If you have any othe SPI device connected to the same pins, make sure it's not enabled - that might be as simple as having the device's CS pulled high.

The way you'll make the connection is up to you, you might need to use some clips, pogo pins or simply solder some wires to the MCU pins.

If you have other things connected to any of the MCU programming pins, you might need to disconnect, but that will vary case by case.

Cheers


message:
Is it possible to move a servo without knowing it's current position?

My Servo has already been built into my project, and I can't remove it without damaging many other things. During the process of inserting it, it was turned by hand. So I don't know at what position it is in. It turns a potentiometer that doesn't rotate fully. So I'm worried that if I just set a degree it could turn too far and damage the potentiometer or the servo.

What should I do to find the current position? Is it even possible?

body:
A normal servo is an absolute positioning device. [The position of the servo is directly proportional to the length in time of the sync pulse][1].  This means if you tell the servo to be in a given position, it will seek that position with out regard to the initial position.  It will simply figure out which way to go on it's own and stop when it gets there.

I should add, that in all likely hood, when you manually moved the servo you moved the positioning potentiometer inside the servo.  So it is expected that if the servo is told to go to a particular angle, it will still go to the same angle as it did before you manually moved it.

  [1]: https://en.wikipedia.org/wiki/Servo_control#Pulse_duration


body:
Yes. Servo can rotate to a particular angle irrespective of previous position.

But you may face an issue here if you rotated the shaft manually by hand (when servo is not powered), and if you reassembled the shaft to the servo in a different orientation. Actually it is really hard to re assemble a removed shaft to the same angle position.


message:
ATtiny44 millis() not working with 16 MHz external clock

I'm using ATtiny44 with Arduino IDE according to this tutorial: [http://highlowtech.org/?p=1695][1]

I have a problem with `millis()`. When I use an internal 1 MHz clock it works correctly but when I use external 16 MHz clock it takes `millis()` much more time than one second to be divisible by 1000.

I tested it with LCD and Hello World sketch, modified to correspond ATtiny's pins. Do `millis()` actually work with Tiny's?

Why does it work properly with 1MHz and not with 16 MHz which is the same as used in Arduino platform.

  [1]: http://highlowtech.org/?p=1695

body:
Let me guess: "_much_ more time" is about, ohhh, 16 times?

When `millis()` was written, it had to assume what the input clock was. There is no way to detect the speed of the input clock: to do so would require another clock! So the writers of the function defined a starting constant, set it to `1000000`, and required anyone that changed the clock would have to change that constant.

Find the constant, and set it to `16000000`. Voilà!

Here's an article on the source code of the function:

https://ucexperiment.wordpress.com/2012/03/16/examination-of-the-arduino-millis-function/


message:
Bit shifting fails with warning: left shift count >= width of type

Given the following minimal working example. I tested this initially with uint16_t and it worked with no warnings. After that, I adjusted everything to work with uint32_t.

    #include <stdint.h> /* needed for the uint16_t type*/
    #include <inttypes.h> /* needed for sscanf uint16_t format placeholder  */
    #include "printf.h"

    #define SET_CMD_ID(ID)    ( (ID) << 27)
    #define SET_CMD_CMD(CMD)  ( (CMD)  << 25)
    #define SET_CMD_TYPE(TYPE)  ( (TYPE) << 19)
    #define SET_CMD_PKT(PKT)  ( (PKT)    )

    void setup() {
      Serial.begin(115200);
      printf_begin();
      Serial.print(F("\n\rExample command\n\r: "));

    }

    void loop() {
      uint32_t payload = 0;

      uint8_t id = 3;   // 00000 - 5
      uint8_t cmd = 2;  // 00    - 2
      uint8_t type = 1; // 000000 - 6
      uint32_t pkt = 0; // 0000000000000000000 - 19

      payload =
            SET_CMD_ID(id)   |
            SET_CMD_CMD(cmd)  |
            SET_CMD_TYPE(type) |
            SET_CMD_PKT(pkt);
      Serial.print(F("Now sending "));
      Serial.println(payload);
      delay(2000);        // Try again soon
    }

Verifying this sketch outputs:

    /path/to/ino/Arduino32bitTest.ino: In function 'void loop()':
    /path/to/ino/Arduino32bitTest.ino:5:37: warning: left shift count >= width of type [enabled by default]
     #define SET_CMD_ID(ID)    ( (ID) << 27)
                                         ^
    /path/to/ino/Arduino32bitTest.ino:28:9: note: in expansion of macro 'SET_CMD_ID'
             SET_CMD_ID(id)   |
             ^
    /path/to/ino/Arduino32bitTest.ino:6:39: warning: left shift count >= width of type [enabled by default]
     #define SET_CMD_CMD(CMD)  ( (CMD)  << 25)
                                           ^
    /path/to/ino/Arduino32bitTest.ino:29:9: note: in expansion of macro 'SET_CMD_CMD'
             SET_CMD_CMD(cmd)  |
             ^
    /path/to/ino/Arduino32bitTest.ino:7:41: warning: left shift count >= width of type [enabled by default]
     #define SET_CMD_TYPE(TYPE)  ( (TYPE) << 19)
                                             ^
    /path/to/ino/Arduino32bitTest.ino:30:9: note: in expansion of macro 'SET_CMD_TYPE'
             SET_CMD_TYPE(type) |
             ^

    Sketch uses 3,174 bytes (9%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 216 bytes (10%) of dynamic memory, leaving 1,832 bytes for local variables. Maximum is 2,048 bytes.

Executing the sketch on an Arduino Uno results in:

    Example command

    : Now sending 0
    Now sending 0
    Now sending 0
    Now sending 0

I googled the message of the warning and found out that it could mean that I'm trying to shift 32bit which is undefined, but I'm not sure on that. So my question is:
What am I doing wrong here? How can I get this to work?

body:
It's basically an inability of the compiler to auto-promote the source variables to a size big enough to fit the shifted version.

The default type for all operations, unless otherwise specified, is 16-bit. By shifting more than 16 bits you are overflowing that default type.

To get around it you have to manually tell the compiler that you want to work with 32-bits:

    #define SET_CMD_ID(ID)      ( ((uint32_t)ID) << 27)
    #define SET_CMD_CMD(CMD)    ( ((uint32_t)CMD)  << 25)
    #define SET_CMD_TYPE(TYPE)  ( ((uint32_t)TYPE) << 19)
    #define SET_CMD_PKT(PKT)    ( ((uint32_t)PKT)    )


body:
Another solution would be to not shift values at all.
It seems to be very common in Arduino and other micro-controller projects to use antique ANSI C. But ALL major compiles support "bit fields". The language removes your headache of packing bits into and unpacking bits from a larger type.

It goes like this:

    struct {
        uint32_t pkt  : 19;
        uint32_t type :  6;
        uint32_t cmd  :  2;
        uint32_t id   :  5;
    } payload;

As long ans 19 + 6 + 2 + 5 does not exceed 32, the struct will still take up only 32 bits.

Setting values works like this:

    payload.id = 3;
    payload.cmd = 2;
    payload.type = 1;
    payload.pkt = 0;

Reading values works the same way. No need to shift mask or do any other operations by hand. The compiler does everything for you without making any mistakes or without forgetting about to mask when reading...

The only thing you have to remember is that bitfields are packed from least significant bit to the most significant bit. So a struct like this:

    struct {
        uint8_t r :  2;
        uint8_t g :  3;
        uint8_t b :  2;
        uint8_t a :  1;
    } someType;

Will result it a byte where the values are layout like this:

    abbgggrr

This also works for signed values. But you have to make sure they fit and be aware of the twos complement representation.

Hopefully more Arduino and micro controller developer will adopt this and take advantage of the compiler.


message:
Serving binary file with ESP8266WebServer

I am currently using a Nodemcu ESP8266-12E with the Arduino IDE in order to control my boiler. Everything is working fine, however I haven't figured out yet how to serve binary files, eg. images. (I am hosting them on a server at the moment).

    ESP8266WebServer server(80);

    void setup()
    {
      [...]
      server.on("/", handleResponse);
      server.onNotFound(handleResponse);
      server.begin();
    }

    void handleResponse() {
      if (server.uri() == "/style.css") {
        server.send(200, "text/css", "[css]");
        return;
      }
      if (server.uri() == "/favicon.ico") {
        server.send(404, "text/html", "Not set");
        return;
      }
      [...]
    }

    unsigned char favicon_ico[] = {
      0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
      0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
    };
    unsigned int favicon_ico_len = 894;

Converting the arary to a string and serving it with `server.send` does not work and  `server.stream` expects a file.

body:
It looks like you can use the `send_P` function to send raw PROGMEM data:

  void send_P(int code, PGM_P content_type, PGM_P content, size_t contentLength);

I.e., (from what I can gather):

    PGM_P favicon = {
      0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
      0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
    };

    server.send_P(200, "image/x-icon", favicon, sizeof(favicon));

Incidentally, `PGM_P` is just a `typedef` for `const char *`.


message:
Where can i get touch sensitive buttons with RGB-LED like in Ableton Push

I am searching for this component: a touch sensitive button with LEDs like in the [Ableton Push][1] or in other Launchpads. Does anyone have an idea about where I can buy something like this? The best would be an RGB LED.

This is what I've [found][2] so far. It has no RGB LED though.

Thanks!

  [1]: http://46.20.46.151/wp-content/uploads/2012/10/push_01_72dpi_rgb-632x412.jpg
  [2]: https://www.sparkfun.com/products/10442

body: Just a little more searching would have led you to this, along with its associated breakout board, bezels, and LEDs.


body:
The specific buttons you link to are custom made. They're not something you can buy off the shelf. In fact they aren't even buttons.

What they are is a translucent moulded silicone rubber sheet with conductive pads behind (typically in a ring shape) with an LED mounted on a PCB behind them.  The pad is pressed, which flexes the silicone rubber, to press the conductive portion against exposed tracks on the PCB behind.

There are some similar products around, such as [the Sparkfun one Ignacio points to](https://www.sparkfun.com/products/7835) but it is highly unlikely you will find anything off-the-shelf that does exactly what you want.  Coupling a pre-moulded translucent rubber keypad membrane (if you can find one somewhere) with your own custom designed PCB to take the RGB LEDs you want (preferably surface mount to keep the size small enough) and provide the exposed tracks is probably the only way you can get exactly what you want.

You may be able to create your own sheet by first making a suitable mould, maybe with wood or modelling clay or something like that, then filling it with silicone (translucent bathroom sealant) and then impress on the back of that a second mould to provide the contact points and indents etc. Then, after a few days when it's all dry, add to the contact points some self-adhesive copper foil, or paint them with conductive paint. Don't quote me on that though, I haven't tried it ;)


message:
Scale Magnometer to Servo

I'm trying to determine what is the best way to scale a magnometer to a servo, I am using the BNO055 from Bosch I get a heading say 50 degrees, and I want to be able to input 45 degrees and have the servo motor move accordingly. I am using a 180 degree motor. I would like to be able to input 45 degrees, and then the motor if 50 degrees was 95, would decrease in value step by step until the magnometer read 45; I'm having difficulty creating the logic to do this.

Bosch output is between 0 and 360; so I could end up with servo 0 is 120; and servo 180 is 300. Meaning the values are 300 - 360, 0 - 120 making the full 180, so I am not sure how I could use something like map in arduino to solve this issue.

body:
Okay, lets say the output of your BNO055 is called `x` and the value for your servo is `y`. We need to translate `x` to `y` and you are correct to use the `map()` function. But what you are forgetting is that you do not need to map all the values of `x` to all the values of `y`. You can split it up.

In your example the values of the BNO055 relate to the servo as follows:

    x   | y
    0   | 0
    120 | 0
    300 | 180
    360 | 180

The servo only rotates from 0 degrees to 180 degrees between the BNO055 sensor values of 120 and 300. So you only need to map those values, while all values below should result in 0 and all values above should result in 180 degrees for the servo.

This translates into the following code:

    //x is the output of BNO055 sensor
    if(x < 120){
      servo.write(0);
    }
    if(x > 300){
      servo.write(180);
    }
    if(x > 120 && x < 300){
      y = map(x, 120, 300, 0, 180);
      servo.write(y);
    }

Another way of coding this is:

    if(x < 120){
      servo.write(0);
    }
    else if(x > 300){
      servo.write(180);
    }
    else{
      y = map(x, 120, 300, 0, 180);
      servo.write(y);
    }


body:
You need to remember that you are working with a circle. You have degrees 0 to 360, but only if counting clockwise. If you work anticlockwise you also have degrees 0 to -360.

So your angles of interest are, clockwise from 0, 0-120, and anti-clockwise from 0, 0 to -60

To make things easier on you you need to create a range that is wrapped around so that anything in the "left" half of the circle is counted as anticlockwise from 0 and anything in the "right" half of the circle is counted clockwise from 0.

So values 0-180 are 0-180, but values of 180 to 360 are -128 to 0.  Then your entire range spreads from -180 to +180 instead of 0-360 (if that makes sense).

It's simple enough:

    if (angle > 180) angle = 0 - (360 - angle);

So if `angle` is 300 you get:

    0 - (360 - 300) = 0 - 60 = -60

If `angle` is 330 you get:

    0 - (360 - 330) = 0 - 30 = -30

Now you can map the new values using the `map` function @Len has detailed above:

    servo = map(angle, -60, 120, 0, 180);

It is also possible to combine it all into one line should you wish, using the C "inline if" format:

    servo = map((angle > 180 ? (0 - (360 - angle)) : angle), -60, 120, 0, 180);

But that is kind of cryptic :)


message:
What's on an Arduino board? Can i build one of these boards myself?

My question is: What is on an Arduino board besides the microcontroller?

body:
This list is probably not exhaustive but comes reasonably close:

 - A power supply (voltage regulator and filter capacitor);
 - A USB connector for powering from a USB port and passing data to/from
   your PC;
 - A second processor (Atmega 16U2) for handling USB <-> serial data
   conversion;
 - A barrel-jack for powering it from a 7 - 12v;
 - A MOSFET for selecting whichever power source is being used;
 - An LED connected to the chip's digital pin 13;
 - A pushbutton for manual reset and a capacitor for auto-reset;
 - A 16 MHz crystal and load capacitors;
 - Several lengths of female headers for connecting plug-wires or shields to the Arduino.

And yes, it's relatively easy to build one - instructive, too! There are how-to project details all over the Internet. I've hand-built any number of them, just soldering up whatever parts I wanted.

Here is an Arduino home brew project, [CSEDuino][1], that was easy and fun to build, with good detailed directions. It is an Arduino clone that does everything the Uno does, except that it isn't physically compatible with Arduino shields.

All of my gadgets are on home-brewDuinos. I usually skip the USB connector and 16U2 processor, and keep one or two FTDI USB to serial cables on my bench to power or program whatever board I'm currently working on. I usually skip the auto-reset capacitor too, and manually reset the board to upload it.

Have fun building!

In service, I just power them from a USB wall charger. Any of them that need to communicate get an radio of some kind, usually Bluetooth or Wifi. Some of them just collect data to non-volatile memory for me read out later.

  [1]: http://jpralves.net/cseduino/


body:
When I first built my first Arduino clone, I fount very useful the Fritzing examples *(boards and schematics)*. http://fritzing.org/home/

Mind that in order to upload sketches, an FTDI module is very handy *(unless you use ISP via another Arduino board)*.

In any case, I should recommend you to build an Arduino clone on a breadboard, before trying soldering.

Good luck.

Additionally, you may use this picture *(this is how  I create an Arduino on breadboard)*:

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

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

External power *(battery)* is connected to the screw pins *(bottom left of the breadboard)*.


message:
Sampling rate of analog read

I have a simple following analog reading code:

    void setup()
    {
      // initialize serial comms
      Serial.begin(9600);
    }

    void loop()
    {
      // read A0
      int val0 = analogRead(0);
      int val1 = analogRead(1);
      int val2 = analogRead(2);
      // print to serial
      Serial.print(val0);
      Serial.print(" ");
      Serial.print(val1);
      Serial.print(" ");
      Serial.print(val2);
      Serial.print("\n");
      // wait
      delay(50);
    }

How do I determine the sampling rate? I understand for the serial print, it's 3*4 bytes (for val0,1,2) + 2 bytes for space and 1 bytes for \n, which is 15/9600.

How much time is spent on analogRead?

body:
The sample rate will be somewhat inconsistent since the first few samples' print output will go into the print buffer with little delay. Once the buffer fills, subsequent samples' time spent in Serial.print() will vary somewhat depending on how long printing the currently printing character takes to finish, when Serial.print() is called. But the average sample rate will settle to about to *about* 64 Hz (1 sec / (15/960 lines/sec).

The printing time for one line is about 15.6 msec, much longer (140 times) than analogRead() takes, about 0.111 msec, according to [this author's measurements][1].

Update: <br>
> So I could just use 50ms + 15.6 for the sampling rate, ignoring
> analogRead?

That would get you pretty close to the average sampling interval. If consistency is important to you, you'd need to measure that.

How many samples do you need at a time? Another way is to store the data in an array and print it later. Then the jitter in the sampling interval will be much smaller. You'd be limited to the number of samples you could fit in memory, though. Each 10-bit sample would need 2 bytes of storage.

If the range of your data is less than 256, you could subtract from each sample, the lowest value you expect to see; the difference will fit in 1 byte, doubling your storage capability. Don't forget to add back that lowest value to each one when you print them, though.

It would also be a good idea to test each sample against that lowest number and the lowest + 255, and if any sample is outside those limits, store the low or high limit value instead. Then when you plot your data,
you'll see it "clipping" and know that it exceeded your bounds. Otherwise you'll get overflows in the arithmetic and the out-of-bounds numbers will appear to suddenly take on high values when they really are low, and vice versa.

  [1]: http://meettechniek.info/embedded/arduino-analog.html


message:
I2C communication between 2 Arduinos with updated wire library

I would like to enable communication between two Arduino 101. From what I have read, the best method is to use I2C using the wire library. However, it seems as though the newest Arduino IDE has an updated version of the Wire library that no longer includes the `begin(int)` and `onRequest` functions.

All of the tutorials for I2C communication use these methods, so I am unable to follow and use them. It looks like when I change the board to Arduino Uno these functions are found, but as soon as I change the board to Arduino 101 the following errors appear no matching function for call to `TwoWire::begin(int)`.

When I try replacing my wire library with the older version, I get other errors for missing libraries and if I replace everything it is unable to compile on Arduino 101.

Can someone please help me or direct me to a I2C tutorial that uses the most updated version of the Wire library?

body:
The problem I see is the Arduino 101 uses an Intel microprocessor (Curie) instead of an Atmel microprocessor.

The only information I could find is on the [Arduino page for the 101][1], which mentions it has dedicated pins for I2C, but it also says that you can use the Wire library. Maybe you just need to update your IDE?

I'd help more, but I can't seem to find any useful information on the Curie...

  [1]: https://www.arduino.cc/en/Main/ArduinoBoard101


body: Although I did not manage to get wire communication to work, I was able to get the Arduinos to communicate through serial port. You just need to ensure to use Serial1 rather than Serial.


message:
Increase the resistance of a photoresistor with increase in light intensity

I'm building a laser tripwire of sorts and instead of shutting up when the laser points on it (which is essential for my project) it beeps louder.

Here's the code

    int buzzPin = 11; // buzzer connected to digital pin 11

    void setup() {
        pinMode(buzzPin, OUTPUT); // sets the digital pin as output
    }

    void loop(){
        if(analogRead(0) < 750){ // this number depends on calibration of the photocell
            digitalWrite(buzzPin, HIGH); // turns buzzer on
            delay(5000); // waits for 1 second
            digitalWrite(buzzPin, LOW); // turns buzzer off
        } else{
            digitalWrite(buzzPin, LOW);
        }
    }

body: Just invert it in software. Instead of `analogRead(0)` use `(1023-analogRead(0))`.


body:
Arduino can not measure resistance. It can measure voltage.
To measure resistance you can convert resistance to voltage using a voltage divider.

In Arduino world a voltage divider consists out of 2 resistors in series between 5V and gnd. The connection to the 2 resistors is connected to a analogue pin.
Depending whether your LDR is connected to gnd or 5V the measured value on the analogue pin will go up or down with the resistance of the LDR.

In other words swap the resistor and your LDR from position.


body: You could change your circuit or just change `analogRead(0) < 750` to `analogRead(0) > 750`.


message:
changing from long to bytes and vice versa

I want to converse data from long to bytes and vice versa. After searching around, I sticked together some code, which seems to work *(the same code works for int and floats as well)*.

The long value `LongVal` changes to a byte array, and the four bytes construct `LongVal2`. Obviously `LongVal = LongVal2`.

    long LongVal = -4080;
    long LongVal2;

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

    //byte* my_function(long LongVal){
    //  byte *LongVal_byte = (byte *) & LongVal;
    //  return & (LongVal_byte[0]);
    //}

    //long my_function2(byte & LongVal_byte){
    //  long LongVal2;
    //  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
    //  return  LongVal2;
    //}

    void loop(){

      byte *LongVal_byte = (byte *) & LongVal;
      memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
      Serial.println(LongVal2);
      Serial.println(" ");

    //byte LongVal_byte = my_function(long LongVal);
    //LongVal2 = my_function2(byte & LongVal_byte);

    }

But should I try to wrap the two first lines of `loop()` in two individual functions, errors occur. The remarked lines are my attempts to create two functions.

How to wrap them up properly?

**EDIT**
This is what appears if I try to use the remarked functions:

     In function 'long int my_function2(byte&)':
    15:51: error: invalid conversion from 'byte {aka unsigned char}' to 'const void*' [-fpermissive]
    25:0,
    1:
    117:14: error:   initializing argument 2 of 'void* memcpy(void*, const void*, size_t)' [-fpermissive]

     In function 'void loop()':
    26:33: error: expected primary-expression before 'long'
    27:30: error: expected primary-expression before '&' token

body:
So many problems here:

1) in function call there shouldn't be types, only arguments. `byte LongVal_byte = my_function(LongVal);`

2) & before variable means "get variable address". However in function prototype `long my_function2(byte & LongVal_byte)` it means reference to passed variable (and it must be byte), not a pointer.

3) pointer to local variable is returned from my_function. It might be working until pointed memory gets rewrited by something else (another function call or so)

And whole code might look like that:

    long LongVal = -4080;
    long LongVal2;

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

    byte * my_function(long & LongVal) {
      return (byte*)&LongVal;
    }

    long my_function2(byte * LongVal_byte) {
      return *((long *)LongVal_byte);
    }

    void loop(){

      byte * LongVal_byte = my_function(LongVal);
      LongVal2 = my_function2(LongVal_byte);

      Serial.println(LongVal2);
      Serial.println(" ");
    }

But it is basically exactly the same as before without functions (just no need for memcpy)


body:
> 15:51: error: invalid conversion from 'byte {aka unsigned char}' to 'const void*' [-fpermissive]
>

    memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));

LongVal_byte is a single byte. It's not a pointer, and `memcpy` expects a pointer.

> 26:33: error: expected primary-expression before 'long'

    byte LongVal_byte = my_function(long LongVal);

You do not specify the variable type when passing a variable to a function. The variable already knows what it is, and the function already knows what it wants.

> 27:30: error: expected primary-expression before '&' token

    LongVal2 = my_function2(byte & LongVal_byte);

Same there.

You are showing a fundamental lack of understanding of some concepts of C.  Other errors you are making:

    long LongVal2;
    ...
    long my_function2(byte & LongVal_byte){
        long LongVal2;

You should never ever re-define a global variable inside a function. It's not actually syntactically incorrect, but from a reading perspective it becomes almost impossible to keep track of *which* `LongVal2` variable is being used at any one time.

    long my_function2(byte & LongVal_byte){

You are passing a reference to a *single* byte, not an array of bytes. For that you need a pointer.

You should re-write your functions to be like this:

    byte* my_function(long LongVal) {
        return (byte *)&LongVal;
    }

(although that is completely pointless, you just need to cast the value, you don't need a function to do it:

    byte *byteval = (byte *)&LongVal;

)

    long my_function2(byte *LongVal_byte){
        long LongVal2;
        memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
        return LongVal2;
    }

That is a long winded, but "safe" way of doing it. It is needed only on CPUs where alignment matters.  On an 8-bit CPU the alignment is 8-bit, and so a 32-bit word can be at any address.  On a 32-bit system a 32-bit word will be at a 4-byte alignment, so that method is needed.  On an 8-bit though you can just cast the array into a long:

    long *LongValue = (long *)&LongVal_byte;

A better solution to the whole thing, though, is to use a union:

    typedef union {
        byte byteval[4];
        long longval;
    } LongBytes;

    LongBytes myVal;

You can then access:

    myVal.longval = 4893723284;

And also:

    myVal.byteval[i];

where `i` is 0-3.


message:
Force compiler to execute instructions sequentially?

Is there a way to force the Arduino compiler to compile individual commands sequentially?  Looking at the disassembly, lines of the assembly code for different C/Arduino commands are mixed.  I was thinking something like a dmb or dsb command in ARM assembly.  I realize it's done the way it is for timing optimization, but I would like to see if changing it fixes some other timing issues I'm having.  I'm working on an Arduino Zero.  Thanks!

body:
You can use the `optimize` function attribute to change the compiler optimization level for an individual function. That's the closest you'll get.

> **optimize**
>
> The optimize attribute is used to specify that a function is to be compiled with different optimization options than specified on the command line. Arguments can either be numbers or strings. Numbers are assumed to be an optimization level. Strings that begin with O are assumed to be an optimization option, while other options are assumed to be used with a -f prefix. You can also use the `#pragma GCC optimize` pragma to set the optimization options that affect more than one function. See Function Specific Option Pragmas, for details about the `#pragma GCC optimize` pragma.
>
> **This attribute should be used for debugging purposes only. It is not suitable in production code.**

E.g.,:

    void __attribute__((optimize("O0"))) myFunction() {
        // ...
    }


message:
Send values to a PHP page using Arduino ESP8266

I still a noob, and I'm learning Arduino. I built a PHP page to send values using GET parameters.

I would like to send a specific value from Arduino to that PHP page. I bought an ESP8266, and I would like to see it working.

I found this code and I made some changes there, but the the code is not working. I don't receive any value on my database. Can you guys help me?

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(10, 11);
    String cmd;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      Serial.println("Started");
      // set the data rate for the SoftwareSerial port
      esp8266.begin(115200);
      esp8266.write("AT\r\n");
    }

    void loop() {
      if (esp8266.available()) {
        Serial.write(esp8266.read());
        teste();
      }
      if (Serial.available()) {
        esp8266.write(Serial.read());
      }
    }

    void teste(){
      // Connect to the server
      esp8266.write("AT+CIPSTART=\"TCP\",\"http://bubu.esy.es\",80\r\n");
      //make this command: AT+CPISTART="TCP","192.168.88.35",80
      //wait a little while for 'Linked'
      delay(300);

      //This is our HTTP GET Request change to the page and server you want to load.
      cmd = "GET /teste.php?test=5 HTTP/1.0\r\n";
      cmd += "Host: http://bubu.esy.es\r\n\r\n";
      //The ESP8266 needs to know the size of the GET request
      esp8266.write("AT+CIPSEND=");
      esp8266.write(cmd.length());
      esp8266.write("\r\n");
      esp8266.write("GET /teste.php?test=5 HTTP/1.0\r\nHost: http://bubu.esy.es\r\n\r\n");
      esp8266.write("AT+CIPCLOSE\r\n");
    }

body: `Host: http://bubu.esy.es` needs to be `Host: bubu.esy.es`.


message:
Can anyone help me spot where my buffer overflow might be occuring?

I'm using dtostrf() to transcribe a float into a string for my touchscreen. I'd leave it as a float, but my screen orientation library function only works with a string.

So I have a char array, then a float value. then dtostrf().

    char buffer[6]
    float X; //changes each loop with incoming sensor data from pixy camera
    float thingposition = X * .0064  //float calculations are performed.

    void loop(){
    Camera.Get_X();   //retrieves X from the camera. waits until X has been recieved via UART serial
    dtostrf(buffer, 5, 2, thingposition) // writes float to string with a controled decimal place and all that - dtostrf(floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, charBuf);
    Tft.drawString(buffer, 70, 215, 5, WHITE);   //print output to screen
    }

Note that this is a simplified version. In my code I also have methods for overwriting my last string value on the LCD when the new one has changed.
I also have several "if" conditionals that control whether I write the buffer value to the screen or instead send an error message. Those things do not seem to be causing me problems though, except to say that my buffer overflows only occur when I cause the sensors to flip the conditionals at just the right interval.

For example, when I place my hand in front of the camera, that triggers the error message. Take my hand away, and then the number "thingposition" is printed to the screen. But if I time my hand just right, the buffer overflows and numbers loop across the screen. Usually this freezes the whole sketch. The best I can figure is that since dtostrf() does not check bounds, and since the calculated float values can be longer than the buffer has room for, that sometimes dtostrf() tries to write too many digits to the buffer. Something timing-related seems to trigger the problem, but what I need is some way to prevent the overflow in the first place.

I've tried rounding "thingposition" to a certain number of sigfigs, but I can't seem to truncate it at the desired decimal point. That shouldn't matter though, since dtostrf has controls for the minimum total length including the decimal point, as well the number of digits after the decimal. I also tried making sure that the last byte in my char array is null by adding this right after dtostrf():

    stringval[5] = NULL;   //make sure buffer is null-terminated to prevent buffer overflow

I've tried doubles, different ways of rounding, and anything I could find, but the problem has persisted for several weeks and a few steady days worth of searching for a solution. I'll be glad to provide further information if anyone has any ideas on what to try. Thanks everyone.

body:
The problem with using "simplified code" is that your 'simplification' may not have captured your problem. But I will take your code as given and assume that it's correct (which I'm afraid it isn't).

    var
        char buffer[6]  // Won't compile - no semicolon (';')
        float X;        // Uninitialised value - could be 1000000000000
        float thingposition = X * .0064 // No ';', and .0064 of 10000000000 is huge!

    void loop(){
        Camera.Get_X(); // Should this be "X = Camera.Get_X();" ?
        dtostrf(buffer, 5, 2, thingposition)  // No ';'. You NEED to recalculate thingposition!

If the above code is a good representation of what you've got, you seem to be assuming that you define the formula once (in the `thingposition` line), and it automatically applies that formula, like Excel, when you change its input, `X`. Sorry, programs don't work that way.

Once you calculate `thingposition`, it becomes independent of where it came from. If you change other variables, `thingposition` kees its value until you explicitly change it.

How do you fix it? You recalculate `thingposition` every time:

    var
        char buffer[6];      // Hopefully big enough - see below
        float X;             // Used by Camera.Get_X()
        float thingposition;

    void loop(){
        X = Camera.Get_X();        // Get X from Camera
        thingposition = X * .0064; // Calculate thingposition
        dtostrf(buffer, 5, 2, thingposition);

Note that `dtostrf()` will try to obey your size parameters, **BUT**. If the float is larger than your maximum size, it WILL print out the full number anyway. That is, if `thingposition` is `1000`, it will produce 5 characters all right: `"1000."`. But if it's `1000000`, it will produce `"1000000"` which is seven characters. You need to ensure that `buffer` is big enough to handle larger numbers than you expect.

Do the maths. If `X` is guaranteed to be between `0` and `255`, then multiplying it by `0.0064` will result in a maximum value of `1.632`, so the above `dtostrf()` woud produce `" 1.63"`. No problem!


message:
Controlling 4 motors using the Arduino Uno

I've decided to make a quadcopter but since I'm a rookie, i decided against doing it from scratch. I'm planning to order [this][1] kit, first understand the dynamics and then try and make a quadcopter on my own using the components in it.
My first question are

 - Can I control the 4 motors using 2 H-bridges (L293D)?
 - Are ESC's necessary if I use the PWM pins?

Thanks in advance!

  [1]: http://www.amazon.in/ENGINEERSTOYS-ET-01-Engineerstoys-Mini-Quadcopter/dp/B01HTIM5WG/ref=sr_1_4?ie=UTF8&qid=1468170793&sr=8-4&keywords=kit quadcopter

body:
> Can I control the 4 motors using 2 H-bridges (L293D)?

Yes. Two per chip.

> Are ESC's necessary if I use the PWM pins?

There is one thing you must understand first: there are two kinds of DC motor - Brushed and Brushless.

The Brushed motor is the "normal" kind - you apply power to it and it spins.  These you control with the likes of an L293D and use PWM to control the speed.

Brushless motors are the kind you have in hard drives and the like. They consist of a number of coils that get turned on and off at the right time to pull a magnet around in a circle (to put it crudely). These require special timing and control to get the coils energised at the right time and in the right way. This is what an ESC is for.

Brushless motors are smaller and lighter for the same power than brushed ones. They also have a longer life. Because of this they are generally preferred to brushed motors on quadcopters.

Brushed motors have a very high starting torque, don't require complex control logic and use less energy when not running full speed.

If you use brushless motors, which ideally you should (though I can't tell what kind of motors those are in that kit) then you must either use an ESC or build your own ESC using an Arduino and multiple motor driver circuits. Simplest to use an ESC.

If you don't use brushless motors then an ESC is not what you want to use - just the L293D chips and PWM.


body:
I fully agree with the answer of Majenko but I think something is missing in the explanation.
When you say "I want to control a motor" then it is not yet clear what is needed.
There are the following options
1) on/off in one direction (forward).
2) on/off in 2 directions (forward and backwards).
3) on/off in on direction with speed control.
4) on/off in two directions with speed control.

For a brushed dc motor this can be achieved with.
1) a single pole single throw relay (this is similar to a on of switch)
2) a single pole single throw relay and a double pole double throw relays (this is a on off switch and a switch to change the wires to the motor)
3) a mosfet (this is similar to a single pole single throw switch that can go on/off very fast)
4) a H bridge. That is 4 mosfets that are controlled in a certain way.

Now here comes the trick: H bridges often come in 2 half H-bridges. And with a half H-bridge you can control a motor at level 3.

In other words ... with a chip that has 4 half H bridges (an as such 2 H- bridges) you can control 4 brushed DC motors at the level 3 (forward speed controlled) or 2 brushed DC motors at the level 2 (back and forward speed controlled).


body:
You also need to consider the current needed by your motors (they are DC brushed indeed) and the power/energy you will lose in your driver.

If you use a 3.7V power supply like provided, and the L293D "eats" 1.2V out of it, you lose nearly one third of your energy. See https://electronics.stackexchange.com/questions/108686/what-h-bridge-drivers-are-preferred-for-applications-controlling-a-low-voltage-m for an very interesting review of drivers.

If I can believe that, it looks like DRV883x is the only reasonable choice. It even allows you to use one cell (3.7V) for the logic and 2 cells (7.4V) or more for the motors. But don't do that with the motors you've got, you'd probably burn them.

Unfortunately the other ST or Allegro devices also covered in the article all need more voltage to work.

Regarding the Arduino, a UNO can't be recommended, too heavy, 5V only, power hungry etc. It won't fly. I'd recommend you use a pro mini 3V3 with some LDO power supply such as the TPS73633. Be careful that most LDO regulators (like 1117) have a too high dropout voltage to be used with a 3.7V input, more than 1V.

I'm not affiliated with TI at all, it just happens that when looking for "the right chip for the right job", I keep having to eliminate the others because of data sheet numbers.

On the SW part however, it becomes difficult to find SW for the 328P. Most addicts have moved to 32-bit CPUs. But that's another debate.


message:
Programming an Arduino Mini 05

So, I recently bought an Arduino Mini (5V, 16MHz), and a USB to Serial Converter.
Provided are the links to both the products:
[Arduino Mini,][1]
[USB to Serial Converter][2]

Now, I tried programming the mini by connecting the pins in this order:
Rx -> tx, tx-> rx, VCC -> 5V, GND -> GND, DTR -> DTR

The computer detected the USB to Serial converter after I installed the drivers manually. However, the Arduino IDE failed to program the Arduino Mini every single time, even after I swapped the TX, RX pins.

I tried to program the Arduino Mini using an Arduino Uno (I removed the onboard Atmel Atmega microcontroller on the Uno before programming). I connected the pins in this order: TX->TX, RX->RX, 5V-> VCC, GND-> GND, RST -> DTR. From the IDE, I chose Arduino Pro Mini (5V, 16Mhz).

The Mini was programmed successfully this time.

My question: What was wrong with the USB to Serial converter? Why couldn't it program the Arduino Mini with the USB to Serial Converter?

  [1]: https://www.techshopbd.com/product-categories/boards/1455/arduino-mini-china-techshop-bangladesh
  [2]: https://www.techshopbd.com/product-categories/modules-98775/808/usb-to-serial-converter-techshop-bangladesh

body: Try to reset manually just after compiling end


body:
As you have said the Arduino Mini seems to be fine and the USB to Serial Converter seems to be working too.

**This might be a crazy idea but this might work**

try connecting the boards like this,

**TX -> TX  and  RX -> RX**

I'm not totally sure, but this might work.


body:
>  The Mini was programmed successfully this time

If so, one of them had its tx/rx pins mislabeled.


message:
Arduino Due SRAM

I'm trying to create an array in Arduino Due and when the
array exceeds the size of 32768 integer elements
the compiler (Atmel Studio) complains.

I read that Arduino Due SRAM size is 96K in 2 banks. 64Kb and 32Kb.

Anyone knows any details?

body: Size of int in arduino due is 4Bytes. If you're trying to create array of 32768 integers, it means you need **128kB** of free space.


body:
I've read in several places that e.g. PROGMEM const int foo[] = { 1, 2, 3, ... } would work, but was unable to do it in my environment ( debian, arduino-mk package ). I had a number of arrays I needed to commit to flash to conserve sram. This worked fine for all variables, but not for arrays. Try that... What say the wizards?

Note to moderators and others: I _know_ I am not answering the question definitively, but it is relevant to OP's question.


message:
motor does not move without Serial.println

having strange behavior with motor shield and steppers. when i'm trying to make `onestep`, motor just makes some high-frequent noise, but when i add `Serial.println` for debugging, it moves as intended.

what is going on here?

here is an example:
<pre>
#include AFMotor.h //dunno how to put angle brackets here

AF_Stepper lrM(48, 1);

void rightStep() {
  lrM.onestep(BACKWARD, INTERLEAVE);
}
void leftStep() {
  lrM.onestep(FORWARD, INTERLEAVE);
}

void setup() {
  Serial.begin(9600);
  Serial.println("ready");
}

void loop() {
  rightStep();
//Serial.println("right");
}
</pre>

body:
When you have a Serial print statement running really quickly the output buffer will fill up and the `print` command will have to wait for there to be room; That causes the command to take a substantial amount of time to complete.

When the statement is missing, you loop probably runs a few hundred times faster than without it (depending on how long `onestep` takes), probably fast enough that the physical motor can not keep up.

Try adding a delay of a few milliseconds or some kind of rate limiting to the program and then see how much of a difference `serial.println` makes.


body:
My guess is `Serial.println` adds additional delay so stepper motor can react. Without it changes are way too fast (= high frequency noise) to do whole step.

Try to add `delay(1);` or more into the main loop.


message:
Burn arduino bootloader using ubuntu 16

I get the following error when I try to burn the arduino bootloader on an atmega328 mcu:

    avrdude: verification error, first mismatch at byte 0x0000
             0xfd != 0x05

I am using an Arduino as ISP programmer. My computer runs Ubuntu 16.

This did not happen when I was using Ubuntu 14. I also tested it on another machine with Ubuntu 14 and this error does not appear. Seems to be something with Ubuntu 16. I installed Arduino IDE using the out of the box repo.

The avrdude command launched by the IDE is:

    /usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -cstk500v1 -P/dev/ttyUSB0 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0x05:m -Uhfuse:w:0xde:m -Ulfuse:w:0xff:m

Am I safe replacing the -Uefuse:w:0x05:m with -Uefuse:w:0xfd:m ?? If answer is yes how can I get the IDE to do this correctly?

Uploading a sketch works pretty well.

body:
I had same problem and I think I have solved it.

In boards.txt file, I had:

    ##############################################################

    diecimila.name=Arduino Duemilanove or Diecimila

    diecimila.upload.tool=avrdude diecimila.upload.protocol=arduino

    diecimila.bootloader.tool=avrdude diecimila.bootloader.low_fuses=0xFF
    diecimila.bootloader.unlock_bits=0x3F
    diecimila.bootloader.lock_bits=0x0F

    diecimila.build.f_cpu=16000000L diecimila.build.board=AVR_DUEMILANOVE
    diecimila.build.core=arduino diecimila.build.variant=standard

    ## Arduino Duemilanove or Diecimila w/ ATmega328
    ## --------------------------------------------- diecimila.menu.cpu.atmega328=ATmega328

    diecimila.menu.cpu.atmega328.upload.maximum_size=30720
    diecimila.menu.cpu.atmega328.upload.maximum_data_size=2048
    diecimila.menu.cpu.atmega328.upload.speed=57600

    diecimila.menu.cpu.atmega328.bootloader.high_fuses=0xDA
    diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0x05
     diecimila.menu.cpu.atmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

    diecimila.menu.cpu.atmega328.build.mcu=atmega328p

    ## Arduino Duemilanove or Diecimila w/ ATmega168
    ## --------------------------------------------- diecimila.menu.cpu.atmega168=ATmega168

    diecimila.menu.cpu.atmega168.upload.maximum_size=14336
    diecimila.menu.cpu.atmega168.upload.maximum_data_size=1024
    diecimila.menu.cpu.atmega168.upload.speed=19200

    diecimila.menu.cpu.atmega168.bootloader.high_fuses=0xdd
    diecimila.menu.cpu.atmega168.bootloader.extended_fuses=0x00
     diecimila.menu.cpu.atmega168.bootloader.file=atmega/ATmegaBOOT_168_diecimila.hex

    diecimila.menu.cpu.atmega168.build.mcu=atmega168

    ##############################################################

I have replaced the line containing:

    diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0x05

with:

    diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0xFD

Everything is ok now.

I can install boot loader on an ATMEGA328P (with an usbasp programmer), and I can install sketchs after that (via usb serial).

I don't know if it's the best way to solve the problem, but it works.
Hope this will help you, if not already solved.


message:
why am I losing data over serial communication between arduino and pc

I'm working on a project for school. I'm trying to rotate a servo by writing the letter that identify the servo and then the angle.

the problem is that sometimes the last number of the angle is lost or the whole angle all together. for example i want to rotate servo "a" 50 degrees. i enter a50 this works most of the time but sometimes i only get a 5 without the zero and sometimes i just get a zero. can anyone help, thanks.

please keep in mind i only did computer science in high school and intro to c++ in college. go easy on me please.

attached is the code and an image illustrating my problem.

    #include <Servo.h>

    Servo servo1;
    Servo servo2;
    Servo servo3;

    String angle1="";
    String angle2="";

    char serialbuffer[4];
    int index=0;
    int charcount=0;

    int lastangle;
    int dif;

    void setup() {
      servo3.attach(3);  // attaches the servo on pin 9 to the servo object

      Serial.begin(9600);

      serialbuffer[0]='0';
      serialbuffer[1]='0';
      serialbuffer[2]='0';
      serialbuffer[3]='0';
    }

    void loop() {

           charcount=0;
           index=0;
           serialbuffer[0]=99;

       while (Serial.available() > 0) {

          char charbuffer = Serial.read();
           if(charbuffer=='\n'){
              index=0;
            }
            else{

               serialbuffer[index]=charbuffer;
               index++;
               charcount++;
              }

          }

      angle1="";
      if(serialbuffer[0]=='a'){

          for(int i=1;i<charcount;i++){
             angle1+=serialbuffer[i];
          }
          move_servo3(angle1);
          index=0;
          serialbuffer[0]=99;
        }
      delay(15);
    }

    void move_servo3(String angle2){

       Serial.println(angle2.toInt());
       servo3.write(angle2.toInt());

      }

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

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

body:
I don't understand why the problem is being caused, your code looks OK, but this is too big for a comment.

 - I think it would be better if you initialised you serialbuffer with NULL rather than '0'.  This way angle2.ToInt() will just read the number you have typed, rather than what was in there last time.  Try entering a111 and then a2.  You will get a211 second time.  NULL is the end of a string.
 - In loop() change your while loop to this:

        char charBuffer = Serial.read();
        while (charBuffer != '\n' && index < 4) // Index < 4 stops a buffer overflow.
        {
          serialbuffer[index++] = charBuffer;
          charCount++;
          charBuffer = Serial.read();
        }

This will keep reading until it sees a new line, which I think is what you want.

 - You don't need the delay statement now, the speed is controlled by
    how fast you can type.

 - The for statement could be changed to:

        for (int i = 0; i < 4 && serialbuffer[i] != NULL; ++i)

If you make these changes I think it might help see the problem.  Also printing the number that has been typed in before the for loop might help, it will print now because you have initialised it to NULL.


body:
Are you hand-typing the commands? It is pretty difficult to do that consistently. I ask because your code collects data from the serial buffer until the buffer is empty - i.e. when you pause even slightly in your typing - and tries to act on whatever it has collected so far. That may be (probably will be!) an incomplete command. Even if your terminal uses line-by-line entry, there is still the risk that your code could notice an empty buffer between characters within a line.

Try collecting characters until it sees a newline, instead. That is probably what you intended, and it will be immune to your typing speed. You'll still need to test for .available, but that should only allow the code to collect more characters. Keep collecting until it sees a newline.

What (I think) is happening now is called a race-condition. That means that the program's behavior is dependent on which of two (or more) events happens first, and the order of their occurrence is indeterminate. Race conditions are especially hard to find when the order of two events is almost always the one you expected. Notice the "gotcha" word in that sentence? :)


message:
Change max and min read value of potentiometer

I'd like to know if there is a function or some way to define min and max value to potentiometer, for example: I'm using a mechanical part that only tour the potentiometer a little bit, what means the potentiometer doesn't start in the beginning and doesn't finish in the end. So, how can I make this space the potentiometer tour means 0 to 255 the start to end, respectively?

body: Either use a reference voltage closer to the maximum voltage the potentiometer is capable of, or use <a href="https://www.arduino.cc/en/Reference/Map">`map()`</a> to map the existing limited range to a larger range. Note that using `map()` will not improve precision.


body: If the values from the pot are 0 - 1023 you can divide the number by 4 which would give you a closer range to what you need. The map() function can be used instead.


body:
You cannot declare that the `min` and `max` values of a potentiometer are `x` and `y`. What you can do is `map()` the values of the potentiometer to your own desired scale.

To do this, you'll have to get the following values:

 - Minimum value of the potentiometer, `pMin`
 - Maximum value of the potentiometer, `pMax`

But these values aren't what you want. For example, what you want is `pmin` to be `0` and `pMax` to be `100`. So, you'll have to scale `pMin` and `pMax` to those values.

For this, you use the `map()` function. What `map()` does is changing the value in a given scale, to that of another scale. Let's get some example code:

    int pMin = 14;  //the lowest value that comes out of the potentiometer
    int pMax = 948; //the highest value that comes out of the potentiometer.

    int x = 0;  //we will use this value to store the readings of the potentiometer

    void setup(){
      Serial.begin(9600); //Serial monitor can be used to check the values
    }

    void loop(){

      x = analogRead(A0); //connect the potentiometer to the A0 pin of the Arduino

      Serial.print(x);  //prints the original reading

      x = map(x, pMin, pMax, 0, 100) //take the value of x, compared it to the scale of the potentiometer pMin to pMax, and translate that value to the scale of 0 to 100

      Serial.print("\t"); //a tab to make the reading more easy
      Serial.println(x);  //post mapped value, println is a linebreak as well
      delay(100); //so we don't post to much in the serial and you can read data better.
    }

With this example you can clearly see how your potentiometer behaves and how you can use the 'weird' values from its readings in a useful way for your projects.


message:
using millis() for a timer

Basically the user presses a button and cycles thru 3 different modes. Mode 1 the LED is on, mode 2 the LED is off and mode 3 the LED is kept on for a certain amount of time. I'm using the millis() to keep track of the time. the LED in the third mode just stays on and never switches to off. I have the Serial.Writes in there to help me debug. I have the delay after the button read since if I didnt put it in it would register a lot of button presses.

    int ledPin = 5;
    int buttonApin = 9;
    int ledMode = 0;

    boolean lastButton = HIGH;
    boolean currentAButton = HIGH;

    // debounce button
    boolean debounceFUNC(boolean last)
    {
     boolean current = digitalRead(buttonApin);
     if (last != current)
     {
      delay(5);
      current = digitalRead(buttonApin);
     }
     return current;
    }

    void setMode(int ledMode)
    {
     // turns on led
     if (ledMode == 1)
     {
      digitalWrite(ledPin, HIGH);
     }
     // turns off led
     if (ledMode == 2)
     {
  digitalWrite(ledPin, LOW);
     }
     // timer - turns off after 5000
     if (ledMode == 3)
     {
      long interval = 5000;
      unsigned long cMillis = millis();
      static unsigned long pMillis;

      if (cMillis - pMillis > interval)
      {
      pMillis = cMillis;
      digitalWrite(ledPin, HIGH);
      Serial.println("On");
      Serial.println(interval - cMillis);
      }
      else
      {
      digitalWrite(ledPin, LOW);
      Serial.println("Off");
      }

      }
     }

    void setup()
    {
     Serial.begin(9600);
     pinMode(ledPin, OUTPUT);
     pinMode(buttonApin, INPUT_PULLUP);
    }

    void loop()
    {
     // sets led mode
     currentAButton = debounceFUNC(lastButton);
     delay(500);
     if (currentAButton == LOW)
     {
      ledMode++;
      Serial.println(ledMode);
     }
     else if (ledMode > 3)
     {
      ledMode = 0;
     }
     // ledMode function call
     setMode(ledMode);
    }

screenshot of the serial monitor.

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

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

body:
The problem is in the logic, basically your statement:

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

        if (cMillis - pMillis > interval)
        {
           pMillis = cMillis;
           digitalWrite(ledPin, HIGH);
            Serial.println("On");
            Serial.println(interval - cMillis);
        }
        else
        {
           digitalWrite(ledPin, LOW);
           Serial.println("Off");
        }

will always be true, this is as the difference in time, `cMillis - pMillis` is always greater than `interval`.

This means that it never enters the else statement to turn off the LED, and thus means the `else` statement is usually the first thing that rune at `ledMode = 3`.

What you need to do as the simplest fix is to change your comparison, change **`>` to `<`**, in the is statement:

    if (cMillis - pMillis > interval)

to

    if (cMillis - pMillis < interval)

this will ensure the LED is always on during the 5000 mS and then as soon as it is greater it will definitely go to the `else`


body:
There is a problem with your debounce logic. You want to compare the
current button state with the previous state, which is supposed to be
stored in `lastButton`. But that variable is initialized to `true` and
then _never_ updated. Your program may work better if you issue
`lastButton = currentAButton` somewhere.

You can find lots of tutorials on button debouncing, and there are
several methods. The one you are using, which is based on `delay()`, is
probably the worst: it should work in this simple case, but `delay()` is
toxic as soon as your Arduino has more than one thing to do. A very
common (and my preferred) method is to just ignore the button for some
“debounce time” after you detect a state change. A debouncer function
can be based on something like:

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

    if (now - last_state_change < DEBOUNCE_TIME)
        return last_state;

Then you have to detect the button presses, which is not the same as the
button being down: you don't want to interpret the down state as a
continuous stream of very fast button presses. Instead, a button press
is the button being down now whereas it was up on the previous read. A
`button_press()` function could call the `debounce()` function and then
have something like

    bool press = last_state && !state;

This is effectively detecting falling edges of the debounced button. You
can combine the debouncer and the falling-edge detector into a single
function as follows:

    bool button_press()
    {
        static bool last_state;
        static uint32_t last_state_change;
        uint32_t now = millis();

        // Ignore the button during the debounce time.
        if (now - last_state_change < DEBOUNCE_TIME)
            return false;

        bool state = digitalRead(BUTTON_PIN);
        if (state != last_state) last_state_change = now;
        bool press = last_state && !state;
        last_state = state;
        return press;
    }

Next there is the management of the LED states. What you are trying to
implement is called a [finite state
machine](https://en.wikipedia.org/wiki/Finite-state_machine), sometimes
abbreviated “FSM”. If you search the Web for that term, you will find a
few examples on how to implement it. It canonically revolves around a
`switch` statement that enumerates all the possible states and tells
what to do in each of those states. Something like

    switch (state) {
        case STATE_FOO:
            if (some_condition()) {
                do_some_action();
                state = STATE_BAR;  // switch to the next state
            }
            break;
        case STATE_BAR:
            ...
    }

Below is a FSM implementation of your LED logic. Note that you did not
completely specify what should happen when the “timed” state times out:
you could go to a forth “timed out” state, or you could just go back to
the “off” state. In the code below I've taken that last option:

    void loop()
    {
        static enum { OFF, TIMED, ON } state;
        static uint32_t timed_started;
        uint32_t now = millis();

        // Switch state on button press.
        if (button_press()) switch(state) {
            case OFF:    // -> TIMED
                digitalWrite(LED_PIN, HIGH);
                state = TIMED;
                timed_started = now;
                break;
            case TIMED:  // -> ON
                // LED is lready on.
                state = ON;
                break;
            case ON:     // -> OFF
                digitalWrite(LED_PIN, LOW);
                state = OFF;
                break;
        }

        // Turn off after LED_ON_TIME.
        if (state == TIMED && now - timed_started >= LED_ON_TIME) {
            digitalWrite(LED_PIN, LOW);
            state = OFF;
        }
    }

Note that it would have been more “canonical” to have the tests
`if (button_press())` inside the `switch` rather than the other way
around. Then the test for the timeout would also be inside the same big
`switch`. It's just that it seemed easier to me to write it this way.

For the sake of testability, here are the pieces that would be missing
for having a complete working program:

    const int BUTTON_PIN = 9;
    const int LED_PIN = LED_BUILTIN;
    const uint32_t DEBOUNCE_TIME = 50;
    const uint32_t LED_ON_TIME = 5000;

    void setup()
    {
        pinMode(BUTTON_PIN, INPUT_PULLUP);
        pinMode(LED_PIN, OUTPUT);
    }

    // button_press() and loop() as above.


message:
Motion Tracking Using Arduino?

I'm trying to make a human following robot.Tried using ultrasonic sensors to follow a specific person by Having ultrasonic sensor with the person to send echo to the robot,But it didn't workout.
Any way to track a specific person and follow ?
Any sensors/algorithm to track fast moving object(a person but not specific)?

body:
You need the person to emit a signal and the robot to receive it, sounds simple, but it isn't.  What you are trying to do is position fix the transmitter, in the same way as an ATC locates a plane.

The robot will need at least two directional receivers positioned a certain distance apart (depends of frequency and accuracy) to allow the robot to triangulate the transmitter.  The more receivers the more complex the triangulation.  The frequency of the signal you transmit will affect the distance that the robot can be from the person, research Frequency spectrum and transmission distances.  The longer the distance the signal can travel the stronger the signal will be at close range.  You also have to counter reflections and side lobes which will give you inaccurate readings on the transmitter direction.
Once you have dealt with all of that all you need to do is scan for the strongest signal on your frequency, triangulate it and then head towards it.
Whatever sensor you use the theory is the pretty much the same.

Could you tag the person with a GPS receiver and WIFI/BT and get it to transmit its location.  The robot could then consult its GPS and calculate the delta and move accordingly.


body:
If you are clever with software you may be able to simplify your hardware requirements down to 1 IR ASK transmitter and 1 IR ASK IR receiver.

I mention IR ASK as the transmitter (simply a remote control with a button pushed down) and the [receiver][1] are [COTS][2] parts.

Consider your robot looking for an IR ASK signal by rotation until one is found.  Then consider your robot traveling in a serpentine path adjusting its average vector along the angle where the IR ASK transmitter is detected.

You might need to create an variable aperture the IR ASK receiver will look through.  This is because most IR ASK receivers have a built in [AGC][3] circuit which will abstract you from knowing how strong the signal is.

So, while searching, the aperture will be large allowing the IR ASK receiver a wide field of view.  But once locked on, the aperture should be reduced so that the robot will know in which direction the IR ASK signal is from.

  [1]: https://www.adafruit.com/products/157
  [2]: https://en.wikipedia.org/wiki/Commercial_off-the-shelf
  [3]: https://en.wikipedia.org/wiki/Automatic_gain_control


message:
How do you use an Arduino to control a 4 - 20 mA transmitter?

I am using an Arduino Mega to control the speed of an AC pump. This can be done by connecting to the variable frequency drive. Here is a link of the relevant datasheet, pages 66 and 67 relate to what I am doing.

http://www.parker.com/Literature/SSD Drives/AC Drives/AC650/HA464828U003.pdf

From what I have read and been told already, I should be able to control this using a 4 - 20 mA loop, which is fed into AIN2, as long as I connect the 0V terminal as well?

My question is what is the best way to make a current loop transmitter using an Arduino Mega.

So far the options I have are:

 - Create a circuit out of discrete components, this would then be controlled using the Megas PWM
 - Use an IC circuit, I was looking at the AD694JNZ
 - Use an add on board, I was looking at this one: http://uk.rs-online.com/web/p/products/8828929/?grossPrice=Y&cm_mmc=UK-PLA-_-google-_-PLA_UK_EN_Semiconductors-_-Semiconductor_Development_Kits&mkwid=sm9dTYvCc_dc|pcrid|88057061283|pkw||pmt||prd|8828929&gclid=CjwKEAjwk6K8BRDM3aCSkdCtzSQSJAA3Vf38mNs9lZrg2A1AjrVpS3SCubT0AbAr7L8OImUZbfCPzRoCIXjw_wcB

I have a budget for my project so cost is not an issue, however I am running out of time. What would be the easiest method to implement and how?

I have been thinking of using options 2 or 3, however my issues are that this is my first Arduino project. I understand what PWM is but I don't know how I would go about implementing it. I also can't find any tutorials online that demonstrate how to program the MIKROE board using an Arduino.

Thank you in advance for any help :)

body:
I can recommend the Click boards from MikroElektronica (I am the chief engineer porting support for them, and the PIC32-based Clicker development board series, to the chipKIT™ system).

The 4-20mA-T Click board is controlled by the Microchip MCP4921 DAC. This is a common DAC family used in many Arduino projects and there are plenty of libraries around for them (mine is [here](https://github.com/MajenkoLibraries/MCPDAC) though it's aimed at the 4822 not the 4921).

Basically you set the DAC output voltage which sets the current output from an XTR116 current loop transmitter.

The XTR116 takes an input of 0 - 4.095v, and provides a convenient 4.095v reference voltage to the MCP4921.

* [Datasheet for the XTR116](http://www.ti.com.cn/cn/lit/ds/symlink/xtr116.pdf)
* [Datasheet for the MCP4921](http://ww1.microchip.com/downloads/en/DeviceDoc/21897a.pdf)
* [Manual for the 4-20mA T Click](http://download.mikroe.com/documents/add-on-boards/click/4-20ma/4-20ma-click-manual-v100.pdf)

The whole thing is isolated from your main board through an ADu M1411 to keep everything safe from industrial process noise.


body:
>  I don't know how I would go about implementing it.

Both option 2/3 require coding - generally simple and doable, even for newbies.

To go down the DAC route, current-feedback DACs are quite common, especially in the good old days. they are ideal here -> make sure your device matches up with the dac in terms of current source vs. current sink.

option 1 is good if you don't like coding. turning a voltage into a current is fairly simple.