message:
L298N vs Motor Shield R3

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

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.


sender: user

message:
Sound Recognition

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?

sender: assistant

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


message:
How to calibrate a PID?

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;
       }
    }

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


message:
Continuous Rotation

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!

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.


message:
Arduino Uno "Keyboard Not Found"

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

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


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

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. :(

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.


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

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

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).


message:
USB Communication like serial RS232 with an Attiny

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.

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


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

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.

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.


message:
Stepper motor release L298N

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.

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


message:
Send and Read packet XBee AT mode

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();

    }

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.


message:
Arduino and industrial stepper driver

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!

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.


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

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?

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.


message:
Re-enable Arduino after short

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.

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.


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

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!

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


message:
Library, instantiation of a class object

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!)

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.


message:
What boards have integrated USB charging?

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.

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.


message:
Why are some letters reserved?

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

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


message:
(SOLVED more or less) Direct reading/writing to PORTD, unexpected readback, how does the serial library use it?

**TL;DR** When Serial is invoked on a rev3 Uno, the UART uses the Tx and Rx pins on PORTD regardless of what you try to do to PORTD I/O directly. The warnings on arduino.cc about avoid those bits appears to be wrong. Readbacks from PORTD on those pins reflects the last user input, not the state of those pins.  **/TL;DR**

I have extensive assembler (other platforms) and python experience, but no C and am still on the lowers lopes of the Arduino learning curve. I am using the Arduino/C IDE at the moment for simplicity, though I have a feeling that once I bite the bullet (not for this project if possible), I am going to find the direct AVR route suits my style more.

I'm developing a charliplexed LED driver application on Uno hardware which uses most of the I/O pins, so am having to use portD. I'm using direct writes to DDRD and PORTD rather than digitalWrite(), for a number of reasons not all related to speed.

I am aware of the use of pins 0 and 1 for serial comms, so am using the recommended DDRD |= Bxxxxxx00 format when setting to 1, and DDRD &= Bxxxxxx11 when setting to 0.

I hadn't intended reading back the port, though I'm knee-deep in debug readbacks, so did it eventually. When I read back DDRD, it's Bxxxxxx00 every time. But my readbacks are working, so serial communication using the Serial.println(xx) format and the monitor in the IDE, continues to work.

I would have expected the Tx direction bit to be 1. Is it the case that the Serial library grabs the port when it needs to transmit, and then reverts it? So is it actually 0 when I read it, or am I reading wrongly, or I can't read it? As I expect DDRD &= Bxxx to work, I should be able to read it.

I'm comfortable working with the bare metal, where I have total control, and with python where it's all magic, but get a bit uneasy when I'm not sure whether I expect magic to be happening under the hood or not.

Here's the code

    const byte portD_1_mask = B11111100;
    const byte portD_0_mask = B00000011;

    #define DEBUG_LEN 20
    char debug_str[DEBUG_LEN+1];
    #include "debug_formats.h"

    byte counter;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // send an intro:
      Serial.println("\n\ndebug portD demo:");
      Serial.println();
    }

    void loop()
      {
        counter += 3;
        Serial.println(counter);
        drive_LEDs(counter);
        delay(100);
      }

    void drive_LEDs(int a)
    {
        // create port programming variables, initialised to 0
        byte D_dir = 0;
        byte D_data = 0;

        // prepare bytes to be written to the ports
        // the anode gets driven by ORing into both data and direction
        D_dir |= 4;  // constant for this demo
        D_data |= 4;
        // the cathode(s) get driven by ORing into the direction only
        D_dir |= a;   // wave these around

        Serial.println("generated programming bytes");
        Serial.print("direction - data - ");
        debug_format(D_dir, D_data);
        Serial.println(debug_str);

        // finally write all pins to their new values
        // D port needs to pussyfoot around not changing the TxRx pins

        // reset D port 7-2 to all 0s
        PORTD &= portD_0_mask;
        // and then set the ones we've got in the 7-2 positions
        D_data &= portD_1_mask;
        PORTD |= D_data;

        // and the same for D direction
        // switch D 7-2 to inputs first
        DDRD &= portD_0_mask;
        // then set the outputs
        D_dir &= portD_1_mask;
        DDRD |= D_dir;

        // and see what we have written to port
        Serial.println("what the hardware has been set to");
        Serial.print("direction - data - ");
        D_dir = DDRD;
        D_data = PORTD;
        debug_format(D_dir, D_data);
        Serial.println(debug_str);
    }

and the results it produces on the monitor

    debug portD demo:

    3
    generated programming bytes
    direction - data - 00000111..00000100..
    what the hardware has been set to
    direction - data - 00000100..00000100..
    6
    generated programming bytes
    direction - data - 00000110..00000100..
    what the hardware has been set to
    direction - data - 00000100..00000100..
    9
    generated programming bytes
    direction - data - 00001101..00000100..
    what the hardware has been set to
    direction - data - 00001100..00000100..
    12
    generated programming bytes
    direction - data - 00001100..00000100..
    what the hardware has been set to
    direction - data - 00001100..00000100..

The hardware is doing what I'd expect, LEDs are flashing.

Now I'm not concerned that the 'generated programming bytes' have LSBs set and they don't appear in the readback, as I'm doing a data &= portD_1_mask which clears the LSBs before ORing into the port.

What I am questioning is the fact that the two LSBs on DDRD are always read back as 0. If the Serial library grabbed and kept those pins continuously, then I would expect the Tx pin to be an output, whenever I read it. But it's not reading back that way. So does that mean Serial only makes the Tx an output when it's transmitting, and then puts it back to input when not? Or is my read of the DDRD Tx bit not working for some reason, though it seems to be working for the other bits?

OK, so I've got the 'scope out, put a resistor network on the Tx pin so I can see whether it's high or low Z, and it stays low Z even when not transmitting, so the UART does 'retain' the port. This means the readback of the DDRD contents is a lie. Section 19.6 of the AVR doc 8161 does say the port pins are *overridden* by the UART, which this seems to confirm.

