Problem with programming an ATtiny85: Error - avrdude: Yikes! Invalid device signature I'm trying to program an Attiny85 chip using an Arduino Uno as an ISP following this two tutorials: Instructables: Program an ATtiny With Arduino and Programming an ATtiny w/ Arduino 1.6 (or 1.0) but every time I try to upload the sketch I get this error message:

     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

I have tried different Arduino boards/changing port and different ATtiny chips but the results are all the same. I have also checked the wiring multiple times and it seems to be correct.

This is the full error message (on verbose mode):

     avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM7
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATtiny85
     Chip Erase delay              : 400000 us
     PAGEL                         : P00
     BS2                           : P00
     RESET disposition             : possible i/o
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
       flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          2    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

     avrdude: AVR device initialized and ready to accept instructions

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000 (retrying)

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000 (retrying)

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

     avrdude done.  Thank you.

Try connecting the RESET pin of the Attiny85 to GND the second before you hit "program".

In my experience, the Arduino does not always send the RESET signal when it should (or on the pin that you think it would send it).

In these cases, manually resetting the Attiny by connecting the RESET pin to ground makes it programmable.

You can keep RESET low during the whole programming process, but if you keep it low for many minutes before programming the chip, it might not always work. In those cases, set RESET high for a moment before setting it back low, and the Attiny should be good for another round of programming.

And of course, when you want the Attiny to start doing what you have programmed it to do, you have to pull RESET high again.

This error (in particular the 0x000000) usually, but not always, means that the ATtiny has the fuses set for an external oscillation, but there is no functioning oscillator:

avrdude: Device signature = 0x000000

You probably need to add an external oscillator, i.e. a 16 MHz crystal, and a couple of 22 pF ceramic capacitors:

However, as this Engbedded Atmel AVR® Fuse Calculator shows, there are a number of permutations that could be set:

So, instead of using a crystal, you may need to provide an external clock:

These schematics come from What's the schematic to share one crystal with two micros?


USB Serial port not recognized Have both an Arduino Uno R3 and a Blend Micro that I have used to prototype a number of projects. Just got a new MacBook Pro and cannot get it to recognize the boards through the USB serial port.

I am using the same USB cable as before so I know it is not power only.

Have tried both USB ports. Have also tried them with other devices, so I know they work.

I have tried installing both the FTDI and CH34x drivers (both the older and the new signed one).

Don't know what to try next... any help?

I have an Arduino Uno which works on my Mac running 10.11.3 this uses the Serial Port /dev/cu.usbmodemFA131.

It is 18 months since I installed this (on a previous OS) and I can't recall whether I had to install a driver

ioreg -p IOUSB shows this as

  | | +-o IOUSBHostDevice@fa130000  <class AppleUSBDevice, id 0x100000955, registered, matched, active, busy 0 (40 ms), retain 13>

system_profiler SPUSBDataType shows this as:-
            Communication Device:

          Product ID: 0x0043
          Vendor ID: 0x2341
          Version: 0.01
          Serial Number: 5543434373335120A2B0
          Speed: Up to 12 Mb/sec
          Manufacturer: Arduino (www.arduino.cc)
          Location ID: 0xfa130000 / 3
          Current Available (mA): 1000
          Current Required (mA): 100
          Extra Operating Current (mA): 0

OK, sorry, my bad... it was a bad USB cable... two of them actually, that had both worked previously. What are the chances?


Multiple .ino files in the same sketch Yeah yeah, I know people ask this type of thing a lot, but I couldn't find an answer anywhere.

I understand that you can have multiple .ino files in one sketch, but I don't just want functions and variables separated, I want functionality.

I am writing a Braille program for the NodeMCU -- It takes a message from a served website and moves servos to emulate the appropriate Braille. I want to have 2 files: one to serve the website and get input from it (website.ino), and the other one to manipulate the servos(braille.ino). The only problem is, I can't figure out where to declare/attach the servos.

I plan to have a list of servos in braille.ino that will be looped over with each servo being set to a different value. If I declare them  in website.ino (my "main" file, ie, with a setup and loop), I will have to pass them to my braille function every time. On the other hand, if I choose to declare them as globals in my braille.ino, where would I attach them? Can I have another setup in braille.ino?

What isn't obvious is that with Arduino, you can have normal C and C++ files in the same directory as the .ino file. These can have functions and variables inside them, and Arduino will link them into the main program too. You only need one .ino file - all the rest can be in modules with a .c or .cpp (for C++) extension.

That way, you can group "helper" functions in different files by category - for example, a BrailleServo.c file. These contain the functions and variables for just that category.

If you haven't programmed native C/C++:

Put the functions and variables in the BrailleServo.c file, and then repeat the functions' header in the BrailleServo.h file.
Inside the BrailleServo.c file, at the top, put the following line:

#include "BrailleServo.h"

Note the quotes (" "), not angle brackets (< >)
Inside the .ino file, put the same #include line. That tells the module that "there are other functions elsewhere, and these are their definitions".

The only problem? Getting the silly Arduino environment to let you add .c and .h files to that directory. You could just use Notepad, but there's a trick (if you're using Windows):

Choose File|Open…
Right-click the pane with the files in it, and choose New >|Text Document
Give it a complete name, and make sure you replace the .txt part of the name too with .c or .h. You may get the "If you change the extension, the file may be unusable" warning - just click OK.
Select the new (blank) file in the file pane, and a new tab will appear.

  Note that 3. above assumes that you've told Windows File Explorer to NOT hide the extensions of known file types. I always do that - if you haven't, you'll need to. With:

  Windows 10:
  In any folder's View tab, tick the File name extensions checkbox;
  Windows 7:
  In Control Panel | Appearance and Personalization | Folder Options' View tab, untick Hide extensions for known file types

Here are three examples:

BrailleServo.h

//
// BrailleServo.h
//

// Call this function once in setup()
void BrailleInit();

// This function activates the six servos to form the passed-in pattern.
void BrailleShow(byte pattern);

BrailleServo.c

//
// BrailleServo.c
//

#include "BrailleServo.h"

// The number of servos
const byte NumServos = 6;

// These are the pins for the six servos
const byte servo[NumServos] = { 3, 4, 6, 7, 9, 10 };

// This initialises the six servos
void BrailleInit() {
   for (byte i=0; i<NumServos; ++i) {
      pinMode(servo[i], OUTPUT);
      // Do what else you need to do with servo[i]
   } // for
} // BrailleInit()

// This is how to use the six servos to form the passed-in pattern
void BrailleShow(byte pattern) {
   // … Complicated code here …
} // BrailleShow(pattern)

Main.ino

//
// Main.ino
//

#include "BrailleServo.h"

void setup() {
   BrailleInit();
   // Other stuff
} // setup()

void loop() {
   BrailleShow('A');
   delay(1000);
   BrailleShow('B');
   delay(1000);
} // loop()

Incidentally, for ideas you may want to check out my answer to a more generic Braille question.

I wanted the same and my solution was to use MS Visual Studio with Arduino IDE from Visual Micro.
It makes using multiple files easy and has lots of additional advantages.


Use doorbell output (12VDC) to power arduino? Not sure if this is possible, but could I use my existing doorbell setup to power an Arduino? I'd also like to preserve the existing chime's functionality either through the existing button or triggering it through the arduino.

My doorbell chime is made by Nicor and its input is 120VAC, but outputs 12VDC. This seems to be a very unconventional setup, but I've confirmed its output with a multimeter (it's also printed on the chime itself). The chime is very similar to this: http://www.amazon.com/Nicor-18888-Door-Chimes/dp/B006T38PTU (only difference I can see is the output). The 12V line runs to my front door where it's connected to a light up button. Here is a picture of the button's circuitry: http://imgur.com/IjA50rT

What I'd like to do is use the chime's 12VDC output to power the arduino so I don't have to rely on another power source or batteries. I will be adding smart features to the doorbell via the arduino, but my main hangup is getting power to the arduino. I've tried connecting the doorbell wires to VIN and ground, which successfully powers on the Arduino, but it also triggers the chime. It appears closing the circuit triggers the chime to play.

Is this possible to do?

This seemingly simple task is actually quite complicated; a good challenge that's not impossible or easy to overcome.

The AC/DC transformer in your link only provides "12VDC/6mA"; not enough to run the Arduino, chime, and button LED; so it likely needs upgraded to something beefier; you can't have too many amps on such a transformer.

Then there's your chime, which could use a lot of current (buzzer/bell) or a little bit (speaker-based chime tones). If it uses a lot, you should replace it to simplify the other connections. Remember that power goes through the chime to get to the button; otherwise the circuit would be incomplete and the ringer's LED would be dark.

The chime is activated by the resistance of the button lowering itself to the point where the chime gets enough power, no longer being current-limited by the diode, 2.2k resistor, and small LED. Very simple design, but not ideal for easily intercepting.

So what's the easiest way to accomplish your task?

Looking at it closely, it seems the basic circuit is there for you already; you have a power-consuming node on the network in the form of the button's LED.

You need to replace/augment the LED on the ringer with the Arduino. The 2.2k R19 could/should be replaced with the Arduino as well; just make sure your LED isn't over-drawn when the Arduino is chugging at full-steam, and add additional inline resistance as needed to keep it safe.

The other problem is powering the MCU while ringing. You'll notice the LED goes out while ringing. While that's nice feedback to the user, it's not because the circuit designers were UX-focused, it's because the chime's simple circuit  pulls all the current out from under the LED, just as it will an MCU in the same slot.

You can get around this using a super capacitor. I would use an LM7805 in front of the Uno to deliver VIN +5 V instead of 12 V. Then you can "short" the Uno's GND to VIN with a 1 F 5.5 V capacitor ("F", NOT "uF"). Those caps are (amazingly) available for just a few dollars on eBay.

