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

Robotics Stackexchange is more suitable for questions like this.

PIDs are reasonably on-topic here. Is the question specifically about robotics?

How about telling us the value of gPwmCommand while running your code? There also a possibility that the error is not because of your code, but your electronics.

@NickGammon, I'm inclined to disagree that tuning a PID is on-topic here (but nevertheless won't vote to close as off-topic).  Also, I think PID expertise is stronger in R.S.E than here.

If the OP requests it, I will migrate to Robotics.

as @dpw says, It's possible that it's not actually the PID that is the problem, that's why I posted here. Either way i'm very happy with the answer son if you want to keep this on your(our) awesome site, i'd be glad to have it here!

You likely need to tune the limits the control applies before you can tune the PID.  I.e.: MAG_PROX_THRESHOLD_MIN/MAG_PROX_THRESHOLD_MAX and MAG_LIMIT_MIN/MAX.  If those aren't set correctly for your particular device & magnet, then the PID within those ranges might not help you.

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:

The time of the Analog to digital conversion at the input to the PID
The speed of the Arduino to process the code it runs
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.

Thanks for the clarification. I must admit that I could never totally get PIDs to work properly, particularly with the derivative part. Saying it is rarely used helps to concentrate on the more important parts.

this is a really nice, very extensive answer. I was thinking about that analog PID might be better aswell. My project is a reproduction of an existing project: https://forum.arduino.cc/index.php?topic=89241.0 so I don't think the design is the problem, it's probably something with my implementation. For example, how short long wires would start causing a problem?

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.

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.


text:
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!

Please be detailed on what kind of servo you use? Analog or digital servo?

Can you please be more specific! As @dpw asks, what type of servo is it? Do you have any web links to this servo? What have you tried so far? Please add links to the forums visited. What do you mean by "all of them just show how to make it run by changing the servo physically"?

As long as you use a continuous rotation servo, you can use the standard Servo library on Arduino: 0 will stop the servo, 90 will make it go full speed forward, -90 will make it go full speed backward.

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.

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.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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

Are there tutorials with the same board? Have you tried code that is verified to be working on other boards (from other tutorials)?

Based on the documentation :

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.

On the Arduino Get Started Page it says for the Arduino Micro in order to program it I need to select Arduino/Genuino UNO as my board thats why I added it at the end. My actual device is the Arduino Micro

Well, how about look at this "Get Started Page" instead : https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro go to Select your board parts, and have fun

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


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

1.) What Arduino do you use? Each Arduino can have different voltage regulator. 2.) Use another method to observe your Arduino. TX LED is blinking because of communication. It wont blink if there are no communication from Arduino. You can use LED_BUILTIN pin to observe it

https://www.youtube.com/watch?v=QyseW-sm6ig

that link for video is complete the same situation as mine. (that is not me on the video)
I used arduino uno. thanks :)

Try this, and tell if its blink or not when you used external power supply : https://www.arduino.cc/en/tutorial/blink

Thanks! It worked. LED blinks with 9V external power supply. hope that this would work with my program as well?

Hopefully yes, if there are no problem on electronics. Good luck on your competition!

Note that 9V batteries can't supply a lot of current.

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.

There is a possibility that you blew the regulator circuit with too much current while supplying your Vin pin with the 9V source. This would depend on your system power draw; something that you were using the board with before the blinker program - and also what kind of board you have.
To check this, try another similar board with the blinker program and the same 9V source. Don't forget to make the changes as suggested in the previous answer.
The other problem could be your power source: to check whether your power source supplies the desired volts, measure the power source terminal voltage while connected to the board. Most boards will have the minimum voltage requirement on Vin, depending on their regulator design.

A 9V battery can't supply enough current to blow up a regulator.

Would be interesting to know what facts you based that claim on. A 9v battery has enough juice to supply 0.5A for an hour so do the math. For the Uno's regulator 1A is enough, even if for a millisecond.