So if they are overridden, all this warning on the arduino.cc site tutorials about not stomping on the pins is incorrect. The following code bashes the bejaabers out of PORTD while using it to receive and send.

      int count;

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      // send an intro:
      Serial.println("\n\ndebug portD demo:");
      Serial.println();
    }

    // the loop function runs over and over again forever
    void loop() {
      count += 1;
      if ((count&1)==0) DDRD = 0; else DDRD = 0xff;
      if ((count&2)==0) PORTD = 0; else PORTD = 0xff;

      PORTB = 0xff;
      byte dd = DDRD;
      byte pp = PORTD;
      Serial.println();
      Serial.println(count);
      Serial.println(dd);
      Serial.println(pp);
      PORTB = 0;
      delay(2000);

      if (Serial.available() > 0)
      {
        byte inByte = Serial.read();
        Serial.print("got >");
        Serial.println(inByte);
      }
    }

and this fragment of output captured from the monitor shows it keeps working. I used a sufficiently long delay so I'd be able to hit all phases of the write to data and direction on PORTD.

    9
    255
    0
    got >49

    10
    0
    255
    got >114

    11
    255
    255
    got >99

    12
    0
    0
    got >115

    13
    255
    0
    got >115

Lessons

a) When Serial is in use, the UART hardware does override the Tx Rx pins, at least on a rev3 Uno.

b) It does hang on to the hardware between active transmissions

c) The warnings on arduino.cc tutorials about writes to PORTD and DDRD don't seem to be valid, it appears the hardware just ignores them

d) Reads back from PORTD and DDRD show what you last wrote in pins 0 and 1 when the UART is in use, not what's on the pins.

body:
See the datasheet: **14.3.3 Alternate Functions of Port D**

> * TXD/PCINT17 – Port D, Bit 1
TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1.
> PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.
>
> * RXD/PCINT16 – Port D, Bit 0
RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input regardless of the value of DDD0. When the USART forces this pin to be an input, the pull-up can still
be controlled by the PORTD0 bit.
> PCINT16: Pin Change Interrupt source 16. The PD0 pin can serve as an external interrupt source.

So basically if you turn on the USART the pins are configured as input/output regardless of DDRD.

---

> but get a bit uneasy when I'm not sure whether I expect magic to be happening under the hood or not.

It's not the IDE - it's the underlying hardware.

---

>  This means the readback of the DDRD contents is a lie.

No it isn't. The hardware is ignoring DDRD in those bits. See this example:

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

    void setup()
    {

    DDRD = 0;
    byte a = DDRD;
    DDRD = 0xFF;
    byte b = DDRD;

    Serial.begin (115200);

    DDRD = 0;
    byte c = DDRD;
    DDRD = 0xFF;
    byte d = DDRD;
    Serial.end ();

    Serial.begin (115200);
    Serial.print ("a = ");
    Serial.println (a);
    Serial.print ("b = ");
    Serial.println (b);
    Serial.print ("c = ");
    Serial.println (c);
    Serial.print ("d = ");
    Serial.println (d);
    }

    void loop()
    {
    }

Output:

    a = 0
    b = 255
    c = 0
    d = 255

The code is setting DDRD and reading it back as set. However the hardware is ignoring those bits because of the alternative use of those ports.


message:
Problem with connecting pins on an Arduino board with an L239D shield

I have an L239D motor shield just like the Adafruit motor shield. I had a question in my mind. While making a robot, I could not connect my pins from various sensors in Arduino as the motor shield is already fitted on the board. So how can I connect my pins?

PS: I have the same board as shown in the picture [![enter image description here][1]][1]

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

body:
That's a common problem that has many solutions.

The cheapest way is to solder the wires directly as many comments said. Though this is quite dirty, it should work for you.

The more professional way is to use these [Arduino stackable header][1]. They can even let you have a shield on top of your shield. This is the best choice in my opinion.

  [1]: https://www.sparkfun.com/products/10007


message:
Where are the Special Function Registers located? (Atmega 328)

I'd like to program my Arduino using Assembler. We have to learn this at college.
The problem is that I can find a documentation for the instruction set but I can't find the Special Function Registers.

Something like this would be great or similar to make a sheet like this by myself.

body:
> Where are the Special Function Registers located? (Atmega 328)

Please see Chap. 36 Register Summary, pp. 612, in
http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

The registers are available "by name" in the AVR IO header files.

Cheers!


body:
There are several options for programming the AVR in assembly, but since
you have an Arduino and the Arduino IDE bundles the gcc toolchain, using
this toolchain is probably the easiest way. Besides, if you learn
assembly in the GNU syntax, you will be able to use it together with C++
and the Arduino libraries.

The gnu compiler will run through the C preprocessor any assembly
program having the `.S` extension (in uppercase). You would then start
your program with

    #include <avr/io.h>

in order to get all the SFR definitions from avr-libc. That include file
is intended to work both in C and in assembly. The SFRs so declared
should be considered as opaque identifiers. To get their addresses, you
should use the macros `_SFR_IO_ADDR()` or `_SFR_MEM_ADDR()`. I
personally find those names too cumbersome to type, so I tend to
`define` my own shortcuts.

Just to get you started, here is a minimal “blinky” program in assembly
for the Arduino Uno (ATmega328P with the LED on PB5):

    ; Blinky in assembly.

    #include <avr/io.h>
    #define io(reg) _SFR_IO_ADDR(reg)

    .global main
    main:
        sbi io(DDRB), PB5  ; PB5 as output
    0:  sbi io(PINB), PB5  ; toggle PB5

        ; delay 16 * 65536 * 5 cycles ~ 0.31 s
        ldi  r26, 16
    1:  sbiw r24, 1
        sbci r26, 0
        brne 1b

        rjmp 0b ; restart


message:
Turn Arduino on with timer every 24h

I'm currently working on an Arduino project that sends the charge of my car battery once a day via an ESP8266 to me. During the winter I don't drive my car, and I would like to get informed when the battery drops beyond a critical value, so I can charge it and prevent damage.

So energy efficiency is important for the project, so it doesn't discharge the battery itself. I read a lot about sleep mode, efficient drop down regulators etc. These all have in common that the voltage regulator is always running, which is not what I want.

I'm looking for some kind of "swich-on-timer circuit". It should count down 24 hours and then turn on a relay or MOSFET, which connects the voltage regulator to power and with that turns on the Arduino and the ESP8266. When the Arduino has finished with the transmission, it resets the timer, which disconnects the voltage regulator from power, and so on. Of course, the timer circuit should use only very little power.