So, at the end of the day, you basically just need to "upgrade the LED" and maybe upgrade the transformer. You could also re-create the switching pattern on your ringer with diodes if you're handy with circuit design, but if i were you, i would just "bodge" a few wires onto the existing PCB, and possibly alter that resistor.

Good luck; sounds like a fun project and a good challenge.

EDIT:
I realized you might not need any circuit mods at all; a hall-effect current sensor anywhere the line, or just paralleling the chime terminals with a voltage-divider input to the Uno might suffice, if you didn't need the MCU physically at the button. Heck, a microphone sensor taped inside the chime could accomplish the task of detecting doorbell rings...

You must connect the arduino vin pin to the doorbell 12vdc and it should work.
Edit:
Now I understood the chimes out, that is connected to relay coil driven by the button. If the relay is mechanic you can play with delay times and use pwm to drive your arduino without turning on the chime. The system I have described is used in NEST thermostat, that self powers with heater relay wires.


Getting inverse values of acceleration and tilt for the MPU 6050 I'm using the I2C library to connect to a GY-521 board and, when executing the getAcceleration() methods I get gyro values and viceversa..

This is my setup (I'm using a proto shield but that shouldn't change anything as far as I understand):

It follows this schematic:

And this is the code I'm testing:

#include "Wire.h"

#include "MPU6050.h"

MPU6050 accel;

int16_t ax, ay, az;

void setup() {
    Wire.begin();
    Serial.begin(9600);
    Serial.println("Initializing I2C devices...");
    accel.initialize();
    Serial.println("Testing device connections...");
    Serial.println(accel.testConnection() ? "Connected" : "Connection failed");
}

void loop() {
    accel.getAcceleration(&ax, &ay, &az);
    Serial.print("acc x:    ");
    Serial.println(ax);  // This prints the gyro value of the Y axis!
    delay(1000);
}

I don't think it has to do with the wiring since inverting the 4 and 5 analog pins yields zero values.

Is this a problem with the library? Or with my chip?

There are a lot of libraries, I wouldn't use the accelerometer library in wire, download and add the I2Cdev library, you can get it on a variety of different sites like github.com


8relay module asks more than specs I have a 8 relay module that should use not more than 20 mA per relay.
Altough when measuring it asks around 70.
If I use 6 relays, that would be more than an Arduino Mega can give.
(I already lost 1 arduino here.)

How this is possible..?

Most of Arduino relay modules have a relay and a supporting circuit. The circuit connects the VCC line to relay coil if signal line is HIGH. Some relays have it conversely, they disconnect if signal is HIGH and hold the coil if signal is LOW.

Your relays need VCC which you can supply for 8 relays from 5 V pin of Arduino. This pin is connected over regulator to power supply of the board so it is limited only by power supply and regulator parameters. The power doesn't go over MCU.

The signal pins of individual relays should be connected to digital pins of Arduino. The signal pins don't draw much current since they only signal a state to the circuit of the relay module.

it is solved by giving the relay module power with external transfo. Not by arduino


Serial.begin(): Why not always use 28800? In a lot of the sample code online people add the line Serial.begin(9600) in the setup block.

When I look up what Serial.begin() is on the official documentation, it says that it controls the bit per second data transfer.

So the obvious question is, why not use 28800, the highest transfer rate? Why do people settle for 9600? What is the limitation here?

Why do people settle?

People settle because it is more than fast enough.  The most common use is just to print some stuff on a terminal for debuggin.  9600 baud is 960 characters per second, or 12 x 80 character lines per second.  How fast can you read? :)

If your program is using the serial port for bulk data transfer, you would choose not to settle.

  What is the limitation...

The limits on serial are high.  Directly you can use 115200 baud in your programs and it will just work.  The Arduino terminal will allow a max of 115200, but other programs such as RealTerm would let you run higher.

Hardware serial will run to 1 M baud.  If you read around you will see people have used up to 1 M by directly controlling the UART.  You might get benefit of high baud rates for uses such as transmitting via a bluetooth chip.  If you are using the hardware serial interface to exchange from chip to chip with just a short distance, then 1 M baud is completely feasible.  Think of all the SPI and I2C devices that operate just fine at 1 MHz clock rate.

Over larger distances, you will start to have problems with noise when using logic level (plain 0 to 5V) signalling.  To use larger distances, you would add a transceiver to provide robust signalling, commonly RS-232 and less commonly RS-485.  With RS-232 you could run a mega bit at distances of 10's of feet.

The microprocessor clock speed will be the real limit.  With a hardware UART, the processor must load one byte to the UART every 10 bits (for N81).  So when you get to 1 M baud it will be a challenge for the 16 MHz processor to keep the UART supplied with data.  A new byte will be sent every 160 clock ticks, which is very few lines of code.  For a short burst of data, you might achieve that rate.  The message is, the processor will run out of speed before the UART is the limit.

Note, this all applies to HardwareSerial, software serial is very different.

Human Reaction Time

Because being able to stop the serial monitor when your Arduino is thrashing on the port is required by users 100% of the time, and having the maximum transfer speed is required less than 100% of the time.

9600 baud is a compromise between "easy to kill a runaway process" and "annoyingly slow".


ESP8266 EEPROM seems not working, saved data are different when I try to read them I'm working on project which require to save some data into the EEPROM.
As I read online the ESP8266 has no real EEPROM, it use a section of FLASH just after the SPIFFS. Due to this read/write is quite different from standard Arduino, you need to call EEPROM.commit(). You also have to call EEPROM.begin(size) (I used size = 512) before start to use it.

I follow different tutorials online and I made some tests but it seems not working at all. When I try to save a value and then read it, values are different. I tried with

EEPROM.write(..)
...
EEPROM.read(..)

and with

EEPROM.put(..)
...
EEPROM.get(..)

but nothing change.

Is there any configuration on the board I need to set into Arduino IDE/Board Configuration?

EDIT: here's the code

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

    EEPROM.begin(512);
    EEPROM.write(0, 62);
    EEPROM.write(10, 103);
    //EEPROM.commit();
    EEPROM.end();
    Serial.print("Read at 0:"); Serial.println(EEPROM.read(0), DEC);
    Serial.print("Read at 10:"); Serial.println(EEPROM.read(10), DEC);
}

I always read 0 in the output.

You can read the emulated EEPROM only between begin and end. It works with memory image.

begin allocates the in-memory image.
commit writes it to flash.
end commits and deletes the memory image.

Here is some ESP8266 example code to store and read strings from EEPROM data:

#include <EEPROM.h>

void writeString(char add,String data);
String read_String(char add);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  EEPROM.begin(512);  // Note::

  String data = "Hello World";

  Serial.print("Writing Data:");
  Serial.println(data);

  writeString(10, data);  //Address 10 and String type data
  delay(10);
}

void loop() {
  // put your main code here, to run repeatedly:
  String recivedData;
  recivedData = read_String(10);
  Serial.print("Read Data:");
  Serial.println(recivedData);
  delay(1000);
}

void writeString(char add,String data)
{
  int _size = data.length();
  int i;
  for(i=0;i<_size;i++)
  {
    EEPROM.write(add+i,data[i]);
  }
  EEPROM.write(add+_size,'\0');   //Add termination null character for String Data
}

String read_String(char add)
{
  int i;
  char data[100]; //Max 100 Bytes
  int len=0;
  unsigned char k;
  k=EEPROM.read(add);
  while(k != '\0' && len<500)   //Read until null character
  {
    k=EEPROM.read(add+len);
    data[len]=k;
    len++;
  }
  data[len]='\0';
  return String(data);
}


Where are the Arduino Due registers? Having most of my experience on ATmega chips, and just starting up with Arduino (to reduce hardware development time) I'm happy to see that the usual registers such as TIMSK0, PCICR, TCNT1H and others can be used from the Arduino IDE just as they appear in the Atmel datasheet.

Migrating to the Arduino Due, however, came with a shock: the registers specified in the datasheet of the Cortex-M3 are not recognized by the Arduino IDE (although I downloaded the extension necessary for being able to select the Due). I wanted to do something very simple, like configuring a timer. I found TC_CMR0 in the datasheet, but the Arduino IDE doesn't recognize it. I found an example using the Arduino Due with timers in an obscure forum, and they used REG_PWM_CMR0. I tried it in the Arduino IDE, and it was accepted by the compiler.

I searched the Arduino and other forums, and couldn't find any hint whatsoever about the naming of the registers. Why are the names of the registers different? And can I find a conclusive documentation about the register names, or am I doomed to research each and every one of the hundreds of registers individually?

There are a few files in the Arduino Due core that you should have a look at. They give great insight into the SAM register set up; variant.h, variant.cpp and chip.h

After that you can dive into the libsam and the many components (include/source).

The SAM code has a very different structure and style compared to AVR.

Cheers!

The Arduino Due files you are after are located here on a Windows PC:

 C:\Users\name\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\component


Using Arduino as Keylogger Is it possible to use arduino uno r3 as USB keylogger by connecting the usb male pin to CPU and keybord cable to female USB pin of arduino.
So that the keystrokes are stored in EEPROM. Without using an external storage modules or other components?

I am new to arduino, even suggestions are appreciated.

Thanks in advance.

USB-host is hard if not impossible to implement on an UNO.

Though I believe most USB keyboards support PS2 as well (normally done with a USB-to-PS2 plug). So you should be able to talk to the keyboard using the PS2 protocol, which is a lot easier. There are libraries to do this for you.

Next you could use V-USB to emulate a keyboard to the PC. For that USB connection you need to add some resistors and zener diodes, to stay withing the usb specification. This is all explained on the V-USB website.

Using a different Arduino that has real USB support might be a better option. Also the UNO is rather large, so not that easy to hide.

No, it's not. Or not with any degree of ease. The best you could hope for would be to intercept the USB data and try and decode it, but that really is beyond the ability of a lowly Arduino.

