body:
I recently bought [Blend Micro](http://redbearlab.com/blendmicro/) and I am setting up Arduino IDE to start using it, but after installing the required libraries and the Blend Micro drivers, the IDE suddenly crashes without any visible error whenever I plug the blend micro to my PC. If it is already plugged in, the ide won't even start up. This was not happening before I installed the drivers. I don't know if it's relevant but blend micro was connected to my pc during the drivers installation. I have already looked for a way to solve this on Google without relevant results.

I am using Windows 10 with Arduino IDE 1.6.12

I would really appreciate any help with my problem, thank you in advance.

title: Arduino IDE crash when I connect Blend Micro

Answers: 2

body:
you should try to run the arduino from the consolle, on windows digit cmd on the search bar and the command promp program should appear.

Well, then you should navigate in out arudiono folder: digit `cd "XXX"` where XXX is the arduino executable location (something like c:/program files/blabla), you can copy paste it from the folder explorer.

then write `arduino_debug.exe` and you should see on the terminal the error appear; with that we may find the issue.

body: The final solution to my problem was to download [the latest arduino hourly build](https://www.arduino.cc/download.php?f=/arduino-nightly-windows.zip). There is probably a bug in the stable version that has been solved in the hourly build.


body:
I am doing a simple circuit with a 12V power supply to power a 12V LED strip. I'd like to be able to switch ON/OFF the strip with a relay connected to my Arduino. I'd like to know if I can power my Arduino directly from the VIN pin using 12V source. I saw that the Arduino can support up to 12V.

Thank you in advance for the help.

title: Power an arduino on a 12V circuit

Answers: 2

body: As you have noted, many Arduino (and clones) are rated for supply voltage up to 12V. But note that if you use 12V power, the on-board regulator will get rather hot.  Providing decent ventilation and maybe even extra heat sink would be a good idea.

body:
The answer is yes, you can. Since there are no information about which Arduino you are using, Lets assume that you use Arduino uno. Based on the [official webpage][1] documentation, the recomended voltage input is ranging from 7 - 12 V. Therefore it is possible.

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


body:
I'm trying to communicate with an Arduino Uno via pyserial using a code that I wrote for Ubuntu. However, when I try to use the same code in OSX Yosemite after identifying the serial port for the case of OSX, it doesn't work. This is the offending line:

    In [32]: ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

If I run the above line when the Arduino IDE is not running there is no error message, but the Arduino doesn't do anything (the Arduino IDE Serial Monitor must be open in order for the code to work). However, if I open the Arduino IDE and use the Serial Monitor (which works fine, i.e. it shows data that the Arduino is sending), I get the following error message:

    SerialException: [Errno 16] could not open port /dev/cu.usbmodem1421: [Errno 16] Resource busy: '/dev/cu.usbmodem1421'

If I run `lsof | grep /dev/cu.usbmodem1421` then I get that the only program using said port is Arduino IDE:

    Arduino   2012 germanchaparro   94u     CHR               18,7   0t15249    1285 /dev/cu.usbmodem1421

Clearly OSX is not letting Arduino IDE and pyserial to use the serial port (to which the Arduino UNO is connected) at the same time. I don't know how to fix this, and it's especially frustrating since Ubuntu doesn't put up a fight.

Any ideas?

title: Arduino IDE in conflict with pyserial for use of serial port in OSX Yosemite

Answers: 1

body:
Ok, I solved it. First I stopped using the IDE serial monitor as Majenko suggested, and focused on getting the Arduino readings within the python code. Besides trying to use the python code and the IDE monitor at the same time (which apparently you can do in Ubuntu but not in OSX), the original problem was that my python code was not clearing the serial buffer in the r/w process. In order to do this, I wrote the following function to be called before and after a serial write:

     ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

     def readarduino(ser):
        did=True
        while ser.inWaiting(): # Check number of characters left in buffer
            if did and ser.inWaiting() < 490: # Select last 500 characters in buffer
                for i in range(6):
                    print ser.readline() # Print 6 lines in buffer
                did = False
            ser.readline()  # Clear buffer line by line until ser.inWaiting goes to 0

This ensures that the buffer is clear whenever I am writing to the Arduino.

This solution works for OSX Yosemite and Ubuntu 14.04


body:
I'm building a BMX start gate controller. It requires a voice sample to be played ("Riders ready, watch the gate!") before playing a series of tones at very specific frequencies and intervals. After the tones are complete, a relay is triggered which drops the start gate.

I'm intending to use one of the header pins with the tone() function to output the tones, and an Adafruit AudioFX board to play the voice sample.

How do I connect both of these to an Adafruit mono amplifier (https://www.adafruit.com/product/2130) ?

Note that only one or the other will be playing at one time.

Can I use a "passive mixer" (which I think is putting a 10kΩ resistor on each input source for the amplifier?)

title: How do I output tone() and audioFX board output through a single speaker?

Answers: 1

body:
Yes, a passive mixer would do fine. I would recommend capacitors to remove any DC component too, before you do the mixing. 22uF should do fine.

I will draw a circuit in the morning.


body:
I use Arduino and I'm beginner. I use the code below, but I don't understand what `stepper.step(num)` and `STEPS` in `Stepper stepper(STEPS, 2,3,4,5)` are, and I want to use stepper for specific degree and I don't know what I can do. for example if I want to use stepper for 40 degree what are STEP and num?

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

    #include <Stepper.h>

    // change this to the number of steps on your motor
    #define STEPS 100

    // create an instance of the stepper class, specifying
    // the number of steps of the motor and the pins it's
    // attached to
    Stepper stepper(STEPS, 2,3,4,5);

    // the previous reading from the analog input
    int previous = 0;

    void setup()
    {
      // set the speed of the motor to 30 RPMs
      stepper.setSpeed(100);
    }

    void loop()
    {
      // get the sensor value
      //int val = analogRead(0);

      // move a number of steps equal to the change in the
      // sensor reading
      //stepper.step(val - previous);
      stepper.step(25);
      delay(1000000);
     // stepper.step(-5);

      // remember the previous value of the sensor
      //previous = val;
    }

-----------------------------------------EDIT #2-----------------------------
my stepper is the first one in this link:
https://grahamwideman.wikispaces.com/file/view/28byj48_models_table.jpg/538898220/604x265/28byj48_models_table.jpg
( I think! )
and I don't know what it means?
------------------------------------------EDIT #3----------------------------
Thank you very much, I saw the link.

> Step Angle (8-Step sequence: Internal Motor alone): 5.625° (64 steps
> per revolution)

and I run this code for 45deg :

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

    #include <Stepper.h>

    #define STEPS_PER_MOTOR_REVOLUTION 32
    #define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  //2048
    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 2, 3, 4, 5);

    int  Steps2Take;

    void setup()
    {

    }

    void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
    {

      Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 8.11;
      small_stepper.setSpeed(100);
      small_stepper.step(Steps2Take);
      delay(10000);
    }

 because I understand each turn has 2048 steps, for example if I want to have 1/2 turn, I have to have num=1024 ( 2048/2). ok, So, for 45deg, it's 1/8 turn so I have to set num=2048/8. but for example for 33 deg what should I do?
I thought num= 33*5.61
so for 45deg I use num=45*5.61
you know we have a lot of floating point and I'm not sure we do it correct. right? I'm a little confused.

title: How can I use stepper for specific degree?

Answers: 1

body:
`stepper.step(num)`is used to rotate your motor 'num'-step. i.e. `num=25`, then calling `stepper.step` will cause your motor do 25-step.

STEPS is number of steps per revolution for your motor. It will be depending on the motor you used. For more information, you can check [here][1].

You have to check for your motor stepper resolution. Most common motor stepper has 200 steps per revolution, which means 1 step is 360/200 = 1.8 degree. If you try `Stepper.step(1)`, your motor will rotate 1.8 degree.

So in your case, if you already found out the resolution of your motor stepper, just do a simple conversion task:

    const float resolution  = xx.xx; // put your step resolution here
    int step_degree(float desired_degree){
        return (desired_degree/resolution);}

This can be use by calling

    stepper.step(step_degree(40)); //rotate 40 degree.

**--EDIT--**
You can check this [link][2], since it (perhaps) using same motor stepper (24BYJ48)

Based on 24BYJ48 [datasheet][3], it has 5.625 degree resolution / 64 steps per revolution.

  [1]: https://www.arduino.cc/en/Tutorial/StepperOneStepAtATime
  [2]: https://arduino-info.wikispaces.com/SmallSteppers
  [3]: https://www.google.co.id/url?sa=t&rct=j&q=&esrc=s&source=web&cd=7&cad=rja&uact=8&ved=0ahUKEwi-7Lf4sa_QAhWKpY8KHWL1D7AQFggrMAY&url=http://smart-elektronic.strefa.pl/silnik/datasheet.pdf&usg=AFQjCNGcovDwZtfT8XvQGshhTXc1g-o5Qw&sig2=F752FfDr8P0FzKlwsoRzTQ&bvm=bv.139138859,d.c2I


body:
I have a doubt interfacing with fingerprint module (R305) with the Arduino Mega.
I have been able to interface it to Arduino Uno before but not Arduino Mega so far.

I have used the Mega's hardware Serial1 pins 19 (Rx) and 18 (Tx) pins.

However, I am unable to get output from the module. How do I connect hardware serial and what is a sketch to do this?

title: Regarding Arduino Mega hardware serial

Answers: 1

body:
Try Pin digital pins 0 (RX) and 1 (TX), as they also should be Serial0 on ArduinoMega (PWM 0 and 1)

see:
https://www.arduino.cc/en/Reference/Serial

The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX). To use these pins to communicate with your personal computer, you will need an additional USB-to-serial adaptor, as they are not connected to the Mega's USB-to-serial adaptor. To use them to communicate with an external TTL serial device, connect the TX pin to your device's RX pin, the RX to your device's TX pin, and the ground of your Mega to your device's ground.


body:
I am trying to run a clock off of an arduino following this site: http://www.cibomahto.com/2008/03/controlling-a-clock-with-an-arduino/comment-page-1/ and I tried to combine it with this to get it to run accurately. https://contractorwolf.com/arduino-pwm-interrupt-clock/

For the project that I want to do I need to slow down the minute hand by 23.9345 (So that it will run on sidereal time)

Now the bare code of the first link with some mods works perfectly, but the delay does not seem to be accurate:

        const int a1  =  8;     //use digital I/O pin 8
        const int a2  =  9;
        const int tick1 = 1000;
        const int tick2 = 50;

        void setup()
        {
        pinMode(a1,OUTPUT);   //set pin 8 to be an output output
        pinMode(a2,OUTPUT);   //set pin 9 to be an output output
        }

        void loop()
        {
           delay(tick1);          //delay 1000 milliseconds
           digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
           delay(tick2);          //delay 1000 milliseconds
           digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
           delay(tick1);          //delay 1000 milliseconds
           digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
           delay(tick2);          //delay 1000 milliseconds
           digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
        }

For this reason I have tried to merge it with the 1 wire clock project and got

    const int a1  =  8;     //use digital I/O pin 8
    const int a2  =  9;
    const int tick1 = 1000;
    const int tick2 = 50;

    int cyclesPerSecond = 974;

    //pins
    int clockInterrupt = 0; //interrupt 0 is pin 2 on UNO
    int pwmOut = 6; //pin 6

    //timekeeping
    int seconds = 0;
    int masterClock = 0;//number of square waves

    void setup()
    {
    attachInterrupt(clockInterrupt, clockCounter, RISING);
    pinMode(a1,OUTPUT);   //set pin 8 to be an output output
    pinMode(a2,OUTPUT);   //set pin 8 to be an output output

    Serial.println(pwmOut);
    analogWrite(pwmOut, 127); // this starts our PWM 'clock' with a 50% duty cycle//digital pin 10 for analogWrite pwm out
    }

    void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
    {
    masterClock ++; // with each clock rise add 1 to masterclock count
    if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
    {
    seconds ++; // after one cycle add 1 second
    masterClock = 0; //reset clock counter
    }
    }

    void loop()
    {
      if (seconds == 1){
       digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
       else if(seconds == 2)
       seconds = 0;
       digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
      }
    }
However this does not seem to move the second hand properly, so the clock does tick but not strong enough to actually work. Is this a hardware thing or a processor thing? I have no idea why this would not work while the other code does.

title: Running quartz clock off an arduino

Answers: 3

body:
I'm not 100% certain of what you are trying to do but I noticed a few bits in the code which don't look right to me.  For instance this function:

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

    void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
    {
      masterClock ++; // with each clock rise add 1 to masterclock count
      if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
      {
        seconds ++; // after one cycle add 1 second
        masterClock = 0; //reset clock counter
      }
    }

This is causing a part of your inaccuracy.  You are incrementing the integer `masterClock` variable and then seeing if it is `>=` to a floating point value, the equals is not necessary and will almost never be true.  If the condition occurs then you increment seconds before setting `masterClock` to zero, losing any part of a second you had left over.

Looking at what others have said I would be inclined to take a different approach to this project rather than try and fix this code.

body:
As I said in my comment, the idea of using the Arduino's own PWM as a
clock source is completely misguided. It will be no more accurate than
using `millis()` or `micros()`: both these functions and the PWM rely on
the same primary clock source, namely the ceramic resonator clocking the
chip.

Also, you should avoid using `delay()` for timekeeping. The time it
takes to run around the `loop()` is the sum of all your delays _plus the
time needed to execute the actual instructions_, which you do not know
accurately. It is far better to use either `millis()` or `micros()`.

Here is a tentative sidereal clock code, not tested:

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

    // Pins driving the clock.
    const int a1 = 8;
    const int a2 = 9;

    // Length of one sidereal second in microseconds.
    const unsigned long SIDEREAL_SECOND = 997270;

    void setup()
    {
        pinMode(a1, OUTPUT);
        pinMode(a2, OUTPUT);
    }

    void tick()
    {
        static int activePin = a1;

        // Pulse the pin.
        digitalWrite(activePin, HIGH);
        delay(50);
        digitalWrite(activePin, LOW);

        // Next time use the other pin.
        if (activePin == a1) activePin = a2;
        else activePin = a1;
    }

    void loop()
    {
        static unsigned long last_tick;
        if (micros() - last_tick >= SIDEREAL_SECOND) {
            tick();
            last_tick += SIDEREAL_SECOND;
        }
    }

You can tune the speed of the clock by changing the constant
`SIDEREAL_SECOND`. I set the constant to the actual length of a sidereal
second, in microseconds, but you may find that the clock does not run
exactly at the correct speed. This is because the ceramic resonator
inside the Arduino is not very accurate. You can remove most of the
inaccuracy by calibration: measure how fast or slow it runs and change
the value of `SIDEREAL_SECOND` to compensate. You will still face some
residual inaccuracy owing to the fact that the resonator's frequency is
not very stable, and is highly temperature-dependent.

If you want to build a clock that has decent accuracy, your best bet is
to use a 32768 Hz quartz crystal, as suggested by Ignacio
Vazquez-Abrams in his comment. I did that on a bare ATmega chip (a
“barebones Arduino”) to make a
[24-hour analog wall
clock](https://www.logre.eu/wiki/24-hour_analog_clock). You should be
able to easily adapt the code I published in that page to fit your
project.

body:
Writing another answer because I just had a completely different idea.

A standard option for keeping reasonably accurate time with an Arduino
is to use an RTC module. If possible, choose one based on the DS3231
rather than the DS1307, as the former has builtin temperature
compensation, which makes it significantly more accurate.

The RTC is typically used to provide the time over I2C in a broken-down
form: year, month, day, hour, minute and second. This is not really
convenient for a sidereal clock, as it would require complex conversions
to derive the sidereal time. However, most RTC modules have the option
to output a 32,768 Hz square wave. If you can feed this signal to
the digital pin 5 of your Arduino Uno, then you can use the
Timer/Counter 1 to count the cycles and raise an interrupt every
sidereal second, i.e. every 32,678.53 cycles of the RTC signal.

There is small issue with the above number not being an integer. One
could just round it to the nearest integer, which would make the clock
slow by about 14 ppm, or 1.2 s/day. This may not seem like a
large error, but the DS3231 is capable of much greater accuracy:
±2 ppm from 0°C to +40°C.

An elegant solution is to count the cycles internally using a 32-bit
fixed-point number, with 16 bits for the integer part and 16 bits for
the fractional part. On each timer interrupt, we compute what value the
timer should have on the next interrupt (variable `next_count` below),
simply by adding 32,678.53 to the previous value. Then we use the
integer part of the result (16 most significant bits) to program the
next interrupt. This way the interrupts will be spaced by either 32,678
or 32,679 signal periods, with the average being exactly the value we
need. This provides very high granularity, as our time unit is now
effectively 2<sup>−31</sup> s ≈ 0.466 ns.

In the code below, the first three functions are left empty, as “an
exercise for the reader”. Or rather because they are dependent on the
specifics of the hardware setup. I am only showing the logic of using
the Timer 1 for getting an interrupt every sidereal second.

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

    /*
     * RTC-based sidereal clock.
     *
     * Configure the RTC to output a 32,768 Hz square wave.
     * Feed this square wave to pin T1 = PD5 = digital 5.
     */

    #include <avr/sleep.h>

    static void setup_rtc()
    {
        // Configure the RTC to output a 32,768 Hz square wave.
    }

    static void setup_clock_pins()
    {
        // Configure the pins for driving the clock.
    }

    static void tick()
    {
        // Advance the clock by one second.
    }

    /*
     * For better granularity, time is counted in units of 2^-16 cycles of
     * the 32768 Hz square wave (~ 0.47 ns), as a 32-bit unsigned integer.
     * Timer 1 holds the 16 most significant bits.
     */
    const uint32_t SI_SECOND       = 32768UL << 16;
    const uint32_t SIDEREAL_SECOND = 0.99726958 * SI_SECOND;

    // Interrupt fired every sidereal second.
    ISR(TIMER1_COMPA_vect)
    {
        static uint32_t next_count;
        next_count += SIDEREAL_SECOND;
        OCR1A = next_count >> 16;  // use the 16 most significant bits
        tick();
    }

    void setup()
    {
        // Configure Timer 1.
        TCCR1A = 0;            // normal counting mode
        TCCR1B = _BV(CS10)     // count rising edges of T1
               | _BV(CS11)     // ditto
               | _BV(CS12);    // ditto
        TIMSK1 = _BV(OCIE1A);  // enable COMPA interrupt

        // Enable pullup on T1 = PD5.
        PORTD |= _BV(PD5);

        setup_rtc();
        setup_clock_pins();
    }

    void loop()
    {
        sleep_mode();
    }


body:
This is a segment of an Arduino sketch, that I am trying to understand.

I know that the purpose of the entire code is to control 2 stepper motors linked to their respective drivers which are linked to a Mega 2560, but since I am new to Arduino, I am having problems with some functions.

This is a segment of the code. I am having problems with some statements such as `unsigned short FLG = 0;` and I cannot make out at all the timer interrupts part.

What does it all mean?

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

    /* The “define” function is NOT A PROGRAMMING STATEMENT. Actually it sets up a macro which causes a text replace to occur before code is compiled. The pre-processor of the IDE will replace the variables such as “stp” to the integer value 22 in the following subsequent sections like the “void setup” function and the “loop” function if they are called. This function helps reduce RAM usage. */

    #define stp 22
    #define dir 23
    #define stp2 26
    #define dir2 27
    #define EN  24
    #define dir_ 25

    int i, j, t, X = 0, Y = 0, Z = 0;
    // here, the integer is creating variables such as i, j, t
    //and also assigning values to some of them such as X, Y and Z.

    unsigned short FLG = 0;

    unsigned int Speed1 = 0, Speed2 = 0; // creating variables assigning initial values; due to unsinged only positive

    int ser_1[3];

    int po(int, int);

    void setup() {     // You define how your Arduino will be used and set up any pins and communications you will be using. This will run first and only once.

      Serial.begin(9600); // begin the data transmission between Arduino and pc at speed of 9600 bits per sec
      delay(500); // stop for 500 milliseconds

      Serial.println(“hi”); // this will print the word “hi” on the serial monitor window on pc via serial port

      pinMode(stp, OUTPUT); // tells arduino to use digital Pin 22 to output electricity
      pinMode(dir, OUTPUT); // tells arduino to use digital Pin 23 to output electricity
      pinMode(stp2, OUTPUT); // tells arduino to use digital Pin 26 to output electricity
      pinMode(dir2, OUTPUT); // tells arduino to use digital Pin 27 to output electricity
      pinMode(EN, OUTPUT); // tells arduino to use digital Pin 24 to output electricity

      noInterrupts(); // to prevent disruption of timing of codes, disables some functions in the background

      /* To use timers, the built-in timer registers on the AVR chip that store timer settings need to be configured.  There are a number of registers per timer.  Two of these registers –the Timer/Counter Control Registers- hold setup values, and are called TCCRxA and TCCRxB, where x is the timer number (TCCR1A and TCCR1B, etc.).   Each register holds 8 bits, and each bit stores a configuration value. */

      TCCR1A = 0x80; //
      TCCR1B = 0x0A; // Enable reset on compare match, 1:8 clock. don’t understand
      OCR1AH = 0x9C;
      OCR1AL = 0x3F;
      TIMSK1 = (1 << OCIE1A); // enable timer compare interrupt
      interrupts();
    }
    ISR(TIMER1_COMPA_vect)   // timer compare interrupt service routine
    {
      res();
    }
    void loop(){

    if(Serial.available())
     {
      ser_1[i] = Serial.read();
      char ch = Serial.read();
    if(ch==’S’)
       { i=0;
         X=0;
         while(1)
    {
      if (Serial.available() > 0)
         {
          ser_1[i]=Serial.read();
          ser_1[i]=ser_1[i]-48;
          X=X+(ser_1[i]*(po(10,i)));
          i++;
         if(i==3)
           {
            FLG++;
            break;
            }
          }
        }
    }

    if (ch==’A’)
      { i=0;
        Y=0;
         while(1)
         {
            if (Serial.available() > 0)
          {
          ser_1[i]=Serial.read();
          ser_1[i]=ser_1[i]-48;
          Y=Y+(ser_1[i]*(po(10,i)));
           i++;
          if (i==3)
              {
               FLG++;
               break;
               }
              }
            }
          }

         if(FLG==2)
        {
          Speed1=X;
          Speed2=Y;
          digitalWrite(EN,LOW);
            delay(100);
          StepForwardDefault();
            delay(1000);
          StepForwardDefault2();
             delay(1000);
          ReverseStepDefault2();
          ReverseStepDefault();
          delay(1000);
          digitalWrite(EN,HIGH);
          delay(1000);
          }
          else
          Serial.println(“sequence is stop”);
    }
     /*****************po******************/

    int po(int num, int pow)
    { int result=1;
      if(pow==0)
      return 1;
      else
     {
      for(int f=1;f<=pow;f++)
        {
      result=result*num;
        }
     return result;
     }
    }

    /************ MOTOR 1 Function *****************/

    void ReverseStepDefault()
    {
      Serial.println(“motor a reverse”);
      Serial.println(“Moving in reverse at default step mode.”);
    digitalWrite(dir_, HIGH); // Pull direction pin high to move in “reverse”
    digitalWrite(dir, LOW);
    delay(100);
    for(int x=1; x<200; x++) // Loop the stepping enough times for motion to be visible
    {
      digitalWrite(stp, HIGH); //Trigger one step
      delay(305-X);
      digitalWrite(stp, LOW);  // Pull step pin low so it can be triggered again3
      delay(305-X);
      }
    }

    /************ MOTOR 2 Function *****************/

    void ReverseStepDefault2()
    {
      Serial.println(“Moving b reverse”);
      digitalWrite(dir_, HIGH); // Pull direction pin high to move in “reverse”
      digitalWrite(dir2, LOW);
      delay(100);
      for(int x =1; x<200; x++) // Loop the stepping enough times for motion to be visible
      {
       digitalWrite(stp2,HIGH); // Trigger one step
       delay(305-Y);
       digitalWrite(stp2,LOW); // Pull step pin low so it can be triggered again3
       delay(305-Y);
       }
    }

    void StepForwardDefault2()
    {
       Serial.println(“motor b forward”);
       digitalWrite(dir_,HIGH); // Pull direction pin high to move in “reverse”
       digitalWrite(dir2,HIGH);
       delay(100);
       for(int x=1; x<200; x++) // Loop the forward stepping enough times for motion to be visible

    {
      digitalWrite(stp2,HIGH); // Trigger one step forward
      delay(305-Y);
      digitalWrite(stp2,LOW); // Pull step pin low so it can be triggered again
      delay(305-Y);
        }
    }

    void res()
     {
       if(Serial.available())
      {
       ser_1[i]=Serial.read();
       char ch = Serial.read();
       if(ch ==’T’)
          {
           FLG=0;
           Serial.println(“stop is pressed”);
          }
       }
    }

title: Problem understanding code

Answers: 3

body:
> I am having problems with some statements such as
> "unsigned short FLG = 0;"

This is the C and C++ syntax for declaring a variable. The statement
means “Let `FLG` be an unsigned short integer and let it's initial value
be zero”. An `unsigned short` can hold any integer value between 0 and
65535 inclusive.

The Arduino language reference documents the types
[`short`](https://www.arduino.cc/en/Reference/Short) and
[`unsigned int`](https://www.arduino.cc/en/Reference/UnsignedInt) but,
for a mysterious reason, it does not document `unsigned short`.

> I cannot make out at all the timer interrupts part.

Nobody can unless they know the internals of the AVR timers, which are
non trivial but are well covered in [the
datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf).
It's a thick document, but you only need to study chapters 14:
_Interrupts_ and 17: _16-bit Timer/Counter (Timer/Counter 1, 3, 4, and
5)_.

I recommend you first read the [Timers and counters
tutorial](http://gammon.com.au/timers) by Nick Gammon, then go to the
datasheet for the most authoritative information.

**Edit**: Just a comment... I find the program you have posted to be
written with poor programming style. More specifically, the section
setting the Timer 1 registers would be better written as follows:

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

    TCCR1A = bit(COM1A1);  // set OC1A to LOW on compare match
    TCCR1B = bit(WGM12)    // CTC mode, TOP = OCR1A
           | bit(CS11);    // clock at F_CPU / 8
    OCR1A  = 40000 - 1;    // period = 40000 prescaled clock cycles
    TIMSK1 = bit(OCIE1A);  // enable COMPA interrupt

It is still obscure if you don't know the timer, but using explicit bit
names instead of pure numbers makes things a lot easier when you refer
to the datasheet. Also, there is no point in setting each byte of
`OCR1A` in a different statement: it only makes things harder to read.

body:
I'm assuming you don't mean "all" when you ask "what does it _all_ mean?"
I also assume that the comments are from you - in which case you've done reasonably well!

    /* The “define” function is NOT A PROGRAMMING STATEMENT... */

True, `#define` isn't a programming statement that produces code: it's a way of defining a symbol that you can use in the rest of the code, both for explanation purposes and ease of changing: without having to search for all copies of `22` - and then decide if _this particular_ `22` is for that pin or not.

    unsigned short FLG=0;

`int` is 16 bits in the Arduino, but in some systems it's 32 (and in others 64). `short` is (practically) always 16 bits regardless of system, so many programmers use `short` when they know they definitely want a 16-bit integer. `unsigned` merely means that it can never go negative - which allows the variable to hold higher values (0 to 65,535 instead of -32,768 to 32,767).

    int ser_1[3];

This is an array of 3 `int`s called `ser_1`, which can be accessed as `ser_1[0]`, `ser_1[1]` and `ser_1[2]`. In C, all arrays start at `0`. Why use an array? It makes it possible to use _another_ variabe to say _which_ `ser_1` you want: e.g. `ser_1[i]`. If `i` is `2`, you get the last one.

    int po(int,int);

This says that there will be a function called `po` that takes two `int` values, processes them, and returns an `int` result.

    noInterrupts(); // to prevent disruption of timing of codes, disables some functions in the background

Pretty much. An interrupt can happen at any time: the CPU will stop executing the main program, execute the interrupt code, then resume where it left off in the main program. Sometimes that's a bad thing! If the interrupt code is going to change something that _this_ code needs to stay the same (or vice versa!), then Bad Things can happen. To prevent that, you can turn off interrupts temporarily with this function, and turn them on again later with `interrupts()` (which you'll see below).

    /* To use timers, the built-in timer registers on the AVR chip that store timer settings need to be configured.  There are a number of registers per timer.  Two of these registers –the Timer/Counter Control Registers- hold setup values, and are called TCCRxA and TCCRxB, where x is the timer number (TCCR1A and TCCR1B, etc.).   Each register holds 8 bits, and each bit stores a configuration value. */

     TCCR1A = 0x80; //
     TCCR1B = 0x0A; // Enable reset on compare match, 1:8 clock. don’t understand

OK, this is complicated:

* By default, a timer simply counts from `0` to `65,535` (maximum 16 bit value), then resets and starts again.
* How quickly? One 'tick' is the system clock, so _very_ quickly! But you can "pre-scale" that with a divisor. In this case, they're using a divisor of 8, so the timer will "tick" an eighth as fast.
* You can configure the timer to interrupt when it resets, so that special code will execute on a timed basis.
* You can also tell it that if at any time it hits a certain number to _also_ interrupt (Compare Match) - that's two different interrupts.
* You can _also_ tell it that when it hits that Compare number, to reset back to `0` and start counting again. That means that the timer will interrupt more often.

`OCR1AH = 0x9C;`
`OCR1AL = 0x3F;`

These stand for "Output Compare Register 1A High" and "Output Compare Register 1A Low" - a 16 bit value that is 0x9C3F (37839 decimal). If you divide the system clock by that number, (and a further 8 for the pre-scaler), you'll find out how often it interrupts.

    interrupts();

This turns on interrupts again.

    ISR(TIMER1_COMPA_vect)   // timer compare interrupt service routine
    {
    res();
    }

This is the code that executes every timer interrupt. I don't know what `res()` does.

body:
Here is some explanation :

    TCCR1A = 0x80; //OC1 will cleared on compare match
    TCCR1B = 0x0A; //Turn on CTC mode --> it means the interrupt counter will reset to 0, and causing the interrupt happen again and again.
                   //Divide clock 1:8 (prescaler)
    OCR1AH = 0x9C;
    OCR1AL = 0x3F; //compare value = 0x9C3F = 39999
    TIMSK1 = (1<<OCIE1A); // the micro will jump to the Output Compare A Interrupt vetor upon compare match.

Overall, this setup will make your program do whatever you put in the Interrupt Service Routine `ISR(TIMER1_COMPA_vect){...do whatever here...}`

The interrupt interval is =

> (OCR1A+1) × prescaler ÷ F_CPU
>
> (39999+1) × 8 ÷ 16.000.000 = 0.02 sec

as for `res();` and `unsigned short FLG;` I dont know what that is, since its probably your own creation (not from arduino libs)

You can found more detailed explanation [here][1] and [here][2]

  [1]: http://www.avrbeginners.net/architecture/timers/timers.html
  [2]: http://letsmakerobots.com/node/28278


body:
I'm new to Arduino and need some clarification on motor drivers.

I was wondering if I can use a L298N instead of the Motor Shield R3, I hope not to be comapring apples to oranges, the doc of the Motor Shield R3 say "The Arduino Motor Shield is based on the L298"  and more or less I see similar projects (Robot cars) using both but as mention I don't if I can use one or the other as "replacement".

(L298N)
[![L298N][1]][1]

(Motor Shield R3):

[![Motor Shield R3][3]][3]

  [1]: https://i.stack.imgur.com/aaSXa.jpg
  [3]: https://i.stack.imgur.com/vRYan.jpg

title: L298N vs Motor Shield R3

Answers: 1

body: Yes.  The shield is easier to user, but the breakout board you've shown uses the same chip.  I'd suspect that the breakout board, which has a much bigger heat sink, can handle larger motors, though.  You'll need to put wires from PWM and digital pins to the breakout board you're showing, but it's not super challenging to use those.  I've used extremely similar boards in the past, as well as shields, and both work great.  How big are your motors?  If they're WAY too big (the breakout board can only handle 2 amps IIRC) then you'll need something else anyway.


body:
I'm looking to recognize a particular sound using arduino uno.

I need to recognize a clap sequence to trigger a relay.

Having given it some thought i need it to be continuous listening mode with out any trigger such as a button press. The background will be quiet.

Is the arduino uno powerful enough to do this and how will i get stated on this? Any help is appreciated.

Note i need to do this entirely onthe Uno itself and not on PC like https://arduino.stackexchange.com/questions/8781/how-do-i-listen-for-a-sound-that-matches-a-pre-recorded-sound

I am thinking i will prerecord the sound and compare with a live sample, is this feasible?

title: Sound Recognition

Answers: 3

body:
If it's just a clap sound and the background is quiet, then really all you'd need is to sense how loud the sound is.  This can be done using an analog comparator interrupt (this is present on the chip itself but not on the Arduino library).  If all the uno is doing is measuring the sound and maybe setting an output pin when it's loud, then just poll the analogs attached to your microphone and trigger the condition when the output is loud enough.  You'd probably need to amplify the microphone if you haven't already, but yes, the uno can handle that.

Edit: if it's a clapping *sequence*, then it can still do it.  Again, just measure the time between loud and quiet, don't worry about what the sound is (that is, you don't need to worry about exactly recording and analyzing the sound, you just need to know when it's loud and when it's quiet)

body:
Adding to Michaels answer above which only works for some cases (and  it wont work perfectly even with a sequence of claps). To make it work in more cases you would need to store more information about the clap noise- as Michael points out in his comment above "properly identify" the clap- to make the identification more accurate. There are various ways to do this- you could compare it with live recording as you wrote in your question. I suggest tyou try neural networks to do such a comparision I. I would say you would need a two layer neural network with say a sample of different claps for training it-(its probably quicker to train it not with arduino).
Here is a library for neural networks for arduino

http://robotics.hobbizine.com/arduinoann.html

that you may use. Or you can implement you own neural network. Its well known that sound recognition can be used to analyse sounds.

The built in ADC of Arduino can probably be used to  record and good enough for something like a clap in your case-though it cant be used for high quality sound recordings.

body:
I have not tested it but there is an example for the [ArduinoSound library][1] which especially detects claps.

https://github.com/arduino-libraries/ArduinoSound/tree/master/examples/ClapDetector

    /*
     This example reads audio data from an Invensense's ICS43432 I2S microphone
     breakout board, and uses the input to detect clapping sounds. An LED is
     togggled when a clapp is detected.

     Circuit:
     * Arduino/Genuino Zero, MKRZero or MKR1000 board
     * ICS43432:
       * GND connected GND
       * 3.3V connected 3.3V (Zero) or VCC (MKR1000, MKRZero)
       * WS connected to pin 0 (Zero) or pin 3 (MKR1000, MKRZero)
       * CLK connected to pin 1 (Zero) or pin 2 (MKR1000, MKRZero)
       * SD connected to pin 9 (Zero) or pin A6 (MKR1000, MKRZero)

     created 18 November 2016
     by Sandeep Mistry
     */

    #include <ArduinoSound.h>

    // the LED pin to use as output
    const int ledPin = LED_BUILTIN;

    // the amplitude threshold for a clap to be detected
    const int amplitudeDeltaThreshold = 100000000;

    // create an amplitude analyzer to be used with the I2S input
    AmplitudeAnalyzer amplitudeAnalyzer;

    // variable to keep track of last amplitude
    int lastAmplitude = 0;

    void setup() {
      // setup the serial
      Serial.begin(9600);

      // configure the LED pin as an output
      pinMode(ledPin, OUTPUT);

      // setup the I2S audio input for 44.1 kHz with 32-bits per sample
      if (!AudioInI2S.begin(44100, 32)) {
        Serial.println("Failed to initialize I2S input!");
        while (1); // do nothing
      }

      // configure the I2S input as the input for the amplitude analyzer
      if (!amplitudeAnalyzer.input(AudioInI2S)) {
        Serial.println("Failed to set amplitude analyzer input!");
        while (1); // do nothing
      }
    }

    void loop() {
      // check if a new analysis is available
      if (amplitudeAnalyzer.available()) {
        // read the new amplitude
        int amplitude = amplitudeAnalyzer.read();

        // find the difference between the new amplitude and the last
        int delta = amplitude - lastAmplitude;

        // check if the difference is larger than the threshold
        if (delta > amplitudeDeltaThreshold) {
          // a clap was detected
          Serial.println("clap detected");

          // toggle the LED
          digitalWrite(ledPin, !digitalRead(ledPin));

          // delay a bit to debounce
          delay(100);
        }

        // update the last amplitude with the new amplitude
        lastAmplitude = amplitude;
      }
    }

  [1]: https://github.com/arduino-libraries/ArduinoSound


body:
I am reading a TSL1402R with an Arduino Mega2560.  The code is based on the sketch from the arduino playground here:http://playground.arduino.cc/Main/TSL1402R

The application is a digital caliper for moving strands of filament.  I would like to have the scan rate as fast as possible.  I am making my own filament and need some means of quality control.

I am reading the analog values of each photodiode (256) of the sensor to an array.  I find an average value of 25 reads for each of the diodes and place that in another array.  I then I compare the averaged values for each of the 256 diodes and assign them into 3 groups: dark1, dark2 and dark3 I then count the assigned values and get a total. +1/4 for dark1, 1/2 for dark2 and 1 for dark3.  This figure represents the width of a piece of filament casting the shadow on the sensor.(dark1 is partially blocked photodiode, dark2 is 1/2 blocked, dark3 is fully blocked)

I am looking at the clock pin on the sensor with a scope.  When I output data with serialprint at (any speed) 115200  The program speed slows down considerably.  When I change the program to serialprint only if the previous value changes, it gets even slower.  If I serialprint every time through the loop, the buffer fills and the values are not accurate.

I get accurate data from my program.  What is the most efficient way to get it out and into a usable form? By way of form I mean to have the data saved so I can see the size deviation of the filament I am producing.  It would also be great if I could visualize the data in real time and make adjustments during the extrusion process.

I have been researching this for weeks, tweaking the program and trying different ideas based on responses to questions similar to mine.

My background is industrial electrical systems, not programming.  This is my first attempt at something like this.  Any advice would be greatly appreciated.

Thanks to all in advance,
Dave Stewart, aka bigstew123

    #include <EEPROM.h>
    #include <TimerOne.h>
    #define NPIXELS 255  // No. of pixels in array

    // Define various ADC prescaler:
    const unsigned char PS_32 = (1 << ADPS2) | (1 << ADPS0);
    const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

    const byte PWMDAC1pin = 11; // PWM DAC, only pins 9 and 10 are allowed
    const byte period = 128; // for 10 bit DAC

    const int LEDpin = 8;
    const int CLKpin = 3;    // <-- Arduino pin delivering the clock pulses to      pin 3 (CLK) of the TSL1401
    const int SIpin = 4;     // <-- Arduino pin delivering the SI (serial-input) pulse to pin 2 of the TSL1401
    const int AOpin = 1;    // <-- Arduino pin connected to pin 4 (analog output 1)of the TSL1401

    unsigned int intArray[NPIXELS]; // <-- the array where the readout of the photodiodes is stored, as integers

    int nAggr = 5;        // image averaging count per one scan. should not exceed 10
    int timer = 5;        // value output averaging counter
    int sensor_value = 0;
    int sensor_value_1 = 0;
    int sensor_value_2 = 0;
    int sensor_value_3 = 0;
    float sensor_value_mapped = 0;
    float dark_pixels_1 = 0;
    float dark_pixels_2 = 0;
    float dark_pixels_3 = 0;
    float dark_pixels_total = 0;
    float dark_pixels_avg = 0;
    float width_mm = 0;
    float width_mm_old = 0;

    // default filament width
    double lowpassValue = 1.75;
    double lowpassFactor = 0.5;

    double calibFactor =  15.75; // (default pixel per mm = 15.748 for 400dpi     sensor

    boolean debugMessage = false;
    boolean doCalibration = false;

    int timerCounter = 0;
    double timerValue = 0;

    void setup() {
    // To set up the ADC, first remove bits set by Arduino library, then choose
    // a prescaler: PS_16, PS_32, PS_64 or PS_128:
     ADCSRA &= ~PS_128;
     ADCSRA |= PS_32; // <-- Using PS_32 makes a single ADC conversion take ~30 us
     pinMode(PWMDAC1pin, OUTPUT);
    // Timer1.initialize(period);
     Timer1.initialize(40);
    // Next, assert default setting:
     analogReference(DEFAULT);

    // Set all IO pins low:
     for (int i = 0; i < 14; i++) {
      digitalWrite(i, LOW);
     }

     pinMode(LEDpin, OUTPUT);
     initSensor();
     Serial.begin(115200);
    //Serial.begin(9600);
    }

    void loop() {
     Timer1.pwm(PWMDAC1pin, (dark_pixels_avg));
     sensor_value = 750; //this is the 0-1023 value for the light/dark threshold
     sensor_value_mapped = sensor_value;
     sensor_value_1 = sensor_value_mapped;
     sensor_value_2 = sensor_value_mapped * 75 / 100;//this is 3/4/
     sensor_value_3 = sensor_value_mapped * 65 / 100; //this is 1/2
     delay(50);
     scanSensor();
     MATH();
     delay(50);
     /*
      *   testing code here: if the value is different, serial print with 100 delay, if the value is unchanged, update at 1000
      *   this is code I used to try to plot the values to a python script running on a raspberry pi 2b
      *   with this setup, the program slows and the scan rate is so slow I miss deviations in the filament.
      *
      if
      (width_mm != width_mm_old)
      {
      Serial.println (width_mm, 4);
      delay(100);

      }
      else
      {Serial.println (width_mm_old, 4);
      delay(1000);

      }
      */
    // every scan, print the width
     Serial.println(width_mm, 4);

    // Command processor
     if (Serial.available() > 0) {
      char incomingByte = Serial.read();

      switch (incomingByte) {
       case 'd':    // Debugging message toggle
        debugMessage = !debugMessage;
        break;

       case 'c':    // Calibration
        doCalibration = true;
        break;

       case 'h':
        //helpMessage();
        array_value();
        break;
      }
     }

     if (debugMessage) {
      //   Serial.print("Number of dark pixels       ");
      //   Serial.println(dark_pixels);
      // delay(300);
      Serial.print("Dark pixel average          ");
      Serial.println(dark_pixels_avg, 4);
      Serial.print("Dark pixel 1                ");
      Serial.println(dark_pixels_1);
      Serial.print("Dark pixel 2                ");
      Serial.println(dark_pixels_2);
      Serial.print("Dark pixel 3                ");
      Serial.println(dark_pixels_3);
      Serial.print("dark_pixels_total             ");
      Serial.println(dark_pixels_total);
      Serial.print("filament width in mm       ");
      Serial.println(width_mm, 4);
      //  Serial.print ("sensor pot value          ");
      // Serial.println (sensor_value);
      //  Serial.print ("sensor value mapped        ");
      //   Serial.println (sensor_value_mapped);
      delay(200);
      //  Serial.print("Raw:\t");
    //    printDouble(lowpassValue, 4);
    //   Serial.print("\t(mm)=\t");
    //    printDouble(mmValue, 3);
    //   Serial.println();
    //Serial.println(intArray[i]);//////////////////////////////////////////
    //Serial.print(";");
     }

     width_mm_old = width_mm;
    }

    void initSensor() {
    // Initialize two Arduino pins as digital output:
     pinMode(CLKpin, OUTPUT);
     pinMode(SIpin, OUTPUT);

    // Clock out any existing SI pulse through the ccd register:
     for (int i = 0; i < NPIXELS + 4; i++) {
      ClockPulse();
     }

    // Create a new SI pulse and clock out that same SI pulse through the sensor register:
     digitalWrite(SIpin, HIGH);
     delayMicroseconds(1);
     digitalWrite(CLKpin, HIGH);
     delayMicroseconds(1);
     digitalWrite(SIpin, LOW);
     delayMicroseconds(1);
     digitalWrite(CLKpin, LOW);

     for (int i = 0; i < NPIXELS + 4; i++) {
      ClockPulse();
     }
    }

    void scanSensor() {
     // Stop the ongoing integration of light quanta from each photodiode by  clocking in a
     // SI pulse:
     // Create a new SI pulse and clock out that same SI pulse through the sensor register:
     digitalWrite(SIpin, HIGH);
     delayMicroseconds(1);
     digitalWrite(CLKpin, HIGH);
     delayMicroseconds(1);
     digitalWrite(SIpin, LOW);
     delayMicroseconds(1);
     digitalWrite(CLKpin, LOW);

     // Next, a new measuring cycle is starting once 18 clock pulses have passed. At
     // that time, the photodiodes are once again active. We clock out the SI pulse through
     // the NPIXELS bit register in order to be ready to halt the ongoing measurement at our will
     // (by clocking in a new SI pulse):
     for (int i = 0; i < NPIXELS + 4; i++) {
      if (i == 18) {
       // Now the photodiodes goes active..
       // An external trigger can be placed here
      }

      ClockPulse();
     }

     // The integration time of the current program / measurement cycle is ~2ms. If a larger time
    // of integration is wanted, uncomment the next line:
    //delay(1);
    // Stop the ongoing integration of light quanta from each photodiode by clocking in a SI pulse
    // into the sensors register:
    // Create a new SI pulse and clock out that same SI pulse through the sensor register:
     digitalWrite(SIpin, HIGH);
     delayMicroseconds(1);
     digitalWrite(CLKpin, HIGH);
     delayMicroseconds(1);
     digitalWrite(SIpin, LOW);
     delayMicroseconds(1);
     digitalWrite(CLKpin, LOW);

    // Next, read all 256 pixels in parallell. Store the result in the array. Each clock pulse
    // causes a new pixel to expose its value on the two outputs:
     for (int i = 0; i < NPIXELS; i++) {
      delayMicroseconds(2);// <-- We add a delay to stabilize the AO output from the sensor
      intArray[i] = analogRead(AOpin);    //(AOpin);
      ClockPulse();
     }
    }
    //here we have a sensor value that is an integer number between 0 and 1023 to represent the value of the pixels read in intArray[]
    //  the number varies, so really dark pixels are set at 75, medium at 100, and light at 125....  of course, this will be a % and scaled
    //so when the operator adjusts the sensitivity, each value will adjust accordingly.
    // each function only counts the pixels in its range so there is no overlapp
    //for a sensor value of 200, sensor value 1 will be 200, value 2 will be 150 and value 3 will be 100
    ////////////////////////////////////////really dark///////////////////

    void MATH() {
     int x = 0;
     int y0 = 0;
     int y1 = 0;
     int y2 = 0;
     int y3 = 0;
     float dpa = 0;

     for (int i = 0; i < NPIXELS; i++) {
      x = intArray[i];

      if (x <= sensor_value_1 && x >= sensor_value_2 && x >=  sensor_value_3) { //less than 200, but greater than 150 and 100
       y1 = y1 + 1;   //////////////////////////////////////not very dark/////////////////////////
      }

      if (x <= sensor_value_1 && x <= sensor_value_2 && x >= sensor_value_3) { //less than 200, less than 150, but more than 100
       y2 = y2 + 1;   //////////////////////////////////////medium dark////////////////////////
      }

      if (x <= sensor_value_1 && x <= sensor_value_2 && x <= sensor_value_3) { //less than 200 or 150 or 100 (really dark pixel(low intArray value)
       y3 = y3 + 1;   //////////////////////////////////////very dark/////////////////////////
      }
     }

     dark_pixels_1 = y1 * 25 / 100; ///1/4 of a count for each pixel
     dark_pixels_2 = y2 * 50 / 100; // half a count for each pixel
     dark_pixels_3 = y3; // full count for each pixel
    /////////////////////////add up the totals///////////////////////////////
     dark_pixels_total = dark_pixels_3 + dark_pixels_2 + dark_pixels_1;

     for (int q = 0; q < 25; q++) {
      dpa  += dark_pixels_total;
     }

     dark_pixels_avg = dpa / 25;
     float k = 0;
     k =  map(dark_pixels_avg, 50, 97, 157, 313); //map the values to a known     width and convert to mm
     width_mm = k / 100;
     //
     //   Serial.print("Number of dark pixels       ");
     //   Serial.println(dark_pixels);
     // delay(300);
     //Serial.print("Dark pixel average          ");
     // Serial.println(dark_pixels_avg);
     // Serial.print("Dark pixel 1                ");
     // Serial.println(dark_pixels_1);
     // Serial.print("Dark pixel 2                ");
     //  Serial.println(dark_pixels_2);
     //  Serial.print("Dark pixel 3                ");
     //  Serial.println(dark_pixels_3);
     //  Serial.print("dark_pixels_avg             ");
     //  Serial.println(dark_pixels_avg);
     //  Serial.print ("filament width in mm       ");
     //  Serial.println (width_mm, 4);
     //   Serial.print ("sensor pot value          ");
     //   Serial.println (sensor_value);
     //   Serial.print ("sensor value mapped        ");
    //    Serial.println (sensor_value_mapped);
    //    delay(200);
    }

    // This function generates an outgoing clock pulse from the Arduino digital pin 'CLKpin'. This clock
    // pulse is fed into pin 3 of the linear sensor:
    void ClockPulse() {
     delayMicroseconds(1);
     digitalWrite(CLKpin, HIGH);
     digitalWrite(CLKpin, LOW);
    }

    void array_value() {
     for (int i = 0; i < NPIXELS; i++) {
      Serial.print("ARRAY VALUE");
      Serial.print(i);
      Serial.print("\t");
      Serial.println(intArray[i]);
     }
    }

title: Faster output of Serial.print() data coming from TSL1402R sensor

Answers: 0


body:
I'm working on a pid-controlled levitating magnet device. It uses a hall-sensor to turn on and off an electro magnet in ordet to achieve levitation.

When I hold a magnet close to the hallsensor, I can sense a pulsation from the electro-magnet, however, I if let go of the magnet, it always sticks to the electro-magnet every time, as though the pid is not properly calibrated, the code i'm using came with a pre built possibility to calibrate the PID, you can change set point, Proportion, integral and derivative I've tried messing with it, but it doesn't seem to make any difference.

    /*
       Magentic Levitation

       1) connect the digital pin PIN_COIL to the MOSFET gate for electromagnet activation.
       2) connect the analog input pin PIN_HALL_SENSOR to the hall sensor signal pin (the other
          two pins shall be wired to gnd and +5V).
       3) (optional) connect the digital pin PIN_CTRL_INDICATOR to the LED that indicates when the
          controller loop is running.
       4) run Arduino, on the serial port the following commands are available:
          - press 's' or 'S' to decrease or increase the setpoint,
          - press 'p' or 'P' to decrease or increase the P gain,
          - press 'd' or 'D' to decrease or increase the D gain,
          - press 'i' or 'I' to decrease or increase the I gain,
          - press 'x' or 'X' to show the current settings
       5) the system enters in IDLE mode, with a minimum PWM command that allows the orientation of the
          permanent magnet, when in range the system goes in CONTROL mode. When the magnet is too close to
          the coil, the system switches in OFF mode by turning off the PWM command.

       version 1.0: 23/12/2011 -  E.Assenza
    */

    const int PIN_COIL = 11; // Pins 3 and 11 are connected to Timer 2.
    const int PIN_HALL_SENSOR = 0;
    const int PIN_CTRL_INDICATOR = 13;
    // Coil resistance 3 ohm, max 1 A = 3 Volt max.
    const int COIL_MAX_PWM_VALUE = 160;
    // Minimum magnetic field when in idle mode (needed to properly orientate the magnet).
    const int COIL_IDLE_VALUE = 50;
    // Proximity thresholds, when the magnetic field is in this range enters in control mode.
    const int MAG_PROX_THRESHOLD_MIN = 585;
    const int MAG_PROX_THRESHOLD_MAX = 615;
    // Magnetic field limits, when outside this range enters in idle mode.
    const int MAG_LIMIT_MIN = 560;
    const int MAG_LIMIT_MAX = 700;
    // Control loop frequency.
    const int CTRL_LOOP_PERIOD_MS = 1;
    // Control loop bias value (PWM midpoint)
    const int CONTROL_BIAS = 65;
    // Set point corresponding to the control bias
    const int CONTROL_SETPOINT = 597;
    const int MAX_ERR_INTEGRAL = 10000;
    // PID controller parameters
    const float PGain = 2.1;
    const float DGain = 23.6;
    const float IGain = 0.001;

    const float P_INCR = 0.1;
    const float D_INCR = 0.1;
    const float I_INCR = 0.001;

    // State machine constants.
    const byte MODE_OFF = 0;
    const byte MODE_IDLE = 1;
    const byte MODE_CONTROL = 2;

    const char     *gAppName = "Arduino Magnetic Levitation";
    byte            gMode;
    int             gSetPoint;
    int             gSensorReadout;
    int             gPrevSensorReadout;
    int             gPwmCommand;
    int             gIntegral;
    float           gBias;
    float           gP;
    float           gD;
    float           gI;
    unsigned long   gMillisCounter;

    void setupCoilPWM()
    {
       // Setup the timer 2 as Phase Correct PWM, 3921 Hz.
       pinMode(3, OUTPUT);
       pinMode(11, OUTPUT);
       // Timer 2 register: WGM20 sets PWM phase correct mode, COM2x1 sets the PWM out to channels A and B.
       TCCR2A = 0;
       TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
       // Set the prescaler to 8, the PWM freq is 16MHz/255/2/<prescaler>
       TCCR2B = 0;
       TCCR2B = _BV(CS21);
    }

    void writeCoilPWM(uint8_t pin, int val)
    {
       if( pin == 3 )
       {
          OCR2B = val;
       }
       else if( pin == 11 )
       {
          OCR2A = val;
       }
       else
       {
          OCR2A = 0;
          OCR2B = 0;
       }
    }

    void processCommand( int cmd )
    {
       char tmp[64];

       switch(cmd)
       {
          case 'p':
             gP -= P_INCR;
             if( gP < 0 ) gP = 0;
             break;
          case 'P':
             gP += P_INCR;
             break;
          case 'd':
             gD -= D_INCR;
             if( gD < 0 ) gD = 0;
             break;
          case 'D':
             gD += D_INCR;
             break;
          case 'i':
             gI -= I_INCR;
             if( gI < 0 ) gI = 0;
             break;
          case 'I':
             gI += I_INCR;
             break;
          case 's':
             gSetPoint --;
             break;
          case 'S':
             gSetPoint ++;
             break;
          case 'x':
          case 'X':
             sprintf(tmp, "s(%d) c(%d) h(%d) P(%u) D(%u) I(%u,%d)\n", gSetPoint, gPwmCommand, gSensorReadout, (uint16_t)(gP*1000.0), (uint16_t)(gD*1000.0), (uint16_t)(gI*1000.0), gIntegral );
             Serial.print(tmp);
             break;
          default:
             break;
       }
    }

    byte executeOffMode()
    {
       digitalWrite(PIN_CTRL_INDICATOR, LOW);

       // turn off magnetic field
       gPwmCommand = 0;
       writeCoilPWM(PIN_COIL, gPwmCommand);

       gSensorReadout = analogRead(PIN_HALL_SENSOR);

       if( gSensorReadout <= MAG_LIMIT_MIN )
       {
          // Switch to idle mode.
          return MODE_IDLE;
       }
       else
       {
          return MODE_OFF;
       }
    }

    byte executeIdleMode()
    {
       digitalWrite(PIN_CTRL_INDICATOR, LOW);

       // Apply minimum magnetic field.
       gPwmCommand = COIL_IDLE_VALUE;
       writeCoilPWM(PIN_COIL, gPwmCommand);

       gSensorReadout = analogRead(PIN_HALL_SENSOR);

       if( (gSensorReadout >= MAG_PROX_THRESHOLD_MIN) && (gSensorReadout <= MAG_PROX_THRESHOLD_MAX) )
       {
          // Switch to control mode.
          gIntegral = 0;
          return MODE_CONTROL;
       }
       else if( gSensorReadout > MAG_LIMIT_MAX )
       {
          return MODE_OFF;
       }
       else
       {
          return MODE_IDLE;
       }
    }

    byte checkOutOfLimits(int val)
    {
       if( val <= MAG_LIMIT_MIN )
       {
          return MODE_IDLE;
       }
       else if( val >= MAG_LIMIT_MAX )
       {
          return MODE_OFF;
       }

       return MODE_CONTROL;
    }

    byte executeControlMode()
    {
       int err;
       int der;

       byte mode = MODE_CONTROL;

       // Execute control loop at frequency = 1/CTRL_LOOP_PERIOD_MS.
       if( (signed long)( millis() - gMillisCounter ) >= 0)
       {
          gMillisCounter = millis() + CTRL_LOOP_PERIOD_MS;

          digitalWrite(PIN_CTRL_INDICATOR, HIGH);

          gPrevSensorReadout = gSensorReadout;

          // Read hall sensor.
          gSensorReadout = analogRead(PIN_HALL_SENSOR);

          // Check if out of limits (the magnet is out of coil range).
          if( (mode = checkOutOfLimits(gSensorReadout)) != MODE_CONTROL )
          {
             return mode;
          }

          err = (gSetPoint - gSensorReadout);
          der = (gPrevSensorReadout - gSensorReadout);
          gIntegral += err;
          gIntegral = constrain( gIntegral, -MAX_ERR_INTEGRAL, MAX_ERR_INTEGRAL);

          gPwmCommand = gBias + (int)(gP*err) + (int)(gD*der) + (int)(gI*gIntegral);

          gPwmCommand = constrain( gPwmCommand, 0, COIL_MAX_PWM_VALUE);

          // Apply output.
          writeCoilPWM(PIN_COIL, gPwmCommand);

          // Write data to serial port.
    /*      Serial.write( (uint8_t)0xAF );
          Serial.write( (uint8_t)gSetPoint );
          Serial.write( (uint8_t)(gSetPoint >> 8) );
          Serial.write( (uint8_t)gSensorReadout );
          Serial.write( (uint8_t)(gSensorReadout >> 8) );
          Serial.write( gPwmCommand );
       }

       return mode;
    }

    void setup()
    {
       setupCoilPWM();

       pinMode(PIN_CTRL_INDICATOR, OUTPUT);

       Serial.begin(115200);

       gMillisCounter = 0;
       gMode = MODE_IDLE;
       gSetPoint = CONTROL_SETPOINT;
       gBias = CONTROL_BIAS;
       gSensorReadout = 0;
       gIntegral = 0;
       gP = PGain;
       gD = DGain;
       gI = IGain;
    }

    void loop()
    {
       // User commands.
       if( Serial.available() )
       {
          processCommand( Serial.read() );
       }

       // State machine.
       switch( gMode )
       {
          case MODE_OFF:
             gMode = executeOffMode();
             break;

          case MODE_IDLE:
             gMode = executeIdleMode();
             break;

          case MODE_CONTROL:
             gMode = executeControlMode();
             break;

          default:
             break;
       }
    }

title: How to calibrate a PID?

Answers: 2

body:
Gidday!  First response as a new member.  PID control is not an easy subject to grasp for starters but here is a link to a site that does explain it:
http://www.csimn.com/CSI_pages/PIDforDummies.html

The first thing about your project is that your output is digital (HIGH/LOW) whereas traditionally PID control is analog.  AnalogIN to PID to AnalogOUT. So ideally you would need to vary the current through an electromagnet and have the hall-effect make very quick updates (feedback) to the PID controller. Now most young engineers (armed with some maths) learn to control the level of a tank (water or chemical or whatever) and yes, they follow a calibration method.  The P is done first and this is the GAIN of the system the Integral usually follows & this is like a 'speed of response' type of adjustment. (Derivative rarely used).

I'm guessing your levitation system would require and extremely fast response & I think it would suffer from:

1. The time of the Analog to digital conversion at the input to the PID

2. The speed of the Arduino to process the code it runs

3. The time it takes for the OUTPUT to be applied to the electromagnet (e.g. the PWM updates inside the Arduino if you decided to use this as a pseudo 'analog output').

I know this is not good news for you but don't give up as someone will have found a work-around to this problem I'm sure.  It just seems like a bit more research is required.  Maybe some other members can assist further.

body:
Well, the response time should not be a major issue, since the ball movement is based solely on the acceleration due to gravity and the magnetic force due to the coil. If you let the ball free fall from being stopped, it would take 14.3 ms for it to move the first 1 mm, and that is a lot of time for computing and for electrical circuits to respond.

To calibrate the PID, a process usually called PID tuning, you would start with the proportional constant, Kp. Since your system is unstable, that is, without the PID either the ball will fall or stick to the electromagnet, it will be hard to tune the Kp, even with minor errors on your hall sensor readings. If the position error is large or the sensor takes too much time to update, that can also complicate the tuning.

You should check the furthest away the ball can be and still be drawn to the magnet, that point is the limit where your PID can save the ball from falling. As a rule of thumb, try tuning the Kp with the setpoint being in between the magnet and that point. At first you want just the Kp being non-zero, and it should have a value great enough so that, if the ball falls a little bit bellow the setpoint the magnet is fully powered and if it goes a bit over the setpoint the magnet turns off. This should lead to the ball oscillating around the setpoint. This method will work on your system because the output is limited between a PWM with duty 100% and 0% (you can change these limiting values if needed!), (I suppose) turning the coil to its maximum and minimum doesn't damage the system and the system is relatively slow (the gravity effect is always the same and the acceleration due to the magnet depends on the mass of the ball).

After you got it to work so-so, try lowering the Kp to the minimum value that keeps the ball oscillating around the setpoint and then read on [Ziegler–Nichols tuning method][1].

> When I hold a magnet close to the hallsensor, I can sense a pulsation from the electro-magnet, however, I if let go of the magnet, it always sticks to the electro-magnet every time, as though the pid is not properly calibrated,

That behavior is odd, even a bad PID should eventually turn off the magnet after detecting the ball went above the setpoint. Maybe the sensor reading is causing the problem, e.g. the ball goes close to the magnet but the sensor/code interpret it as going away from the magnet.

  [1]: https://en.wikipedia.org/wiki/Ziegler–Nichols_method
  [2]: https://en.wikipedia.org/wiki/Integral_windup


body:
I was wondering how can I make a Servo rotate continuously by using an Arduino code.
I looked through several forums and websites already, but all of them just show how to make it run by changing the servo physically, I wanted to be able to do it with just the code.

Thanks for your help already!

title: Continuous Rotation

Answers: 2

body:
The objective you seek will require a servo that has been manufactured to be continuously rotatable. The locations you've found are for those with extra servos who might not want to purchase a slightly more expensive servo and might want to use what they have on hand.

Once you have such a servo, self-modified or purchased as such, your code will work as you suggest. You should be able to easily locate the necessary code to operate a 360 degree servo using current libraries.

body:
Normally, a servo is rotating 180 degrees because it has a drag  inside on gears who stop rotating continuously (360 degrees).
To make a servo to rotate 360 degrees, you need to buy a new servo or modify this one.


body:
This is my first script written with Arduino. I wrote a simple Hello World program but I'm getting the following error.

    Test:18: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
       Keyboard.begin();
       ^
    exit status 1
    'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

Here is the code:

    #include "Keyboard.h"

    void typeKey(int key)
    {
      Keyboard.press(key);
      delay(50);
      Keyboard.release(key);
    }

    void setup()
    {
      // Begining the Keyboard stream
      Keyboard.begin();

      // Wait 500ms
      delay(500);

      delay(400);

      Keyboard.print("Hello World!");

      // Ending stream
      Keyboard.end();
    }

    void loop() {}

I have `Arduino/Genuino UNO` selected as my board on the IDE. Any suggestions on how I can fix this? Thanks

title: Arduino Uno "Keyboard Not Found"

Answers: 1

body:
Based on the [documentation][1] :

> These core libraries allow a 32u4 based boards or Due and Zero board to appear as a native Mouse and/or Keyboard to a connected computer.

Core libraries (such as `Keyboard.h`) are not availabe if your board doesn't mentioned.

I don't know which one is right, since your question title mentioned "Arduino Micro" while at the end of your question, the board is "Arduino Uno".

Just for further information, Arduino Uno is based on - ATmega328P, and Arduino Micro is based on - ATmega32U4. So sure, that "hello world" program will works on Arduino Micro, but not on Arduino Uno.

  [1]: https://www.arduino.cc/en/Reference/MouseKeyboard


body:
Can anyone please help me figure out/ point the reason of this arduino problem? I uploaded a simple arduino sketch (blink an LED ) just to test if my real program was the reason of the "abnormality" of this board. It works fine when I connected it to PC via arduino cable, but doesn't run the program when I use an external power supply(9v) and connected it to the Vin pin of arduino.

Need help and hoping for fast replies. I will be having a competition tomorrow, this is very urgent. please guys.

for the schematic diagram, there are no other parts inserted to the arduino board, aside from the 9v battery. I was able to say that the program work on "LED blink" by observing the lights of "TX" LED on the board. please help me. :(

title: Arduino not running the sketch with external power supply of 9v, but runs the program when connected to pc

Answers: 2

body:
TX LED is blinking because of communication (indicating data transmit via serial). It will not blink if there are **no communication from Arduino through USB cable**.

For simple observation, use LED_BUILTIN pin. Its a build in-LED indicator on Arduino.

    pinMode(LED_BUILTIN, OUTPUT);

then

    digitalWrite(LED_BUILTIN, HIGH);
    delay(500)
    digitalWrite(LED_BUILTIN, LOW);
    delay(500)

Arduino fail on external power supply is usually because of voltage drop or your system draw too much current.

body:
There is a possibility that you blew the regulator circuit with too much current while supplying your Vin pin with the 9V source. This would depend on your system power draw; something that you were using the board with before the blinker program - and also what kind of board you have.

To check this, try another similar board with the blinker program and the same 9V source. Don't forget to make the changes as suggested in the previous answer.
The other problem could be your power source: to check whether your power source supplies the desired volts, measure the power source terminal voltage while connected to the board. Most boards will have the minimum voltage requirement on Vin, depending on their regulator design.


body:
My [Trinket Pro][1] waits about 10 seconds upon booting before starting the program that I have loaded on it.

Can I avoid this delay and the bootloader taking up space if I flash my program directly to the Arduino with ArduinoISP?

  [1]: https://learn.adafruit.com/introducing-pro-trinket

title: Can I avoid having a bootloader if I use ISP to flash to an arduino?

Answers: 1

body:
It looks like the Trinket Pro has an Atmega328P processor. You can change the fuses to not run the bootloader, in which case you don't need the space taken by it.

I have a [hex uploader](http://www.gammon.com.au/forum/?id=11638) sketch which will upload a .hex file from an SD file directly to the chip, removing the need for a bootloader. Using ArduinoISP is another approach which will probably work. I'm not sure whether that fixes up the fuses for you.

If you just want to avoid the time (and not the space - the bootloader is probably only 512 bytes) you can use the sketch I linked to (without needing an SD card) to make fuse changes.

See [Engbedded Atmel AVR® Fuse Calculator](http://www.engbedded.com/fusecalc) for fuse calculations. Basically you need to toggle the BOOTRST fuse (the low-order bit of the High fuse).


body:
Basically I want to use an Attiny running an Arduino boot loader as an usb device. I'm not sure how to even start or what phrases to search for.

So here's what I ultimately wish to do.

 - Load a listener like that of an RS232 serial communication program
 - trigger pin states based on received commands
 - plug the Attiny directly into a windows environment USB port for
   communication.

I understand that this will require some kind of driver to do this but i don't know what. I do have experience with serial port communication using Visual Studio C# as well.

Assuming what I would like to do is possible, im looking for pointers in how to make the Attiny can be seen by windows.

title: USB Communication like serial RS232 with an Attiny

Answers: 1

body:
Generally there are (or could be many) [USB Devices][1] and (only one controlling) USB Host.  The differences are discussed in [this stackexchange.com question][2]. Briefly, USB Hosts are usually very complex hardware and software devices that may know about many many different types of peripherals.  They are usually only found on computers.  USB Devices are usually dedicated peripherals.  They only need to know about them selves.  Many people do not realize that there are many protocols built into USB.  These are normally called [Device Classes][1].  The [USB Serial Protocol (or CDC)][3] is one of dozens of Device Classes.

So, assuming you want a build a Serial Port USD Device, you would first need a processor with built in USB Device hardware.  (There are likely some project out in the wild that have implemented this feature using software. It might be a good experience.  But for practical purposes it is usually better to use hardware for this.)  The next feature you need to implement is a software USB Device driver.  This is not trivial.  But is much simpler than the USB Host software.  The next feature you need to implement the serial protocol inside the USB protocol.

In the real world, the USB code, even for a USB Device, is complex enough that most developers use the USB code provided by the processor manufacturer.  This is very common as most manufacturers want you to use their hardware and provide the USB code for free. [Here is Atmel's support page][4] for CDC USB (serial port) support. (Of course, Atmel makes the processor found in most Arduino boards.)

Thus far this answer has been general and is likely difficult to implement in a practical sense.  A more turn key solution is to use an existing platform which contains a USB CDC Device. The Arduino Uno comes in several versions.  One has a USB CDC chip made by FTDI.  Another has a 2nd processor programmed specifically to handle USB CDC type communications. Either version provides a USB CDC interface used for programming.  I believe [this web page][5] explains how you can also use this port to communicate with your sketch.

  [1]: https://en.wikipedia.org/wiki/USB#Device_classes
  [2]: https://electronics.stackexchange.com/questions/49140/what-exactly-are-the-difference-between-a-usb-host-and-device
  [3]: http://http:https://en.wikipedia.org/wiki/USB_communications_device_class//
  [4]: http://asf.atmel.com/docs/latest/uc3l/html/udi_cdc_quickstart.html
  [5]: http://playground.arduino.cc/Main/InterfacingWithSoftware


body:
Actually i am trying to do IoT based work.

Until now the sensed data(temperature and humidity) has been made available to only for one user on the Internet using Apache tomcat. So far we have just created a one way communication link between the sensor node and the Internet through the PC.

Now I need to control a device (say a fan) according to the variation with sensed temperature from anywhere through the internet. For the HTML I have used Java Script, which I am new to.

title: How to control an Arduino connected device accross the Internet?

Answers: 4

body:
Perhaps a message brokering service like [MQTT][1] is what you are looking for. Far too much to it to explain it all here, but basically it lets you publish messages and subscribe for messages, over a network.

  [1]: http://www.hivemq.com/blog/how-to-get-started-with-mqtt

body:
How about this:

http://www.instructables.com/id/How-to-communicate-with-Arduino-using-HTML-Chrome/

But i also would prefer MQTT, but this requires Network connection for Arduino

body:
> For the HTML i have used JAVA SCRIPT(but i am new to java)

You have to keep in mind Java is not the same as javascript.

I've once used my Raspberry Pi to communicate with my Arduino Uno. There is a library available to use on your RPi called [PySerial][1], you can use Python on your Raspberry to listen to your Arduino output and store your values to a database for example. You can also use some Python scripts to send things over your serial connection to your Arduino, for example for your fan to start. You can build a web interface to read or view your data and to control your fan with Java or Javascript.

It may not be the most useful way to do it because you can use a Raspberry Pi as your main device but I've done it before and it is nice for learning purposes.

Good Luck!

  [1]: https://github.com/pyserial/pyserial

body:
If you are planning on keeping the Arduino connected to the PC then you are looking for help with your javascript, which isn't a question for this forum.

If you are looking at making the Arduino independent from the PC then you want to look at possible network options for the Arduino, ESP8266 shield, Mobile phone, C5100 (?).

Of course you might also want to look at using an ESP8266 rather than an Arduino and programming that through ArduinoIDE and using its web server rather than Apache.  There are samples that would show you how to do this, you could get them without getting the hardware, but obviously they won't run.


body:
I'm Driving a stepper using a L298N driver and an arduino mega. I want to release the stepper after the movement so it can swing freely, because it gets hot, and it doesn't need to hold position.

Anyone know how to do it? I'm using just the basic stepper library.

Thank you.

title: Stepper motor release L298N

Answers: 1

body: Usually you should set Enable (A and B) pins on L298 to LOW, effectively turning off the driver.


body:
I have a simple network created using XBee Series 2 devices.

My network is very simple, my end-device with Arduino Uno read a temperature and Lightning, display this value into LCD and send using XBee to a coordinator. It is setting for sleep and wake up using PIN hibernation.

It is setting like End-Device AT mode.

I try to send a Remote AT command with XCTU from coordinator to my end device and it parse this command and response.

What I try to do is parse received packet into my Arduino code and decide what response (for example discharge it).

It is possible to do using only one Serial? The Arduino Uno and XBee are connected with an XBee shield.

I have try using this code but the Arduino don't display the packet received from the Coordinator.

This is my code:

    #include <avr/sleep.h>
    #define XBEE_sleepPin 7
    #include <LiquidCrystal.h>

    //Sensor variable
    int sensorPin = 0;
    int fotoResistenzaPin = A1;
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    String data = "";
    String name = "Arduino1";

    //Time Variable
    unsigned long seconds = 1000L;
    unsigned long minutes = seconds * 60;
    unsigned long hours = minutes * 60;

    void setup() {
      pinMode(fotoResistenzaPin, INPUT);
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("Status:");
      lcd.setCursor(0, 1);
      lcd.print("Connected");
      Serial.begin(9600);
      delay(2000);
    }

    void xbeesleep() {
      delay (300);
      pinMode (XBEE_sleepPin, OUTPUT);   // put XBee to sleep
      digitalWrite(XBEE_sleepPin, HIGH); // Setting this pin to LOW turns off the pull up resistor, thus saving precious current
      //delay(10 * minutes);
      delay(5 * seconds);
    }

    void xbeewake() {
      pinMode(XBEE_sleepPin, OUTPUT);  // Set the "wake-up pin" to output
      digitalWrite(XBEE_sleepPin, LOW); // wake-up XBee
      delay(10 * seconds); //make sure that XBee is ready, time to connect to Xbee Coordinator

    }

    void loop() {
     //wait message
      if (Serial.available()>0) {

     //see if it is a Xbee packet
     if (Serial.read() == 0x7E) {

          for (int i = 0; i < 15; i++) {
            byte skip = Serial.read();
            Serial.println(skip);

      //check if it is a Remote AT commnad
      if (skip == 0x17) {

       //do something when i find the Remote AT command packet
              lcd.setCursor(0, 0);
              lcd.print("Remote AT command ");
            }
          }
        }
      }

      xbeewake();
      int reading = analogRead(sensorPin);
      int val = analogRead(fotoResistenzaPin);
      float voltage = reading * 5.0;
      voltage /= 1024.0;

      float temperatureC = (voltage - 0.5) * 100 ;
      data = name + ',' + temperatureC + ',' + val;
      if (Serial) {
        Serial.println(data);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Temp: ");
        lcd.print(temperatureC);
        lcd.print(" C");
        lcd.setCursor(0, 1);
        lcd.print("Lightning: ");
        lcd.print(val);
      }
      else {
        lcd.setCursor(0, 0);
        lcd.print("Serial Error ");
        lcd.setCursor(0, 1);
        lcd.print("Stop Trasmission");
      }

      xbeesleep();

    }

title: Send and Read packet XBee AT mode

Answers: 1

body: I'm not sure about this, but similar to any other serial communication modules used on the Arduino, you need to setup a software serial pins which act as Tx and Rx between the Arduino and the module, XBee in this case. Look at software serial. this should solve your problem. Then you can use the "Serial" object to debug your communication between the two. I have worked with both a GSM and a Wifi module and the method was the same as I have explained above.


body:
For a project I need to use an industrial stepper driver with an arduino. There it is: http://www.omc-stepperonline.com/bipolar-stepper-motor-driver-max-4a-current-40vdc-input-16-subdivision-st6600-p-246.html

The motor: https://prototypes.haydonkerk.com/ecatalog/hybrid-linear-actuators/en/linear-actuator-57F42-3.25-099#

I'm not familiar with this driver, so can I use it with the Arduino Stepper Library?

I didn't see a lot of tutorial for this driver compared to many other popular driver.

Thanks!

title: Arduino and industrial stepper driver

Answers: 1

body: Absolutely you can. Looking at the picture, this is set up for bipolar and a unipolar motor. There you have to wire according to the wire diagram.


body:
I am an absolute noob in FPV quadcopters and quads in general. My aim is to create a simple quadcopter with a live video transmission. Based on my research I need:

 - 4 rotors
 - 4 Props
 - 4 Electronic Speed Controllers
 - Camera Kit
 - Lipo battery
 - Power Distribution Board
 - Accel. and Gyro
 - Arduino UNO
 - Receiver Kit

Am I missing anything? and how would you wire it?

title: I need help purchasing materials for a arduino fpv quadcopter

Answers: 1

body:
**These are my suggestions.**

You don't need the following:

 - Accel. (a gyro is enough)

---

You are missing the following:

 - You need 2 sets of receiver/transmitter. One of them is for the controller, the other one, for video.

 - You also need a screen or PFV goggles to display the received video.

 - You need a frame.

---

Here is my suggestions for a couple of your parts.

- Buy a DIY Flame Wheel Kit. They should include : motors, ESCs, props and the frame itself.

- Get a GoPro Hero (original) for your camera. They're cheap and should give you good enough quality for a DIY quadcopter build.

- Use and Arduino Pro Mini, they are smaller. Note that you need an external FTDI programmer for it.

- Use at least a 3S lipo.


body:
I happened to short-circuit my Arduino by mistake. It was powered by USB on my Windows 7. The OS was so smart to pop-up warning about USB power surge and shut it down immediately. Arduino survived.

I fixed the circuit and connected it back. Arduino was powered again, but it was not recognized as COM port anymore. There was no unknown device in Device manager. I tried different USB connector on the same computer and it was found and it worked. But the other USB was out.

I restarted the computer and connected the Arduino back to the broken connector. The drivers were automatically reinstalled (I don't know why) and it worked again.

Is it possible to re-enable Arduino on the same USB connector without restart? I'd like to understand what happened on the computer side.

title: Re-enable Arduino after short

Answers: 1

body:
Most likely, your motherboard detected a over-current situation, and disabled power to that port. Since it has to way to know if the cause of the over-current has been fixed, it will continue to disable the port (since the only way to know would be to turn the power back on, and doing that to many times might cause permanent damage).

I wouldn't expect there to be a way to force your MoBo to reset the port, as this is an unlikely event. You should be glad the MoBo prevented any damage.

Using a different port sounds like an okay solution.


body:
First things first, I am new here and this is my first post. So if this is in the wrong place I apologize and please just let me know.

I am a programmer that is getting into working with an Arduino compatible board, so my questions are 99% of the time with the hardware side and not the software side.

I just went through a tutorial on how to connect LEDs in parallel to a shift register so that I can control each LED individually.

My project goal is to make a Christmas house for a family member that will use some predefined songs to blink the lights to. So what I am actually looking for suggestions for is how to make a string of LEDs (5mm) that I can hook up to a small house without it looking messy. I was thinking I could maybe use 2 wires to run along the + and - of all the LEDs and then maybe there is some kind of connector I can use to split the 8 LEDs off to their respected hookups on the shift register.

Any good ways of doing this and keeping the metal unexposed?

I thank you in advance for your answers and your time!

title: How to wire Christmas lights with LEDs to use for Arduino Project?

Answers: 1

body:
[![enter image description here][1]][1]
Here is a string of Stripleds operated from a CPU 12V supply with built-in double-sided tape under the hand rail in one of my homes. Red downstairs and blue upstairs.

Now define your input and output attributes to modulate the current.

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


body:
I am python experienced, an arduino noob, and absolutely no experience of C other than what has been forced upon me by arduino use.

I have just spent a day hammering google for the precise syntax of creating and using a class for user libraries, and have finally won.

However, I find that there are two forms that both seem to work for instantiating an object in the main program.

With my python experience, I find it easier to recognise the obj= style, used by Alan Zucconi in his examples, though the arduino.cc library tutorial on the Morse library uses the other form.

Is either preferrable, or are they equivalent in every way? Are there any subtle side effects of which I am unaware, that will bite me if the interfaces get more complicated, or some assumptions get corrected in future releases of the arduino IDE or compiler?

    #include "Minimal_library.h"

    // allocate buffer to be used
    #define BUF_SIZE 40
    char buff[BUF_SIZE+1];

    // which of these two instantiation calls works?

    // Minimal_library obj = Minimal_library(BUF_SIZE, buff);  //alanzucconi - works
    Minimal_library obj(BUF_SIZE, buff);   //  Morse - that seems to work as well now
    ...

I presume that any private variables defined within the class become fully fledged persistent variables unique to the object created (it's been a long and frustrating day, not quite got around to testing the persistence or uniqueness yet, compiling without error, and then working, are enough for today!)

title: Library, instantiation of a class object

Answers: 1

body:
The statement

    Minimal_library obj(BUF_SIZE, buff);

means “create an object named `obj`, initialized by calling the class
constructor with the supplied parameters”.

On the other hand,

    Minimal_library obj = Minimal_library(BUF_SIZE, buff);

means “create an _unnamed_ object initialized as before, then copy it
into an object named `obj`, then delete the unnamed object”.

The compiler would normally optimize the second form into the first one.
It is even allowed to do so in some weird cases where they may not be
equivalent. In the end, it's mostly a matter of style. I prefer to do
the optimization myself and write the first form. But if you find the
second form more readable, go ahead: you can normally trust the compiler
to optimize out the unneeded copy.


body:
I've been building wearables, using the adafruit trinket, which I love, its small size is easy to tuck away. But I hate having to unplug the battery to charge it every time. I wired in a SPDT switch, and a small USB charger, but it's kind of a cockamamie solution.

I've seen some devices with a battery adapter, and integrated USB charging,
but they are larger, and harder to tuck away.

I don't need more than 4 IO ports, I'm just looking for a tiny microcontroller platform with integrated USB charging. I just saw the mkr1000 today, which looks decent, but is still larger than I would like. If you know of a product that meets this description, please let me know.

title: What boards have integrated USB charging?

Answers: 1

body: The Feather mainboards are fairly small and have integrated LiPo/Li-ion charging. They're not as small at the Trinket but if you don't need the space on the proto boards then you can examine the design files to see what can be cut away.


body:
I wrote a function that takes characters and noticed that the Arduino Compiler treated some characters like system-reserved, and other like functions, and a few just like characters. Lowercase doesn't seem to be effected.
I'm just wondering why. [![enter image description here][1]][1]

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

title: Why are some letters reserved?

Answers: 2

body:
In WString.h is a define:

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

    #define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))

In other words, the letter `F` is already a macro.

I don't know what your code:

    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

is supposed to do. I suppose you are just testing the syntax highlighting?

The syntax highlighting is designed to try to "help" you by colouring words in a pre-supplied file in a different way. It doesn't in any way affect how the compilation works. And, judging by what you posted, it can't always be relied upon. Personally, I ignore it.

body:
The Arduino IDE does keyword coloration according to a very crude system. It simply scans for all the keywords.txt files included with:

- Arduino IDE
- Libraries bundled with the Arduino IDE
- Libraries you have installed to the libraries subfolder of your sketchbook
- Libraries bundled with the hardware package of the currently selected board - Hardware package of the currently selected board ([recent IDE versions only](https://github.com/arduino/Arduino/pull/3847))

There are several types of keyword identifiers that determine which color is used. The reason those letters are colored in your IDE is because some library you have installed just happens to have added them to its keywords.txt file.
The Arduino IDE makes no attempt to determine whether you have included those libraries and so coloration doesn't necessarily mean they are "reserved". If you have not included the library that defines a specific keyword then the coloration of that keyword is meaningless.

For more information on keywords.txt see:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#keywords