Does anybody know a circuit like that? I searched on [AliExpress](http://www.aliexpress.com/) with all variations of words that came to my mind, without success. Or maybe an IC which can be used (easily) to create such a circuit?

body:
The timer or timer-circuit itself would have to draw some current. Any of the pico-power AVR chips draw very little current in sleep mode - in the 10s of micro-amps for the 328, if I recall correctly. Sleeping an AVR for the least current draw needs just about everything shut down but the watchdog timer, and the maximum WDT period is 8 sec. A library like Narcoleptic will manage longer periods for you. What you would need to do though, is to provide a much more efficient regulated power supply than the one built onto the Arduino board (if that is what you'll be using). That done, the Arduino's load on your car battery should be microscopic.

One possible design for an efficient supply is an array of alkaline batteries, say 3 in series for a 4.5 output (while fresh) times 2 or more such strings in parallel, connected directly to the 5v bus.

I haven't done the power budgeting to know the capacity you'd need and whether you'd need D cells or could make a practical array from smaller ones, say AAs, but that is a way to achieve zero load on the car battery (discounting the car-battery voltage sensor's requirement). You might want to include the Arduino battery-array's health in the daily report, or, for the price of a few Alkalines, you might so over-design the Arduino battery that monitoring it would become unnecessary.

A couple of data points suggest a separate battery is a feasible approach:

- A single 9v Alkaline runs a smoke detector for over a year including over-wintering in an unheated attic (in my own experience), and 9v Alkalines are _not_ known for their capacity.
- My digital setback thermostat has run for a couple of years on 2 AA cells, before a) they died, and b) I wised-up and started changing them annually. :)


body:
One approach would be use of a DS3231 (Precision Real Time Clock) module.  Such modules sell on Ebay for under $1.  Search for `ds3231 arduino`.

Typically, these modules have a six-pin connector, with pins labeled 32K, SQW, SCL, SDA, VCC, and GND.  As noted in DS3231 specs, the INT/SQW pin is used either for square-wave output or for interrupt output.  On page 13 of specs, in the Control Register section, it says:
>Bit 2: Interrupt Control (INTCN). This bit controls the INT/SQW signal. When the INTCN bit is set to logic 0, a square wave is output on the INT/SQW pin. When the INTCN bit is set to logic 1, then a match between the time-keeping registers and either of the alarm registers activates the INT/SQW output (if the alarm is also enabled).

Initially, you would run a sketch to set up the DS3231: turn on a daily alarm, enable an interrupt rather than square wave, set the current time, etc.  Then, load an operational program that reads car-battery voltage each time it runs, and acts appropriately.

The DS3231 INT/SQW pin would be wired to the gate of a P-channel mosfet that switches 12V power to the Arduino.  The P-fet would turn on when the alarm's open-drain output pin INT/SQW turns on.  The operational program does its business and then clears the DS3231 interrupt flag, to shut down power until the next alarm occurs.  (For debugging, set briefer intervals than a day; for example, once a minute, as described in Table 2, Alarm Mask Bits, on page 12 of specs.)

Typically, the DS3231 draws 0.84 μA when running from a 3.3V battery, or 1 μA from 5V.  See Electrical Characteristics, page 3 of specs.


body:
Consider using "Adafruit TPL5110 Power Timer" <BR>
https://learn.adafruit.com/adafruit-tpl5110-power-timer-breakout/overview


message:
Is it possible to use Wi-Fi as a wireless connection to my Arduino/Windows PC LAN without using the internet

My Situation and Problem:

I am wanting to put together a system to help monitor the soil moisture content in my garden and a small heated greenhouse I use in the winter. Also, In the near future I would like to build a system to remotely monitor the nutrients in my soil and other grow media, and have it accessible through my computer using a system similar to the one I'll have monitoring the moisture levels. In both situations I am growing nearly all crops hydroponically.

I have found several instances of people doing this by having the information posted to a service provider's website. Then it is possible to access the information by way of email or connecting in some manner to the service provider's site.

I plan to store the data in the cloud, but where I live we get internet access through satellite dish or land based re-transmission sites. So, I am planning to keep all gathered data in "The Cloud" manually, once received when I turn on my computer. I even have to use a booster device in my house to get dependable cell phone service. My land line telephone service provider doesn't offer high speed internet service, so I don't presently use a smart phone. I recently read a news article talking about a similar, though more widespread situation in Australia. In Australia they call it the tyranny of distance.

In addition to my garden and greenhouse, I have several other ideas for using Arduino to gather data using wifi and do any number of other things, and most of these ideas include accessing the gathered data through my computer connected to an Arduino device as required. It would certainly be helpful if anyone would be willing to share any ideas or point me toward inexpensive solutions.

Thanks for your kind consideration.

body:
Ok, my idea is that you could connect the arduino AND your computer to the same router ( that doesn't need to internet access) to create a simple LAN. Then program the arduino to send every X amount of time data to the computer with a simple protocol like UDP knowing the LAN address of the computer ( example would be 192.168.1.2) and the one of the arduino, you could send UDP packets with IP address of the computer and since the router sees that the IP is in its internal LAN it just sends it straight away. Now there are a few problems to this approach:

1) The arduino needs to have signal to be connected with the router, so the distances need to be reasonable.

2) Both the arduino and the computer needs to be always on. The arduino isn't a big issue, just remember that if for some reason you'll use the millis() or micros() functions eventually they'll reset to 0 and start again. As for the computer instead, this could be a bit expansive, since having a normal pc on for all the time can impact the electricity bill quite a bit. The solution to this would be for example to make the arduino write data on a  SD card and when it sees that the computer is on and that it's able to send it to it, it starts retriving data from the SD, sending it to the PC and then deleting it. The problem with this is that the SD has a limit as well, so just keep this in mind.


body:
I have a hydroponic setup working. Actually I'm working in a second version. My solution is this:

[![Monitor setup][1]][1]

I'm using a nodeMCU, because it have WiFi and lots of memory. In the breadboard I also have a real time clock (RTC), a LDR to measure real light level, and a temp/humidity sensor (DH-11), plus a small OLED display. The green led represent the HID light for testing purposes. I still need to add more elements, but it's good enough to show you my setup.