I have thousands of dollars worth of equipment aimed at doing that kind of thing - it's not a simple task.


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

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.


Button to not run script I'm looking to have a button that, when pressed down, will mean that the script loaded on the Arduino doesn't run. So far I have:

void setup() {
  pinMode(3, INPUT_PULLUP);
  if (digitalRead(3) == LOW) {
    while(1);
  }
  // Beginning the Keyboard stream
  Keyboard.begin();
  // then the rest of the code.

I have a push button soldered to the ground and 3 pin. Could you see what is wrong with the code?

I would do it this way:

void setup () {
    pinMode(3, INPUT_PULLUP);
}
void loop () {
    while (digitalRead(3)==LOW) {}; //do nothing, wait for release button
    // do all my stuff
}

or even better I would use some LED to indicate, that the button is pressed (or released) to have some visual state indicator (or another stuff to do while the button is pressed

void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    while (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       };
    digitalWrite(13,LOW);
    // do all my stuff
}

eventually

void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    if (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       while (digitalRead(3)==LOW) {
          // do some other stuff
       };
    digitalWrite(13,LOW); // switch indicator off
    // do my regular stuff
}

You need to move the code that checks the button into loop(). Put the code that you want to pause in the if block.

void loop() {
    // Only execute if not pressed
    if (digitalRead(3) != LOW) {
        // Do stuff
    }
}


"variable does not name a type Hey guys I'm getting an error that is im pretty sure to do with how i am initializing my variables. It is:
exit status 1
'threshold' does not name a type

Here's my code:

//Global Variables for moving max:

int analogValues[100];
int ir=0;
int maxA0=0;
int threshold = 0;
//Global variables for moving max ^^

//Global Variables for moving average ECG:
const int no_averages = 2;

unsigned long time = 0, peak1 = 0, peak2 = 0;
int binaryrange, bpm, i=0; //not sure what i does tbh
int readings[no_averages]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average which we will display as ECG

void setup() {
// initialize serial communication with computer:
Serial.begin(115200);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < no_averages; thisReading++) {
readings[thisReading] = 0;
}

//set moving max shit to zero
  for (int is = 0; is < 100; is++) {
analogValues[is]=0;
  }
}

void loop() {
  //int maxA0=0; //Whether I intitate the variables here or globally, same error
  //int threshold = 0;
time = millis();

average=0;
readings[readIndex] = analogRead(A0);
readIndex++;
for (int ir=0; ir < no_averages; ir++) {
  average = average + readings[ir];
}
if (readIndex >= no_averages) {    // ...wrap around to the beginning of array if it has hit the end:
readIndex = 0;
}
average = average/no_averages;
if (average>1000) {
  average = 600;
}
Serial.print(average);

analogValues[ir]=average;
ir++;
if (ir>=100) {
  ir=0; } //This is to roll back to the start of the array if it surpasses the 100th array spot
for (int is = 0; is < 100; is++) {
 if (analogValues[is]>analogValues[is-1])
 analogValues[is]=maxA0;
  }
}

//**************************

//This line with error:

threshold=maxA0-40;

//**************************

if (average<threshold){
  binaryrange=0; }
if (average>threshold && binaryrange==0){
  peak1=peak2;
  peak2=time;
  bpm=60000/(peak2-peak1);
  binaryrange=1;
  }
   Serial.print(" ");
  Serial.println(bpm);
//BPM code ^^

delay(8); // delay in between reads for stability
i++;
}

THANKS!

"The line with the error" falls outside of any functions. In C and C++ we write executable code inside functions. You placed your

threshold=maxA0-40;

(and everything that follows) outside of any functions. Hence the error.

Errors like this are typically cased by improper placement of { and } braces. But this is something you have learn to check for yourself. Most C or C++ oriented code editors can usually help you with this. And proper code formatting can help you with this too. What you have now is such a mess, that a simple error is virtually impossible to see.


Is there something like a Virtual Environment for Arduino? I'm using Arduino IDE for a variety of projects.
The libraries and boards used in different projects are different and I would like to have a customized environment for each project.
Eg: In a project involving an Arduino, I don't want all the ESP boards or Adafruit libraries that I might use on another project.
Python has something called Virtual Environments, where you can switch between environments and have a different setup of libraries and configurations for each project.
Is there something like this I can configure for Arduino?

Sorry, but in Arduino IDE no such functionality as virtual enviroment. To add your own version of libraries to each projects you may only add it (libraries) directly to a project dir.


Bare Metal Programming of Due I don't know much about Arduino but I am interested in buying a Due 32bit board. I was wondering if you can program it bare-metal and if this requires a separate debugger or not?
Thanks

In my understanding all ic in general can be hardwired but at a cost which is that some greater expense is incured say time or additional accessories also the datasheet and instruction set are a big must


Arduino Micro just blinks, won't connect to PC Edit - Sorry it's a Micro not a Nano

I have a Micro board hooked up to an EasyDriver breakout using its 5V output to power the Micro.

Today I plugged it in and instead of booting up like normal the power LEDs on the wall plug, the easy driver, and the Arduino started flashing. The Micro became very hot, but not hot enough to burn.

After that if I plug the Micro into the USB port it just rapidly blinks the pin 13 LED. The PC does not detect the device but it does receive power.

Holding or pushing the reset button doesn't seem to help at all. I've used different USB cables, and different ports on the PC as well to no effect.

Is this something it can recover from? Why did all the LEDs blink like that?

I have something similar happen a couple of times with some atmega328s (on arduino unos). I believe it was the bootloader that some how became corrupted and so no longer responded to the computer. The only way to fix this is to reflash the bootloader using an ISP programmer. Luckily the arduino can act as an ISP programmer so all you need is another working arduino.

See https://www.arduino.cc/en/Tutorial/ArduinoISP for how to do this on an uno. The same can be done with the micro/nano as they all use the same atmega328p chip its just a matter of wiring it up correctly.

If you cannot reflash the bootloader with this method then one of the chips is probably damaged and would need to be replaced. At this point it might be easier to replace the whole board.

I faced the same problem with my Arduino Uno.
I am 100% sure that You will have to buy a new board. When Iwas facing problem, I reinstalled all the drivers, Arduino IDE as well as My Windows 7 but still the same problem.

I bought a new board from different seller and its Working Perfectly. Replace the board. You have no Option Left. Arduino World is amazing...


I can't upload sketches to my Arduino 101 When connected to USB green Power LED on but doesn't upload sketch(that says press master reset therefore i've pressed several time but timeout). And main thing is device doesn't show in device manager.(I'm working on windows10).

Have I "bricked" it?
What steps can I take to work out what is wrong?
What can I do to fix it?

I've search in many sites but doesn't give me detail about hardware repairing guide for arduino 101.

I've checked working usb cable and another laptop but not work.I think hardware problem.Once arduino getting hot near usb.

It's hard to tell, but you can try a lot of options:

Use another USB port
Use another USB cable
Reinstall the Arduino IDE
Remove the device in the device manager and try reinstalling the Arduino IDE again
Try another Arduino (to see if the USB/install is ok)
Try on a different computer/laptop

Simply replace it because it has a 1 year warranty outside the US.


HTTPS Client with MKR1000 I am making an IoT device with the MKR1000.

As a part of the process, I would like to set up an HTTPS connection to https://hit.tl8.co/api/ping (This is a website I have made and control).

The problem is that client.connect(url, 443) is returning false. I have tried normal HTTP and the URL works on a browser. I can also access https://www.google.com. The code is a small variation of the example HTTP client.

As such, I believe that the TLS cert I am using is not accessible by the MKR1000. Running this report shows that it is a RSA 2048 bits (e 65537) with SHA256withRSA cert.

Is there a way to get the MKR1000 to accept this cert? Failing that, what changes do I need to make to this cert for it to work?

Is there a software solution to get this cert working?

You need to use connectSSL() instead of connect(). And possibly add your certificate to mkr1000 as described on Hackster


Rotary encoder on Uno and interrupts issue This question is regarding a project using an Arduino Uno.

I have one of these quadrature rotary encoders.

I'm using a slightly modified version of the code from the article, Quadrature Encoder too Fast for Arduino (with Solution), which uses a library called digitalwritefast.

My version of the code on pastebin - I modified to use different pins for the Uno and a single encoder:

#include <digitalWriteFast.h>  // library for high performance reads and writes by jrraines

#define c_LeftEncoderInterrupt 0
#define c_LeftEncoderPinA 2
#define c_LeftEncoderPinB 3

volatile bool _LeftEncoderBSet;
volatile long _LeftEncoderTicks = 0;

void setup()
{
  Serial.begin(115200);
  pinMode(c_LeftEncoderPinA, INPUT);
  digitalWrite(c_LeftEncoderPinA, LOW);
  pinMode(c_LeftEncoderPinB, INPUT);
  digitalWrite(c_LeftEncoderPinB, LOW);
  attachInterrupt(c_LeftEncoderInterrupt, HandleLeftMotorInterruptA, RISING);
}

// Interrupt service routines for the left motor's quadrature encoder
void HandleLeftMotorInterruptA()
{
  _LeftEncoderBSet = digitalReadFast2(c_LeftEncoderPinB);   // read the input pin
  _LeftEncoderTicks -= _LeftEncoderBSet ? -1 : +1;
}

void loop()
{
  Serial.print(_LeftEncoderTicks);
  Serial.print("\n");
  delay(20);
}

I am attaching output A of the encoder to pin 2 and output B to pin 3.

This setup works fine and I can detect turns in both directions, but my problem is, if I set pin B to any other pin, I get positive direction only (regardless of the direction in which the encoder is turned) - as if pin B isn't plugged in at all (I am modifying c_LeftEncoderPinB accordingly).

I'm assuming that this is something to do with pin 3 being the only other interrupt pin on the Uno (I can't see anything else unique about that pin). Yet I don't know why because the interrupt is on pin A (we're reading the value of pin B in that interrupt, though).