I think you are looking at the mAh rating, not the A. Duracell's 9V will drop to 5V after almost 2 hours at 250mA. You need at least 6-7V for the regulator.

Agreed, but the point is to damage the protection diode on the regulator you just need a transient high current.


text:
Can I avoid having a bootloader if I use ISP to flash to an arduino?
My Trinket Pro 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?

Please read the other question linked above.

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 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 for fuse calculations. Basically you need to toggle the BOOTRST fuse (the low-order bit of the High fuse).

Thanks!
On the arduino I have, a Trinket Pro, the bootloader is 4kb, which is one reason why I wanted to get rid of it.

The sd-card thing is funny, much like a game cartridge :)


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

How far have you got? Do you have the Attiny plugged in and ready to go? Are you able to find and run an example program which, say, prints something to the serial port, and run a terminal on the PC and view the output? That's how I'd start.

Which ATTiny? If you want to add USB, you'll likely drop in an usb-uart chip, like the CH340G or a FTDI chip. But UART may need a more accurate crystal. So you'll be wasting 2pins for the crystal and another 2 for the uart.. Which won't leave a lot for the rest.

You could try using an 32u4 which have built-in USB.

So far I have basically gotten no where. Mostly because I just don't know where to start. using serial im good to go. its the USB idea that has me stuck. Comments so far have given me some insight though.so there's a place to start looking.  What i have are some 84s and 45's that i wanted to use one or the other for this.. I assumed that i could load some kind of usb driver onto the chip to let me communicate with it directly.

How integrated do you want to make it. Do you need a USB driver at all? Could you use an FTDI adapter, treat it as a serial device and send text commands to it? Come up with a simple protocol, similar to AT commands for example?

@MarkSmith I was hoping to utilize USB drivers to have windows recognize it as a device. As st2000 suggested, An Adifruit Trinket as a fake USB Serial might be the answer. Im familiar with windows serial communication so that might just be better than re-inventing the wheel.

You may want to take a look at V-USB, a software-only USB Device library. It is used, among other projects, by USBasp, a very cheap ISP programmer.

Generally there are (or could be many) USB Devices and (only one controlling) USB Host.  The differences are discussed in this stackexchange.com question. 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.  The USB Serial Protocol (or CDC) 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 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 explains how you can also use this port to communicate with your sketch.

You didn't say what arduino you are using.  If this link helps, I can add it to the above answer to make it more specific.

sounds like I want some kind of usb device. Based on what you have said what I was hoping to do was turn something like an Attiny84 into a usb device. Then use custom win32 software to tell it to specify analog pin voltages to control MOSFET transistors.
It sounds like i might need a different MCU or to add an additional USB device chip.
Can you recommend any beginner articles on arduino usb device development ? a 32u4 was suggested. Ill do a little looking into that too.

I had a glance at the Trinket link you posted. At a glance it looks like it just may do everything i need it to for my project. Thank you for that suggestion. I am still curious about learning to make a USB Device if you have any suggestions there.

Sorry my turn around was so long.  Busy days.  I'll try and flesh out the answer.  As for USB, on stackexchange.com opinions are usually frowned upon.  Regardless, this is the book I use.

authors: Вячеслав Глушак


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

I'm voting to close this question as off-topic because you are asking a Java related question. At leat you should add an example about what you have tried to far.

Possible duplicate of Arduino Control over the internet

@Mattia JavaScript is not Java...

Perhaps a message brokering service like MQTT 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.

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.

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

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


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

Set Enable A; Enable B to LOW.

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


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

}

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.

That not correct for all Arduinos, some have multiple serial ports (Mega), but for the Uno (which it looks like this is) then its the right way of doing things.


text:
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!

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.

Thanks! But I'm not sure with the configuration of the function ''Stepper(steps, pin1, pin2, pin3, pin4)''. Which pin goes to Pul, Dir and Ena?

I have no idea what do you mean by Pul, Dir and Ena