The nodeMCU send information to a MQTT *broker* . I can watch that information using an MQTT *client* in my Android smartphone. With the same client I can send orders to the nodeMCU (like changing light schedule, etc.)

MQTT is a protocol designed for Internet of Thing. It small and simple. You need a *broker* (server) to receive and send messages. I'm using Mosquitto running on Linux, on a old laptop that is on all time.

This is the big picture (no Internet involved):

[![Local Area Network][2]][2]

Mosquitto is free, and it's available for PC, Mac and Linux [here][3].

You have free clients for Android, iPhone, Windows, Mac, and Chrome. I'm using [MQTT Dash][4].

MQTT is lightweight, easy, multiplatform, multiclient, and the best part of it: minimal programming.

  [1]: https://i.stack.imgur.com/VGBrE.jpg
  [2]: https://i.stack.imgur.com/lASo3.png
  [3]: https://mosquitto.org/download/
  [4]: https://play.google.com/store/apps/details?id=net.routix.mqttdash&hl=en


message:
SPI Overflow in 328 slave with i2c sensor

I am working on creating sensor poller that is going to be polling multiple sensors and then, on request, provides its data to the master.

The master polls the slave (SPI) at 50hz and the slave is polling it's sensor (BNO055) (I2C) at 100hz.

The transaction works most of the time but every once in a while it returns an overflow.

Any ideas why this might occur?

Slave code:

    /*************************************************************************
     *
     * objeeAirlines
     * __________________
     *
     *  Written by Julian Blanco
     *
     *  Spi slave code written by
        Nick Gammon
        February 2011
     */

    #include "Adafruit_BNO055.h"

    float yawInput=0;
    float yawOffset=0;
    float pitchInput=0;
    float rollInput=0;

    int calibration=0;

    volatile byte command = 0;
    Adafruit_BNO055 bno = Adafruit_BNO055();

    void setup (void)
    {

      if(!bno.begin())while(1){};
      bno.setExtCrystalUse(true);
      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);
      // turn on SPI in slave mode
      SPCR |= _BV(SPE);
      // turn on interrupts
      SPCR |= _BV(SPIE);
    }  // end of setup

    // SPI interrupt routine
    ISR (SPI_STC_vect)
    {
      union first_union{
        float f;
        byte b[4];}
      data;

      byte c = SPDR;

      data.f = yawInput;

      command = c;

      switch (command)
      {
      // no command? then this is the command
      case 0:

        SPDR = 0;
        break;

      // incoming byte, return byte result
      case 'a':

        SPDR = data.b[0];
        break;

      // incoming byte, return byte result
      case 'b':

        SPDR = data.b[1];
        break;

      // incoming byte, return byte result
      case 'c':

        SPDR = data.b[2];
        break;

      // incoming byte, return byte result
      case 'd':

        SPDR = data.b[3];
        break;

      } // end of switch

    }  // end of interrupt service routine (ISR) SPI_STC_vect
    float tiempo=millis();
    void loop (void)
    {

      // if SPI not active, clear current command
      if (digitalRead (SS) == HIGH) command = 0;

        if(millis()>(tiempo+10))
        {
          tiempo=millis();
          SampleGyro(bno);
        }

    }  // end of loop

    void SampleGyro(Adafruit_BNO055 &gyroIMU){
        /* Display the floating  point data */
        imu::Vector<3> euler = gyroIMU.getVector(Adafruit_BNO055::VECTOR_EULER);
        yawInput=euler.x()-yawOffset;

        if (yawInput >= 360)
        {
              yawInput -= 360;
            }
        else
        {if (yawInput < 0)yawInput += 360;
        }
        pitchInput=euler.y();
        //rollInput=fmod((euler.z()+(360+90)), 360)-180;
        rollInput=euler.z();
        uint8_t system, gyro, accel, mag = 0;
        gyroIMU.getCalibration(&system, &gyro, &accel, &mag);
        calibration=system;
    }

Master Code:

    #include <SPI.h>

    #define SS 10
    void setup (void)
    {
        pinMode(MOSI, OUTPUT);
        pinMode(MISO, INPUT);
        pinMode(SCK, OUTPUT);
        pinMode(SS, OUTPUT);

      Serial.begin (115200);
      Serial.println ();

      digitalWrite(SS, HIGH);

      SPI.begin ();

      SPI.setClockDivider(SPI_CLOCK_DIV8);
    }

      byte transferAndWait (const byte what)
    {
      byte a = SPI.transfer (what);
      delayMicroseconds (10);
      return a;
    }

      union first_union{
        float f;
        byte b[4];}
      data;

    void loop (void)
    {

      digitalWrite(SS, LOW);

      transferAndWait ('a');

      data.b[0] = transferAndWait ('b');
      data.b[1] = transferAndWait ('c');
      data.b[2] = transferAndWait ('d');
      data.b[3] = transferAndWait (0);

      digitalWrite(SS, HIGH);

      Serial.print("data.f = ");Serial.println(data.f);

      //Serial.print("data.b[0] = ");Serial.println(data.b[0]);
      //Serial.print("data.b[1] = ");Serial.println(data.b[1]);
      //Serial.print("data.b[2] = ");Serial.println(data.b[2]);
      //Serial.print("data.b[3] = ");Serial.println(data.b[3]);

      delay(10);
    }

body:
It is likely that your SPI interrupt on the slave is firing in the middle of updating your global `yawInput` variable. This would cause the value to be partially updated when you send it back to the master. You might even be sending part of the old value and part of the new value back to the master. It depends on when the interrupts fire.

You need to lock your `SampleGyro` function somehow. The easiest way would be to disable interrupts when modifying any interrupt accessible variables (i.e. `yawInput`).

Something like this should tell you if the interrupt timing is the issue:

    void SampleGyro(Adafruit_BNO055 &gyroIMU){
        /* Display the floating  point data */
        imu::Vector<3> euler = gyroIMU.getVector(Adafruit_BNO055::VECTOR_EULER);
        uint8_t system, gyro, accel, mag = 0;
        gyroIMU.getCalibration(&system, &gyro, &accel, &mag);

     // Disable interrupts while modifying the global variable
        noInterrupts()
        yawInput=euler.x()-yawOffset;
        if (yawInput >= 360) {
              yawInput -= 360;
        } else if (yawInput < 0) {
              yawInput += 360;
        }
        pitchInput=euler.y();
        //rollInput=fmod((euler.z()+(360+90)), 360)-180;
        rollInput=euler.z();
        calibration=system;
        // re-enable interrupts once your global variable
        // modification is done.
        interrupts();
    }