When turning one way, A is asserted, then B is asserted, then A is deasserted then B is deasserted. You can detect this because A is asserted first, even if you can't tell when B has changed. But if you turn the opposite way then you fail to detect the initial assertion of B, and the code fails.

What you may be able to do is use PinChangeInt to capture the pin change interrupt rather than an external interrupt. This should allow you to use almost any I/O pins on the Uno for the encoder.

Use library attached here:
http://forum.arduino.cc/index.php?topic=275248.msg1938244#msg1938244
Regards,


can I program a nano over SPI with another nano? I'm fairly new to arduino, but I want to program a nano over SPI to skip the bootloader. I know I can program the nano with an uno as a programmer to do this, but I don't have an uno, but I do have a couple of nanos. Can I set up one as a programmer, connect it to another over SPI, and program the 2nd?

Yes, you can. They use ATmega328 / Atmega328P microcontrollers, which are basically the same.

(The differencies of those microcontrollers are about Brown Out Detection - how they could be set to react on too low voltage. No problem in nearly any Arduino operation.)

The boards differ mainly in the board size and places for pins.


I would like to know the ATMEGA wiring to Arduino I would like to know which pins are connected to the output of the Arduino.

For example:

PC6 is digital 12
PB5 is analog 13
etc...

Image searching for the term "arduino uno pinout" reveals a better pinout diagram.

Updated: Pins PB6 & PB7 while available as I/O pins (D6 & D7) are committed to the external crystal on this board and not brought out to the connectors.


Attiny85 not able to understand data from 433Mhz using VirtualWire.h The basic plan is to have a Attiny85 pass information from a 433Mhz RF module to another chip/Arduino via I2C using VirtualWire and Wire libraries. I have been able to make this system work on their own using Arudino Nano's to debug, but the Attiny85 (A85) seems unable to grab the data from the RF 433 Mhz.

So have spent a few days doing some more research, and basically putting each component separate, to make sure what is being sent is correct.

433 Mhz transmitter is working by sending a 9 digit number, using VirtualWire.h.
Nano with a 433 Mhz receiver is receiving 9 digit
number, VirtualWire.h.
Attiny85 is sending either a no data, or the 9 digit number, to another Nano using Wire.h.
The Nano is getting only No Data, so the I2C is working between A85 and Nano.

Attiny85, on Pin 1 (pin 6 on chip) is not getting any data from the 433 Mhz, which works on (2). I connect the GND of the 433 RX to the chip.

Here is the Receiver code:

#include <VirtualWire.h>
#include <Wire.h>
void setup() {
  pinMode(A3, OUTPUT);
  Wire.begin(); // join i2c bus (address optional for master)
  vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(4000);   // Bits per sec
  vw_set_rx_pin(1);
  vw_rx_start();       // Start the receiver PLL running
}
void loop() {
  uint8_t buf[15];
  uint8_t buflen = 15;
  if (vw_get_message(buf, &buflen)) // Non-blocking
    {
      digitalWrite(A3, LOW);
      Wire.beginTransmission(8); // transmit to device #8
      for (int i = 0; i < buflen; i++) {
        Wire.write(buf[i]);
      }
      Wire.endTransmission();    // stop transmitting
    } else {
      digitalWrite(A3, HIGH);
      Wire.beginTransmission(8); // transmit to device #8
      Wire.write("no DATA");
      Wire.endTransmission();    // stop transmitting
     }
}

Here is the Transmitter code:

#include <VirtualWire.h>
int xPin = A7;
int yPin = A6;
int buttonPin = 2;