I have not read deep into it , but It looks like this driver has logic attached to it. IT is really not a good driver to be used with you arduino since  it defeats the purpose to get the experience the programing the logic from the Arduino IDE.  Get a Darlington chip or just create your own with transistors and diodes.


text:
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?

I'm sorry but I can't see what this has to do with Arduino's so I have voted to close it.  To be honest if you have to ask what parts you need then maybe you should consider if it would be safe for you to build one.  Maybe you should look at kits to get more familiar with the subject.

Transmitter, battery charger, display, a smaller arduino that the UNO (e.g. Pro Mini), wire-connectors (especially for connecting to the battery).

This is not a practical approach.  If you want to experiment with applications such as FPV, you should be using on off-the-shelf flight stabilization computer and radio link, the engineering of both of which has moved far beyond Arduino experiments.  If your goal is instead to build the flight computer, for safety reasons you should be experimenting on a platform far smaller and lighter than one that can lift an Uno.  There was a point a few years ago when Arduino based flight computers almost made sense, but today they are so crude and limited compared to the options actually in use.

I wanted to create one from scratch

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.

A MEMS gyro is not enough. They drift over time (derivative), so you need an accelerometer, to know which way is down.

@Gerben - actually that is untrue.  The goal of the gyro is not to consistently orient the vehicle, but to slow its uncommanded rotation (or in this case multi-axis tumbling) to the point where a human pilot can achieve desired oritentation by command inputs based on visual observation.  Systems which also include accelerometers are more friendly to beginner pilots as they can also be self orienting, but that is only a feature that became common in the past few years.

I am using a display instead of goggles. The receiver kit comes with a transmitter and remote controller (a.k.a transmitter). The frame I was planning to use wood.


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

Windows wouldn't have reacted fast enough to shut it down itself.  The hardware driving the USB port will have overcurrent protection built in and would have shut down the port and notified the OS of this occurrence.  It might be possible to avoid having to restart the PC by disabling and re-enabling the USB system from the Windows Device Manager but since your keyboard and mouse probably are USB devices this might be tricky.

But that said, shorting out the USB host controller can cause damage to your motherboard.  If you are worried this might happen again, I'd suggest you run your arduino from a powered USB hub instead of directly from the PC, that way it won't risk maging the motherboard.

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.

I happened to do it again (shame on me), I noticed Win7 produced a background popup asking if that buggy device is disconnected with option to turn it on again. After that, another device such as mouse can be connected to it, but not Arduino until reset. So I guess it is a Windows feature.


text:
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!

Honestly? Find yourself a string of WS2812s and use that instead of trying to tear apart a conventional string of lights.

I have no idea what that is. I am trying to make my own string of lights using 5mm LEDs.

This is a string of WS2812s: https://www.amazon.com/Mokungit-WS2812B-WS2812-Integrated-Drivers/dp/B01EUAKLT0. You'll spend more time (your time = money) soldering together 5mm LEDs and getting them to be robust and not break than the cost of a pre-made string of LEDs would set you back. They are individually addressable, so you can command each one as you please. There also are dozens of tutorials on using these with Arduinos which you may find helpful.

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.

"in one of my homes" .... +1 for being subliminally ostentatious ;-)

( that I have previously lived in)FYI  +0  value added comment


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

Should be equivalent. See https://en.wikipedia.org/wiki/Copy_elision

I'm sure that wikipedia article was relevant to those in the know, however I don't understand a word of it. Do you have anything that simplifies rather than complicates?

Put out of your head the idea that the Arduino IDE has some special syntax. It's just C++ which is very widely covered on the Web in tutorials. See my post about How the IDE organizes things - there is some pre-processing of sketches before they go to the C++ compiler, but apart from that, whatever works in C++ works on the Arduino (exceptions excepted because they are disallowed by a compile-time option).

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.