It's also worth noting that you want to put as little code between the `noInterrupts()` and `interrupts()` calls as possible. Things like I2C and SPI and basically any other communication will likely not work inside of that block. I rearranged your `SampleGyro` function to put all calls to the gyro outside of the lock. This is to prevent the sensor reading from failing.


message:
DC motor not start?

My aim is to create a simple obstacle avoiding robot using Arduino.

I have used L293D motor shield to drive the DC motors and supply it all with 12 V. I am using a sonar module to detect the obstacles. I have used an IR Receiver to control the motors of the robot.

From the serial prints I can tell that every IR signal is received and the expected functions are called. Unfortunately, when I press the button to start the motor, the motor does not start.

When I remove IR Receiver and start robot the code works fine.

In my code posted below I have commented some code so that it only calls the `startFan()` function.

What is wrong with my code? And how do I fix it?

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

    #include <AFMotor.h>
    #include <NewPing.h>
    #include <Servo.h>

    #include <boarddefs.h>
    #include <IRremote.h>
    #include <IRremoteInt.h>
    #include <ir_Lego_PF_BitStreamEncoder.h>

    #define TRIG_PIN A4
    #define ECHO_PIN A5
    #define MAX_DISTANCE 200
    #define MAX_SPEED 75 // sets speed of DC  motors

    NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

    AF_DCMotor motor1(1, MOTOR12_1KHZ);
    AF_DCMotor motor2(3, MOTOR12_1KHZ);
    AF_DCMotor motor3(2, MOTOR12_1KHZ);

    Servo myservo;

    boolean goesForward = false;
    int distance = 100;
    int speedSet = 0;

    int DisObstaclePin = 0; // This is our input pin
    int DisObstacle = HIGH; // HIGH MEANS NO OBSTACLE

    int receiver = 6; // Signal Pin of IR receiver to Arduino Digital Pin 11
    int power_status ;

    IRrecv irrecv(receiver);           // create instance of 'irrecv'
    decode_results results; // create instance of 'decode_results'

    //----( SETUP: RUNS ONCE )----//
    void setup()
    {
      Serial.begin(9600);
      Serial.println("IR Receiver Button Decode");

      int power_status = 0;
      motor3.setSpeed(150);
      motor3.run(FORWARD);

      pinMode(DisObstaclePin, INPUT);
      myservo.attach(9);
      myservo.write(115);
      delay(1000);

      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      DisObstacle = digitalRead(DisObstaclePin);
      delay(100);

      irrecv.enableIRIn(); // Start the receiver

    }

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

      Serial.println("Begin loop");
      delay(1000);
      if (irrecv.decode(&results)) // have we received an IR signal?
      {
        Serial.println("wada");
        translateIR();
        irrecv.resume(); // receive the next value
        delay(500);
      }

     /* else {
        if (power_status == 1) {
          Serial.println("POWER ON");
          int distanceR = 0;
          int distanceL =  0;
          delay(40);
          if (distance <= 25 || DisObstacle == HIGH)
          {
            Serial.print("Turning");
            moveStop();
            delay(100);
            moveBackward();
            delay(300);
            moveStop();
            delay(200);
            distanceR = lookRight();
            delay(200);
            distanceL = lookLeft();
            delay(200);

            if (distanceR >= distanceL)
            {
              turnRight();
              moveStop();
            } else
            {
              turnLeft();
              moveStop();
            }
          } else
          {
            moveForward();
            Serial.print("Forword");
          }
          distance = readPing();
          delay(50);
          DisObstacle = digitalRead(DisObstaclePin);
          delay(50);
        }if (power_status == 0) {
           Serial.print("POWER OFF");
        }
      }
      */

    }/* --(end main loop )-- */

    /*-----( Functions )-----*/
    void translateIR() // takes an action based on the IR code received
    {
      switch (results.value)
      {

        case 0xFF30CF: Serial.println("Movement-ON- 1");
          power_status = 1;
          break;
        case 0xFF18E7: Serial.println("Movement-OFF -2");
          power_status = 0;
          break;
        case 0xFF10EF: Serial.println("Fan-on-3");
          startFan();
          break;
        case 0xFF38C7: Serial.println("Fan-off-4");
          stopFan();
          break;
        default:
          Serial.println(" other button   ");
      }
      delay(500); // Do not get immediate repeat
    } //END translateIR

    int lookRight()
    {
      myservo.write(50);
      delay(500);
      int distance = readPing();
      delay(100);
      myservo.write(115);
      return distance;
    }

    int lookLeft()
    {
      myservo.write(170);
      delay(500);
      int distance = readPing();
      delay(100);
      myservo.write(115);
      return distance;
      delay(100);
    }

    int readPing() {
      delay(70);
      int cm = sonar.ping_cm();
      if (cm == 0)
      {
        cm = 250;
      }
      return cm;
    }

    void moveStop() {
      motor1.run(RELEASE);
      motor2.run(RELEASE);
      delay(100);
    }

    void moveForward() {

      if (!goesForward)
      {
        goesForward = true;
        motor1.run(FORWARD);
        motor2.run(FORWARD);

        motor1.setSpeed(100); //set the speed of the motors, between 0-255
        motor2.setSpeed(100);
        delay(100);
        motor1.setSpeed(55); //set the speed of the motors, between 0-255
        motor2.setSpeed(55);
      }
    }

    void moveBackward() {
      goesForward = false;
      motor1.run(BACKWARD);
      motor2.run(BACKWARD);

      motor1.setSpeed(100); //set the speed of the motors, between 0-255
      motor2.setSpeed(100);
      delay(500);
    }

    void turnRight() {
      motor1.run(FORWARD);
      motor2.run(BACKWARD);
      delay(300);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
    }

    void turnLeft() {
      motor1.run(BACKWARD);
      motor2.run(FORWARD);
      delay(300);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
    }

    void startFan() {
      motor3.setSpeed(150);
      motor3.run(FORWARD);
      Serial.println("FAN  start  ");
      delay(2000);

    }

    void stopFan() {
      motor3.run(RELEASE);
      Serial.println("FAN  stop  ");
      delay(2000);
    }

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