int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
const char *controller;
void setup() {
  Serial.begin(9600);
  pinMode(12,OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(yPin, INPUT);
  pinMode(xPin, INPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  vw_set_ptt_inverted(true); //
  vw_set_tx_pin(12);
  vw_setup(4000);// speed of data transfer Kbps
}

void loop(){
   xPosition = analogRead(xPin);
   yPosition = analogRead(yPin);
   buttonState = digitalRead(buttonPin);
if(xPosition > 0 || yPosition > 0) {
  String Data = (xPosition + yPosition);
  controller = Data;
  vw_send((uint8_t *)controller, strlen(controller));
  vw_wait_tx(); // Wait until the whole message is gone

} else {
  digitalWrite(13, 0);
  digitalWrite(4, 1);
  controller = "#s0_0";
  vw_send((uint8_t *)controller, strlen(controller));
  vw_wait_tx(); // Wait until the whole message is gone
}

Serial.println(controller);

}

So basically the A85 is not getting past if (vw_get_message(buf, &buflen)) { on pin 1. But does when using the Nano on pin D2, from the same transmitter, but not at the same-time of-course.

Am I using the wrong Pin on the A85? Chip pin 5 and 7 are used for the I2C so it only leaves analog pins so not sure they would work either. I also tried 8 Mhz and 1 Mhz when loading the A85.

I  have tried different Cores as suggested from Google, different versions of VirtualWire and clocked the Attiny 1Mhz, 8Mhz and 16Mhz. None of have worked.

Not sure what else I am missing?

Have you tried using the Radiohead  library? I know you said you tried different versions of Virtual Wire. The RH_ASK class works on a 328p and a nano for sure and they claim a simple Rx program can run on a ATTiny85. They have documentation under RH_ASK regarding the changes you need make to the library.
Another possible fix is to edit the Virtual Wire library files, they might have variables like "Max_payload" (Radiohead does) whose size can be decreased.
I haven't actually read the Virtual wire library, but I am sure Radiohead should fix your problems.

If this doesn't work, do you have an oscilloscope? Maybe we can try debugging it like that.

Edit: Maybe try commenting out the vw_set_ptt_inverted line first. I don't think you are using the DR3100. Might not make a difference because you haven't actually set a pin for ptt.
Next thing you can try is just connecting the data pin of the Tx to the Rx. You should be able to check if the module is actually connected to the ATTiny with this.

ATtiny85 internal oscillator has to be calibrated to work with VirtualWire or you have to use a resonator.

This link provides useful information on how to calibrate the internal oscillator of an ATtiny MCU.

I used a 16Mhz crystal connected to pin 2 and 3, then you have to change type to external and burn bootloader to change fuses.

I don't think that you can use Wire libraries with attiny85. Did you not got any error messages!


Arduino Nano (clone) not recognized Asking here cause I ran out of options in searching. My Arduino Nano clone isn't recognized by my computer anymore. It was, until I plugged into a Windows machine, that did not recognize it... and now even my Linux Mint distro doesn't detect the Nano at all. Here's the thing, though: the green power LED still lights up and, if I connect my DC motor to it like I used to before, the LED turns off and the motor is powered only a little bit, with less speed than if it were powered by a 1.5V battery.

My voltimeter reads a 2.18V out of the 5V pin.

Here's all I did: uploaded a sketch to power a 5v motor, it worked, unplugged the Arduino, took it home to my Windows machine on the casing I got it from my school, plugged it there, then it didn't detect anything. Go back to the lab today, plug it in, doesn't detect it there either.

From there, I've replaced USB cables, tried different USB ports, checked with lsusb and dmesg, tried finding it using the FTDI tool (the chip underneath is FTDI), then tried powering it from a phone charger, but the voltage readings at the 5v pin still are around 2.18V with that. Nothing seems to give this little thing an output greater than 2.18V.
The only thing I haven't tested is powering it through the VIN pin.

I came across other questions of similar problems but nothing that seems quite like mine... since they all either are able to detect the device but it is displayed as an unknown device or can't recognize the device at all but their power LED does not turn on.

Any ideas on what is going on?

It sounds like a blown protection diode MBR0520 in between USB and +5V of the nano.

Standards compliant USB ports will only supply 100mA unless a higher current is negotiated by USB.

I suspect that you problem is the USB serial (Chinese Nano clones often have cheap chips). This happened to one of my Nano clones.


How to round up millis() when divided into minutes? unsigned long milliseconds=millis();
// if at time of reading the above milliseconds = 599999 ie 1 millisecond short of 600000 ie 10 minutes
unsigned long minutes = (milliseconds/1000)/60;
// this will return 9 instead of 10.

How do you round the result to 10 minutes? I don't mean adding 1 to final result. It has to be within the calculation.

To round to the nearest X in fixed point arithmetic: add 1/2 X (in the base units, msec, in this case) and divide by X (again, in the base units) so:
milliseconds = (milliseconds + (30*1000L))/(60*1000L);

The addition of 1/2 X causes a carry of one whole X if the fractional X in the original quantity was 1/2 X or greater. (Likewise, if the fractional X was less than 1/2 X, no carry will result).

Integer division naturally truncates any fractional amounts, so you'll be left with the rounded integer result.

I guess that rounding within the language requires declaring as double or casting to double (and then, if required, casting “back” to unsigned long). Rounding is not a process conceptually associated with integer arithmetic. The results are not always easily predictable. I give an illustrative example for rounding non-negative numbers in your context. (The effect of casting is compiler-dependent, it either truncates or rounds, but this works in both cases.)

double millisecs = 599999L;
double minutes = (millisecs / 1000) / 60;
unsigned mins_rnd = minutes;
mins_rnd += minutes - mins_rnd < 0.5 ? 0 : 1;
printf("%f\t%f\t%d\n", millisecs, minutes, mins_rnd);


Number of elements in an array char What kind of function can I use to know how many elements are in an array char?

sizeof() gives the number of 'spaces' available so it doesn't work for me.

You want strlen.

char foo [100] = "bar";
Serial.println (strlen (foo));   // --> prints 3

use sizeof

char nnn[10];
for(int i=0; i< sizeof(nnn)/sizeof(char); i++){

}


HC-05 TX,RX divider rule I'm using the HC-05 Bluetooth module but I'm confused about the TX,RX pins.
I want to know when should I connect the RX to a divider circuit to convert 5v to 3.3v.
Because while searching, I saw both of the following:

either RX is connected to TX of the UNO and TX is connected to RX of the UNO without a divider circuit.
or RX is connected to a divider circuit and then connected to any digital pin , TX is connected to any digital pin as well.

So can you give me a thought about both the situations?
my thought is that only digital pins needs a divider rule, but the TX,RX pins can be connected directly and operates without any problems but if so, then what's the difference between both??
Note that I'm using HC-05 to turn on a LED.
Hope to see some good explanation that suits a new Arduino learner.
Thank you..

While you should use a voltage divider on the Arduino TX --> BT RX signal, you honestly don't need to. Many people, including myself, have used HC-05s without voltage dividers and haven't let "the magic smoke" out of the device. Adding a voltage divider may, though, may increase the lifespan of the HC-05.


Can I connect a NEO-6M GPS Module and ESP8266 to the same Arduino? Can I connect a NEO-6M GPS Module and ESP8266 to the same Arduino? I think both modules require the use of the RX and TX pins.

You can use Software serial for this.

and assign pins like
SoftwareSerial mySerial(2, 3); // RX, TX

This is a link for better understanding https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


How to make auto keyboard using arduino nano V3.0 ATmega 328P ? I have an Arduino Nano v3.0 ATmega328p board. I want to make an auto keyboard that types in a string when its plugged in. I have googled and found that these chips doesn't support that feature unlike "pro micro". keyboard.h is not supported with this chips. So is there any alternative way to use it as a HID and emulate keyboard inputs using any other additional shield other than using the built in USB port. Im a noob in this field, please help. Thanks in advance.

I found this link : http://www.practicalarduino.com/projects/virtual-usb-keyboard  Is that what you've been looking for?


How can I communicate from Arduino to MATLAB I want to use sensors on an Arduino to control values in a MATLAB program. What are my options for communicating?

I've used Processing to receive data sent via the serial cable, and that strategy has worked pretty well. Is there something similar I can do using MATLAB? I'm somewhat new to MATLAB, so gentle guidance would be great.

I'm not really looking for something like the ArduinoIO package -- I want to have separate computation executing on the Arduino and occasionally informing my MATLAB program (which will occasionally poll the serial line, I suppose).

MATLAB Support Package for Arduino (aka ArduinoIO Package) allows you to do it fairly easily.

  Sample usage:

  %-- connect to the board

  a = arduino('COM9')

  %-- specify pin mode

  a.pinMode(4,'input');

  a.pinMode(13,'output');

  %-- digital i/o

  a.digitalRead(4) % read pin 4

  a.digitalWrite(13,0) % write 0 to pin 13

  %-- analog i/o

  a.analogRead(5) % read analog pin 5

  a.analogWrite(9, 155) % write 155 to analog pin 9

clc
clear all
global value
global value1
global val5
global val6
global val7
global val8
global val9
a=arduino('COM4');
   value = zeros();
   value1 = zeros();
   val5 = zeros();
   val6 = zeros();
   val7 = zeros();
  val8 = zeros();
  val9 = zeros();
for i=1:1000

val1(i)=analogRead(a,0)/2; %incomming

val2(i)=analogRead(a,1)/2; %heater

val3(i)=analogRead(a,2)/2;   %heat sink

val4(i)=analogRead(a,5)/2; %atmsphr

val8(i)=analogRead(a,6)/2; %pressure

val9(i)=analogRead(a,7)/2; %pressure

val(i)=analogRead(a,0)/2;

value(i)= (val1(i)+val4(i)+val3(i))/3;

value1(i) =(val8(i)-val9(i)); %pressure

val5(i)=analogRead(a,0)/2 %incoming

val6(i)=analogRead(a,4)/2 %outgoing

val7(i) = value(i)-val6(i)
    plot(value, 'r');
    title('heat sink temprature');

hold on

plot(val5, 'k');

title('incoming air temprature');
plot(val6, 'g');

title('outgoing air temprature');

 plot(val4, 'k');
 title('atmospheric temperature');

plot(val7,  'c');
title('change in temprature');

pause(6)

figure
plot(value1,  'r');
title('change in pressure');

pause(6)

end


How to connect a 5V submersible motor to Node MCU? I connected the D1,D2 pins of the the Node MCU to the positive and negative of a 5V submersible motor. I wrote the following code, its getting uploaded without any errors but the motor is not working. I tested the condition of the motor by connecting to a battery,it does work.the code:

void setup() {
  // put your setup code here, to run once:
    pinMode(D1,OUTPUT);
pinMode(D2,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(D1,HIGH);
digitalWrite(D2,HIGH);
}

I think you have got two issues here.

Firstly, as mentioned in the comments, you are driving the motor off the data pins so it will be getting less than 20mA which is almost certainly not enough to break the stall.  You need to use the digital pins to switch a MOSFET, transistor or relay (Electrical switch) and then that will switch on a larger supply directly from a "battery pack".  Have a Google for 'transistors' or 'relays' and see how they work, then you should get what I mean.

Secondly you seem to be using the pin names D1 and D2. There are a number of Node MCU boards out there but they all seem to have one thing in common and that is the pins labelled D1 and D2 on the board are generally not D1 and D2 in the code.

https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu_pins.png?w=924

If this is you board then unless you have a header file that does this for you, you should be using GPIO_5 and GPIO_4 for D1 and D2 (respectively).

Oh and the last thing, make sure you sub is leak proof :)

First of all if you don't know Then the positive pin of the submersible motor has to be connected to a power source to either switch the valve and secondly the negative pin has to be connected to the GND!
Next thing is that you should never drive a motor or anything like that directly with a microcontroller. You should use either a MOSFET or something similar.
Now for that solution would be is first of all make a circuit similar to this. With the control pin  referring to the microcontroller's output and then you could exchange the 12V input with the desired voltage your motor is compatible with ! Next connect the negative pin of the motor to the common ground of the battery pack and the microcontroller and output pin to the motors positive pin.


What is the best way to define an I/O pin? I read definitions like

const int ledPin = 9;

and also

#define ledPin 9

I know that a definition like

int ledPin = 9;

is a bad practice if you're not going to change it (which you usually won't), though I've see this several times in Arduino programs.
Which one of the other two is preferred?

#define ledPin 9 is preferred. By doing int ledPin = 9; you will be allocating an int memory whose value is used every time you use ledPin. #define is different in the sense it doesn't allocate memory. there is no memory called ledPin. Before compiling all "ledPin"s in the code(other than strings) are replaced by 9. So basically

digitalWrite(ledPin);

becomes

digitalWrite(9);

Advantages of #define : Saves memory and since all ledPin are replaced by 9 before execution, it saves processor time.
Doesn't really matter in small codes...

Not only will

const int ledPin = 9;

take up RAM, but in this case, will use more RAM than necessary as digitalWrite(uint8_t, uint8_t) only needs one-byte arguments, and an int is usually two bytes (compiler-dependent, but typical). Note that you can give the literal an explicit type in the #define:

#define ledPin ((int)9)

though in a context such as a function argument where a specific type is required (because the function was properly prototyped!) it would either be implicitly cast or get an error message if the types don't match.


Detecting distance moved by accelerometer? I have an accelerometer connected to an Arduino Uno board, is there a way I can detect the distance it this accelerometer moved on each of the 3 axis?

This is normally referred to as Dead Reckoning.  The processes of determining position using known values, such as acceleration.

First we have to relate acceleration, velocity and position mathematically.  Velocity is the integral of acceleration with respect to time:

Similarly, position is the integral of velocity with respect to time:

Here is an explanation that should tie this all together.  However, it appears this explanation goes in the reverse order.  That is using derivatives of position to find velocity.  And derivatives of velocity to find acceleration.  Simply put, finding a derivative is the opposite process of finding an integral.

A final note, this all works well on paper.  In reality Dead Reckoning based only on acceleration does not work very well.  For instance, I believe most vehicle GPS systems tend to use steering and speed if Dead Reckoning is to be used for guidance.

Added later...

Found this web site where someone talks specifically about Dead Reckoning using an Arduino. He is simply using the deltas of filtered acceleration readings:

velocity(i) = velocity(i-1) + acceleration (i)
position(i) = position (i-1) + velocity (i)

But goes on to say accumulated errors causes drift and positioning errors.

Think about it:

Accelerometers measure acceleration.
Acceleration is a change in speed.
Distance travelled is speed multiplied by time.

If you know the starting speed (e.g., stationary) and you know how much you have accelerated between two points in time you can calculate the average speed for that time period - and since you know the time of that time period (one would hope) then you can get an approximation of the distance travelled in that axis.

I say approximation, because you are working with finite time points (quanta) and only looking at the acceleration at those points in time. It's far from perfect, but it can give you a rough ballpark figure. The smaller your quanta the better your accuracy - but it will never be anything more than a guestimation at best.

Now it's just, as they say, a SMOP.


Bluetooth Modules not communicating correctly I plug in BT rx to digital 11, BT tx to digital 10 and then 5v and ground from the HC-05 to the arduino. I then upload this code to the HC-05 that is set as a master.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

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

void loop() { // run over and over
  Serial.println(mySerial.read());
  delay(2000);
}

I then upload this code to the arduino with the HC-05 that is set as a slave:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX , TX

void setup() {
  // put your setup code here, to run once:
  mySerial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  mySerial.write("100");
  delay(2000);
}

The issue is that I never receive "100" on the serial monitor, I only ever receive 49 and occasionally 48. When I changed it from "100" to "10" same thing happened. Any help would be appreciated.

SoftwareSerial.read() returns a single character as an integer. When you print an integer the print() functions convert it to a human readable format.

You want to covert (cast) the output of read() to the char type. Either:

void loop() {
  char c;
  c = mySerial.read(); // store the result in a temporary variable c
  Serial.println(c);
  delay(2000);
}

or

void loop() {
  Serial.println((char)mySerial.read()); // cast the type to char befor printing.
  delay(2000);
}

However since only one character at a time is being read your output will be one character per line (assuming no data loss due to the delay):

1
0
0

You should change the TX and the RX pins on the arduino board and pin it on to another pin other than the TXD and RXD as the are hardware pins....


How can I add two different programs of bldc motor and servo motor in one so that they work in parallel? This is for the servo motor:

#include <Servo.h> //Servo library

Servo servo_test;
//initialize a servo object for the connected servo
int angle = 0;

void setup() {
  servo_test.attach(9);
}

void loop() {
  for(angle = 0; angle < 180; angle += 1) {
    servo_test.write(angle);
    delay(15);
  }
  delay(1000);
  for(angle = 180; angle>=1; angle-=5) {
    servo_test.write(angle);
    delay(5);
  }
  delay(1000);
}

This is for the bldc motor with esc:

#include <Servo.h>

Servo esc_signal;

void setup() {
  esc_signal.attach(12);
  esc_signal.write(30);
  delay(3000);
}

void loop() {
  esc_signal.write(55);
  delay(15);
}

Depending on how the code is driven. The simplest would be to simply run loop1 and loop2 in the new loop.

Try out this code. It may be helpful.

#include <Servo.h> //Servo library

Servo servo_test;  //initialize a servo object for the connected servo
int angle = 0;

Servo esc_signal;

void setup()
{
  servo_test.attach(9);

  esc_signal.attach(12);
  esc_signal.write(30);
  delay(3000);
}

void loop()
{
  servoFun();
  bldcFun();
}

void servoFun()
{
  for(angle = 0; angle < 180; angle += 1)
  {
      servo_test.write(angle);
      delay(15);
  }
  delay(1000);

  for(angle = 180; angle>=1; angle-=5)
  {
      servo_test.write(angle);
      delay(5);
  }
  delay(1000);
}

void bldcFun()
{
  esc_signal.write(55);
  delay(15);
}


Error uploading Arduino Micro Sketch using Kubuntu I have an arduino micro which I want to program from my Kubuntu 15.10 system. I installed the arduino software using apt-get, but when I try to upload the program (for test purpose I use the Basics\BareMinimum sketch) I get the following error:

Found programmer: Id = "0.00 V1"; type =
    Software Version = 0..; Hardware Version = 0.0
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?

The proper device "Arduino Micro" is selected and also the proper port "/tty/ACM0". I found people on the internet which have the same error and could solve it by using another USB port or cable. But I tried it with two different cables and different ports and didn't manage to get it working. I even tried it on my Laptop running an older version of Kubuntu which produced the same error.

Therefore I tried the newest version of the Arduino software from the arduino homepage. With this I get a different error:

avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy
avrdude: ser_send(): write error: Bad file descriptor

My user is added to the dialout group, so I should have access to the port. It is also the right port as the port disappears from the arduino menu when I unplug the board.

The arduino itself shouldn't be the problem, as I can upload the sketch from another windows laptop without problems.

EDIT: when I plug in the arduino, the following is added to the dmesg output:

[ 8390.293960] usb 1-2: new full-speed USB device number 6 using xhci_hcd
[ 8390.424861] usb 1-2: New USB device found, idVendor=2341, idProduct=8037
[ 8390.424863] usb 1-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 8390.424864] usb 1-2: Product: Arduino Micro
[ 8390.424865] usb 1-2: Manufacturer: Arduino LLC
[ 8390.425283] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
[ 8390.426815] input: Arduino LLC Arduino Micro as /devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2:1.2/0003:2341:8037.0007/input/input21
[ 8390.482163] hid-generic 0003:2341:8037.0007: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC Arduino Micro] on usb-0000:00:14.0-2/input2

