body:
I have a test program running on my LoLin NodeMcu board, with a Rotary Encoder connected.

I use `Task.h` and `RotaryEncoderTask.h` from this library: https://github.com/Makuna/Task (though my issue is the same when I use example code from here: https://tkkrlab.nl/wiki/Arduino_KY-040_Rotary_encoder_module

Link to `RotaryEncoderTask.h`: https://github.com/Makuna/Task/blob/master/examples/RotaryEncoder/RotaryEncoderTask.h

**The problem**

When I turn the knob right and left a bit quickly, multiple successive times, the current value of the rotary encoder increases, rather than staying at the same value.

I've read something about `interrupts`, and I believe the issue is there somewhere, but I am not able to comprehend it enough to set it into practice.

Here is the code I am running:
<!-- language-all: lang-cpp -->

     /*
     * Pin mappings on LoLin:
     *
     * static const uint8_t D0   = 16;
     * static const uint8_t D1   = 5;
     * static const uint8_t D2   = 4;
     * static const uint8_t D3   = 0;
     * static const uint8_t D4   = 2;
     * static const uint8_t D5   = 14;
     * static const uint8_t D6   = 12;
     * static const uint8_t D7   = 13;
     * static const uint8_t D8   = 15;
     * static const uint8_t D9   = 3;
     * static const uint8_t D10  = 1;
    */
    // RotaryEncoder
    // This demonstrates the use of the custom Task object feature of Task library
    // It will instance one custom RotaryEncoderTask to monitor three pins that a
    // rotary encoder is connected to and make call backs when they change state;
    // the press button will have debouce and auto repeat support;
    // the rotary will tell direction and keep track of "clicks" rotated
    // This requires a standard rotary encoder be attached to the defined pins,
    //
    // Usefull information will be sent to the serial monitor
    //
    // make sure that you connect your rotary encoder correctly, include gnd and Vcc (+)

    #include <Arduino.h>

    // nothing special about these pins, just make sure they don't collide with
    // other active features
    #define ClockPin 5  // labeled either as CLK or as A
    #define DataPin 4   // labeled either as DT or as B
    #define ButtonPin 0 // labeled as SW

    // include libraries
    #include <Task.h>

    // include sub files
    #include "RotaryEncoderTask.h" // this implements the rotary encoder task

    TaskManager taskManager;

    // foreward delcare functions passed to task constructors now required
    void HandleButtonChanged(EncoderButtonState state);
    void HandleRotationChanged(int8_t rotationDelta);

    RotaryEncoderTask RotaryTask(HandleRotationChanged,
        HandleButtonChanged,
        ClockPin,
        DataPin,
        ButtonPin);

    void setup()
    {
        Serial.begin(57600);
        while (!Serial); // wait for serial monitor to connect

        taskManager.StartTask(&RotaryTask);

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

    void loop()
    {
        taskManager.Loop();
    }

    void HandleButtonChanged(EncoderButtonState state)
    {
        if (state == EncoderButtonState_Pressed)
        {
            Serial.println("Pressed - ");
        }
        else if (state == EncoderButtonState_Released)
        {
            Serial.println("Released - ");
        }
        else
        {
            Serial.println("Auto-repeat - ");
        }
    }

    void HandleRotationChanged(int8_t rotationDelta)
    {
        if (rotationDelta > 0)
        {
            Serial.print("clockwise = ");
        }
        else
        {
            Serial.print("counter-clockwise = ");
        }

        Serial.println(RotaryTask.RotationValue());
    }

Here is the result, where you see the current value increasing:

    counter-clockwise = -1
    counter-clockwise = -2
    counter-clockwise = -3
    counter-clockwise = -4
    counter-clockwise = -5
    counter-clockwise = -6
    counter-clockwise = -7
    counter-clockwise = -8
    counter-clockwise = -9
    clockwise = -8
    clockwise = -7
    clockwise = -6
    clockwise = -5
    clockwise = -4
    clockwise = -3
    clockwise = -2
    clockwise = -1
    clockwise = 0
    counter-clockwise = -1
    counter-clockwise = -2
    counter-clockwise = -3
    counter-clockwise = -4
    counter-clockwise = -5
    counter-clockwise = -6
    counter-clockwise = -7
    counter-clockwise = -8
    counter-clockwise = -9
    counter-clockwise = -10
    counter-clockwise = -11
    clockwise = -10
    clockwise = -9
    clockwise = -8
    clockwise = -7
    clockwise = -6
    counter-clockwise = -7
    counter-clockwise = -8
    counter-clockwise = -9
    counter-clockwise = -10
    clockwise = -9
    clockwise = -8
    clockwise = -7
    counter-clockwise = -8
    clockwise = -7
    clockwise = -6
    clockwise = -5
    counter-clockwise = -6
    counter-clockwise = -7
    counter-clockwise = -8
    counter-clockwise = -9
    clockwise = -8
    clockwise = -7
    counter-clockwise = -8
    clockwise = -7
    counter-clockwise = -8
    counter-clockwise = -9
    counter-clockwise = -10
    counter-clockwise = -11
    clockwise = -10
    counter-clockwise = -11
    clockwise = -10
    counter-clockwise = -11
    clockwise = -10
    counter-clockwise = -11
    counter-clockwise = -12
    counter-clockwise = -13
    counter-clockwise = -14
    counter-clockwise = -15
    counter-clockwise = -16
    counter-clockwise = -17
    counter-clockwise = -18
    clockwise = -17
    clockwise = -16
    counter-clockwise = -17
    counter-clockwise = -18
    counter-clockwise = -19
    counter-clockwise = -20
    counter-clockwise = -21
    counter-clockwise = -22
    counter-clockwise = -23
    counter-clockwise = -24
    counter-clockwise = -25
    clockwise = -24
    clockwise = -23
    counter-clockwise = -24
    counter-clockwise = -25
    clockwise = -24
    counter-clockwise = -25
    counter-clockwise = -26
    clockwise = -25
    counter-clockwise = -26
    clockwise = -25
    counter-clockwise = -26
    counter-clockwise = -27
    counter-clockwise = -28
    counter-clockwise = -29
    clockwise = -28
    counter-clockwise = -29
    counter-clockwise = -30
    counter-clockwise = -31
    counter-clockwise = -32
    clockwise = -31
    clockwise = -30
    counter-clockwise = -31
    counter-clockwise = -32
    counter-clockwise = -33
    counter-clockwise = -34
    clockwise = -33
    counter-clockwise = -34
    counter-clockwise = -35
    counter-clockwise = -36
    counter-clockwise = -37
    counter-clockwise = -38
    clockwise = -37
    clockwise = -36
    clockwise = -35
    counter-clockwise = -36
    clockwise = -35
    counter-clockwise = -36
    counter-clockwise = -37
    clockwise = -36
    clockwise = -35
    clockwise = -34
    clockwise = -33
    clockwise = -32
    counter-clockwise = -33
    counter-clockwise = -34
    clockwise = -33

title: Rotary Encoder on LoLin NodeMcu increases value when rotating right/left

Answers: 0


body:
As per this SO:

https://arduino.stackexchange.com/questions/31533/is-the-mks-gen-v1-2-compatible-with-arduino-ide-as-arduino-mega-board

the MKS GEN board is an Arduino MEGA board mixed with other circuits.

My questions is how does it correlate with the Arduino Mega Board pinouts, especially the ones encircled in red below:

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

E.g. for connector `Jc_M2` where does the `EN`, `STEP` and `DIR` pins connect to the ATmega2560 controller? And also for the other servo controller pins.

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

title: MKS GEN board pinouts for Arduino MEGA

Answers: 0


body:
I am working on a project for knowing the position of a DC motor which has a hall sensor built into it. I am a newbie into programming using the Arduino Uno R3. After some forum search and self checks, I cannot pass this hurdle. I hope I can frame the questions properly here.

My Problem: The DC motor hall sensor sends out 2 high pulse of 11.3V - 13V with a duration of 2.8ms for each revolution. My Arduino interrupt pin doesn't read the high pulse as it gives me "0" count after motor spin (I run 50 loops and results remain the same).

[![Interupt pin asssigment with function call][1]][1]

On my breadboard, I use a voltage divider to reduce hall-effect ouput from max 13V to 5V so that the Arduino pin 2 can read rising voltage when it jumps to 5V (low should be 2.5V).

Couple of things I noted during the motor spin -

a) The `millis()` function returns 79-81ms per sketch run

b) The same hall sensor output if connected to analog pin reads 580,590,590,1001, 1012, 580, 580.. etc. I cannot gauge position of the motor by using these values as they are inconsistent on the way up Vs. way down.

I have attached analog readings while going up and down in snap shot below:
[![enter image description here][2]][2]
2 questions I have:

1. Why is the pin 2 not detecting a high pulse? will it not be able to read 2.8ms durations because of motor speed (9.5 rev/s or 570rpm)?
2. Is it possible to gauge anything from Analog read function? Am I missing something?

Thanks in advance for all responses.. Any questions regarding the circuit, I will be more than happy to post them.

  [1]: https://i.stack.imgur.com/z3mh0.png
  [2]: https://i.stack.imgur.com/RS9u1.png

title: Detecting a 2.8ms pulse using a Arduino Uno

Answers: 5

body:
First, better to see whole source and schematics.

"Why is the pin 2 not detecting"

Check:
1. Hall sensor connected to Pin 2

2. pulses variable declared as volatile.

3. Check if internal pull up resistor setup consistent with hall sensor connection.

4. Check that Hall sensor's lowest signal voltage is below 0.3 VCC (you said 5V, so it should drop below 1.5V), BTW 580 - the lowest analog value you showed means 2.83V

5. Check you are not using nointerrupt();

"Is it possible to gauge anything from Analog read function? Am "

Yes.
Analog read takes about 0.1 ms in default setup, so should make at least 1000 reads per second to catch peak.

So,
Easiest way is to choose some value like 600, when analog read is above mark it as Rising when it drops below mark is Falling.
More complicated ways will include some training and hysteresis to improve detection.

Also I suggest to use voltage limiter instead of voltage divider. This gives better detection.

body:
All,