Thanks, now I understand the copy_elision refernce. I guess it's just the syntax that seems less obvious than python, but partial knowledge is not always helpful. I might understand obj=MinLib(params) to be as you describe, with the leading MinLib taking the role of a cast, but that doesn't work for the first form. Could you link me to the simplest documentation that describes how storage in a class instance is organised. I expect header/public to be persistent attributes, and local on the stack, are header/private persistent by the instance? Can the class take variables like python?

@Neil_UK: I do not have such a reference, as I learned from a combination of books and online resources. public/private does not make a difference storage-wise, the whole object is stored as a single entity in static RAM (for a global or static local), on the heap (if you new it) or on the stack (for a non-static local). A member qualified as static in the class definition belongs to the class itself, not to any particular instance, and is stored in static RAM.


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

https://www.adafruit.com/product/2124 maybe?

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.

Im looking into that, but Im a newb when it comes to eagle cad

You can safely cut away the prototype area of the Feather 32U4. Though you'd also cut away the SPI, I2C, and UART pins. So unless your project isn't using any of those, this is not an option. (PS you could still get to SDA and SCL by soldering a wire to the vias)


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

What is your code supposed to mean?

Are you referring to the different colors of the letters? The syntax highlighter is made to highlight correct C code. Giving it invalid code will produce invalid highlighting. I wouldn't try to read too much into it.

Oh ok. I may have read into it too much

@EdgarBonet its a segment,  you give it forward(a||b) and motor a or b moves forward, or reverse, or brakes, or halts all, etc. It also was working(need more testing) I was just curious about the syntax highlighting which I noticed while I was writing it.

Please copy and paste your code, not a picture of it.  For help see Markdown help. You can format code by selecting the code and pressing Ctrl+K to have your browser do this for you.

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)

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

In WString.h is a define:
#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.

I was just showing the letters that do syntax highlighting.


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

so am using the recommended DDRD |= Bxxxxxx00 format when setting to 1 - how does that set anything to 1? Please post code that proves what you are saying. All this description stuff doesn't prove anything. Please post a Minimal, Complete, and Verifiable example

If your (unposted) code turns on Serial communication, the serial hardware takes over the functions of digital pins 0 and 1.

@NickGammon code posted.

The "Serial library" does nothing with the pins. The "Serial library" controls the UART peripheral which then controls the pins. When using the UART peripheral you have no control over the UART pins directly, and any use of DDR, PORT or DIN on those pins is essentially meaningless.

@Majenko I understood from the examples on the arduino.cc tutorials that it was possible to interfere with the UART's use of those pins, which is why I'm following the DDRD |= xxxxxx00 method of setting the high 6 pins' direction. Are you saying that that's not the case? I would have expected the first use of the Serial library to result in the 'capture' of those pins for the UART, which is why I'm questioning always reading both pins as input. Ultimately I have a method for using the D port and serial communication, I'm just trying to get my mental model to match documentation and HW.

Anything written on Arduino.cc should be taken with a shovel full of salt.

According to the ATmega328 datasheet, USART function seems independent of DDR of the TX and RX pins; that is probably what explains your observations.

I've just put a scope on the portD pin 1 Tx pin, with a weak pullup to 4v so I can tell the difference between driven and high Z. The pin stays low impedance, even when not transmitting, so it looks like the UART does retain the pin. The readback of 0 for the DDRD is therefore not reading what the output is doing. Section 19.6 of the AVR docs does say the TxDn pin is 'overridden' by the UART, rather than having to fight for it. I've just done the experiment where I stomp all over PORTD while using it for output. It still works, I'll post the results. Not tried input under those conditions

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

Yes, thanks. My issues were 'what does 'turn on the USART' mean?' so is it 'on' only when transmitting, or is it 'on' from the time Serial.begin() is called, and it looks like the latter. The second was the warning claptrap in the tutorials on arduino.cc that tell you how to not to mess with those pins. It turns out the hardware 'magic under the hood' is quite strong enough to avoid the need to tell noobs anything about the shared use of those pins, and let them write regardless, as they won't upset Serial, just won't be able to use those pins. I'll find my way round the docs soon. Thanks.