Therefore I tried the newest version of the Arduino software from the arduino homepage.

  The package version I am using is 1:1.0.5+dfsg2-2, the other I tried was 2:1.0.5+dfsg2-4.

That is not the newest version.

I think the more recent versions of the IDE are more robust - after all they have fixed reported bugs. Try 1.6.5 or 1.6.7. The version 1.0.5 is pretty old.

I too have had "upload completed" on my Leonardo (virtually the same as the Micro) when it did no such thing.

I am using Ubuntu 14.04 and don't have any problems programming my Micro with IDE 1.6.7.

When programming you should see the Tx/Rx and yellow LEDs flicker. If not, press Reset when it starts to upload and try again.

Have you followed the instructions here? Arduino Troubleshooting.

  I installed the arduino software using apt-get ...

Personally I download the IDE from this page: https://www.arduino.cc/en/Main/Software

Update

I just compiled and uploaded "Blink" with IDE 1.6.7 to my Micro on Ubuntu 14.04. This is what I saw:

Forcing reset using 1200bps open/close on port /dev/ttyACM1
PORTS {/dev/ttyACM0, /dev/ttyACM1, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, /dev/ttyACM1, } => {/dev/ttyACM1, }
Found upload port: /dev/ttyACM1
/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avrdude -C/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM1 -b57600 -D -Uflash:w:/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/nick/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM1
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587
avrdude: reading input file "/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex"
avrdude: writing flash (4456 bytes):

Writing | ################################################## | 100% 0.33s

avrdude: 4456 bytes of flash written
avrdude: verifying flash memory against /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: load data flash data from input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex contains 4456 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.03s

avrdude: verifying ...
avrdude: 4456 bytes of flash verified

avrdude done.  Thank you.

Can you please compare to what you get? Or post exactly what you see?

What do you see in your Port menu? This is what I see:

Installing Arduino on a fresh Ubuntu system

I did the following steps to get Arduino up on Ubuntu 14.04, on a PC where it was not previously installed.

Download and install

Downloaded Linux IDE 1.6.7 (64 bit) from https://www.arduino.cc/en/Main/Software
Un-archive downloaded file into ~/development folder
Executed from terminal:  ./arduino

Compile "blink"

Selected Uno device type
Loaded "Blink" from examples
Uploaded (checked Uno showed in menu as shown above)
Got error:

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device

Check permissions, join dialout and tty groups

See owner of /dev/ttyACM*

$ ls -l /dev/ttyACM*
crw-rw---- 1 root dialout 166, 0 Feb  1 07:32 /dev/ttyACM0

Am I in that group? (No)

getent group dialout
dialout:x:20:

Add to group dialout:

$ sudo usermod -a -G dialout nick

Am I in that group? (Yes)

$ getent group dialout
dialout:x:20:nick

Try again:

avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Add to group tty:

$ sudo usermod -a -G tty nick

Check groups I am in:

$ groups nick
nick : nick adm tty dialout cdrom sudo dip plugdev lpadmin sambashare

Try again (same error).

Log out and log back in

After logging out and back in, it uploaded OK! Changed to Micro board (very similar to Leonardo) - still uploaded OK (after changing board type in IDE).

Check USB for Micro

After reset:

$ lsusb | grep Arduino
Bus 002 Device 014: ID 2341:0036 Arduino SA

After about 3 seconds:

$ lsusb | grep Arduino
Bus 002 Device 015: ID 2341:8037 Arduino SA

sudo chmod 666 /dev/ttyACM{for your arduino board}

mine happens to be "/dev/ttyACM1" so i did

sudo chmod 666 /dev/ttyACM1


How to confirm a pin is fried How do you confirm a pin has been damaged and is unable to work as a digital input?

I tried detecting a pushbutton (connecting ground to pin 11 with a pullup resistor enabled) on a fresh Arduino Uno and digitalRead() always registers 0, regardless of the pushbutton state.

To confirm it wasn't my pushbutton's wiring, I tested it on some other pins, and they register the button press perfectly. I then tested pin 11 as an output, and it was able to blink and LED just fine.

The Arduino's pretty new, and I don't remember doing anything with it that would have damaged anything, much less pin 11, but is it fair to say that pin has somehow been damaged? As far as I can tell, everything else on the Arduino works perfectly.

Yes, it sounds like that pin is fried.

You seem to have done all the things I would recommend:

Try your circuit on a different pin (works fine)
Try your circuit on the same (faulty) pin on a different microcontroller (works fine)

If you get different results between two chips that should be the same with the same code running on them then one of them is most likely faulty in some way, or has some other setting in it (fuse setting) that could be affecting it.  I am not aware of any settings like that on the '328P, certainly none that you would change without knowing you had changed them.

connecting ground to pin 11 with a pullup resistor enabled...always registers 0
connecting ground to pin 11
ground to pin

There's your problem


Bluetooth Communication Not Working with DC Power But Works With USB Power? I am running a HM-10 Bluetooth Low Energy (BLE) module to transmit serial data (using SoftwareSerial) from an analog sensor onboard my Arduino Uno to a serial terminal app on my Android phone. When I power the Arduino with a USB power bank, the data transmits flawlessly.

When I tried to power the Arduino with a 9V battery through the DC power jack instead of USB power, the BLE module connects to my phone, but no data is transmitted when a serial connection is established.

Any ideas why this would be?

Take two 9 volt batteries with same specifications and connect it into the parallel by using this efficiency of current increases and it full fill the current requirement at the time of data transmission and for others modules u r using with the arduino.


IR Receiver interrupt and arduino sleep mode I need to put my arduino into the sleep mode in order to consume less power. My arduino receives IR data and do some work with it, but I need to make it sleep until there is no data. If the data has appeared it should wake up and do something with data and go back to sleep mode.
Is there any way to do this.
I would be grateful for any help.

This is what I have managed to achieve ...

Library

IRLib - GitHub

  Version 1.51 March 2015
  Copyright 2013-2015 by Chris Young http://tech.cyborg5.com/irlib/

  This library is a major rewrite of IRemote by Ken Shirriff which was covered by GNU LESSER GENERAL PUBLIC LICENSE ...

Code