Here is the code:

    int flag = 1;
    int speedo = 255;
              int counter =0; //counts the number of revolutions
              int timeu=0;
              int timed=0;
              int Voltmeasure=0;
              int times=0;
              volatile unsigned int pulses=0; //pulse counter
              bool upcount=false;
              bool downcount=false;
              unsigned int timeold=0;
              int difference=0;

              void count()
              {
                if(upcount==true)
                  pulses++;
                  else if (downcount==true)
                   pulses--;
              }

              void setup()
              {
                // initialize serial communication:
                Serial.begin(9600);
                pinMode(11,OUTPUT);
                pinMode(12,OUTPUT);
                pinMode(13,OUTPUT);
                pinMode(2, INPUT);
                pinMode(3, INPUT);
                attachInterrupt(digitalPinToInterrupt(2),count, RISING);
              }
              void stopmotor()
              {
                digitalWrite(12,HIGH);
                digitalWrite(13,HIGH);
              }
              void motorCCW()
              {
                analogWrite(11,speedo);
                digitalWrite(12,HIGH);
                digitalWrite(13,LOW);
              }
              void motorCW()
              {
                analogWrite(11,speedo);
                digitalWrite(12,LOW);
                digitalWrite(13,HIGH);
              }

              void loop()
              {
                  if(flag==1)
                  {
                    delay(2000); //wait for 2 seconds to start motor
                    flag=2;
                  }

                //first run motor moves down
                    if (counter<16 && flag==2)
                    {
                      motorCW(); //moving up

                      //Reading Hall-sensor pulses- using analog signal
                      Voltmeasure = analogRead(A3);
                      Serial.print("CW Voltmeasure = ");
                      Serial.print(Voltmeasure);
                      Serial.println();

                      //Reading Hall-sensor pulses - using interuppt signal
                      upcount=true;

                      //counting the number of high pulse
                      if (Voltmeasure>700 && times==0)
                      {
                        counter++; times=1;
                      }
                      else if (Voltmeasure<610)
                        times=0;

                      //timer for number of loops
                      timeu++;
                      Voltmeasure=0;

                      if (timeu==70||counter==16) //move by 70 cycles or until counter is 16
                      {
                        stopmotor();
                        upcount=false;
                        timeu=0;
                        times=0;
                        Serial.print("High-point is reached - Travel complete");
                        Serial.println();
                        delay(2000); //delay by 2 seconds
                        flag=3;
                      }
                    }

                    if (counter>0 && flag==3)
                    {
                      delay(2000); //pause before next run
                      motorCCW();

                      //Reading Hall-sensor pulses - using analog signal
                      Voltmeasure = analogRead(A3);
                      Serial.print("CCW Voltmeasure = ");
                      Serial.print(Voltmeasure);
                      Serial.println();

                      //Reading Hall-sensor pulses - using interuppt signal
                      downcount=true;

                     //counting the number of high pulse
                      if (Voltmeasure>700)
                      {
                        counter--; times=1;
                      }
                      else if (Voltmeasure<610)
                        times=0;
                      timed++;
                      Voltmeasure=0;

                      if (timed==70||counter==0) //move by 70 cycles or until counter is 0
                      {
                        stopmotor();
                        downcount=false;
                        timed=0;
                        times=0;
                        Serial.print("Lowest point is reached - Travel complete");
                        Serial.println();
                        flag=3;//stop motor
                      }
                     }

              //  difference=millis()-timeold;
              //  timeold = millis();
              //
              //  //Printing information after line complete
              //  Serial.print("time for one sketch = ");
              //  Serial.print(difference);
              //  Serial.println();

                Serial.print("Counter = ");
                Serial.print(counter);
                Serial.println();

                Serial.print("pulses = ");
                Serial.print(pulses);
                Serial.println();

              }

[![][1]][1]

General block diagram

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

Motor with Hall sensor, Ve is 13V, Ue is 13.5V:

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

  [1]: https://i.stack.imgur.com/bXoYO.png
  [2]: https://i.stack.imgur.com/6nNYA.png
  [3]: https://i.stack.imgur.com/Id9YP.png

I print the counter (Analog pin) and pulses (interrupt pin) with running this program code.

The Analog pin reads:

CW Voltmeasure = 574

CW Voltmeasure = 588

CW Voltmeasure = 1000

CW Voltmeasure = 999

CW Voltmeasure = 998

CW Voltmeasure = 1002

CW Voltmeasure = 1002

CW Voltmeasure = 589

CW Voltmeasure = 588

CW Voltmeasure = 590

CW Voltmeasure = 588

CW Voltmeasure = 1000......by this time motor spins 6.5 rev (based on time elapsed) but counter is only @ 3 (3 highs)

Pulses read 0.......

This is where i am at. Not able to understand Analog readings dont match the number of revs with the highs & why interupt pin reads 0......

body:
I tried modifying the voltages to interrupt pins

Now interrupt pin voltages read:
High:1.456V
Low: 1.07V

Note: The arduino is running at 12V external source.

My "pulses" counter still reads 0 for interrupts. Any idea why?

body:
All,

My Arduino is not reading interrupts across the interrupt pin:

I am getting a high of 1.456V and a low 1.07V through the interrupt pin 2... But the pulses counter still remain 0....

Any idea why?

      volatile unsigned int pulses=0; //pulse counter
      volatile int8_t steps=0;
      int timeu=0;
      int flag=2;

      void count()
      {
        pulses++;
      }

      void setup()
      {
        // initialize serial communication:
        Serial.begin(9600);
        pinMode(11,OUTPUT);
        pinMode(12,OUTPUT);
        pinMode(13,OUTPUT);
        pinMode(2,INPUT_PULLUP);
        attachInterrupt(digitalPinToInterrupt(2),count,RISING);

      }

      void stopmotor()
      {
        digitalWrite(12,LOW);
        digitalWrite(13,LOW);
        steps=0;
      }
      void motorCCW()
      {
        analogWrite(11,255);
        digitalWrite(12,HIGH);
        digitalWrite(13,LOW);
        steps=-1;
      }
      void motorCW()
      {
        analogWrite(11,255);
        digitalWrite(12,LOW);
        digitalWrite(13,HIGH);
        steps=1;
      }

      void loop()
      {

        if (timeu<=1000)//First time - Going up
        {
            sei();
            motorCW(); //moving up
            flag=8;
            timeu++;
          }
        else if (timeu==1000)
          {
              flag=10;
              stopmotor();
              cli();
              //Serial.print("Completed time cycle of 50");

          }

      if (flag==10)
      {
        Serial.print("pulses = ");
        Serial.print(pulses);
        Serial.println();

      }

      }

body:
All,

I didnt need the voltage comparator in the end, the code was running slower and wasnt picking up all the hall sensor signals that the motor was giving due to loop time. i changed the ifs to else ifs and then i was able to get a faster loop time.

Thanks all for the help.

The device is working as intended..


body:
I have two pulse solenoids.  One is 6V...

http://www.ebay.com.au/itm/282002733837?_trksid=p2057872.m2749.l2649&ssPageName=STRK:MEBIDX:IT

and the other is 3.6V...

http://www.ebay.com.au/itm/131989042565?_trksid=p2057872.m2749.l2649&ssPageName=STRK:MEBIDX:IT

I have a Wemos R2 Mini with an `ESP8266` chip on it, and I'm running the switching operation through a H Bridge motor shield (which handily switches the polarity of the electricity for a short time, which opens/shuts the solenoid).

I want to run this thing off a smallish battery pack that will supply 5V to the WeMos. I have three questions:

1) Can I send a 3.6V solenoid a 60ms pulse to open/shut it from a 5V power source without burning out the coil or causing any other damage?

2) Is 3.3V too low to power a 3.6V solenoid?

3) Do pulse solenoids still generate back EMF?

I don't know a lot about solenoids or electromagnetic fields so, sorry if my questions are noobish.

title: Can I switch a pulse solenoid from the onboard 5V/3.3V power source?

Answers: 1

body:
> 1) Can I send a 3.6V solenoid a 60ms pulse to open/shut it from a 5V
> power source without burning out the coil or causing any other damage?

No. If it's 3.6V then you need 3.6V - 5V will most likely make it smoke. Use a regulator (preferably a buck one, since it is apparently 500mA) to power your H-bridge.

> 2) Is 3.3V too low to power a 3.6V solenoid?

Maybe, maybe not. It may be that 3.6V is the absolute maximum and may switch from 3V to 3.6V.

> 3) Do pulse solenoids still generate back EMF?

Normally, yes, since they are just a coil like any other inductive load. Your H-bridge should deal with that though if designed right.

To get any meaningful answers you will need a datasheet. Buying such things from eBay is never a good idea unless you have used it before and know what it is, what its specifications are, and how you use it, or they provide a link to a datasheet. Without a datasheet most questions will be answered with a "maybe".


body:
I am currently building a prosthetic hand using an Arduino MEGA, an Advancer Tech Myoware sensor, and 3 TB6612FNG Dual H-bridge breakouts. I have the EMG sensor sending an analog value to the Arduino and want to use that value to open or close the hand.

The problem I have is that the motors cannot turn more than 1 second without tightening too much and breaking the hand, so I want to place a limit on the while loop telling them to move that will restrict their movement under the specified conditions to one second. Also, when the analog voltage is no longer present, I need the motors to reverse their movement so the hand releases.