The stuff on the Arduino reference is addressed at beginners. If you read the datasheets you can do what you want. Once the USART is enabled it will continue to take over those pins until it is disabled. (ie. Serial.end()).

In the tutorial, I would have thought that 'port D bits 0 and 1 are don't care, you can do what you like with them but they don't connect to the hardware I/O after a Serial.bgin()' was more accurate, and more noob friendly, than 'dont drive them, because if you do you'll trash your serial comms, and here's a fiddly |= way to avoid that', which is unnecessary, alarmist and wrong. Of course the total noob will stay with digitalWrite(pin_no). I wonder if the tutorials can be corrected, Majenko doesn't appear to like them!


text:
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

With solder and wire to the pins that aren't used by the motor shield? To a prototyping shield between the Arduino and the motor shield? To another Arduino and link the two together through some serial protocol or other? There's millions of ways. You don't have to limit yourself to just sticking bits of LEGO® together. Get creative.

You could use the 6 analog pins, as those are accessible in the bottom-right corner (you can use analog pins just like a digital pin). Second option if to remove the headers from the shield, and replace them with stacking headers

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. They can even let you have a shield on top of your shield. This is the best choice in my opinion.


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

http://playground.arduino.cc/Main/AVR?

Well at least there is "AVR" in the heading. But not more... I know this site and I couldn't find what I search. I have shown an example. Where can I find something like this??

Read the whole thing, I think it might be pertinent. As they say, "Do not judge the book by its cover!".

https://www.arduino.cc/en/Reference/PortManipulation This is what I found (some time ago). But it seems that this is only relevant for the pins. I need "direct" access to the whole atmega not through c functions.

All the registers are given in great detail in the datasheet for the chip.

Chapter 36

Note that C functions already do access the "whole Atmega", you don't need assembly to do that. The only way to do what you want is to read the whole datasheet from the start and ensure you understand it (it may take several reads until you really udnerstand it, this is never an easy read for anyone). From the lack of details in your question, this is the only good advice you'll be able to get.

The Port Registers Arduino tutorial really shows you the most “direct” way to access the SFRs. If you write something like PORTB |= bit(PB5); and disassemble the resulting binary, you will see the compiler translates that statement into a single sbi machine instruction.

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

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!


text:
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 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?

Not all voltage regulators are the same. Some will only use a few micro-amps.

Thinking out of the box... Won't a standard timer-switch suffice?

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.

The P-fet gate probably should be pulled up to +12 through something like a 1 megohm resistor; else it would be effectively open when  the INT/SQW pin is off, and could float to arbitrary levels

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

I have an ATmega48 (very similar to the 328P) running off a couple of AA cells since June 2012. It's awake for a little more than 4 minutes per day, sleeping the rest of the time. Not changed the batteries so far.

That's an impressive run-time - thanks for the additional data point, @EdgarBonet! I expected a sleeping Arduino and an Alkaline battery pack could be a "set-it-and-forget-it" system but without calculating out the energy consumption, I didn't guess it would perform that well. So, @DirkPitt, there's some real-world support data.

It's not a full Arduino: I could not manage to get below ~ 40 mA with my Uno, whereas the bare ATmega in SLEEP_MODE_PWR_SAVE, with only the async timer active, took something like 2 µA.

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

This is more of a comment.  If you want to leave it as an answer, please add further explanation of your solution.

you can use a timer switch. you can buy it from ebay for around 5 euros. i am using this one
https://www.ebay.com/itm/CN101-DC-12V-16A-Digital-LCD-Power-Programmable-Timer-Time-Relay-Switch-New/401190616827?hash=item5d68d2fefb:g:K3sAAOSwNRdX3ggT
i have also tried ds3231 but the arduino is on standby mode and it consume energy. this is the best solution i found