Modified code (from the demo IRrecord example):

/* Example program for from IRLib – an Arduino library for infrared encoding and decoding
 * Version 1.5  June 2014
 * Copyright 2014 by Chris Young http://cyborg5.com
 * Based on original example sketch for IRremote library
 * Version 0.11 September, 2009
 * Copyright 2009 Ken Shirriff
 * http://www.righto.com/
 */

/*
 * IRrecord: records IR signals
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Record a value by pointing your remote at the device
 */

#include <IRLib.h>
#include <avr/sleep.h>
#include <avr/power.h>

const byte LED_PIN = 8;
const byte RECV_PIN = 11;
const unsigned long BAUD_RATE = 115200;
const unsigned long NO_ACTIVITY_TIMEOUT = 2000;  // milliseconds

IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
IRsend My_Sender;
/*
 * Because this version of the library separated the receiver from the decoder,
 * technically you would not need to "store" the code outside the decoder object
 * for this overly simple example. All of the details would remain in the object.
 * However we are going to go ahead and store them just to show you how.
 */
// Storage for the recorded code
IRTYPES codeType;          // The type of code
unsigned long codeValue;   // The data bits if type is not raw
int codeBits;              // The length of the code in bits

// These values are only stored if it's an unknown type and we are going to use
// raw codes to resend the information.
unsigned int rawCodes[RAWBUF]; // The durations if raw
int rawCount;                   //The number of interval samples

bool GotOne, GotNew;

// added by Nick Gammon
EMPTY_INTERRUPT (PCINT0_vect);

void setup()
{
  GotOne=false; GotNew=false;
  codeType=UNKNOWN;
  codeValue=0;
  Serial.begin(BAUD_RATE);
  while(!Serial);//delay for Leonardo
  Serial.println(F("Send a code from your remote and we will record it."));
  Serial.println(F("Type any character and press enter. We will send the recorded code."));
  My_Receiver.enableIRIn(); // Start the receiver
}

// Stores the code for later playback
void storeCode(void) {

  // added by Nick Gammon
  pinMode (LED_PIN, OUTPUT);
  digitalWrite (LED_PIN, HIGH);

  GotNew=true;
  codeType = My_Decoder.decode_type;
  if (codeType == UNKNOWN) {
    Serial.println("Received unknown code, saving as raw");
    // To store raw codes:
    // Drop first value (gap)
    // As of v1.3 of IRLib global values are already in microseconds rather than ticks
    // They have also been adjusted for overreporting/underreporting of marks and spaces
    rawCount = My_Decoder.rawlen-1;
    for (int i = 1; i <=rawCount; i++) {
      rawCodes[i - 1] = My_Decoder.rawbuf[i];
    };
    My_Decoder.DumpResults();
    codeType=UNKNOWN;
  }
  else {
    Serial.print(F("Received "));
    Serial.print(Pnames(codeType));
    if (My_Decoder.value == REPEAT) {
      // Don't record a NEC repeat value as that's useless.
      Serial.println(F("repeat; ignoring."));
     }
     else {
       codeValue = My_Decoder.value;
       codeBits = My_Decoder.bits;
     }
     Serial.print(F(" Value:0x"));
     Serial.println(My_Decoder.value, HEX);
  }

  // added by Nick Gammon
  pinMode (LED_PIN, INPUT);
  digitalWrite (LED_PIN, LOW);

}

void loop() {

  // added by Nick Gammon
  static unsigned long lastActivity;  // when we last woke
  // sleep if no activity for a while
  if (millis () - lastActivity >= NO_ACTIVITY_TIMEOUT)
    {
    Serial.flush ();  // wait for Serial to finish outputting
    Serial.end ();    // shut down Serial
    noInterrupts ();  // timed sequence coming up

    // pin change interrupt for D11
    PCMSK0 |= bit (PCINT3);  // want pin 11
    PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
    PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13

    set_sleep_mode (SLEEP_MODE_STANDBY);
    sleep_enable();

    byte old_ADCSRA = ADCSRA;
    // disable ADC to save power
    ADCSRA = 0;
    power_all_disable ();  // turn off various modules
    interrupts ();
    sleep_cpu ();
    sleep_disable();
    power_all_enable ();   // enable modules again
    ADCSRA = old_ADCSRA;   // re-enable ADC conversion
    Serial.begin(BAUD_RATE);
    lastActivity = millis ();
    }  // end of no activity for a couple of seconds

 if (My_Receiver.GetResults(&My_Decoder)) {
    My_Decoder.decode();
    GotOne=true;
    storeCode();
    delay(500);
    My_Receiver.resume();
  }
}

Explanation

Main changes are in loop (near the bottom) where it sleeps if there is no activity for two seconds. This "no activity" test gives it time to catch an incoming pulse stream.

Before sleeping it turns off Serial (to save power), and sets up to detect the pin-change interrupt. It also turns off the ADC, and calls power_all_disable to disable various internal modules.

Note that it uses pin-change interrupts on Arduino pin D11 (pin 17 on the chip). For a different processor than the Atmega328P, or a different input pin, you would have to change which pin-change interrupt is used.

I found that I had to use SLEEP_MODE_STANDBY rather than SLEEP_MODE_PWR_DOWN, otherwise it seemed to take too long to wake up and handle the incoming pulse.

For testing, I flashed D8 pin to make sure it was working when hooked up in low-power configuration.

Power consumption

I tested with an AX-1838T IR-receiver that I had to hand (same pin-outs as in the Adafruit article).

Measured stand-alone (ie. not connected to the Arduino) it consumed 630 µA, so therefore we could not expect lower power consumption than that.

Connected up to a "bare-bones" board (ie. just the Atmega328P chip, decoupling capacitors, etc.) I measured 1.158 mA when idle.

My tests on my page about power indicate that SLEEP_MODE_STANDBY uses 480 µA more power than SLEEP_MODE_PWR_DOWN, so this sounds about right.

630 + 480 = 1110 µA

You might be able to save more power by operating at a lower voltage. This particular receiver can operate at a lower voltage. As an indication, I tried the setup at 3.3 V (which is out of spec for the processor, but whatever, I was just testing) and it consumed 978 µA when idle. This is a modest saving over the 5 V test.

References

Power saving
Interrupts
Adafruit IR library
IR library source

Connect the IR receiver to INT0 or INT1 (pins 2 or 3 respectively). You can use the attachInterrupt function. E.g. attachInterrupt(0, yourfunctionname, LOW). The function being called can be empty, if you only use it to wake up the MCU.

To wake from sleep you need to use the LOW trigger mode. Once waken up you probably want to remove the interrupt handler (detachInterrupt), or it will swamp the cpu with interrupts.

(Note that most IR receiver will still use something like 3mA.)


How to find the index of the maximum value in an array? Say we have an array named myMeasurements

int myMeasurements[9]={3,4,8,12,7,2,1,67,8};

How can I find the index of the maximum element of this array?

For example the MATLAB code would be:

myMeasurements = [3,4,8,12,7,2,1,67,8];
[maxValue,Index] = max(myMeasurements);

where maxValue is returned as 67 whereas the Index is returned as 8.

For the record, I am using Teensy 3.2 and I program it with the Arduino IDE using the Teensyduino add-on.

First of all, do you really need int values for the measurements or not? If not, and you have numbers between 0 and 255, switch the values to byte, your microcontroller will thank you.

Then, there is a problem with the other answers, which is... The variables cannot be left uninitialized!!! You can use this code to get the info you need:

(I also put the size of myMeasurements in a const variable.. You can thank me later for this)

const byte maxMeasurements = 9;
int myMeasurements[maxMeasurements ]={3,4,8,12,7,2,1,67,8};

byte maxIndex = 0;
int maxValue = myMeasurements[maxIndex];

for(byte i = 1; i < maxMeasurements; i++)
{
    if(myMeasurements[i] > maxValue) {
        maxValue = myMeasurements[i];
        maxIndex = i;
    }
}

Arduino forum has discussed finding the index once you know which value's index you want. Solution was arrived at by traversing the array by value you were looking for.
For your requirement, you will have to
(1) find the maxValue first and then
(2) find the position(index) of that maxValue using the code they have discussed here :
https://forum.arduino.cc/index.php?topic=121116.0


Assigning formatted value to variable Look at this snippet of code (from TinyGPS++ library):

Serial.print(gps.location.lat(), 6);

It prints the latitude location with 6 decimal points.
I want, instead of printing that value, to have it assigned to a variable.

But i want it assigned just like above, with six decimal points. Is there a way to do this?