Here is the code I have where `move(motor #, speed, direction)` is the function to move the hand (1 = forward, 2 = backward).

    void loop(){

      int EMGv = analogRead(EMG);

      while(EMGv >= 900){
        move(0, 255, 1); //motor 1, full speed, left
        move(1, 255, 1); //motor 2, full speed, left
        move(2, 255, 1); //motor 3, full speed, left
        move(3, 255, 1); //motor 4, full speed, left
        move(4, 255, 1); //motor 5, full speed, left

      }

To reiterate. I need the motors to move while the EMG value is over 900, BUT not move more than 1 second, even if the value is 900 for 5 seconds. I then need the motors to move one second backwards when the value dips below 900.

Thanks!

title: Limiting motors to a specific position using while and if loops

Answers: 1

body:
You can use `millis()` feature

    unsigned long starttime;

    void loop(){

      int EMGv = analogRead(EMG);
      starttime=millis();
      while(EMGv >= 900){
     if (millis()-starttime < 1000) //limit on 1000ms
     {
        move(0, 255, 1); //motor 1, full speed, left
        move(1, 255, 1); //motor 2, full speed, left
        move(2, 255, 1); //motor 3, full speed, left
        move(3, 255, 1); //motor 4, full speed, left
        move(4, 255, 1); //motor 5, full speed, left
     } else {/*turn off motor here*/}
      }


body:
**Setup**

- Windows 7 Entreprise
- MPU-6050 : GY-521 breakout
- Arduino Nano (chinese) with CH340 FTDI driver
- Arduino IDE 1.6.12
- [Library for the gyro][1]

---

**Problem**

When I run my code, the MPU will detect the angles at a good enough accuracy, but when I leave it on the table, the MPU starts drifting. Its not anything major, yet, but on something like a rocket guidance system, these values can srew up many things.

---
**Actual questions**

- Is this a common problem?
- Why is this happening?
- What is the best way to solve it?

---

**Note**

I'll include the code if you guys really need it, but I doubt its the problem because multiple codes have had the same problem.

Please do not recommend any other gyros.

  [1]: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050

title: MPU-6050 - angle drift

Answers: 2

body:
> Is this a common problem?

Yes it is. The drift is a common problem.

> Why is this happening?

The drift results, in general, from the fact that to calculate the angles it is made an integration. The errors and noises present in the inicial variable before integration (in this case angular velocity) will be "summed" over time.
For simplicity, let's say your gyro is perfect with noise free but it has a small offset , and lets considere only rotation in one axis, meaning:

    Ang_Velocity(x) = Real_Ang_Velocity(x) + offset_x

if this was the case, the sensor standing still should output only:

    Ang_Velocity(x) = 0 + offset_x
now using the integral over time results in an output of:

    Angle(x) = int[Ang_velocity(x)] = offset_x * t

For example note that using a simple 0.01 offset over axis x, causes the sensor to output 1rad angle after 100 seconds and in fact the sensor didn't move at all.

Taking this as example the sources of errors I'm aware of are:

 - **offset:** already talked
 - **scale factor:**  is the relation between input and output
 - **scale factor linearity:** sometimes the scale factor at slow speeds are not the same as speed increases.
 - **temperature:** (not 100% sure!) this changes the sensitivities of axis. Majority of digital sensores already come with an integrated temperature sensor. If not auto compensated, there will be probably information on the datasheet to guide you how to compensate for this. If your application will not take high temperature variations, it is common sense to let the sensor achieve thermal internal stability and then do a simple calibration.
 - **Random Walk:** This is probably the hardest to process. In general is assumed that the noise is a normal distribution with mean of zero and a certain variance (white noise). If that was true, the integral over time, as time increases would go to zero (because the mean is zero). However, the noise is usually not evenly distributed in the spectrum, causing the integral to not tend to zero (Brownian noise).

> way to solve it?

The first two are simple using calibration. You must do a series of tests at diferent rotation speeds to determining the non-linearities, offsets (at zero speed) and scales factors for each axis.
Then your sensor equation of the module should take acount for this facts. Usually the sensor datasheets describes the equation to be used.
Take a look at **IMU_Zero** in the repository you gave.

As for the other two, it depends on the application. Typically the temperature will be considered stable after a few working minutes. If temperature is important datasheet will probably be your best friend.

As for random walk. The most common use to take into account corrections of this is to use an accelerometer (and in some cases magnetometer) and apply a sensor fusion algorithm generally denoted as AHRS.
Some examples go as:

 - Sebastian Magdwick - [Open source IMU and AHRS algorithms][1]
 - Extended Kalman Filter
 - Direction Cosine Matrix filters
 - Complementary filters

If you really want to model the noise of the sensor to improve the result, you probably should search for Allan variance but you will need a lot of basis in stochastic processes and statistical theory

Some devices like yours already have an Motion processor built-in, that makes a similar application of (probably) one of these filters. See examples **MPU6050_DMP6.ino**

If you just want an implementation, just google for AHRS arduino. Github as a lot of examples used by other sensors that are easy to adapt. [For instance][2] and [this][3]

[More information on IMU errors](http://www.novatel.com/assets/Documents/Bulletins/APN064.pdf)

  [1]: http://x-io.co.uk/open-source-imu-and-ahrs-algorithms/
  [2]: https://github.com/sparkfun/MPU-9250_Breakout/blob/master/Libraries/Arduino/src/quaternionFilters.cpp
  [3]: https://github.com/Razor-AHRS/razor-9dof-ahrs/blob/master/Arduino/Razor_AHRS/DCM.ino

body:
The change in yaw (rotation of the x-y plane around the z-axis) is not drift or an error that needs to be nullified.
I set my MPU-6050 on the kitchen table and collected the axis outputs over a six and one half hour period.  The pitch and roll values were rock solid over the entire period.
  The Yaw values, however, constantly change at an extremely linear rate of 0.25 degrees per minute.  That's 15 degrees per hour. The planet you are on is rotating at that rate. This is not a coincidence.


body:
Below is a screenshot. I used Visual Studio with the Visual Micro [arduino extension] a few months back. I switched computers and installed Visual Studio on the new one but for some reason after Visual Micro has been installed its not seeing any of the boards. In the visua lMicro explorer it doesnt have an option for the board manager. If anyone can point me in the right direction that would be great.

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

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

  [1]: https://i.stack.imgur.com/X5gBy.png
  [2]: https://i.stack.imgur.com/j8DYZ.png

title: Issue with Visual Studio not seeing arduino boards

Answers: 0


body:
Some people have managed to send simple AM signals with just a bare Arduino. An example is [here][1].
This works thanks to the fact that the PWM can reach high frequencies and, setting the divider properly, it is possible to broadcast a 1337 kHz carrier over a short distance with just a wire acting as an antenna.
I know it's not that useful, but it's really nice as an educational tool.

I was wondering if it would be possible to apply the same concept, but for the receiver. For instance simply using a pulseIn() detection on a pin connected to an antenna. Would it be possible to detect the carrier, and, maybe, even demodulate a message, eg, in morse code?

If not, would just a adding an amplifier be sufficient? Any recommendations for the amplfier and the circuit?

Thanks very much for your suggestions.

  [1]: http://mateslab.weebly.com/am-radio-broadcasting-with-arduino.html

title: read AM signal only with an Arduino

Answers: 2

body:
AM (*Amplitude Modulation*) varies the amplitude of the carrier based on the input signal. So, assuming you had some circuitry ([LC circuit][1]) to receive a particular carrier frequency and managed to boost the voltage so that it was in the range 0-5v then you would able to feed this to an analog input on the Arduino.

[AnalogRead][2] requires around 100uS per sample, so your max sampling rate would be 10K/s, which might **just** cut it for voice (up to 3.4Khz, sampling at least 2 * the highest freq).

However, you then need to do something with the sample value (in code) and depending on how long that 'something' takes, your *actual* sample rate will be reduced.

  [1]: https://en.wikipedia.org/wiki/LC_circuit
  [2]: https://www.arduino.cc/en/Reference/AnalogRead

body:
Generating an AM signal is child's play compared to detecting one.

To generate a signal you just need to create an oscillation and vary the amplitude, which can very crudely be done with PWM.

That's simple.

To *receive* a signal you first need to *isolate* that signal. There's a huge number of signals and noise around all the time, and you need to *tune in* to the signal that you are interested in. That's what you are doing when you twiddle the dial on a radio. You're selecting which frequency to listen to.

And to do that requires a *tuned circuit* - a kind of band-pass filter which isolates and amplifies the frequency you are interested in.

Imagine you are in a large hall filled with people. Every single person there is just standing around talking out loud - everyone is saying something different. Some are even just screaming, or whimpering in the corner. It's just a cacophony of noise. Impossible to know what is going on. That's what the air waves are like. You need some way of "tuning in" to one person's voice so you can understand what they are saying. As humans we often do that using sight, to watch a person's lips and our clever brains link the movement to the sound and help us pick out their voice. Coupled with our ability to select on the tonal qualities of a voice as well, we can pick out a single voice in the noise. That's what the tuned circuit does. It picks out one voice from the mayhem.

The Arduino can't do that. It would need to use some fairly sophisticated filtering algorithms, and it just doesn't have the power for that. Firstly you'd need to sample  the raw RF noise at a minimum of twice the frequency you are interested in (so multi-mega-samples per second), and then you'd need to do digital filtering to isolate that one frequency. From then you'd need to do more filtering to demodulate the original signal from the modulated signal.

It's all possible to do in software, but not with an Arduino. It takes a good ADC and a DSP to do all the hard work.

Easier to just build a small tuned circuit from a few passive components.


body:
I'm doing a project for school using Arduino to make a catapult, but I have this error that I didn't have the previous week.

Can anyone see the program and search where is the error?

    #include <Servo.h> //libreria necesaria para utilizar el Servo

    Servo catac; //motor de giro continuo utilizado

    int ledPin = 13; //led conectado a agujero 13
    int button = 8; //boton conectado a agujero 8
    int estado = 0; //varaible que permite saber el estado del boton

    void setup()
    {
        pinMode(ledPin,OUTPUT);
        pinMode(button,INPUT);
        catac.attach(12); // servo unido al agujero 12
        catac.write(180); //coloca al servo en 180 grados
    }

    void loop()
    {
        estado = digitalRead(button); //la variable obtiene el estado del boton
        if(estado == LOW)
        {
            digitalWrite(ledPin,HIGH); //prende led
            catac.write(70); //servo levanta a 70 grados la catapulta
            delay(500);
            digitalWrite(ledPin,LOW); //apaga led
            catac.write(180); //servo coloca a la catapulta en posicion original
        }
    }

Error:

    cataoukta:6: error: stray '\' in program
    cataoukta:8: error: stray '\' in program
    cataoukta:9: error: stray '\' in program
    cataoukta:10: error: stray '\' in program
    cataoukta:13: error: stray '\' in program
    cataoukta:14: error: stray '\' in program
    cataoukta:15: error: stray '\' in program
    cataoukta:16: error: stray '\' in program
    cataoukta:20: error: stray '\' in program
    cataoukta:22: error: stray '\' in program
    cataoukta:23: error: stray '\' in program
    cataoukta:24: error: stray '\' in program
    cataoukta:25: error: stray '\' in program
    cataoukta:26: error: stray '\' in program
    cataoukta:9: error: expected constructor, destructor, or type conversion before 'void'
    cataoukta:6: error: expected initializer before 'u037e'
    cataoukta.ino: In function 'void loop()':
    cataoukta:20: error: 'estado' was not declared in this scope
    cataoukta:20: error: 'button' was not declared in this scope
    cataoukta:20: error: expected `;' before 'u037e'

title: error: stray '\' in program with servo

Answers: 1

body:
You have bad Unicode characters in your code. All your semicolons are something completely different and need replacing with *real* semicolons.

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

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


body:
I am trying to use a HONEYWELL NBPDANN100PAUNV Pressure Sensor.

I found an example here http://www.circuitstoday.com/interfacing-pressure-sensor-arduino

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

As this example says as instrumentation amplifier based on quad op-amp LM324 is used for conditioning the output voltage from the pressure sensor.
<!-- language-all: lang-cpp -->

    int sensor=A0;
    int dig_out;
    void setup(){
      Serial.begin(9600);
      pinMode(sensor,INPUT);
      pinMode(2, INPUT_PULLUP);
    }

    void loop(){
      if (digitalRead(2) == LOW) {
          dig_out=analogRead(sensor); // reads the input voltage
        Serial.print("Pressure Sensor "); // prints "Pressure Sensor"
        Serial.print(dig_out);
        Serial.print("\n");
        delay(1000);
      }
    }

But when I make this circuit and connect to Arduino it just give output about 5, I give the external air pressure but value not change.

Can any one help me Interfacing this type of sensor to Arduino.

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

title: How to use Honeywell NBP Series Sensor with Arduino

Answers: 0


body:
I need to create something for a school assignment, but I'm stuck at the moment.
I have one code, which makes the Arduino Leonardo press space button on my laptop, which works.

I have another code, that turns on the LED when 2 wires are put in water.

Now I want to combine them, but I have no success.

Hope someone will help me with this.

These are the codes:

**The keyboard code leonardo:**

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

    bool eenkeergeweest = false;

    #include <Keyboard.h>

    void setup()
    {
        // make pin 2 an input and turn on the
        // pullup resistor so it goes high unless
        // connected to ground:
        pinMode(2, INPUT_PULLUP);
        // initialize control over the keyboard:
        Keyboard.begin();
    }

    void loop()
    {
        // while (digitalRead(2) == HIGH) {
        //   // do nothing until pin 2 goes low
        //   delay(500);
        //  }
        delay(1000);
        // new document:
        if (!eenkeergeweest) {
            eenkeergeweest = true;
            Keyboard.print(' ');
            delay(100);
            //Keyboard.releaseAll();
        }

        // wait for new window to open:
        delay(1000);
    }

**The code for the water LED:**

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

    int out = 12;
    int in = 4;

    int rd;

    void setup()
    {
        pinMode(out, OUTPUT);
        pinMode(in, INPUT);
    }

    void loop()
    {
        rd = digitalRead(in);
        if (rd == HIGH)
        {
            digitalWrite(out, HIGH);
            delay(100);
        }
        else
        {
            digitalWrite(out, LOW);
            delay(100);
        }
    }

title: Combining arduino leonardo code with water alarm code

Answers: 1

body:
How do you want them to work ? Do you want the spacebar pressed when there is a high signal read (when the light goes on)?

If you want the space bar press when it goes high this might work:

    #include <Keyboard.h>

    bool eenkeergeweest = false;
    int out = 12;
    int in = 4;

    void toggleKeyPress (const char& keypress)
    {
        if (!eenkeergeweest)
     {
            eenkeergeweest = true;
            Keyboard.print(' ');
            delay(100);
     }
    }

    void setup()
    {
        pinMode(out, OUTPUT);
        pinMode(in, INPUT);

        // initialize control over the keyboard:
        Keyboard.begin();

    }

    void loop()
    {
        const int rd = digitalRead(in);
        if (rd == HIGH)
        {
      toggleKeyPress(' ');
            digitalWrite(out, HIGH);
      // wait for new window to open:
      delay(1000);
     }
        else
        {
            digitalWrite(out, LOW);
        }
    }


body:
My traffic light code for the Arduino doesn't run. I was wondering if anyone could point out where my issues lie. The red and green LEDs should be on for 15 seconds and the amber on for 5 seconds.

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

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <stdint-gcc.h>
    /*15 second interrupt*/
    #define INTERRUPTS 975

    /*
     * col = current colour of light.
     * 'g', 'a', 'r', 'o'
     */
    volatile uint8_t count;
    volatile char col;

    ISR(TIMER0_OVF_vect)
    {
     count++;
     if (count >= INTERRUPTS){
      if (col == 'g'){
       /*switch to amber*/
       col = 'a';
       /*reset counter*/
       count = 0;
       /*timer counter to 171 as we only need 85 clicks for 5s*/
       TCNT0 = 171;
       PORTD = 0b00000010;
      } else if(col == 'a'){
       col = 'r';
       count = 0;
       TCNT0 = 0;
       PORTD = 0b00000100;
      } else if (col == 'r'){
       col = 'o';
       counter = 0;
       TCNT0 = 171;
       PORTD = 0b00000010;
      } else if (col == 'o'){
       col = 'g';
       count = 0;
       TCNT0 = 0;
       PORTD = 0b00000001;
      } else{
       return;
      }
     } else{
      if(col == 'g' || col == 'r'){
       TCNT0 = 0;
      } else if(col == 'a' || col == 'o'){
       TCNT0 = 171;
      }
     }
     return;
    }

    int main(void)
    {
     /* normal mode */
     TCCR0A = 0b00000000;
     /* prescaler = 1024 */
     TCCR0B = 0b00000101;
     /* enable overflow interrupts */
     TIMSK0 = 0b00000001;
     TCNT0 = 0;
     sei();
     /*Initialise output*/
     DDRD = 0b11111111;
     count = 0;
     col = 'g';
     PORTD = 0b00000001;
     while (1){
        }
    }

title: Traffic lights using timer

Answers: 3

body: As far that i understand, you set the color using the Ports directly. In case green and red you set PORTD = 0b00000010;

body:
    #define INTERRUPTS 975

    volatile uint8_t count;

    if (count >= INTERRUPTS){

`count` is an 8 bit integer, so the maximum value of it is `255`. Therefor `count` will never be bigger of equal to 975.

Use `volatile uint16_t count;` instead.

PS instead of messing with the `TCNT0` register, I'd use 2 different values of `INTERRUPTS` to change between 15 and 5 second intervals.

Something like `if( count>=975 || ( (col=='g'||col=='r') && count>=325 ) ){`

body:
If you want solution with a timer, I suggest to setup a 35 second cycle (35 = 15+15+5).
Then, you will trigger next LED when 0,15,30 seconds passed, and restart cycle at 35 seconds.

Other ways to achieve same effect are:
1. Use classic `delay()` function.

    while (true)
    {
        TurnOn(Green);
        delay(15000);
        TurnOn(Red);
        delay(15000);
        TurnOn(Amber);
        delay(5000);
    }

2. use `millis()` function


body: I am using an XBee radio setup to transmit bytes over a distance of approximately .25 miles. For the first 20,000, or so, transmissions it was completely error free. However, once there was a single error, every other transmission became an error. For my project a transmission consists of three bytes, with the third byte being an XOR of the first two. The first byte also has a parity bit. The 1st byte is a sensor number and the second byte is data. In the past I've received a few transmissions with errors detectable through the parity or XOR, but these did not cause an "avalanche effect" of errors. However, yesterday when I was running the radio setup, after ~20,000 transmissions (~60,000 bytes) there was an error, and after that error occurred, all transmissions were detected as containing errors. What I am hypothesizing occurred was that a single byte was dropped in transmission completely throwing off the sequence of bytes for a transmission. For example, the second "data" byte was lost, meaning the next transmission would consist of the first "sensor" byte, the third "XOR" byte, and the next first "sensor" byte. This error would continue to effect all later transmissions. I am operating a baud rate of 9600, with a nominal baud rate that is much lower. For this reason, I do not believe this is an issue with the serial buffer instead of a dropped byte, but I could be wrong. Is it possible that a byte would be dropped given the scenario I explained? If so, how could this be fixed in software/hardware? If it is likely to be a serial buffer issue, can this be solved? I know according to the Arduino core documentation increasing the serial buffer size beyond 256 may cause race conditions.

title: XBee radio dropping bytes?

Answers: 0


body:
Is there a way to run a Stepper motor with Arduino MEGA 2560 with A4988 driver component.

I am using this https://github.com/laurb9/StepperDriver library and with this code,

    Serial.println("Starting motor ALL");
    int steps = atoi(third.c_str());
    int duration = atoi(fourth.c_str());

    BasicStepperDriver stepper1(steps, DIR, STEP, ENBL);
    stepper1.enable();
    stepper1.setMicrostep(MICROSTEPS);
    stepper1.setRPM(MAX_RPM);

    BasicStepperDriver stepper2(steps, DIR_2, STEP_2, ENBL_2);
    stepper2.enable();
    stepper2.setMicrostep(MICROSTEPS);
    stepper2.setRPM(MAX_RPM);

    int starttime = millis();
    int endtime = starttime;
    while ((endtime - starttime) <= duration) // mS
    {
         stepper1.rotate(90);
         stepper2.rotate(90);
         endtime = millis();
    }
    stepper1.disable();
    stepper2.disable();
    Serial.println("DONE");

The problem with this is that each stepper motor in this code waits for each other and not simultaneously like a DC motor. What could be done to make it work simultaneously?

title: Running Stepper motors (at least 2) at the same time

Answers: 1

body:
Try the [AccelStepper][1] library. It can control both steppers at the same time. Also provides some useful [examples][2]

AccelStepper with more than one stepper also requires the [Adafruit Motor library][3] to be installed.

  [1]: http://www.airspayce.com/mikem/arduino/AccelStepper
  [2]: http://www.airspayce.com/mikem/arduino/AccelStepper/AFMotor_MultiStepper_8pde-example.html
  [3]: https://github.com/adafruit/Adafruit-Motor-Shield-library


body:
I was trying to build a system that when the user pushes the button, the servo rotates 45 degrees and than returns back to zero. This system is going to be duplicated as there will be two servos and pushbuttons.

Here's my code:

    #include <Servo.h>
    Servo solservo;  // create servo object to control a servo
    Servo sagservo;
    // twelve servo objects can be created on most boards

    int possol = 0;    // variable to store the servo position
    int possag = 0;
    int degsol=0;
    int degsag=0;

    int ledPin = 13; // choose the pin for the LED
    int solPin = 7;   // Pushbutton
    int sagPin = 8;     // variable for reading the pin status
    int valsag = 0;
    int valsol = 0;

    void setup() {
      solservo.attach(9);  // attaches the servo on pin 9 to the servo object
      sagservo.attach(10);
      pinMode(solPin, INPUT);
      pinMode(sagPin, INPUT);
      pinMode(ledPin, OUTPUT);

    }

    void loop() {
      digitalWrite(ledPin, HIGH);    //Arka İsik
      valsag = digitalRead(sagPin);  // read input value
      valsol = digitalRead(solPin);
    //Sag Servo

      if (valsag == HIGH) {
        sagservo.write(45);              // tell servo to go to position in variable 'pos'
        delay(100);                       // waits 15ms for the servo to reach the position
        sagservo.write(-45);

      }
    //Sol Servo
      if (valsol == HIGH){
        solservo.write(45);
        delay(15);
        solservo.write(0);
      }

    }

There'll probably be lots of small errors in this code, like unnecessary ints and such, but when I upload this program and push the button, it just rotates 45 deg, and doesn't come back. Is there a way that I can solve it?

Thanks in advance

title: Servo Control using Pushbutton

Answers: 1

body: Change `sagservo.write(-45);` to `sagservo.write(0);`.


body:
Here is my objective:

If the value of `EMGv` is at or above 900, start moving the motors left. The motors should continue to move left for a maximum of one second, provided `EMGv` stays at or above 900. If during this time `EMGv` goes below 900, the motors should move right for one second. Then the motors should stop. At any time after this should `EMGv` go above 900 again, the process should repeat.

In simpler terms, the project is a robotic hand, wired to an EMG circuit. When the EMG signal gets above 900 the hand should close by the motors all turning left for one second and when the signal goes below 900 the hand should open by the motors turning right for one second.

Here is my loop atm when `move(motor #, speed, direction (1 for left, 0 for right))` is the function to move the motors and `stop()` stops all motors

    void loop(){

      unsigned long starttime; //time limit for hand movement
      int EMGv = analogRead(EMG);
      starttime=millis();
      while(EMGv >= 900){
        if (millis()-starttime < 1000) //limit on 1000ms
        {
        move(0, 255, 1); //motor 1, full speed, left
        move(1, 255, 1); //motor 2, full speed, left
        move(2, 255, 1); //motor 3, full speed, left
        move(3, 255, 1); //motor 4, full speed, left
        move(4, 255, 1); //motor 5, full speed, left
        } else {
          stop();
        }
      }
    }

title: Motor Control Help

Answers: 1

body:
I suspect you would do well to first write (in English) the *exact* set of rules you want it to follow -- don't worry about the code to begin with - get it clear in your head what you want the code to do.  (If this is already clear to you, then just write it :-) )

Here's what I think you might mean -- although it's not exactly what you wrote.

*If EMG is at or above 900, start moving the motors left.  The motors should continue to move left for a maximum of one second, provided EMG stays at or above 900.  If during this time EMG goes below 900, the motors should move right for one second.  Then the motors should stop.*

Once you have that, turning it into code looks well within your ability, judging by the code you've posted.  Here's my attempt - note that it'll only be correct if I have correctly stated your desired rules.  (And if I've correctly guessed how the `move` API works - I guess it starts the motor moving, that you need to cancel it to stop it moving.  Please say if this is wrong.)

I've used LEFT and RIGHT instead of 1 and *whatever*, for clarity.

    void loop(){
      // If EMG is at or above 900
      int EMGv = analogRead(EMG);
      if (EMGv >= 900)
      {
        unsigned long starttime = millis();

        // Start the motors moving left
        move(0, 255, LEFT); //motor 1, full speed, left
        ...and the other motors...

        // Continue for a maximum of one second, and while EMG stays at or above 900
        while ( (millis()-starttime < 1000) && ((EMGv = analogRead(EMG)) >= 900)) {
          // Just wait
          delay(1);
        }

        // If during this time EMG goes below one second...
        if (EMGv < 900) {
          // ...the motors should move right for one second
          move(0, 255, RIGHT); //motor 1, full speed, right
          ...and the other motors...
        }

        // Then the motors should stop.
        move(0, 0, LEFT); //motor 1, stop, left
        ...and the other motors...
      }

    // More stuff here, otherwise it will immediately go round the loop again and start moving again
    }


body: I am currently using a simple protocol I created to send three bytes (unit information, data, and XOR) individually over an XBee radio (3 bytes are considered a single transmission). However, this is not always reliable if a byte is dropped. For this reason I'd like to encapsulate each individual byte as a packet in a way that the Arduino could identify which byte is which and if a byte is lost then just wait for the next transmission. What I am not sure about is creating a packet. I haven't been able to find any tutorials or example code.

title: XBee: How do I create a packet?

Answers: 2

body:
 - The [x-ctu][1] xbee config tool has a few options worth exploring
   such as error checking. This means the xbee would do the work.

*OR using the Arduino(s)*

 - Adding a couple more bytes to you your current system with a checksum
   of the first 3 bytes would be a simple way to check for a valid
   packet.
 - You could also use a struct of values (along with a checksum).
          Bill Porter has written an Arduino Library called [Arduino Easy    Transfer][2]. The library is designed to send and receive a
   struct    along with checksum validation. This is an [overview page][3] for the library.

 - Sending and receiving structs over `Serial` is also covered [here][4]

  [1]: https://www.digi.com/products/xbee-rf-solutions/xctu-software/xctu
  [2]: https://github.com/madsci1016/Arduino-EasyTransfer
  [3]: http://www.billporter.info/2011/05/30/easytransfer-arduino-library/
  [4]: https://arduino.stackexchange.com/questions/203/sending-large-amounts-of-serial-data

body:
The biggest mistake people always make with serial communications of any form is to just send raw data over the connection. While you might just about get away with that on a 100% reliable direct serial connection over a short distance, as soon as you introduce anything with any form of uncertainty to it you are, as you have seen, doomed to failure.

So you have to come up with a reliable method of transferring data in such a way that the receiver knows that it has received valid data, and how to find valid data.

So you need to create a packet. That's not something where you just wave a magic wand and a packet is created. A packet starts it's life in your own head.

In order to reliably transfer data there are a few things you need to consider from the point of view of the receiver:

* Where is the start of my data?
* How much data is there?
* Is this data correct?

The receiver has to have some way of knowing where the start of a packet is amid the torrent of bytes it is being sent. It needs to look out for something unique, something it cannot mistake for anything else. This is called synchronisation. It is often done with a specific sequence of bytes (known as a *preamble*) that can, through various means, never appear anywhere else.

And at that point things start to get a little more complex, for now you need some way of wrestling that kind of thing into a system that can only send bytes of 0 to 255 with no way of distinguishing raw data from control information like this synchronisation sequence. And that is where the concept of *escaping* comes in. This is where you nominate certain byte values as control bytes and decide that these bytes will never appear in your data without some kind of marker to say they are data bytes. A common escape marker is 255 (used in the telnet protocol) or 27 (the ANSI ESC character) although any character can be chosen.

For instance if you choose to have a synchronisation sequence of 0xAA, 0x55, you can then decide that neither of those bytes will ever appear in your data without first being preceeded by character 0xFF. So if you happened to have that sequence in your data you would expand it out to 0xFF, 0xAA, 0xFF, 0x55.  But what if you want to send the value 0xFF, in your data? How do you handle that? Well, you also escape 0xFF as well. 0xFF, being the escape character, has no actual value in the data. It only says that the next character must be interpreted as data. So to send 0xFF you would actually send 0xFF, 0xFF. Your receiver sees the first 0xFF and thinks "ah, the next byte that arrives, whatever it is, just be data." It then gets a second 0xFF and knows it is data. (Actually this is the opposite of escaping which says the next character is a control character, but the underlying concept is the same).

If it ever sees 0xAA, 0x55 then it knows, without a shadow of a doubt, that this is the start of a packet, or random noise. And that is where the next two points above come in: Validating your packet.

If your packets are always the same size then all you need to know is how many bytes to expect, which can be hard coded into your software. If you have different sizes of data to send then you also need to tell the receiver how big the data is. This forms part of the *packet header*. A small block of meta data that preceeds the actual data that holds information about the packet. Depending on your topology that could be things like the size of the data, where the packet came from, where it is going, etc, and maybe a checksum, though some people like to put the checksum after the data since it simplifies sending.

And then there is the checksum. Possibly the most important thing next to the synchronisation. And so easy to get wrong.

Having a checksum that is too simple is not so good. It can be fooled. That is, if values get corrupted in the data with a simple checksum it is far more likely that the checksum still says it's correct than with a more complex checksum. You should read up on existing checksum algoritms, such as Cyclic Redundancy Check (CRC) and things like the checksums used in IP packets. All are good lessons on how to deal with checksums properly.

So far we have just tackled the serial equivalent of UDP - throw a packet at a receiver and hope it gets there. Doing anything more reliable becomes much more complex. If you want to know if your packet actually got there you will need your receiver to acknowledge reception, possibly including some information about the packet it received, such as a sequence number. If the transmitter never receives that acknowledgement it needs to send the packet again, which means it needs to remember what the packet is that it sent. So you need a packet buffer, or even better, a packet queue. And timeouts. And sequence numbers.

That latter is most important. A sequence number is a unique (or unique over a reasonable period of time) identifier for a packet. When a transmitter doesn't receive an acknowledgement is it because the receiver never got the packet, or that the receiver did get the packet but the acknowledgement never made it back to the transmitter? If the latter then the receiver is liable to get the same packet multiple times through retransmission. By including a sequence number the receiver can go "hang on a moment, I have seen this packet already" and it can throw it away sending a new acknowledgement in the process.

So as you can see, reliable communication isn't as simple as just sending data, or even sending data in the form of a struct. There is a whole lot more to learn and understand.

I suggest you read some of the IP networking RFCs to learn more about reliable packet transmission and reception.

Oh, and I haven't even touched on sliding window reception and such like for how to best program your receiver software...


body:
I've built an accelerometer based dice. It changes colour based on what side of the dice faces up. All is well and good, except I'd like the RGB to fade from one colour to the next instead of changes instantly.

Here's the code:

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

    include <Wire.h>
    include <Adafruit_Sensor.h>
    include <Adafruit_LSM303_U.h>
    include <Adafruit_9DOF.h>
    include <Adafruit_L3GD20_U.h>

    /* Assign a unique ID to the sensors */
    Adafruit_9DOF                 dof   = Adafruit_9DOF();
    Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
    Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);

    // OUTPUT: Use digital pins 9-11, the Pulse-width Modulation (PWM) pins
    // LED's cathodes should be connected to digital GND
    int redLEDPin = 11;   // Red LED,   connected to digital pin 9
    int greenLEDPin = 10;  // Green LED, connected to digital pin 10
    int blueLEDPin = 9;  // Blue LED,  connected to digital pin 11

    // Program variables
    int red = 255;   // Variables to store the values to send to the pins
    int green = 255;
    int blue = 255;

    int lastOrientation = -1; // previous orientation

    void initSensors()
    {
      if(!accel.begin())
      {
        Serial.println(F("No LSM303 detected"));
        while(1);
      }
      if(!mag.begin())
      {
        Serial.println("No LSM303 detected");
        while(1);
      }
    }

    void setup() {

      Serial.begin(115200);
      Serial.println(F("RGB Dice... go!")); Serial.println("");

      /* Initialise the sensors */
      initSensors();

      pinMode(redLEDPin, OUTPUT);   // sets the pins as output
      pinMode(greenLEDPin, OUTPUT);
      pinMode(blueLEDPin, OUTPUT);

      int lastOrientation = -1; // previous orientation
    }

    void loop() {

      /* Get a new sensor event */
      sensors_event_t event;
      accel.getEvent(&event);

      int orientation = - 1; // dice orientation
      String orientationString; // string for printing orientation
      /*
       * orientation:
       * 1: cyan
       * 2: blue
       * 3: green
       * 4: magenta
       * 5: yellow
       * 6: red
       */

      // read accelerometer
      int x = event.acceleration.x;
      int y = event.acceleration.y;
      int z = event.acceleration.z;

      // calculate absolute values, and determin largest
      int absX = abs(x);
      int absY = abs(y);
      int absZ = abs(z);

      if ( (absZ > absX) && (absZ > absY)) {

        //base orientation Z
        if (z > 0) {
          orientationString = "1, cyan";
          orientation = 1;
          red = 255;
          green = 0;
          blue = 0;

        } else {
          orientationString = "6, red";
          orientation = 6;
          red = 0;
          green = 255;
          blue = 255;
        }

      } else if ( (absY > absX) && (absY > absZ)) {

        //base orientation Y
        if (y > 0) {
          orientationString = "2, blue";
          orientation = 2;
          red = 255;
          green = 255;
          blue = 0;

        } else {
          orientationString = "5, yellow";
          orientation = 5;
          red = 0;
          green = 0;
          blue = 255;
        }
      } else {
        //base orientation X
        if (x > 0) {
          orientationString = "4, magenta";
          orientation = 4;
          red = 0;
          green = 255;
          blue = 0;

        } else {
          orientationString = "3, green";
          orientation = 3;
          red = 255;
          green = 0;
          blue = 255;

        }
      }

      // if orientation changes, print out a description
      if (orientation != lastOrientation) {
        Serial.println(orientationString);
        lastOrientation = orientation;
      }

      analogWrite(redLEDPin, red);   // Write values to LED pins
      analogWrite(greenLEDPin, green);
      analogWrite(blueLEDPin, blue);
      delay(100);

    }

Every fading example I have adopted has broken the code so far. I guess my initial code isn't set up for it. Any ideas for a workaround?

title: Adding fade to this RGB LED IMU

Answers: 1

body:
You need to be a little clearer about the time that can exist between the sensor values changing. If you fade to slowly the correct value might never be reached before the sensor changes again. Maybe that's what you want?

You can't use a `delay()`.

You need a `currentRed`, `currentGreen` and `currentBlue` so you can fade to the values of red, green and blue.

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

    unsigned long last_reading_ms;
    int red = 255;   // Variables to store the TARGET rgb target values for each pin
    int green = 255;
    int blue = 255;
    int currentRed = 0;   // Variables to store the current rgb values of the pins
    int currentGreen = 0;
    int currentBlue = 0;

    void setup()
    {
       last_reading_ms=millis();
    }

    void loop()
    {
      /* read sensor every 100ms and set red, green,blue if changed */
      if (millis()-last_reading_ms > 100)
      {
        /* Get a new sensor event */
        sensors_event_t event;
        accel.getEvent(&event);
        //the rest of your sensor reading code here

        last_reading_ms=millis()
      }

      /* if orientation changes, print out a description */
      if (orientation != lastOrientation) {
       Serial.println(orientationString);
       lastOrientation = orientation;
      }

      calculateRGBFadeTo();

      analogWrite(redLEDPin, currentRed);   // Write values to LED pins
      analogWrite(greenLEDPin, currentGreen);
      analogWrite(blueLEDPin, currentBlue);

      //*** do not use a delay or use a very small one to slow the transition ***
      //delay(100);

    }

    /* get values 1 step closer to target red, green, blue */
    void calculateRGBFadeTo()
    {
      /* fade to required rgb values */
      if (currentRed<red)
       currentRed ++;
      else if (currentRed>red)
       currentRed --;

      if (currentGreen<green)
        currentGreen ++;
      else if (currentGreen>green)
        currentGreen --;

      if (currentBlue<blue)
        currentBlue ++;
      else if (currentBlue>blue)
        currentBlue --;

    }

Notes:

The fade can be slowed down either with a small delay such as 5 ms. or by using another `millis()` variable to determine the time since the led was last set.

For example: `if (millis()-last_rgb_write_ms > 5)`

It's also possible to speed up the fade by using a larger increment. An increment of two, for example, `currentRed+=2;` instead of `currentRed++;`

Reminder, the comparison of when the target red, green, blue has been reached will be more complex with an increment greater than `1`.

An increment of `2` and a sensor read frequency of `128ms` (instead of 100) would ensure the correct RGB values are always reached. Alternatively reading the sensor every `255ms` (4-5 times per second) would also ensure the correct RGB values has been reached.

Using `millis()` and avoiding delays allows many more tasks to be performed with more accurate timings.


body:
I´m using `LowPower.h` and `PinChangeInt.h` libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.

I´ve reached to wake up the Arduino every 8 seconds using `LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF)` and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with `LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF)` but I can´t combine that periodical awakening with the asynchronous awakening.

Here is my code:

    void setup(){

        Serial.begin(9600);

        //Pines declaration

        loopsToSend = setTimeToSend();  //

        //The three async buttons
        PCintPort::attachInterrupt(4, readOpinion,RISING);
        PCintPort::attachInterrupt(5, readOpinion,RISING);
        PCintPort::attachInterrupt(6, readOpinion,RISING);
    }

    void loop(){

        if(loops < loopsToSend ){

            byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

            if(opinionValue != 0){
                Serial.println("Button pressed!");

                //Writing result in a file
                opiniones++;
                delay(500);
            }
            //Go to sleep 8 seconds
            LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
            opinionValue = 0;
        }
        else {
            wdt_disable();

            if(opiniones > 0){
                //Send file using GSM module
            }
            else{
                loops = 0;
            }
        }
        loops++;
    }

Can anyone help me? Thanks

title: Waking up async the Arduino while it's sleeping periodically

Answers: 1

body:
This one works for me:

    #include <PinChangeInterrupt.h>
    #include <LowPower.h>

    // I want to know when it was interrupted by PCINT:
    volatile byte flag = 0;
    void handler() {
        flag = 1;
    }

    void setup() {
      Serial.begin(115200);
      pinMode(A0, INPUT_PULLUP);
      attachPCINT(digitalPinToPCINT(A0), handler, CHANGE);
    }

    void loop() {
      Serial.println("entering powerDown sleep mode");
      Serial.flush(); // wait for sending all data

      LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

      if (flag == 1) {
        flag = 0;
        Serial.println("Pin change interrupt");
      } else {
        Serial.println("Timeout");
      }
    }

However if you use RISING (or FALLING), it also wakes up from the sleep when pin changes back to the oposite state (and it'll be reported as Timeout).


body:
I'm trying to use an Arduino UNO board with Assembly on MacOS, but I couldn't find any documentation about it.

How can I compile and upload Assembly files to the Arduino with MacOS?

title: Using Arduino with Assembly on MacOS

Answers: 1

body:
You can add source code to the sketch in the Arduino IDE. When adding a new source code file make sure the extension is uppercase `.S`

Files with `.S` extension will be compiled as Assembly.

There is an Arduino IDE for the mac but if you want to use an external editor you have many options.

The simplest is to switch on `File>Preferences>External Editor` in the Arduino IDE. This makes the IDE work in "read-only/auto-reload" mode allowing edit in a different code editor but compile and upload (without reopening the code) in the Arduino IDE.

There are also the `File>Preferences` `Verbose Compile` and `Verbose Upload` options in the Arduino IDE. These options will show you the commands used to compile, link and upload. You will see that the IDE runs other programs, outside of the IDE, such as `avrdude` and `g++`. Therefore a small script file can be created to call the same commands from a different IDE if the external editor doesn't have a facility to run external commands.

The verbose output will show where the tools and sources for build and upload are located. Normally for `Uno` (avr) they are below `[IDE Folder]\hardware\arduino`.


body:
I am attempting to send a simple 1 byte value from one arduino to another using I2C with the Wire library. From reading I see that this is typically done using the event monitor supplied by the Wire library, but this has caused problems for me because the handler function may only have one argument and it must be a `void` function or else the library throws errors during compilation. So I have a couple of questions about what is or is not possible with the Wire library short of modifying the source:

1. Should the `Wire.available()` function respond to attempted transmissions if the event handler referenced above does not exist? My first idea was to simply write my own function that would be called whenever this value is not 0, but it appears that this value never changes - unless the event handler is used.

2. Can you update variables which reside outside of a function from inside of the function WITHOUT passing those variables as pointer arguments? Because recall from above that I cannot pass any arguments besides the one specified for the number of bytes received.

I cannot understand how this library could be useful for Arduino to Arduino communication if it is literally not possible to use the transmitted values anywhere other than inside of the event handler. My next step is start modifying the source to suit my needs, but I would imagine what I'm describing is a basic thing and would be shocked to find out that it's not possible without modification.

title: Update Variable via Arduino to Arduino I2C

Answers: 2

body:
> Can you update variables which reside outside of a function from inside of the function WITHOUT passing those variables as pointer arguments?

Yes, that's exactly what global variables are for. Make them `volatile` as they will be updated inside an ISR (or more exactly, a function called from an ISR).

body:
I see now what the issue was. But to answer my questions:

1. `Wire.available();` will not work if called outside of an event handler. I confirmed this while reading through the `Wire.cpp` source code and it explicitly states that the function should only be called from an event handler.

2. It is as simple as only a matter of updating global variables. I feel quite silly for not realizing that simply declaring variables outside of a function gives ANY function access to it rather than only the main function.

I see that the other answer mentions applying the `volatile` modification to the variables, but this is only necessary when the function in question is attached to an interrupt handler.


body:
Good evening all,

I'm having an issue with a quick "test" project that I am tinkering with (learning the "do's" and "don'ts") the NeoPixel LED strip.  I've been piecing together excerpts from other folks and so far everything is great.

I'm doing it over serial sending switch/case with numbers from the keyboard for different options.  The issue I am currently having is "case 1:", when I hit the "1" key and it fires off, I want to be able to interrupt it immediately by using key "0".  So basically, I'd like it to loop forever after hitting key "1" but terminate after hitting "0".

However, when hitting key "1", then key "0" immediately, the while loop repeats twice, then breaks.  I haven't done any C/C++ since I was 12 and now I'm 38 so now it is all trial and error based so please pardon my syntax.  Any help would be appreciated.

    #include <Adafruit_NeoPixel.h>
    #include <SoftwareSerial.h>

    #define PIN 6
    #define LEDs 16

    int LED_Fade_Interval = 5;

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDs, PIN, NEO_GRB + NEO_KHZ800);

    void setup() {

      Serial.begin(9600);

      strip.begin();
      strip.show();

    }

    void loop() {

      while (Serial.available() == 0);

      int numKey = Serial.read() - '0';

      uint32_t low = strip.Color(0, 0, 0);

      switch(numKey)
      {

        case 1:
          Serial.println("LED Strip is ON - BLUE FADE");
          while (numKey != 0)
          {
            int numKey = Serial.read() - '0';
            delay(50);

            ws2812_FadeInOut(0, 0, 255, LED_Fade_Interval);

            if (numKey == 0)
            {

              for( int i = 0; i<LEDs; i++){
                strip.setPixelColor(i, low);
                strip.show();
              }

              break;

            }

          }

        case 0:
          Serial.println("LED Strip is OFF");
          for( int i = 0; i<LEDs; i++){
              strip.setPixelColor(i, low);
              strip.show();
          }
          break;
       }
    }

    // *******************************************
    // FADER Function
    // *******************************************
    void ws2812_FadeInOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
      for(uint8_t b = 0; b <255; b++) {
         for(uint8_t i=0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
         }

         strip.show();
         delay(wait);
      };

      for(uint8_t b=255; b > 0; b--) {
         for(uint8_t i = 0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
         }
         strip.show();
         delay(wait);
      };
    };

title: Arduino Serial Response is Slow when in While Loop

Answers: 2

body:
[`Serial.read()`](https://www.arduino.cc/en/Serial/Read) reads one character from the Serial stream, or returns -1 if there are no characters to read.

When you send a `1` from the Serial Monitor, the Arduino board first receives an Ascii 1, and then receives a line-end character (eg, an LF from Linux) or characters (eg, a CR and LF from MSWindows).

Since none of 1, CR, or LF are equal to an Ascii 0, the numkey value computed at the fourth line of case 1 is not 0, so the exit condition isn't met.  Thus the fade loop continues running, until it sees a `0` character.

Instead of continuing to read characters within while loops within the switch/case statement, test if more serial input is available.  Note, avoid exiting early from case 1, after you read a digit at the beginning of `loop()`, read and discard the line-ending characters that follow.

body:
NeoPixels' timing requirements are pretty tight - not necessarily high frequency but high accuracy, for at least certain parts of the serial pulse train. To achieve that, I believe the (Adafruit) NeoPixel library takes over one of the timers during the transmission and turns off interrupts for at least some of the time. That will have a negative impact on any background processes. Read through the NeoPixel library code; it should be clear.

However, while researching my answer (so as to not embarrass myself too badly!), I found [this article at josh.com][1] that describes driving NeoPixels with a much lower impact and goes on to demonstrate his technique with a video of a 1000 NeoPixel string(!) driven at 30 FPS by an old, apparently Atmega 168-based, Duemilanove.

  [1]: https://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/


body:
I'm quite new with the electronics part of Arduino, but I thought that this was the basic way to get the DS18B20 temperature device hooked up. However, I can't detect it in my program using OneWire and DallasTemperature.

This is an image of my connections:

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

Basically my approach was like this:

Connect ground on ground on the DS18B20.
Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).
Between the 5V and the two yellow cables, I connected a 4.7K resistor.
Vdd on the DS18B20 is not connected to anything.

Anyone have any idea why this is not working as expected for me?

Thanks in advance!

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

title: Getting the DS18B20 detected and temperature read

Answers: 1

body:
> Vdd on the DS18B20 is not connected to anything.

According to the datasheet:

>  When the DS18B20 is used in parasite power mode, the VDD pin must be connected to ground

---

> Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).

That means port 2 would always be high, right?

---

According to [Temperature Sensor DS18B20](https://arduino-info.wikispaces.com/Brick-Temperature-DS18B20?responseToken=b846613ae07121485e0bd622a9bcd111) this is the wiring for non-parasitic power:

[![Non parasitic power][1]][1]

If you want the two-wire version (parasitic power) it would be:

[![Parasitic power][2]][2]

  [1]: https://i.stack.imgur.com/9JahP.jpg
  [2]: https://i.stack.imgur.com/irbaD.jpg


body:
I have a project where I need an Arduino Uno and 4 DC motors to run on batteries. My first thought was that I'll just hook up 3 or 4 AAs to the Arduino and a 9V to the motor drivers.

I googled to be safe and the internet consensus seemed like that method would be very inefficient. Voltage wasn't the problem, but apparently 9V have very low current and I'd be wasting money, and the Arduino wastes current like a madman. Most solutions involved buying additional hardware.

**Is there a way I can efficiently power my project without buying more chips?**

title: How do you figure out an efficient battery setup for a project?

Answers: 2

body:
Our beloved admin Nick Gammon has made a [very neat articile][1] on this subject, I suggest you read it and apply as many of the methods he described.

Also, it can be worth to check the requirements of your project, how long should it work on battery to be acceptable? Set some realistic boundarys to avoid getting lost in (trying to) optimizing beyond all practical purposes.

There are two places where you can save power:

**In software**

The Atmega328P has a few tricks to save power.
Most notably is powering down peripheral devices and/or using sleep modes.
I believe the P version of the Atmega328 also has more power saving modes/ is more efficient overall.

Also take a look at [this][2].

**In hardware**

An Arduino board has a lot of chips that may not even be neccesary on your battery project.
Most notably the USB interface chip, if you're going to run off battery, you most likely won't need this chip.
But also, the voltage regulator on the Arduino is, I believe, a linear regulator and is likely to be inefficient.
Also power/status LED's will some current.

You can choose to put a ATMega328P on a breadboard, and power it directly with a source that will be between the min/max voltage of the ATMega328P. This way you don't get the losses that a regulator will have.
If you want to use a regulator (for a higher voltage source) you should use a switching regulator, they're typically more efficient.

Mind that on low voltages, the ATMega328P can't do a 16Mhz, but it's actually a pretty interesting point, since it will consume less power on 8Mhz, or even less on 1Mhz.

  [1]: http://www.gammon.com.au/power
  [2]: http://playground.arduino.cc/Learning/ArduinoSleepCode

body:
Agreed, the DC motors would drain the 9V in no time.

Consider the other way around. The 9V powers the Arduino and the 4 AA batteries power the motor.

Then again, you probably don't need the 9V at all, just power everything off of the 4 AA batteries.

I suggest using a large capacitor (something in the 470-1000uF region) to hold up the supply to the Arduino. Adding a diode before the capacitor will prevent the capacitor discharging to the motors when the motors are drawing a lot of current.

Using 4x 1.5V batteries will result in a voltage of just over 6V. The diode will have a voltage drop of around 0.6V, so the resulting voltage would be 5.4V.

This voltage is to low for the onboard voltage regulator on the Adruino. It is within limits for the raw 5V input (ie. 5.5V).

Optionally you can add a 5V zener diode across the Arduino's power input to protect ti from overvoltage. A 6.8 ohm resistor is added to limit the current flowing through the zener diode. As the voltage drops below 5V, the zener diode will turn off, allowing the micro to operate down to 4.5V. If you change to a lower frequency crystal/resonator you can operate the microcontroller down to 2.7V (1.8V is possible is the clock frequency is 4MHz or less but I doubt the motors will run).

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

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

<!-- End schematic -->


body:
Has anyone successfully used the AREF pin on [MKR1000](https://www.arduino.cc/en/Guide/MKR1000)?

I'm trying to use an EXTERNAL voltage reference (I need 1.5V instead of the default 5V) with:

    analogReference(EXTERNAL)

But when I compile I receive the following error message:

> MKR_001:161: error: invalid conversion from 'int' to 'eAnalogReference {aka _eAnalogReference}' [-fpermissive]

In the documentation (for analogReference) I found the following:

> DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)
INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only)
INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only)
EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference.