authors: يوسف الشراري

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


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

You mean like running a HTTP server on it like the examples show?

I'm sorry, but which examples are you referencing? I don't quite understand, but appreciate your efforts.

I would expect it could be hypertext transfer protocol, but don't quite understand. Are you referencing the operations I mentioned? If that is the case, sure. It could be readily converted for my purpose into the data I would need.

The library for the chip you're using likely come with some examples.

Sounds quite promising. What would it be called on the UNO R3 or the MKR1000? I have others as well, but are they on these boards and what are they called?

Other than the ones that come with the Wifi101 library?

There is no requirement that your data pass to an external "cloud" server - it could go directly from the network-equipped Arduino to your PC.  However, if your PC will not be always on, then you will either need to hold the data in the Arduino until you can query it, or come up with some small power-efficient local server to collect and store it, perhaps based on a raspberry pi or by extending an OpenWrt-style router linux install, on any of a router chipset used for custom purpose, a Yun-stype device (which is just an Arduino-sized version of that) or else on your router itself.

In my own crude way, that is a major part of what I was trying to explain.I will have other requirements:

I am really flexible on this, and open to any suggestions. I have worked with computers a long while, but "this" is new and different to me.

I know this sounds silly, but how about ESP8266?

dhimaspw, I have done some checking, and the ESP8266 may work very well. I will need something with a dependable wireless range of approx 60 meters. Are you familiar enough with the devices to know if this will work? The information I will be gathering won't change so quickly that it needs to be sent several times a minute, but perhaps every half hour. I might even be able to connect a chip to the sensor array to record the data, and then do a manual call the recorded data? Thanks for your interest and suggestion. Also, I have a few of the larger ESP8266 boards.

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

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

Mosquitto is free, and it's available for PC, Mac and Linux here.
You have free clients for Android, iPhone, Windows, Mac, and Chrome. I'm using MQTT Dash.
MQTT is lightweight, easy, multiplatform, multiclient, and the best part of it: minimal programming.

You have a small misspell in the picture. It should probably be "Local Area Network" not "Local Arena Network".

@Avamander. Right, it's Local Area Network.

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.


text:
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);
}

Try reducing the SPI clock and/or increasing the micro seconds delay in transferAndWait (10 us is not very much).

Thanks for responding, but no dice, halved the speed of the spi bus and doubled the delay, same results, 97%ish success with the occasional ovf

Why "float tiempo"? Why not "unsigned long"?

Good catch, fixed

Might need to mention that the Arduino millis() ISR/Timer is not accurate. It is a bit slow and will actually to a double increment from time to time.

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.

Getting closer but no dice, see photo


text:
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?
#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);
}

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

You use L293D motor shield, but using AFmotor (Adafruit driver motor) libs, which is odd. Posting Schematics would help.

Don't cross post on other SE sites.

@gre_gor Thank ,I removed it. but I still not received any considerable answer.

After reading @dpw's post can you confirm the version of the AdaFruit motor shield you are using?  And the version of AFMotor library that you are using?  v1 and v2 are not cross compatible.

@Matt I check the library content as A4990MotorShild , but AFMotor I couldn't find any version number. And also , I check code without IR RECEIVER all Motors are working fine.

You are using the I2C pins for the ultrasonic sensor(?) would changing them to A0 & A1 be possible.  (Its unlikely to be the problem, but...)

@Matt yes ,i used ultrasonic sensor and I will change and come with comment.

I haven't seen error on your code, what is the output of serial monitor from your edited code? After a bit browsing, perhaps the problem lies with the "irrecv.recume()"

@dpw ,sir now my trouble motor-shield not running(power) M1 motor after , i put IR Receive. When come to the loop it ,only run one motor.With out IR Receiver every thing working perfectly. my question also same as this http://help.wickeddevice.com/t/motor-shield-question/87 but ,I haven't use this kind of library. so , i didn't understand what should i do.

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 :

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