Merely expanding on what ConnorWolf has said (which I saw yesterday), look at the link he gave you, it gives you a run down on the command you're after.

  The dtostrf() function returns the pointer to the converted string s.

  char* dtostrf ( double          __val,
                signed char     __width,
                unsigned char   __prec,
                char *          __s
  )
  The dtostrf() function converts the double value passed in val into an ASCII representationthat will be stored under s. The caller is responsible for providing sufficient storage in s.

  Conversion is done in the format "[-]d.ddd". The minimum field width of the output string (including the '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. width is signed value, negative for left adjustment.

From that, I wrote a short sketch that divides millis() by 1000 and saves this in a float, we then use this float as a source for dtostrf() to do it's work and store the result in a char array.

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

void loop(){
  char c[12];
  float f = millis()/1000.0;
  dtostrf(f,11,3,c);
  Serial.println(c);
  delay(111);
}

I have picked arbitrary values, you're going to have to do the calculations on the size of the array to create (don't forget the leading negative sign, the digits before the decimal, the decimal and your precision digits as well as the null terminator!

I had the same problem and I found answer

char latitude[20];
char longitude[20];

dtostrf(gps.location.lat(),8,6,latitude);
dtostrf(gps.location.lng(),8,6,longitude);


Convert to and from Unix Timestamp What is the best way to convert between date, hours, min, seconds to Unix timestamp in milliseconds in Arduino? I need to have this conversion, since I'm using RTC (date, hours, min, secs etc) and communicating Unix timestamp over BLE

I found some snippet of codes online, but have not tested it extensively yet.

  byte second = epoch%60; epoch /= 60;
  byte minute = epoch%60; epoch /= 60;
  byte hour   = epoch%24; epoch /= 24;

  unsigned int years = epoch/(365*4+1)*4; epoch %= 365*4+1;
  unsigned int year;
  for (year=3; year>0; year--)
  {
      if (epoch >= days[year][0])
          break;
  }

  unsigned int month;
  for (month=11; month>0; month--)
  {
      if (epoch >= days[year][month])
          break;
  }

  year  = years+year;
  month = month+1;
  unsigned int day   = epoch - days[year][month]+1;

  unsigned int weekday  = (dayOfMonth += month < 3 ? year-- : year - 2, 23*month/9 + dayOfMonth + 4 + year/4- year/100 + year/400)%7;

And to convert to Unix timestamp:

unsigned long epoch = (((year/4*(365*4+1)+days[year%4][month]+dayOfMonth)*24+hour)*60+minute)*60+second;

Are there any library in Arduino that implement this? I would trade off reliability over size of the program.

I think that the two most used libraries are the Adafruit RTClib and the pjrc.com TimeLib.
They both have functions to convert the epoch, and they both are reliable. But both lack the timezone and the DaylightSavingTime.
I think you find the pjrc.com TimeLib just slightly more suitable to handle the epoch time (which is a 32-bit unsigned long defined as 'time_t').

Any half decent c compiler would have a set of time related types and routines to deal with this. Consult your compiker manual for more specifics.

Btw, contrary to conventional wisdom, you don't need an etc to keep track of time. Any good older timer plus your code will do.


Can a motherboard be a simple circuit between arduino uno and a set of devices (ie: motors) Reason for question:
My son is working on a project to build a robot controlled by an arduino uno. This question is more about terminology than process, but since terms are very important at this level, I rather ask some expert advice - I have not found any input on the internet about this!

Question:
What is the correct technical name (if any) of the circuit board that acts as the interface between the arduino-uno (a micro-controller) and the motors (the external devices)? According to the definition of a motherboard*, this "interface" circuit board would act as a very basic motherboard, as it would "allow communication" between the components, but it would not contain expansion slots, so should it be called something else?

Background on project:
The robot will be very basic. A body will be made of plastic legs and motors for joints; an Arduino-uno will provide the logic for motor movement; and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.

We are just missing the proper terminology to use for this "interface" board and I cannot find any concrete info online or on books. If I get good terms in this post, then we can do further research on those terms. Thanks.

https://en.wikipedia.org/wiki/Motherboard

I would call it an "interface" or "driver" board. You don't need to get too hung up on the exact name.
The word "shield" is one of the Arduino-peculiar words (like "sketch" for "code") which now has a generally-understood meaning. That meaning is, something that plugs directly onto the Arduino board, with the pins on the shield matching the sockets on the Arduino board.
Whilst a shield is a quick and easy way of getting started (because you don't need to wire anything) they can have their disadvantages. One being, what if you want two different functions, like a motor driver and an Ethernet interface? Two shields, one on top of the other? What if they both use a certain pin for different purposes?
I made up a radio-controlled car, see photo:

The only shield I used was a generic "put whatever you want onto it" shield, which let me mount some MOSFETs, a radio receiver board, and other components, as required by the design. There is a Uno underneath it, not particularly easy to see. Adjacent on the right is a motor driver board. A LiPo battery is slung underneath.
This kept things reasonably compact, without requiring a specific purpose-made shield which only does one thing.

and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.

It sounds like your project is similar to my car. Just assemble things in a way that makes sense to you.

"Interface board" works as a general term, as @alex had mentioned already.

The word "motherboard" would work if it's larger than each of the components that plug into it.

The word "daughter board" would work if it's smaller than what it plugs into.

Please don't use the word "shield" when referring to extension boards, interface boards, daughter boards, and such.  The word "shield" in this connection was popularized by Arduino marketing.  (More detailed discussion about "shield" in connection with Arduino.)


Motor shields in arduino what is a servo motor shield in arduino? what is the key purpose for using it? I'm newbie in arduino and I've seen some briefings in websites which I couldn't understand, can somebody elaborate it to me?

Servos require power and PWM. Servo shields come in two main forms:

Simple distribution
Active control

The first kind just provides convenient 3-pin headers to the Ardino's PWM pins, and sometimes a dedicated power supply for powering the servos. They're simple and cheap, but can only provide as many servo ports as the Arduino has PWM pins.

The second kind, more expensive, has a PWM chip on it to provide many more PWM pins than the Arduino can natively provide. Again there is sometimes a power supply as well, along with the convenient 3-pin headers. You usually interface with this kind using either I2C or SPI.  These are the ones people usually mean when they talk about a servo shield - a shield designed for powering and controlling many more servos than an Arduino by itself can manage.

Servo Motor Shields should not be confused with Motor Shields, which provide a number of H-Bridge drivers for powering and controlling (both the speed and direction) of a brushed DC motor.

The dumb ones are basically distributors of power for the servo motors.
There are more clever boards that offer the control of multiple servos (usually 10+) by communicating with the Arduino via some higher-than-PWM-level control (Like I2C) thus taking less pins from the Arduino than a dumb servo shield.
Both kinds usually require a power supply to power the servos.

G.


SPISettings was not declared in this scope I'm trying to compile a simple I2C example to read data from an MPU-6050 accel/gyro sensor, but I'm getting the compilation error:

/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:27:8: error: 'SPISettings' does not name a type
 static SPISettings settings;
        ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectHigh()':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:167:9: error: 'class SPIClass' has no member named 'endTransaction'
     SPI.endTransaction();
         ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectLow()':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:9: error: 'class SPIClass' has no member named 'beginTransaction'
     SPI.beginTransaction(settings);
         ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:26: error: 'settings' was not declared in this scope
     SPI.beginTransaction(settings);
                          ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::init(uint8_t, uint8_t)':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:3: error: 'settings' was not declared in this scope
   settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
   ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:53: error: 'SPISettings' was not declared in this scope
   settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
                                                     ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:275:7: error: 'class SPIClass' has no member named 'beginTransaction'
   SPI.beginTransaction(settings);
       ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:279:7: error: 'class SPIClass' has no member named 'endTransaction'
   SPI.endTransaction();
       ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::setSckRate(uint8_t)':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:14: error: 'settings' was not declared in this scope
     case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
              ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:66: error: 'SPISettings' was not declared in this scope
     case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
                                                                  ^
make: *** [.build_ano/uno/SD/src/utility/Sd2Card.o] Error 1
Make failed with code 2

I've commented-out all code until it compiled without error, and I found that the error is caused by the line:

#include <Wire.h>

So my minimal code to reproduce the error is:

#include <Wire.h>

void setup(){
}

void loop(){
}

Why is this include throwing this error? Why is it trying to compile code for accessing an SD card when I have no code that uses that?

I'm using Arduino 1.6.1 and targeting the Uno. I found I can fix this error by copying version 1.0 of the Wire library into my local sketch folder.

If fixed this by deleting this built-in library

/usr/share/arduino/libraries/SD

but then I received the error:

/usr/share/arduino/libraries/Robot_Control/ArduinoRobot.cpp:25:2: error: 'Serial1' was not declared in this scope
  Serial1.begin(9600);

so I deleted these libraries as well:

/usr/share/arduino/libraries/Robot_Control
/usr/share/arduino/libraries/Robot_Motor

which appear to be buggy in the 1.6 Arduino release. It's still unclear why any of these libraries were being used, since I wasn't including any of their files.

Try a later version of the IDE. Try making a completely new sketch (don't just delete things from your current one). It looks to me like it is trying to compile things it shouldn't.

  /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp

That doesn't seem relevant to your empty sketch.


Arduino UNO Rx/Tx speaks to itself I'm trying to make my chinese arduino (which use a chinese CH340G chip) speaks to itself via serial.
I have wired rx/tx together.

Then, I run the arduino IDE and go to the serial monitor.

When I write a message, the arduino should respond with the exact same message, right ? Actually, when I write a message, the arduino doesn't respond anything...

As Mikael Patel pointed out in his answer, you have set up a voltage divider. Mikael has thoughtfully provided a schematic of the clone Uno, where the relevant part is here:

Equivalent circuit

If you jumper together pins D0 and D1 (Rx and Tx) on the Uno effectively you have made this circuit:

Testing

If I set up this with a function generator, I get this result:

You can see that for a square-wave input of 0 to 5V, we only get an output of 2.16 to 5V.

What is LOW?

Now looking at the datasheet for the DC characteristics we see:

For an input to register as LOW it has to be no higher than 0.3 * Vcc = 0.3 * 5. Thus the voltage cannot be higher than 1.5V. Since we are measuring 2.16V, that will not count as a LOW.

Now admittedly that is for the Atmega328P and not the CH340G, but it will probably have similar characteristics.

I found a datasheet for the CH340G, and that shows even stricter requirements for a LOW signal:

Official Uno

Comparing to the official Uno circuit:

You will note there that the indicator LEDs are on a different circuit, and thus do not form a voltage divider.

The Maths

The clone Uno circuit above can be re-arranged like this:

Given that the LEDs have a voltage drop of 1.86V (measured in practice, and about right for the red LEDs I am using) then effectively we have the resistors R1 and R2 connected to 3.14V.

Since they are in parallel they are effectively 500 ohms.

Now using the formula for voltage dividers:

1000 / (1000 + 500) * (5 - 1.86) = 2.09V

This is close enough to the observed result. I didn't check each resistor to make sure it was exactly in spec.

I don't think R4 affects the results because it is effectively "floating".

the capacitor on pin 4 is connected to GND not to +5V