Thanks,
Corrado

title: Analog Reference (AREF) pin on Arduino MKR1000 not working?

Answers: 2

body:
The compiler error

    MKR_001:161: error: invalid conversion from 'int' to 'eAnalogReference {aka _eAnalogReference}' [-fpermissive]
Is actually really simple once you understand what it means.

    analogReference(EXTERNAL);
The function `analogReference` takes an integer as a parameter, but you are passing it `EXTERNAL` which is an enumeration.  Its probably an enumeration that uses integers for its values, but to the compiler there is a difference.

If you want to disable the warning then you can use the `-fpermissive` flag on the compile command line, this is not a good idea because it invalidates the "type-safeness" of the language for the whole program.  Instead it is better to address them on a case by case basis and just cast EXTERNAL to an int.

    analogReference((int)EXTERNAL);

body:
In fact, the [documentation][1] suggests that for SAMD boards (MKR1000 is based on Zero) a different enumeration should be used where each value is prefixed with `AR_` so for example you should use `analogReference(AR_EXTERNAL);`.

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/


body:
I am powering solenoid with 24 volt as required however I am using TIP122

transistor that has base connected to Arduino Digital Pin 6 via a 1K Resistor.
And the collector is connected to negative side of 1N4001 diode, this also serves as the Negative out for solenoid. and emitter is connected to the 24 volt power input.
The positive input from power source is connected to positive terminal of diode is directly connected to solenoid.

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