==============After change pin attachment =============================
I will change my code as follow and remove , 0,1 pin attachment sensor. Now code like below.

      #include <AFMotor.h>
    #include <NewPing.h>
    #include <Servo.h>

    #include <boarddefs.h>
    #include <IRremote.h>
    #include <IRremoteInt.h>
    #include <ir_Lego_PF_BitStreamEncoder.h>

    #define TRIG_PIN A4
    #define ECHO_PIN A5
    #define MAX_DISTANCE 200
    #define MAX_SPEED 75 // sets speed of DC  motors

    NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

    AF_DCMotor motor1(1, MOTOR12_1KHZ);
    AF_DCMotor motor3(2, MOTOR12_1KHZ);
    AF_DCMotor motor2(3, MOTOR12_1KHZ);

    Servo myservo;

    boolean goesForward = false;
    int distance = 100;
    int speedSet = 0;

    int DisObstaclePin = 2; // This is our input pin
    int DisObstacle = HIGH; // HIGH MEANS NO OBSTACLE

    int receiver = 13; // Signal Pin of IR receiver to Arduino Digital Pin 11
    //int power_on;
    int fan_status,power_on;

    IRrecv irrecv(receiver);           // create instance of 'irrecv'
    decode_results results; // create instance of 'decode_results'

    //----( SETUP: RUNS ONCE )----//
    void setup()
    {
      Serial.begin(9600);
      Serial.println("IR Receiver Button Decode");

      power_on = 1;
      fan_status = 0;

      pinMode(DisObstaclePin, INPUT);
      myservo.attach(9);
      myservo.write(115);
      delay(1000);

      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      DisObstacle = digitalRead(DisObstaclePin);
      delay(100);

      irrecv.enableIRIn(); // Start the receiver

    }

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

      Serial.println("Begin loop");
      delay(1000);
      if (irrecv.decode(&results)) // have we received an IR signal?
      {
        Serial.print("Start reciving");
        translateIR();
        irrecv.resume(); // receive the next value
      }

      //delay(2000);
      if (power_on == 1) {
        Serial.println("POWER ON");
        int distanceR = 0;
        int distanceL =  0;
        delay(40);
        if (distance <= 25 || DisObstacle == HIGH)
        {
          Serial.print("Turning");
          moveStop();
          delay(100);
          moveBackward();
          delay(300);
          moveStop();
          delay(200);
          distanceR = lookRight();
          delay(200);
          distanceL = lookLeft();
          delay(200);

          if (distanceR >= distanceL)
          {
            turnRight();
            moveStop();
          } else
          {
            turnLeft();
            moveStop();
          }
        } else
        {
          moveForward();
          Serial.print("Forword");
        }
        distance = readPing();
        delay(50);
        DisObstacle = digitalRead(DisObstaclePin);
        delay(50);
      }

      if (fan_status == 1) {
        startFan();
        delay(50);
      } else {
        stopFan();
        delay(50);
      }

     // irrecv.resume(); // receive the next value
    }/* --(end main loop )-- */

    /*-----( Functions )-----*/
    void translateIR() // takes action based on IR code received
    {
      switch (results.value)
      {
        case 0xFF30CF: Serial.println("Movement-ON- 1");
          //power_on = 1;
          break;
        case 0xFF18E7: Serial.println("Movement-OFF -2");
          //power_on = 0;
          break;
        case 0xFF10EF: Serial.println("Fan-on-3");
          fan_status = 1 ;
          break;
        case 0xFF38C7: Serial.println("Fan-off-4");
          fan_status = 0;
          break;
        default:
          Serial.println(" other button   ");
      }
      delay(500); // Do not get immediate repeat
    } //END translateIR

    int lookRight()
    {
      myservo.write(50);
      delay(500);
      int distance = readPing();
      delay(100);
      myservo.write(115);
      return distance;
    }

    int lookLeft()
    {
      myservo.write(170);
      delay(500);
      int distance = readPing();
      delay(100);
      myservo.write(115);
      return distance;
      delay(100);
    }

    int readPing() {
      delay(70);
      int cm = sonar.ping_cm();
      if (cm == 0)
      {
        cm = 250;
      }
      return cm;
    }

    void moveStop() {
      motor1.run(RELEASE);
      motor2.run(RELEASE);
      delay(100);
    }

    void moveForward() {
      if (!goesForward)
      {
        goesForward = true;
        motor1.run(FORWARD);
        motor2.run(FORWARD);

        motor1.setSpeed(100); //set the speed of the motors, between 0-255
        motor2.setSpeed(100);
        delay(100);
        motor1.setSpeed(55); //set the speed of the motors, between 0-255
        motor2.setSpeed(55);
      }
    }

    void moveBackward() {
      goesForward = false;
      motor1.run(BACKWARD);
      motor2.run(BACKWARD);

      motor1.setSpeed(100); //set the speed of the motors, between 0-255
      motor2.setSpeed(100);
      delay(500);
    }

    void turnRight() {
      motor1.run(FORWARD);
      motor2.run(BACKWARD);
      delay(300);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
    }

    void turnLeft() {
      motor1.run(BACKWARD);
      motor2.run(FORWARD);
      delay(300);
      motor1.run(FORWARD);
      motor2.run(FORWARD);
    }

    void startFan() {
      motor3.setSpeed(30);
      motor3.run(FORWARD);
      Serial.println("FAN start  ");
      delay(100);
    }

    void stopFan() {
      motor3.setSpeed(RELEASE);
      Serial.println("FAN  stop  ");
      delay(100);
    }

Now I notice the M1 motor is not working. My question is also same as this: [ Motor shield question][2] But I couldn't understand how to resolve it using my code. Other trouble I notice, a lot of the time the IR Receiver receives my signal. It executes without noticing a new signal. Sometimes it catches my signal.

  [1]: https://i.stack.imgur.com/1jZO4.png
  [2]: http://help.wickeddevice.com/t/motor-shield-question/87

body:
Based on this thread:

 - https://forums.adafruit.com/viewtopic.php?f=31&t=27069
 - https://stackoverflow.com/questions/18705363/arduino-uno-pwm-pins-conflict
 - http://forum.arduino.cc/index.php?topic=97133.0