As per the logic I am trying to turn on Solenoid based on Signal from Arduino PIN 6, but for some reason Solenoid doesnt power up.

In my code below I want to turn on solenoid if soil moisture goes above 60. the signal is coming from Pin 6 but solenoid doesnt power up.

    #include <SPI.h>

    int solenoidPin = 6;    //This is the output pin on the Arduino we are using

    int GLED = 5; // Wet Soil Indicator at Digital PIN D5
    int RLED = 9; // Dry Soil Indicator at Digital PIN D9
    int SENSE = 1; // Soil Sensor input at Analog PIN A1
    int val = 0;

    int greenLedPin = 2; // LED on pin 2
    int yellowLedPin = 3;
    int redLedPin = 4;

    int lightSensorPin = A0;
    int analogValue = 0;

    void setup() {
      pinMode(solenoidPin, OUTPUT);           //Sets the pin as an output

      // Open serial communications and wait for port to open:
      Serial.begin(9600);

      pinMode(greenLedPin, OUTPUT); // LED on pin 2
      pinMode(yellowLedPin, OUTPUT);
      pinMode(redLedPin, OUTPUT);

      pinMode(GLED, OUTPUT);
      pinMode(RLED, OUTPUT);

    }

    void loop() {
      val = analogRead(SENSE);
      val = val / 10;
      analogValue = analogRead(lightSensorPin);
      Serial.print("LDR value: ");
      Serial.print(analogValue);
      digitalWrite (redLedPin, analogValue < 55) ;
      digitalWrite (yellowLedPin, analogValue >= 55 && analogValue <= 100) ;
      digitalWrite (greenLedPin, analogValue > 100) ;

      Serial.print(" Soil Moisture: ");
      Serial.println(val);
      digitalWrite(GLED, (val < 50));
      digitalWrite(RLED, (val > 50));
      // Turn on Solenoid Valve if soil moisture value greater than 60
      digitalWrite(solenoidPin, (val > 60));

    }

I am doubting on the diode to use , because I am  powering solenoid of 24 volt and not sure if the diode is correct , as per my knowledge, diode can get direct if higher voltage is passed.

Any help will be greatly appreciated.

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

title: How to turn on Solenoid based on Soil Moisture value?

Answers: 1

body:
When looking your schematic and assuming that **J1** connector is not powered by your MacBook as your Arduino board, the main problem is located to the **GND** signal.

In order to have a commutation current to the **Base** of the TIP122 through the 1K resistor, you need to link the **GND** signal its **Emitter** with the **GND** signal of your Arduino board.

See a proposed schematic from **["High-Power Control: Arduino + TIP120 Transistor"](http://bildr.org/2011/03/high-power-control-with-arduino-and-tip120/)**

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

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


body:
How can I have three remote transmitters send distinct signals to a single receiver?

My project requires 3 remote controls, each with 2 inputs.

I need to distinctly identify these 6 signals from the 3 remotes onto one arduino board.

Is this possible to do with one receiver?

Would I be able to pair one remote to one receiver (so 3 receivers), or will there be noise / interference?

What is the simplest and/or cheapest solution to this?

FYI I am going to be using a 315 Mhz remote / receiver (remote control has 4 inputs). I am waiting for them to come in the mail but I want to start thinking about how I will build this.

title: Multiple (3) RF transmitters to a single receiver?

Answers: 1

body:
These transmitter all transmit on the same frequency so if you have multiple receivers they will all get the same signal.

The only way I can see you can do this is make some type of protocol where you send data with a station ID and only the receiver with the station ID matching the message will act on it.

EDIT:

Sorry have to get used to the double-enter making a send.

@JamesWierzba your 'remotes' will need to be more than just a push button to send a HIGH or LOW signal via the transmitter.

Your 'remotes' will need to each have a unique ID, we usually use DIP switches for this. A small microcontroller will need to read these DIP switch and compose the message to be send to the receiver.

A simple message like "ID_BUTTON_PRESS" where ID is the decimal or hex equivalent of the DIP switches.

On reception of the message the microcontroller receiving the message will know which remote it comes from by looking at the ID part of the message.


body:
I am using Arduino DUE in my project. The project is massive (about 7000 lines of code in total, with massive schematic), so I decided not to post the whole code and schematic, except explain the hardware and configuration I am working with:

 - **Arduino DUE;**
 - **12V switching power supply**;
 - **LTC1660 DAC** (used withstandard SPI library);
 - **Nextion HMI** (Used with standard library `#include Nextion.h        //INCLUDE NEXTION LIBRARY)`;
 - **DS3231 RTC module** on I2C bus (Library used: [Wire](http://arduino.cc/en/Reference/Wire)  `#include <DS3231.h>`)
 - **24LC256 EEPROM** on same I2C bus (Library used: [Ext EEPROM](http://github.com/JChristensen/extEEPROM/tree/dev) `#include <extEEPROM.h>`)

The base line, is that on power-on the controller just freezes besides, it can't be the problem with power as I get this problem using both 12 V from switching PSU and 5 V USB cable. I can not really analyse the problem, as the deadlock occurs even before the program start to execute content of `void setup()`. My best guess is that the deadlock occurs due to infinite loops in the Arduino's `twi.cpp` where infinite loop can occur if the controller receives no acknowledge
bit. But then again I can not be sure here. However when I push restart button on the Arduino or enable Serial monitor in Arduino IDE when the circuit is powered on , it starts to work, and it works just as expected.

After reading the datasheet for the DUE's μC, I've found that it have the watchdog option embedded:

> After a Processor Reset, the value of WDV is `0xFFF`, corresponding to
> the maximum value of the counter with the external reset generation
> enabled (field `WDRSTEN` at 1 after a Backup Reset). This means that a
> default Watchdog is running at reset, i.e., at power-up. The user must
> either disable it (by setting the `WDDIS` bit in `WDT_MR`) if he does
> not expect to use it or must reprogram it to meet the maximum Watchdog
> period the application requires. The Watchdog Mode Register (`WDT_MR`)
> can be written only once. Only a processor reset resets it. Writing
> the `WDT_MR` register reloads the timer with the newly programmed mode
> parameters.

I've started to explore it, and as I got it, the watchdog is ON by default, and its timer period is 16 seconds by default, so as it is not normally used in DUE, I assumed, that somewhere it is just disabled, and in `main.cpp` I found the following:

    int main( void )
    {
       // Initialize watchdog
       watchdogSetup();
       init();
       initVariant();

where `watchdogSetup()` led to:

    void watchdogDisable(void)
    {
       WDT_Disable (WDT);
    }
    void watchdogReset(void)
    {
       WDT_Restart (WDT);
    }
    extern "C"
    void _watchdogDefaultSetup (void)
    {
       WDT_Disable (WDT);
    }
    void watchdogSetup (void) __attribute__ ((weak, alias("_watchdogDefaultSetup")));

As I got it, due to this, the watchdog was disabled for DUE by default, and commenting out `watchdogSetup();` in `int main()` would allow the watchdog to work (as watchdog is on at power on by default, according to datasheet).

I've also added the `WDT_Restart (WDT);` to `void loop()` of the program in order to kick watchdog every program cycle.

Well, for some reason, that did not help me, and I'm still receiving the deadlock when I power on the controller, even through the watchdog is technically not disabled, after 16 seconds it still do not restart the system. And, pressing the reset button or the Serial monitor in Arduino IDE makes the system run as expected. Am I missing something out? Your help and suggestions are appreciated, shall any additional info be needed, just let me know, I need to get this project running so badly.

By the way, my `void setup()` function is quite long, and if I set the watchdog to 1 second, using
`void watchdogEnable (uint32_t timeout)` instead of commenting out `watchdogSetup()` in `main.cpp`, and use reset button after power on, I can see the watchdog working as it can't get to `void loop()` in time in order to reset watchdog (as `void setup()` takes about 3 seconds due to delays).

title: Arduino DUE deadlock problem, watchdog not working

Answers: 1

body:
   Found people suffering with the same problem on Arduino's official forum. It turned out that the problem arises from the schematic of Arduino Due, that fails to hold 'reset' pin high for long enough period of time on power-on.

  There are multiple solutions involving adding some capacitance between reset pin and ground pin, but this might damage circuit in long run (at power-off), so I managed to find other way around it: **there is an ATmega16U2 used as USE-to-TLL serial chip that have access to reset pin of AT91SAM3X8E.**

  The ATmega16u2 can be reprogrammed so that on power-on it provide short "HIGH" period to AT91SAM3X8E reset pin. The program for ATmega16U2 can be found here:
https://forum.arduino.cc/index.php?action=dlattach;topic=167492.0;attach=52901

The updating precision is given here:
https://www.arduino.cc/en/Hacking/Upgrading16U2Due

**I've performed the given precision using Arduino UNO as programmer and can confirm that it worked properly.The problem's gone now.**


body:
I'm trying to make my Arduino's LED blink for the first time, but when I try to upload the code I get the following error in the Serial Monitor:

> Error opening serial port '/dev/ttyACM0'.
Try consulting the documentation at http://playground.arduino.cc/Linux/All#Permission

BTW, I have `serial.debug_rate=9600`, so I don't think that's the problem. Can anyone help me with this please?

title: Can't connect to serial port

Answers: 2

body:
It seems your serial does not have the right permissions to be opened in _user mode_. Try adjusting that by typing

    sudo chmod a+rw /dev/ttyACM0

on the console (open it by CTRLALTT).

body:
That issue is due to your username not being in the dialout group.
Try: `sudo usermod -a -G dialout yourusername` and rebooting to load the changes, then check again if the problem still persists...

I wrote an article about that here: [Solving Arduino IDE upload problem, and serial monitor error on Ubuntu](http://osrc.rip/Articles/SolvingArduinoUploadProblemOnLinux.html).


body:
I am sending a packet of sensor information over an Arduino XBee setup. The first byte of the packet is the packet header for synchronization. The second byte is the number of bytes in the packet (excluding header and packet size byte). The first byte of the packet payload is an identifying number for the sensor. The second payload byte is the data from the sensor. The third payload byte is an XOR for simple error checking. The first payload byte for the sensor ID will never need to be escaped, but the other two payload bytes may need to be escaped. The following is code I wrote for sending a single packet:

    Serial.write(PACKET_HEADER); // Packet header for synchronization
    Serial.write(calculatePacketSize(data, XOR)); // Size of packet
    Serial.write(unitInfo);
    // Check if the data byte needs to be escaped
    if(data == ESCAPE || data == PACKET_HEADER) {
        Serial.write(ESCAPE);
    }
    Serial.write(data);
    // Check if the XOR byte needs to be escaped
    if(XOR == ESCAPE || XOR == PACKET_HEADER) {
        Serial.write(ESCAPE);
    }
    Serial.write(XOR);

What I am unsure about is how to process a packet on the receiving end. One issue I see is that because there are a variable number of payload bytes, I cannot check via `Serial.available()` whether or not there are enough bytes to process the payload during this run through of `loop()`. How do I go about processing a packet, and making sure the packet was received error free? I need to just discard incomplete packets or anything without a header.

title: Receiving a packet via XBee radio

Answers: 1

body:
A state machine is what you want. That and to increase your preamble to two bytes, not one.  The reason being is that due to the escaping of the preamble character in the data it is impossible to have that character twice in a row. By then having it twice in a row as the preamble it is unambiguous that it is the preamble.

You should also (if needed) escape the packet size:

    Serial.write(PACKET_HEADER); // Packet header for synchronization
    Serial.write(PACKET_HEADER); // Packet header for synchronization
    uint8_t ps = calculatePacketSize(data, XOR); // Size of packet
    if(ps == ESCAPE || ps == PACKET_HEADER) {
        Serial.write(ESCAPE);
    }
    Serial.write(ps);
    Serial.write(unitInfo);
    ... etc ...

You might like to abstract the escaping into a function:

    void sendEscape(uint8_t c) {
        if (c == ESCAPE || c == PACKET_HEADER) Serial.write(ESCAPE);
        Serial.write(c);
    }

Then you can just call:

    sendEscape(calculatePacketSize(data, XOR));

etc.

Now for receiving. Implement a Finite State Machine. In that machine you have a number of states, such as *look for first preamble*, *look for second preample*, *look for size*, *look for id*, and *look for data*. As bytes arrive they trigger the next state.

So you start by looking for the first preamble byte. When that arrives it triggers looking for the second preamble byte - any other byte besides the second preamble byte causes the FSM to reset. If it arrives, then it triggers the reading of the packet length. And so on.

In pseudocode it may be something like:

    State is idle.
    If character available:
        Read character into variable C

        Select on state:
            State IDLE:
                If C is PACKET_HEADER:
                    Set state to PREAMBLE
            State PREAMBLE:
                If C is PACKET_HEADER:
                    Set state to GETSIZE
                Else
                    Set state to IDLE
            State GETSIZE:
                If C is ESCAPE and you haven't just seen ESCAPE
                    Remeber you had an escape
                Else
                    Store C in variable SIZE
                    Clear array DATA and prepare for reception
                    Reset Seen ESCAPE flag if needed
                    Set state to GETID
            State GETID:
                If C is ESCAPE and you haven't just seen ESCAPE
                    Remeber you had an escape
                Else
                    Store C in variable ID
                    Reset Seen ESCAPE flag if needed
                    Set state to GETDATA
            State GETDATA:
                If C is ESCAPE and you haven't just seen ESCAPE
                    Remeber you had an escape
                Else
                    Append C to array DATA
                    Decrement variable SIZE
                    Reset Seen ESCAPE flag if needed
                    If SIZE is 0
                        If checksum matches
                            Process packet
                        Set state to IDLE

The main thing to watch is the remembering (and subsequently forgetting) that you have just seen an ESCAPE. That way you can know if you have two ESCAPE characters in a row and you only discard the first one - the second gets handled as a real character.

The beauty of an FSM is that at any point in the sequence, if you decide that the packet is invalid (maybe the size is too big, or the sensor ID is invalid) you can just reset the FSM to the IDLE state and reset any flags/counters and you instantly start looking for a new packet.