Both AFmotor library and IRremote are using timer feature. And in addition, IRremote also use TIMER_RESET, which probably causing the motor not function as expected (on comment section)

So the solution available is :

 1. Use another library to drive motor, or you can make you own. See this [tutorial][1].
 2. Edit the library (IRremote or AFmotor) timer configuration (as you can found in the last post of the link I posted)

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


message:
AVR timer overflow interrupt not working

My problem is an interrupt service routine (ISR) that seemingly never executes! Here's some info on my set up: I am flashing an avr attiny85. I have the bare bones of a project set up so far with simply a main.c and two modules: timer and hardwareInit. In the timer module, I have a timer0_init function that I am using to set up timer0 for CTC mode to overflow ever 1 ms. Here is the function:

    void timer0_init( void )
    {
        cli();
        TCCR0B |= 3;    //clock select is divided by 64.
        TCCR0A |= 2;    //sets mode to CTC
        OCR0A = 0x7C;   //sets TOP to 124 so the timer will overflow every 1 ms.
        TIMSK |= 2;     //Enable overflow interrupt
        sei();          //enable global interrupts
    }

with the timer set up, I added an ISR to increment ticks every time the counter overflows, so I can keep track of how much time has elapsed, etc.

    ISR(TIMER0_OVF_vect)
    {
        cli();
        //ticks ++;
        PORTB |= ( 1 << PORTB0 );
        sei();
    }

as you can see, I commented out the ticks++ because it wasn't working, and replaced it with `PORTB |= ( 1 << PORTB0 );` which simply turns on an LED, so if the interrupt is ever executed, I will know by proof of the LED being on.
Unfortunately, I can't get it to turn on and can't see what I'm missing. (to prove that I 1. have the LED set up on the right pin, and 2. am manipulating the correct bit in the correct register, I put just this statement `PORTB |= ( 1 << PORTB0 );` in my infinite loop and confirmed the LED came on)

For further explanation, here is my main.c:

    /*================================= main.c =================================*/

    #define F_CPU   8000000UL

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <util/delay.h>

    #include "timer.h"
    #include "hardwareInit.h"

    int main(){

        //Initialize hardware HERE
        DDRB |= ( 1 << PORTB0 );    //set this pin as an output for an LED

        SetClockPrescale(1);    //internal clock divided by 1 = 8 MHz, from hardwareInit

        timer0_init();          //set up timer0 for 1 ms overflow

        while(1)
        {
            /* if( getTicks() > 0 )
            {
                PORTB |= ( 1 << PORTB0 );
                _delay_ms(1000);
                PORTB &= ~( 1 << PORTB0 );
                _delay_ms(1000);
            } */

        }
        return 0;
    }

So, what you see in the infinite loop is what I tried first, but after that didn't work, I tried something simpler, just having an empty loop (commented out previous stuff), and waiting for the interrupt to get triggered which would turn on the LED.

Any help you could give would be really appreciated. I'm quite puzzled why this hasn't been working.

body:
You are misunderstanding what an overflow interrupt is. That is called when the timer overflows (ie. it reaches TOP which in the case of an 8-bit timer is 255). Since you are counting to 124 that will never happen, and thus the interrupt will not fire.

You want the "compare A vector" which is called when the "A" register compares to the limit. Example code:

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

    void timer0_init( void )
    {
        TCCR0B = bit (CS01) | bit (CS00);    //clock select is divided by 64.
        TCCR0A = bit (WGM01);     //sets mode to CTC
        OCR0A = 0x7C;             //what to count to
        TIMSK = bit (OCIE0A);     //Enable compare match A interrupt
    }

    ISR(TIMER0_COMPA_vect)
    {
        PINB = bit (PINB0);   // toggle pin 5
    }

    int main(){

        DDRB |= bit (DDB0);    //set this pin as an output for an LED
        timer0_init();         //set up timer0 for 1 ms overflow
        sei ();                // allow interrupts
        while(true) { }        // forever
        return 0;
    }

I changed it to toggle pin 5 (which happens extremely quickly) so it will seem to be on but a bit dim. You can see on an oscilloscope or logic analyzer that it is toggling rapidly.

You don't need to turn interrupts off or on inside an ISR. You are better off using the bit names rather than "magic numbers" in your code, as my example shows.


message:
4 IR sensors on Arduino pro micro. 2 are working other aren't

#include <Keyboard.h>
    int IRpin = 5;
    int IRpin2 = 6;
    int IRpin3 = 8;
    int IRpin4 = 9;
    int led = 13;

    void setup() {
      Serial.begin(9600);
      //start the serial port
      Keyboard.begin();
      pinMode(led, OUTPUT);
      digitalWrite(led, LOW);
    }

    void loop() {
      float volts = analogRead(IRpin);
      Serial.println("volts1:");
      Serial.println(volts);
      delay(1000);
      if (volts>500.00){
        Keyboard.press(KEY_RIGHT_ARROW);
        Keyboard.releaseAll();
      }
      float voltss = analogRead(IRpin2);
      Serial.println("volts2:");
      Serial.println(voltss);
      delay(1000);
      if (voltss>600.00){
        Keyboard.press(KEY_LEFT_ARROW);
        Keyboard.releaseAll();
      }
      float voltsss = analogRead(IRpin3);
      Serial.println("volts3:");
      Serial.println(voltsss);
      delay(1000);
      if (voltsss > 500.00) {
        Keyboard.press(KEY_UP_ARROW);
        Keyboard.releaseAll();
      }
      float voltssss = analogRead(IRpin4);
      Serial.println("volts4:");
      Serial.println(voltssss);
      delay(500);
      if (voltssss > 600.00) {
        Keyboard.press(KEY_DOWN_ARROW);
        Keyboard.releaseAll();
      }
    }

I connected 4 IR infrared sensors to Pro micro and only 2 of them are working. The other 2 are sending random values.
Connection for all 4 IR sensors.:
IR VCC->Arduino VCC
IR GND -> Arduino GND
Output-> 5,6,8,9

body:
Pin 5 is not analog pins.

On the pro-micro only pins A0-5 and D4, D6, D8-10, D12 can convert an analog voltage to a value.

Just use the A0-5 pins instead, as that will work on any Arduino.


message:
Connection between ATTiny85 and RaspberryPi3 with nRF24L01+

I'm hoping someone can help me since I've been struggling with this all weekend. I've got 2 nRF24L01+ breakout cards and I'm trying to send data from a ATTiny85 to a Raspberry Pi 3.

My setup is (the attiny85 breadboard has a 3.3V power supply):

[![ATTiny85][1]][1]

[![RaspberryPi3][2]][2]

And the code I'm testing is for the ATTiny85:

    #define CE_PIN 3
    #define CSN_PIN 4

    #include "RF24.h"

    RF24 radio(CE_PIN, CSN_PIN);

    const byte addr[6] = "00001";
    int count = 0;

    void setup() {
      radio.begin();
      radio.openWritingPipe(addr);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();
    }

    void loop(void){
      radio.write( &count, sizeof(count) );
      count++;
      delay(1000);
    }

And for the Raspberry Pi 3:

    #include <cstdlib>
    #include <iostream>
    #include <sstream>
    #include <string>
    #include <unistd.h>
    #include <RF24/RF24.h>

    using namespace std;

    // Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 8Mhz
    RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

    // Radio pipe addresses for the 2 nodes to communicate.
    const uint8_t addr[6] = "00001";

    int main(int argc, char** argv){
      radio.begin();
      radio.setPALevel(RF24_PA_MIN);
      radio.openReadingPipe(1, addr);
      radio.startListening();

      // Dump the configuration of the rf unit for debugging
      radio.printDetails();

      int count = 0;

      while (1)
      {
        while ( radio.available() )
        {
          radio.read( &count, sizeof(count) );
          printf("Count: %d\n", count);
        }
        sleep(1);
      }

      return 0;
    }

  [1]: https://i.stack.imgur.com/zqUPP.png
  [2]: https://i.stack.imgur.com/qibQr.png

body:
As Mikael Patel pointed out, my MOSI and MISO pins were switched.

On the pinout for the ATtiny85, the MOSI and MISO pins are for when the chip is a slave (i.e. programming). DO and DI and used for output as SPI master.

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

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


message:
Same code in setup() and loop() give different results

As the answers to [this question][1] and [this one][2] state, `setup()` and `loop()` are identical in the way they execute code (apart from the obvious looping function of `loop()`).

However.

I get different results with following two pieces of code:
###Code run once, in `setup()`###

    /*
     * light_ws2812 library test
     */

    #include <WS2812.h>

    WS2812 LED(1); // 1 LED

    cRGB value;

    void setup() {
        LED.setOutput(13); // Digital Pin 13

        value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Yellow?
        LED.set_crgb_at(0, value); // Set value at LED found at index 0
        LED.sync(); // Sends the value to the LED
    }

    void loop() {
    }

###Code run once, in `loop()`###

    /*
     * light_ws2812 library test
     */

    #include <WS2812.h>

    WS2812 LED(1); // 1 LED

    cRGB value;

    bool hasBeenSet = false;

    void setup() {
     LED.setOutput(13); // Digital Pin 13
    }

    void loop() {
      if (hasBeenSet == false){
       value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Red
       LED.set_crgb_at(0, value); // Set value at LED found at index 0
       LED.sync(); // Sends the value to the LED
        hasBeenSet = true;
      }
    }

###The difference:###

The code run in `setup()` makes the LED _flash once_ with the desired color.

The code run in `loop()` makes the LED _stay lit_ with the desired color.

With the data being transmitted on pin 13, I can tell (because of the LED on there) in both cases data is being sent only once. With the `loop()` version I can even disconnect the data line after the color has been set, and it will stay lit.

I can only conclude the same code is executed differently in both cases.

Is there some sort of (soft) power reset after `setup()`? That could be a potential cause, as the color is stored in volatile memory on the WS2812B (if I'm not mistaken).

Link to the library used: [http://github.com/cpldcpu/light_ws2812][3]

  [1]: https://arduino.stackexchange.com/questions/4039/is-setup-and-loop-provided-for-convenience
  [2]: https://arduino.stackexchange.com/questions/142/code-for-one-time-execution-in-arduino
  [3]: http://github.com/cpldcpu/light_ws2812

body:
As you can see in the [source code][1] there is really nothing going on between the setup call and the first loop iteration.

If I'm not mistaken, this type of LED needs a frequent "update" on which color to display, at a precisely timed interval (I suppose this gets more important the more LEDs you have, since they are "addressed" bases on this signal timing.)

I think you really should keep calling `sync()` in the loop even if you are not actually changing the desired color, to keep "refreshing" the LED. This is just based of a quick analysis of the library code and examples though.

Why you get different results in the samples below could simply be due to the LED randomly "settling" in two different states when no longer getting data. The chst conversation seems to indicate there may have been other reasons as well.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino "source code"


body:
After [some discussion](http://chat.stackexchange.com/rooms/48846/discussion-between-nick-gammon-and-dajf) it turned out to be a hardware problem. For the sake of completeness I'll outline the suggestions I made.

* There was some initial confusion (see the edits) where the `hasBeenSet` flag was initialized the wrong way around.
* I could not reproduce the problem on my Uno and my WS2812 chip, so the issue was: what was different between his setup and mine?
* Possible wiring issue. Make sure +5V, Gnd and Din (data in) are wired correctly.
* Possibly faulty WS2812 chip - try with another one.
* Possibly faulty Arduino - try with another one.
* Possibly Arduino running at the wrong clock speed which would throw the timings out.
* Possible extra components (eg. capacitors) added to the circuit which were throwing timing out.
* Possible bug in the library. We eliminated that by trying with [my library for Neopixels](https://www.gammon.com.au/forum/?id=13357).

In the end DaJF reported that the problem was solved by using another (or no) breadboard. It seems the breadboard was introducing issues, maybe noise or bad connections.

We never really worked out why doing it in `loop` rather than `setup` made such a difference. I can only conclude that the slight timing difference compensated for the bad connections (or capacitance) on the breadboard.

I'm going to stick my neck out a bit and suggest that the capacitance in the breadboard was affecting the "shape" of the signal (we are talking about timings of around 350 ns here). Possibly if you measured with an oscilloscope you would see the problem.