My Arduino isn't showing up on my computer. What should I do?

Linux

Getting Arduino and Arduino-like boards working properly under Linux can be a troublesome task if you are not familiar with how Linux works.

So I am going to introduce you to some of the basic tools you will need to work out why your board isn’t working as you’d like it to work.

The majority of problems a new user is faced with boil down to one simple thing: permissions. A normal user doesn’t, by default, have permission to talk to much in the way of hardware. That include serial ports and USB serial emulation ports (FTDI, etc). Fortunately granting permission to your user to access the serial ports is a simple matter, and one that you should always do by default to make life much simpler for you. This is done through a Linux permission facility called groups. A group is a name given to a collection of users, files, devices etc., that go together. Permissions can be granted on files to the group that it belongs to, and users that are in that group can access those files. On Linux most devices are just files.

The serial ports are all in the default group dialout, but your normal user isn’t. So you need to add your user to that group. Only root has the permission to do that, so use sudo to execute the commands as root. If you don’t have access to root through sudo or some other means then you will have to seek the assistance of an administrator who does have permission.

First add your user (you’re called fred, right?) to the dialout group:

$ sudo usermod -a -G dialout fred

The “-a” is of vital importance. That says “Add the user to these groups”. Without it you have “Set the user’s groups to be this list”. If you omit the “-a” by accident you will remove your user from any other groups before setting them to be in the dialout group. That means you will never be able to run sudo again. So be sure not to miss that one out, eh?

Now that has only changed the configuration files (/etc/groups in this case) and the change hasn’t actually had any effect yet. The groups are only set when you log in to the computer, so you will either need to log out and back in again or (a more definite solution, especially if you have auto-login turned on) reboot the computer.

Now you should be in the dialout group:

(before)

$ id
uid=1000(fred) gid=1000(fred) groups=1000(fred),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)

(after)

$ id
uid=1000(fred) gid=1000(fred) groups=1000(fred),4(adm),20(dialout),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)

Now try it, see if that has got you working.

Next step, if that doesn’t fix your problems, is to see if the computer knows about the Arduino. First look to see if there is a device file for the Arduino and if it has the right permissions:

$ ls -l /dev/ttyACM* /dev/ttyUSB*
ls: cannot access '/dev/ttyUSB*': No such file or directory
crw-rw---- 1 root dialout 166, 0 Aug 24 11:05 /dev/ttyACM0

Don’t worry about the “cannot access…” message unless you get two of them. There are two sets of device names that the Arduino could be under depending on which type it is. Genuine UNO and similar boards (the ones with the ATMega16U2 chip as the USB interface) are /dev/ttyACM*. Clones using the CH340G, and FT232 based boards appear as /dev/ttyUSB*. We just asked for both there, so it complained when it couldn’t find any entries for one of the types. Which is fair enough. If you get:

$ ls -l /dev/ttyACM* /dev/ttyUSB*
ls: cannot access '/dev/ttyACM*': No such file or directory
ls: cannot access '/dev/ttyUSB*': No such file or directory

however, then worry. That can’t find anything at all. The computer doesn’t know the Arduino exists.

One thing to check is the permissions on the files that have been listed above. You see the word “dialout” in the list? That’s the group that the device belongs to, and it should match the group you added yourself to earlier. There are times when it may say “tty” instead. This is because some other program has grabbed the device and is using it to allow remote access to the computer through that serial port. For that you need to make sure that there are no agetty processes using that port. How you do that is very much down to your version of Linux. Modern Debian based systems (such as Debian Jessie and Ubuntu) use systemd to manage it. You can examine what is running on your system using

$ systemctl status

That returns a tree of all the services that your system is running. Look through that list to see if there are any “serial-getty” services running. If there are you should remove them:

$ sudo systemctl stop serial-getty@ttyACM0
$ sudo systemctl disable serial-getty@ttyACM0

While you’re there look through the list for another troublesome member: ModemManager. This is a program used to dial out to the internet through old-fashioned modems (you know, the kind that go beep beep beep squark squeek squark ) or USB DSL modems (that no one uses any more, we’re all wireless now. Remember the old green “frog” modem from way back when…?). That has a habit of grabbing a serial port as soon as it appears and trying to configure a modem attached to it. While that’s happening nothing else can access the serial port. It’s especially a problem with boards like the Arduino Leonardno or chipKIT Lenny which create a new serial port when they enter programming mode. So unless you really need the functionality that ModemManager provides you should just remove it:

$ sudo apt-get remove modemmanager
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED
modemmanager
0 to upgrade, 0 to newly install, 1 to remove and 138 not to upgrade.
After this operation, 2,826 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 180827 files and directories currently installed.)
Removing modemmanager (1.4.12-1ubuntu1) ...
Created symlink from /run/systemd/system/ModemManager.service to /dev/null.
Removed symlink /run/systemd/system/ModemManager.service.
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for hicolor-icon-theme (0.15-0ubuntu1) ...
Processing triggers for dbus (1.10.6-1ubuntu3) ...

Another useful tool is lsusb. This lists the USB devices that are connected to your computer. You should find your Arduino listed there. This is especially useful for boards that don’t present a serial port for programming, but we’ll cover those in more depth a little later on.

$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 002: ID 80ee:0021 VirtualBox USB Tablet
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

Nothing much on this computer. Well, actually I am using a virtual machine for this, as you can see by the VirtualBox USB Tablet entry. But let’s connect my Arduino UNO:

$ lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 004: ID 2341:0001 Arduino SA Uno (CDC ACM)
Bus 002 Device 002: ID 80ee:0021 VirtualBox USB Tablet
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

So we know that the operating system has identified it. You can find out lots more information about it if you so desire, with:

$ lsusb -v -d 2341:0001

That gives you all the device descriptors for the device. Tells you all you could ever want to know about the information the board sends to the computer when it is connected.

Another useful tool is dmesg. This is the system message log viewer and can be used to find out exactly what is going on with your computer.  It has a useful “keep running” mode specified by the flag -w. I like to run dmesg and then press return a few times to create a breakpoint in the listing, then plug in the board I am diagnosing to see just what the messages are that pertain to that board:

$ dmesg -w
[ 0.000000] Initializing cgroup subsys cpuset
[ 0.000000] Initializing cgroup subsys cpu
[ 0.000000] Initializing cgroup subsys cpuacct
[ 0.000000] Linux version 4.4.0-24-generic (buildd@lgw01-12) (gcc version 5.3
... lots of stuff spools past ...
[ 19.425870] NFS: Registering the id_resolver key type
[ 19.425883] Key type id_resolver registered
[ 19.425885] Key type id_legacy registered
<press return a few times>

<connect Arduino>
[ 131.232511] usb 2-2: new full-speed USB device number 3 using ohci-pci
[ 131.519307] usb 2-2: New USB device found, idVendor=2341, idProduct=0001
[ 131.519312] usb 2-2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 131.519315] usb 2-2: Product: Arduino Uno
[ 131.519317] usb 2-2: Manufacturer: Arduino (www.arduino.cc)
[ 131.519319] usb 2-2: SerialNumber: 64934333235351B002E0
[ 131.605485] cdc_acm 2-2:1.0: ttyACM0: USB ACM device
[ 131.613792] usbcore: registered new interface driver cdc_acm
[ 131.613796] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

Press CTRL+C to terminate the listing.

If nothing appears when you connect the Arduino then there is something fatally wrong. My money is either on a faulty cable (some cheap cables on eBay only have power wires and no data wires) or the Arduino itself is completely dead.

More likely though you get error messages. I can’t replicate them right now (I don’t have a faulty Arduino) but they usually pertain to things like “device not accepting address” and “Error -71”. This is usually caused by bad USB communication. It may, again, be a faulty cable, or it may be that the USB interface chip is not working right. Maybe the crystal has drifted and it’s not running at precisely the right frequency. Maybe it’s a cheap CH340 chip that has failed. Maybe the firmware on the ATMega16U2 has become corrupted.

If all that checks out fine so far and you still can’t upload a sketch there may be something even more fundamentally wrong with your Ardunio board. Maybe it’s time to look to see if there is actually any communication happening. I find the program minicom invaluable, although you could use the ghastly Serial Monitor in the Arduino IDE.

First you need to disable the main chip on your Arduino. You can do this simply by connecting the RESET pin to GND with a piece of wire. Or you can hold the RESET button down, but that means you’re then typing one-handed. That stops the main chip from interfering in any way with the serial communications while you’re testing it. It can also prevent any damage to the chip while testing.

The second step is to connect the TX and RX pins together (pins 0 and 1 usually) with another piece of wire. You are now in what is known as a loopback mode. Any serial data you send to the board should be sent straight back to where it came from. So now fire up minicom and try it out (you will need to install it first of course with sudo apt-get install minicom).

$ minicom -D /dev/ttyACM0 -b 115200

Of course replace the /dev/ttyACM0 with the real device name for your board. The -b 115200 is the baud rate, though that is pretty much irrelevant since we’re not actively communicating with an external device.

Now you should be able to type some gibberish and get some gibberish back. If you do then communication is working fine, and the problem most likely lies within the target MCU – maybe the bootloader has become corrupted and needs re-flashing, or the chip has died.

CTRL+A, X gets you back out of minicom again.

If you didn’t get your gibberish back, or you got back different gibberish than you sent, then there is definitely something up with the serial communications. The main culprit is, again, the USB interface chip.

All this, of course, has been focusing on the traditional Arduino style interface with a USB serial port of some form. Not all boards give you that though. Some, such as the Launchpad boards, use a hardware programmer on the board, and that doesn’t always give a serial port – certainly the programming isn’t done through the serial port. To gain access to those (again by default you don’t have permission to access the low-level devices) you have to get deeper into the operating system.

For these you need to make modifications to the configuration of a system called udev. This is a management system for the devices on your computer and is used to control what happens to them when they are plugged in. One of the things you can do is set the permissions on that device so people can actually access it.

The system is configured by a set of rules in “rules files”. These are stored in /etc/udev/rules.d and there should already be a few in there for other purposes. You will need to, as root, create a new file to put your rules in.

$ sudo nano /etc/udev/rules.d/50-boards.rules

The most important thing to know is the VID and PID (Vendor ID and Product ID) of your board. You can get that from lsusb as above (it’s the vvvv:pppp bit – v = VID, p = PID). You can then feed that into a simple rule, such as:

ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="0033", MODE="0660", GROUP="plugdev"

There we are matching a vendor (04d8 = Microchip) and product (0033 = PICkit2) and assigning it to the group plugdev (make sure you are in that group – default users should be already) and allowing the group members read and write access to it (MODE="0660"). Save that file and restart udev for the changes to take effect (or reboot your computer if you like):

$ sudo /etc/init.d/udev restart

Now plug the device in and you should have permission to access it.


Sending Arduino data to MySQL using phpMyAdmin and XAMPP using Windows10

You should write the PC IP, for example: 192.168.1.53, because 127.0.0.1 is the IP used only for phpmyadmin and the database inside your computer.


Why I get error on string concatination?

The operators of the class String apply only for an instance of String. In your expression you concatenate two c-strings "POST" + "\n"


Connector X1 has the pins you want.

ICSP is shared with the SPI pins. Wire those to your ICE in the same way as you wire the SPI pins of the ICSP header on a normal Arduino to an ICE.


Code for determining beats per min when timing a wooden clock

If the accuracy you require is about 1%, that should be doable with any
Arduino. Much higher accuracies would be hard to achieve because most
Arduinos are clocked off a ceramic resonator, and these have a frequency
tolerance of about 0.5%.

Given that your signal is very slow, the simplest approach may be to
poll the pin connected to the sensor and record the time (using
micros()) of the low → high transition. Then you can compute the
beat frequency as the inverse of the time between consecutive
transitions.

There is, however, the possibility that the sensor is not exactly in
the middle of the swing. Then, for better accuracy, I would measure the
time taken by two beats, i.e. a full swing. This way the pssible
asymmetry will not affect the accuracy.


Try updating the java. Also check whether the device manager shows the USB serial port without any yellow warning sign on it.
If there is a current short in the usb port that specific port will be off for safety, restarting the computer should resolve that problem.


How to use an Arduino Uno + Keyboard Firmware to make a "N Key Rollover" Game Pad

You don't want to send random keys do you?

Well consider using the code below as your base.
It's using Port Manipulation to read the buttons (Digital 0 to 7).

void setup()
{
  Serial.begin(9600);//Start serial connection.
  DDRD = 0b00000000; //Set Data Direction Register of port D to inputs (attach keys to digital pins 0to7;
  delay(200); //Misc delay.
}

void loop()
{
  Serial.write(PIND, 8);    // Send states of PORTD (digital 0 to 7)
}

I strongly suggest you use pull-down/up resistors on the buttons also.
Adjust your code to the amount of keys you're using, or pull the pins low if not used. To avoid receiving random/floating pin values.


The behavior you describe is symptomatic of a floating input.

I guess you have directly wired your buttons between input pins and +5V (or GND, that won't change the observed behavior).

The problem is when you don't push the button, the input pin is left floating and can be read as HIGH or LOW based on strange factors.

The solution to this is to use pullup (if you connect the other side of the button to GND) or pulldown (if your button is connected to +5V) resistors.

The following image, off the arduino website, shows such a circuit with a pulldown resistor, i.e. connect the switch to +5V and the resistor to GND:

An even simpler way is to connect the buttons to GND and use pinMode(pin, INPUT_PULLUP); in setup().


ESP8266 Software serial to ATmega 328 is not properly working

Don't use SoftwareSerial in esp8266. Connect the 328p's SoftwareSerial pins to Serial interface pins of the esp8266. ESP8266 has second Serial interface named Serial1. It has only TX (io 2), but it is enough for debug prints.

To change the firmware or sketch in esp8266 you can use ArduinoOTA library, but you should be ready to disconnect the esp8266 Serial pins from the 328p and use them for Serial upload if the OTA upload fails.

You should use logic level converter from 5 V to 3.3 V to protect the esp8266 RX pin.


The straightforward solution:

const size_t DATA_DIM16 = 84;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
  unsigned long  milli[DATA_DIM16]; // time in milliseconds
  unsigned long padding;   // pad to 512 bytes
};

Now, I suggest to think again about your requirements. Do you really
need a 32-bit timestamp for every data point? If they are closely spaced
in time, a 16-bit, or even 8-bit timestamp should be enough. You could
put a full 32-bit timestamp at the beginning of each block, then only
8-bit timestamps for every data point. This would allow you to store
168 samples per block. You could even pack a 6-bit timestamp with
the data sample into an uint16_t, and have 252 samples per block.


Can the official arduino GSM shield library be changed to work with hardware serial on mega

Before we start, note that it might not be the right pinout for the GSM shield to use a hardware serial port on the Mega. Beware of some nasty wiring.

Poking around on Github, I found this is the directory for the GSM library. Ladies and gentlemen, it's time to break something important get our hands dirty! Draw your  chairs close for a tale of touching code you shouldn't touch!

Click on the src folder to open it up. When I first opened this up, I was somewhat scared by the number of files. However, I had a plan:

Find the name of the SoftwareSerial instance. I'm guessing that they would use only one object to do this to prevent redundancy. In addition, I'm going to guess that most serial data is handles though a single file, but I'll have to confirm this.
Remove instances of the SoftwareSerial Object.
Clean up any remaining issues with the "port"

After more poking around, I noticed that the library actually uses a unique version of the SoftwareSerial library, so it will be even harder to do this. Yay us! On the upside, we know exactly what code to replace. Fasten your seatbelts, this is about to get pretty nasty.

Okay, take a step back here and figure out what we want to modify. First of all, it's a terrible idea to modify the libraries directly in the directory that the Arduino IDE uses.

So, if you were to make a copy from the src folder for the GSM library into the Arduino "libraries" folder, it wouldn't be enough. The Arduino IDE would get confused when there would be two identical header files to use. You will need to rename the main header file and use just that one instead to include into your projects. In addition, most of the files in the library probably reference that file, so make sure to rename any references within the library to that one file. A quick CTRL + SHIFT + F on the Atom text editor will search the entire project I'm working on. I'm not entirely sure if a folder name would mess up the Arduino IDE, but it'd be a good idea to rename the folder to whatever your library is called, at least for readability purposes.

Before we continue, let's make sure that the library still compiles without us playing with the code. Import the new library into a basic GSM example sketch and see if it compiles and works normally.

It compiles? Great. Let's go on!

The file that does serial is the GSM3SoftSerial.cpp file. Without actually porting it, I can't give you a ton of advice here. Look through and see when variables are created, used, and modified. If you're not sure, I'm in chat sometimes: feel free to ask there on minor questions and ping me with @AnnonomusPenguin or leave a comment on this post.

I'd also advise to leave everything in there that you're not sure of, make sure it works with hardware serial, and line by line start removing that variable and see if anything breaks. A great too for this would be to use a tool like Git/Github (or other version control software) to help you revert changes that broke something or to see, overall, what you've changed.

So, after replacing the code inside the functions (finalWrite, the ISRs, and the begin/clear seem like the ones you should touch), compile the code and see if it works!


Interfacing hardware is easier with the Arduino: more available I/O pins
capable of sourcing and sinking more current, 5 V I/O, analog
inputs, very predictable timings, etc. The Raspberry, on the other hand,
is a real computer with a real OS, has a lot more computing power
and memory, has Internet connectivity, can easily run “standard” web
servers like Apache or nginx... or mostly any Linux software for that
matter.

Some projects can benefit from using both. E.g. if you want to make a
web interface for some low-level hardware sensors.


Could someone help me with an Arduino Uno program?

Mansor Its not clear from your post that this is just a simulated system, not a real system to save peoples lives and I think people wanted to point that out for you, because the parts you are listing hardly fall into the safety critical category.  Plus if you are asking this level of question the chances are you software won't be very safe either (no offence intended), after 30 years of writing software I'm not sure I could write code good enough to trust peoples lives with!

Find libraries for each of the sensors you have listed and get them working one by one.  Then start adding them one at a time to your setup and loop functions.
For the SIM800 you are going to need at least 3Amps, so look for a 5A(?) wall wart.  You will need to talk to it over serial, software Serial works most of the time I think (never tried it, just from what I have read on here).
LEDs should be easy, just get them the right way round and remember the resistors.  All you need is a Digital pin set to output and then send high and low to it. (Again do it as a separate program and then integrate it).

This is supposed to be a sight for solving problems, and unless you have some code and a circuit diagram showing your problem you can get a negative response.  So tonight get the first sensor running or post why it didn't work (and your code) and people will help.


Arduino code to control 4 led's from 4 buttons

It is likely you have connected the switches incorrectly.  Normally, people use single poll single throw (SPST) switches connected to 5 volts and the input pin of the Arduino.  This will pull the input pin to 5 volts when the switch is closed.  Then, to pull the input pin to ground when the switch is open, people add a large resistor between ground and the same processor pin.

Almost any large resistor will work here.  Consider using 10K ohms (10,000 ohms) or there abouts.

Of course, if you are using a 3 volt Arduino, do not connect the switch to a 5 volt source.  Instead connect it to a 3 volt source.

Alternatively, a pull up resistor inside the processor, if available, can be activated.  Look at this arduino.cc web page. There this sample code shows how to activate the processor's pull up on pin number 2:

pinMode(2,INPUT_PULLUP);

Because not all processors have a "pull up" feature on all input pins & because the range of internal to the processor pull up resistances can vary (for example 50,000 ohms to 150,000 ohms), it may be more useful and universal to use an external pull up resistor.


How to wire an analog IR sensor for digital input?

Near the bottom of:

https://learn.sparkfun.com/tutorials/qrd1114-optical-detector-hookup-guide

shows a graph of the voltage for a white surface and a black surface. If I understand your question correctly, I think you can get your desired results by controlling the distance between the sensor and the surface. For example, at 0.5mm white reads about 0.1V while black reads about 3.2V

A 330Ω current-limiting resistor and a 10kΩ pull-up resistor were used in their circuit.

Hope this helps.


I think your problem is in wiring. Ethernet shield is using SPI communication, it requires pins: SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). Those pins must be left for the Ethernet shield. Information is from Arduino Uno description.

Does your Arduino communicates with you after you plug-in Tinkerkit? If not, maybe you have a short in Tinkerkit shield.


Arduino Mega 2650 + Matlab/Simulink - Serial decimation

I don't think there will be a problem in this.

I do not understand exactly why you can only send signals every 0.010 s.

The board runs at 16 MHz, that's 16 million cycles per second, however, every 'instruction' normally takes many cycles (let along parsed C/Arduino language).

What you can do is to copy the read information into an array and use it later.

Keep in mind that the serial buffer is 64 bytes. If more is read, data will be overwritten. However, if you copy the buffer into your own (larger) buffer it might help. Also you can change the 64 bytes (it's somewhere in the Serial library).

The buffer works (afaik) with a sort of circular buffer, meaning it can store 64 bytes maximum 'unprocessed' bytes. So you don't have to wait until the buffer is full before processing (actually, this is not even the best method). You can process it as long as there are bytes available.

The pseudo code can be as follows:

lastSignalSent = millis(); // last time signals sent

void loop()
{
    while serial bytes available
    {
        process bytes
    }

    if (millis() - lastSignalSent > 10) // More than 10 ms ago
    {
        Send signals
         lastSignalSent = millis();
    }
}

This assumes the serial byte processing can be done faster than they arrive, but if not, you run into problems anyway, since the serial buffer (of only 64 bytes) will be full too fast.


If OSC is Open Sound Control, there is a library for it at https://github.com/CNMAT/OSC

Physically, you could hook a potentiometer or two to analog inputs and drive it like the sample in http://cnmat.berkeley.edu/oscuino

The code below is copied from that site, with a couple untested changes to not use the USB serial, and appears to use an analogread to sens some sort of message to the OSC system.

#include <OSCMessage.h>

//Teensy and Leonardo variants have special USB serial
//#if defined(CORE_TEENSY)|| defined(__AVR_ATmega32U4__)
//#include <SLIPEncodedUSBSerial.h>
//SLIPEncodedUSBSerial SLIPSerial(Serial);
//#else
// any hardware serial port
#include <SLIPEncodedSerial.h>
SLIPEncodedSerial SLIPSerial(Serial1);
#endif

void setup() {
  //begin SLIPSerial just like Serial
  Serial.begin(38400);
  //while(!Serial)
  //  ; //Leonardo "feature"
}

void loop(){
  //the message wants an OSC address as first argument
  OSCMessage msg("/analog/0");
  msg.add(analogRead(0));
  msg.send(SLIPSerial); // send the bytes to the SLIP stream
  SLIPSerial.endPacket(); // mark the end of the OSC Packet
  msg.empty(); // free space occupied by message

  delay(20);
}

If DMX is https://en.wikipedia.org/wiki/DMX512 then...there is another library at http://www.mathertel.de/Arduino/DMXSerial.aspx


cannot open source file "WProgram.h" in VSCode

I landed here in the same position as you, and after researching the comments mentioning -DARDUINO=10813 and some more googling I found: https://github.com/microsoft/vscode-arduino/issues/1148
This led me to adding one more line to defines in my c_cpp_properties.json
and this also removed the squiggly!
{
    "configurations": [
        {

            ...

            "defines": [
                "USBCON",
                "ARDUINO=10813"
            ],

            ...

        }
    ],

}```


The Uno cannot run python.

The Bridge library is intended for communication either between the two MCUs of the Yun, or between an Arduino board and the MCU on a Yun shield.

It is literally a Bridge between the two systems - Arduino and the Linux system in the Yun.


Logging data to SD card from software serial

use the C as the line start indicator. if received char is 'C' then do a file.println(); example with output to Serial

#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9);

void setup() {
    Serial.begin(9600);
    mySerial.begin(9600);
    mySerial.print("C");
}

void loop() {
 if (mySerial.available()) {
   char c = mySerial.read();
   if (c == 'C') {
     Serial.println();
   }
   Serial.write(c);
 }
}


old topic, but since I'm having the same issues I'll share what I found.

chipSelect is usually 10 for arduino uno, some exemples have other pin setted.

also I found a guy claiming he fixed his issues setting after

pinMode(SS, OUTPUT);
digitalWrite(SS, HIGH);


Purpose of extra pin slots on Pololu DRV8835

A and B are the same as the A and B screw terminals.

The pins on the right, if you use your eyes and follow the traces, are the same as the pins that plug into the Arduino. I guess they are intended to be used to isolate the existing pin assignments (cut tracks on the underside between adjacent holes with a knife) and solder wires to other pins so you aren't limited to just using the pins they have assigned.


Do I need to use a resistor if I am using a potentiometer to control an LED's brightness?

Without a good quality picture of your setup or some schematics, it's hard to tell what's going on, but from your description, what you're doing is potentially harmful for the LED and the output pin D11.

Yes, LEDs almost always need series resistors to limit their current. They don't limit currents and will burn if you don't do it for them.

If you had the pot in series with the LED, which seems to be what you think is going on, you'd still need a series resistance so that when the pot is all the way to one side, effectively behaving like a 0Ω resistor or a short, you'd still be limiting the current with the 2nd resistor. One would usually use Ohm's Law to calculate that 2nd resistance so that it lets the maximum current the LED can take when the pot is at 0Ω position, usually 20mA for common LEDs.

But that's not how your circuit seems to be wired. The pot is indirectly controlling the LED through an analog input and a PWM output via MCU. So it's not limiting the LED current, in the traditional sense. The pot seems to be wired between 5V and GND with the middle lead (the cursor) hooked up to the analog input A0. That's a variable voltage divider configuration that let's you select a continuous voltage between 0 and 5V that is in turn converted to a value between 0 and 1023 by the MCU ADC (Analog to Digital Converter) - that's the result of the analogRead() call.

That value is then fed to a PWM analog output, through the analogWrite() call, that will output a square wave to the LED. The relative position of the pot will determine the duty cycle of the PWM, i.e., how long the square wave is HIGH or LOW. The problem here is that this circuit where the LED is wired should have its own series current limiting resistance.

To me, if you didn't burn the LED or the D11 pin yet, is pure luck. If you were to turn the pot all the way to maximum brightness (don't do it), the PWM output would act like a digital output put in HIGH level (5V continuously), and without a current limiting resistor, the D11 pin would exceed it's 40mA absolute maximum source current and burn. Unless there's another factor limiting the current that I don't know of, that is.

There are some exceptional cases in which you can control the LED voltage closely so you don't need to limit the current (multiplexing, constant-current supply etc.), but these are really advanced configurations for us newbies. So, from know on, do it like I do it: ALWAYS put a series resistor, until you become familiar with these advanced configurations.

Finally, below are some links that you may find helpful about the topic:

SparkFun Tutorial on LED Current Limiting Resistors
WikiPedia Article about LED series resistors


Fingerprint sensor code won't work correctly with LCD 16x2

You have pins 2 and 3 used by both the LCD and the SoftwareSerial used for the fingerprint sensor.

Use different pins for one or the other.

Worth looking at the Software Serial reference to understand more about how it works.


I have reformatted your code and the problem becomes very clear (to me).

void loop()
{
  while(Serial.available()>0)
  {
    num= Serial.parseInt();
    Serial.print(num);
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

You are getting some input from the user and then setting the servo to that point.

When there is no data in the Serial buffer you set the servo to the value of write and delay 15ms before checking the buffer again.
I think what you want to do is if there is no data then you don't want to change the Servo position.  In short move the servo1.write(num); line inside the } of the while loop.

Now much more importantly the first time you enter loop() you won't have any data there so the servo will be moved to the number held in num which is? Undefined, it could be anything at all from 0 to 4294967295 and if its the upper end of that it will take a while for the servo to get there, it might seem like all it does is spin.  ALWAYS INITIALIES VARIABLES BEFORE USE :)

A minor point, your while loop could be, probably should be an if statement.  That will prevent a cat sitting on the keyboard and blocking the servo movement.


How to get rid of low quality sound out from DFPlayer plus amplifier?

The DFPlayer already has a 3W amplifier on it, so you can connect a speaker directly to the DFPlayer. There is no need for an extra amplifier.
If you do connect an extra amplifier to the DPlayer, and turn the volume of the DFPlayer up too far, the input of the second amplifier will clip and it won't sound good. Also, the output of the DFPlayer is probably from a class-D amplifier designed to be connected directly to a speaker; it won't play nice with other amplifiers.
You should try how the DFPlayer sounds when you connect a speaker directly to it. The 0.5W speaker you have is not a good fit; it can't handle the power of the DFPlayer's amplifier.
A 3W (or more), 8Ω speaker would be good for this if you want to use the maximum power the DFPlayer can deliver. According to most publications on the interwebs a 2W, 8Ω speaker will also do, but I would be careful with turning the volume all the way up.
Note that the DFPlayer can pull a fair bit of current (about 25mA in standby, and in the order of 200mA when playing) and it needs a power supply that can deliver that.


As u mentioned that u want to move your GPS far away .... but frankly speaking Bluetooth modules will not work for far away (I have used one of them , it has some limitations and restrictions) , they are good only for in the range of room only like 10 meters to 15 meters maximum . and in case any obstacle comes between the bluetooth devices , your device will lose its signals !
So better use SIM900A (it is wireless) , it cost a bit harder than bluetooth , but much better than bluetooth !


How come my code does not wait for a specific time before going into an if statement?

I added some more debugging, and I think I have your issues detected.

Amended code:

#include <Servo.h>
#define trig 22
#define echo 24
long duration;
boolean turned130 = false;
int cm50, cm, cm130;
Servo servo;
boolean checkRight = false;
boolean mainPing = true;
unsigned long counter;
unsigned long servoTimer = millis();
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(echo, INPUT);
  pinMode(trig, OUTPUT);
  servo.attach(12);
  servo.write(90);
  delay(2000);
}

void loop() {
  counter = millis(); //my timer
  if (((counter - servoTimer) >= 250) && mainPing) { //distance measured 4 times a second
    Serial.print ("Doing ping at time ");
    Serial.println (counter);
    ping();
    cm = duration / 29.1 / 2;
    Serial.println(cm);
    servoTimer = counter; //this if statement works fine
  }
  if ((cm < 30) && mainPing) {

    mainPing = false; //makes the 90 degree ping and this if statement unable to run
    checkRight = true;//enables next if statement to run
    servoTimer = millis();
    servo.write(130);
    cm = 30; //so that this if statement does not get called again until distance is obtained
    Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called
  }
  if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes
    Serial.print ("counter = ");
    Serial.println (counter);
    Serial.print ("servoTimer = ");
    Serial.println (servoTimer);
    checkRight = false;
    ping();
    cm130 = duration / 29.1 / 2;
    mainPing = true;//enable to other 2 if statements to run
    servoTimer = millis();
    Serial.print ("cm130 = ");
    Serial.println(cm130);
    servo.write(90);//turn motor back
    Serial.println("Inside other loop");//for debugging
  }
  delay(2);
}

void ping() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
}

With no server (or anything) attached I get this output:

Doing ping at time 1999
0
Inside less than 30 loop
counter = 1999
servoTimer = 2693
cm130 = 0
Inside other loop

First note that servoTimer is somewhat higher than counter because the pulseIn function takes a while to execute (times out after 1 second allegedly, although that was less than a second).

Now we come to the problem "if" statement.

  if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes

That can't be right, eh? counter is 1999 and servoTimer is 2693, and there is not 2000 difference. However you are doing the maths the other way:

counter - servoTimer =  1999 - 2693 = -694

Since we are using unsigned long, it cannot hold negative numbers so the result of the subtraction is 4294966602.

That is much larger than 2000, so the "if" branch is taken.


Can any Arduino Due pin be used for PWM?

According to the manual:

"The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs."

https://www.arduino.cc/en/Reference/AnalogWrite


The Arduino website has a list of LCD displays and link with more information about each one. For controlling the display you may want to look at Arduino's LiquidCrystal Library.

If you are looking for a step by step guide for using a lcd display with the Arduino, there is a nice guide on Adafruit.


why can Arduino variables of int type contain a value such as A2

You are correct. A2 is just a number (like everything in a microcontroller). We can look at the corresponding part in pins_arduino.h (a file defined in the variants folder of your used core and of your used board, for me: ~/arduino-1.8.9/hardware/arduino/avr/variants/standard/pins_arduino.h):
#define PIN_A0   (14)
#define PIN_A1   (15)
#define PIN_A2   (16)
#define PIN_A3   (17)
#define PIN_A4   (18)
#define PIN_A5   (19)
#define PIN_A6   (20)
#define PIN_A7   (21)

static const uint8_t A0 = PIN_A0;
static const uint8_t A1 = PIN_A1;
static const uint8_t A2 = PIN_A2;
static const uint8_t A3 = PIN_A3;
static const uint8_t A4 = PIN_A4;
static const uint8_t A5 = PIN_A5;
static const uint8_t A6 = PIN_A6;
static const uint8_t A7 = PIN_A7;

So here the core first defines the macro PIN_A2 as 16 (which is the pin number of that pin) and then it declares a static constant A2 with PIN_A2. So A2 is just the pin number of that pin, 16 in this case.
This is done to make the code more readable. The analog pins are marked with A0 to A7, so it is good to also be able to refer to that with these names. If you wanted, you could also use the pin number directly. But that wouldn't be as easy to read.


Android Studio project for Redbearlab BLE Shield apps

It was much simpler than expected to put together the Android Studio projects. They are on GitHub now.

Note that the apps built from source are actually different from the ones published by Redbearlabs on the Play Store. On top of that, the chat app is not working.


Arduino components for smartening my current doorbell

Because you asked for recommendations I would like to recomment the solution I have at home for some years:

Auerswald doorbell speaker sorry for german product description - the a/b is important so that you could use it as analoge phone on 2! You also need a transformator as you should already have for your doorbell.
AVM Fritzbox router
Doorbell or not ....
Two Sipgate (or similar) VOIP accounts

After configuring your fritzbox router and your android phone, your phone will ring and you could talk to the person in front of your door werever you are on this planet ;-)

Just my recommendation....


This is not a simple chip to use.  These parts of the data sheet may help you understand what is happening.  It is internally an analog device and needs clean power.  I would highly recommend you download the Allegro data sheet, it has a lot of information that will help you.  Below is a short section of the data sheet, The first paragraph should give you a hint that the output voltage will be about 2.5V with a 5V unipolar power supply.

"Quiescent output voltage (VIOUT(Q)). The output of the device
when the primary current is zero. For a unipolar supply voltage,
it nominally remains at VCC⁄ 2. Thus, VCC = 5 V translates into
VIOUT(Q) = 2.5 V. Variation in VIOUT(Q) can be attributed to the
resolution of the Allegro linear IC quiescent voltage trim and
thermal drift.

Electrical offset voltage (VOE). The deviation of the device output
from its ideal quiescent value of VCC / 2 due to nonmagnetic
causes. To convert this voltage to amperes, divide by the device
sensitivity, Sens.

Accuracy (ETOT). The accuracy represents the maximum deviation
of the actual output from its ideal value. This is also known
as the total output error. The accuracy is illustrated graphically in
the output voltage versus current chart at right."

I realize this does not answer your question but it does give you a good starting point to resolve your problem.  Hopefully you or a buddy has some analog experience, that will help a lot.  Oh Yes clean power supplies are imperative for this to work.


You could make the following changes to your code by making use of WifiClientSecure (which is already part of the ESP8266 Wifi library).

The tricky part is finding out the SHA1 fingerprint for your own MQTT server and hard coding it into the *fingerprint PROGMEM = "..."  part (for example by examining the certificate via a PC browser and copying the SHA1 fingerprint).

Alternatively, you could set the connection to setInsecure. This means that the connection will be encrypted but it will accept any server certificate without checking.

...
const char* mqttPassword = "pass";

WiFiClientSecure espClient;     // <-- Change #1: Secure connection to MQTT Server
PubSubClient client(espClient);

// Change #2: Set the SHA1 fingerprint for the connection -->
static const char *fingerprint PROGMEM = "44 14 9A 3F C3 E9 F1 F3 84 1A B4 9F B6 4D 19 8A B2 92 31 D6";
...
...
void setup() {
    ...
    setup_wifi();

    espClient.setFingerprint(fingerprint);   // <-- Change #3: Set the SHA1 fingerprint
    // Alternative: espClient.setInsecure;

    client.setServer(mqtt_server, 8883);  // <-- Change #4: Set the port number to 8883
    client.setCallback(callback);
 ...

Good luck!


the bootloader doens't listen on RX/TX3.
to start the bootloader reset is required
to communicate with the bootloader a serial programmer must have STK500 protocol or a telnet bridge for avrdude, which your NodeMCU sketch doesn't have

If your NodeMCU sketch has OTA, then the sketch could be updated to an avrdude telnet bridge. then reset would be needed to activate the bootloader. If your NodeMCU doesn't have a wire to Mega reset pin or you don't have a command in your Mega sketch to activate the reset, some serial overload of your Mega sketch could be a way.
But all this doesn't have an effect because the bootloader only listens at RX0


What are examples of large Arduino code bases and how are they organized?

Big projects are likely not developed with Arduino IDE. Arduino IDE was make for designers/inventors, not for programmers.

  Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed at students without a background in electronics and programming.

Source

Programmers will use a fully-fledged IDE which has many features a programmer needs on a daily basis, such as:

handling multiple files efficiently
allowing to create libraries instead of just setup() and loop()
code completion (suggestions as you type)
debugging (inspection and changing of variables at runtime)
refactoring (modifying the structure of your code without changing the behavior)
integrated version control (like Git / Github)

Such an IDE could be Eclipse with an Arduino Plugin or Atmel Studio and perhaps Visual Studio.

So, what do you need to look for? Don't look for .ino files. Instead, look for .h and .cpp code, just like other non-Arduino C++ code.

Some examples:

SPI: 297 lines
Wire: 453 lines
SoftwareSerial: 486 lines
I2S: 533 lines
USBHost: several files, up to 1600 lines


How can I exactly put my sensor at 4 Hz readings?

The difference between your first code and the second one is that the first one is blocking execution when it reaches the delay function, but the second code keeps running without being blocked.

Now your algorithm has a drawback, the loop may or may not reach the if condition exactly when the modulo is strictly equal to 0. So you may prefer to use something like :

unsigned long T = millis();

...

if( millis() - T >= 250 ) {
    ... // sensor stuff
    T = millis();
}

This idea is also presented in this article https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.

Another approach is to use Timers and Interrupts, but this is far more complicated (http://playground.arduino.cc/Code/Timer1).


Arduino Mega and gyroscope erroneous values

It is possible to use your sketch and get angle information. It is not very accurate and it drifts.

I started with your sketch, and improved it until I had the angle.
The Serial.println functions take time and they are printed too often. To measure the interval between the samples, I used millis.

This test is done with:

arduino M0 board (with 3.3v i2c bus)
gy-521 module with onboard voltage regulator, but no level shifter
vcc of the gy-521 module connected to 5v (because of the voltage regulator)

The arduino M0 is faster than the arduino mega or uno.

// test with arduino M0 board
#include <Wire.h>

#define SER SerialUSB    // 'Serial' for arduino Uno, 'SerialUSB' for Leonardo and Arduino M0

const int MPU = 0x68;   // I2C address of MPU

int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;

float pitch = 0.0;
float roll  = 0.0;
float yaw   = 0.0;

unsigned long previousMillisSample;
unsigned long previousMillisOutput;
const unsigned long intervalOutput = 500;  // half a second update to serial monitor

void setup() {
  SER.begin(9600);
  while(!SER);         // wait for serial monitor to open for Leonardo and M0
  SER.println("Angle from gyro");

  Wire.begin();

  Wire.beginTransmission(MPU);
  Wire.write(0x6B); //power management register 1
  Wire.write(0);
  Wire.endTransmission();

  // get the values of the gyro and use them as offset
  GetXYZ(x_offset, y_offset, z_offset);
}

void loop() {

  int16_t GyX;
  int16_t GyY;
  int16_t GyZ;

  GetXYZ(GyX, GyY, GyZ);

  unsigned long currentMillisSample = millis();  // time in millis when this sample is taken

  // remove offset
  GyX -= x_offset;
  GyY -= y_offset;
  GyZ -= z_offset;

  float v_pitch = float(GyX) / 131.0;    // convert to float and calculate degrees
  float v_roll  = float(GyY) / 131.0;
  float v_yaw   = float(GyZ) / 131.0;

  // calculate time in milliseconds between previous and current sample
  unsigned long t = currentMillisSample - previousMillisSample;

  // time in seconds as a float
  float float_t = float(t) / 1000.0;

  // adjust the number of degrees during the time
  float a_pitch = v_pitch * float_t;
  float a_roll  = v_roll  * float_t;
  float a_yaw   = v_yaw   * float_t;

  // remember the time in millis when the sample was taken for the next time
  previousMillisSample = currentMillisSample;

  pitch += a_pitch;
  roll  += a_roll;
  yaw   += a_yaw;

  // Once in a while, print the output
  if(millis() - previousMillisOutput >= intervalOutput) {
    previousMillisOutput = millis();

    SER.print("pitch = ");
    SER.print(pitch);
    SER.print(" | roll = ");
    SER.print(roll);
    SER.print(" | yaw = ");
    SER.println(yaw);
  }
}

void GetXYZ( int16_t &x, int16_t &y, int16_t &z) {
  // Get the gyro values
  Wire.beginTransmission(MPU);
  Wire.write(0x43);     // first register of gyro values
  Wire.endTransmission(false);

  Wire.requestFrom(MPU,6);
  x = Wire.read() << 8 | Wire.read();
  y = Wire.read() << 8 | Wire.read();
  z = Wire.read() << 8 | Wire.read();
}

Can you try this sketch? It drifts between 10 and 60 degrees per 5 minutes. That is a lot. I think the sensor is better than that, so that means the sketch is far from perfect.


Arduino Uno - What can I make with just the base board

Well,

Your question is very broad. But the Arduino essentially needs controlling gadgteers to make things easy ( and funny ).

However if you know a bit of electronics, then you may be able to use the IN/OUT analog ports and build other interfaces to control, for example the lights of your home, or even better. You can measure and control priate things should be linked. Increasing the power of your home.

If you have interest in cars, then you can perform to connect the on-board computer of your car to the Arduino, like this.

Well, there are numerous ideas, none of these I'm saying is new and there are even libraries ready to be used in these segments mentioned above.

Regards,
Andrew Paes


Control relay with both Arduino and DAQ at the same time

I guess, that you drive the digital pin of the Arduino directly with digitalWrite() for HIGH and LOW and that the DAQ does the same (I didn't researched this).

In that case your circuit is dangerous for the devices. As long, as they both output the same, everything is ok. But take the case, that the Arduino is driving it's pin HIGH, while the DAQ driving it LOW. That would be a short through the pin driving circuit's of both devices and most likely the flowing current will exceed the maximum current rating of the pin. This can fry the involved pins hardware or even the complete devices. You get some kind of race condition here: The device, that can handle drain/source more current will be the winner.

In general you have to implement rules, how the devices should work together. Do you need the actions from the DAQ to be executed no matter what the Arduino does? Or should the Arduino be the master here? Or something inbetween? It is not clear, what do you need here.

I will give you 2 suggestions about possible ways:

You could control the relay only with the Arduino. The DAQ can be connected to a digital input of the Arduino (so that it can sense the DAQ's output state) and in the Arduino code you can implement all the logic you need to drive the relay to your liking.
You could define an idle state of your relay input and set it with a pullup or pulldown resistor. It will ensure, that the relay input is at the defined idle state, as long as no device is driving the line to the opposite state. For this you need the devices outputs to be high impedance (on the Arduino this means the pin is configured as input; for the DAQ you need to know yourself or research it).

Let's say the idle state would be HIGH. We would connect the relay pin with 5V through a high resistor (this is the pullup resistor) (maybe 10k, the value is not critical). Both devices can be connected directly. If one device needs to change the state to LOW, it can drive it's output pin actively low, forcing the relay pin to also go to LOW. If it doesn't need the state to be LOW anymore, it should put it's pin into high impedance mode. The pullup resistor will pull the state to HIGH again. You can also add relatively low resistors between the devices to protect against damages from accidentally driving active HIGH while the other is LOW (These can be calculated from the maximum current rating for the pins; 20mA for the Arduino). This kind of logic is often called open drain logic.

simulate this circuit – Schematic created using CircuitLab

If the DAQ cannot put it's pins to high impedance, you can setup that circuit yourself with a single MOSFET:

simulate this circuit

If you use this circuit on both devices, you don't need the small resistors anymore.

The second possibility already implements a specific logic. You need to decide if this logic is good for you. You can invert it's logic (idle state LOW). Personally I would go with the first option, because it is easier and more flexible.


This is a X->Y problem. Here is a solution for X:

Bit 3 of high fuse of the ATmega328p controls if EEPROM memory is preserved through the chip erase. You can change the high fuse setting in boards.txt. Restart the IDE to apply the new setting.

The fuses are written when you select the "burn bootloader" option in the Arduino IDE.


The IC on the MKRZERO is an Atmel SAMD21.  Look up the datasheet and read the section on timer counter.  Yes, it's a long document, but you will find all of the information there.


How to control a DC Motor with absolute encoder using Arduino and Motor Driver?

This is a quite high-level question, so I will answer in general terms,
skipping the fine details. You can ask here more specific questions once
you are implementing the stuff.

Yours is a 10-bit absolute encoder. It can tell you its shaft position
with a resolution of 1/1024 revolution. It's way overkill for your
application. I suggest you connect only the four most significant bits
(pins 9 – 12), which will give you a resolution of 1/16 revolution.

It's better to read the four bits simultaneously. This can be done using
direct port
manipulation. I
would connect pins 9 – 12 of the encoder to pins 4 – 7 of the Arduino
respectively. As the encoder outputs are open-collector, you have to
enable the pullups in setup():

PORTD |= 0xf0;  // enable pullups on pins 4..7

and you can read the encoder simply as

uint8_t ecoder_value = PIND & 0xf0;

Notice that this will give you a result that is left-aligned. This way
you can treat it as an 8-bit Gray code.

Next step is to decode the Gray code. I let you research how to do that,
as you can probably find examples, or even ready-made libraries for
that.

Next, you have to extend the value to a wider bit length in order to
know the absolute position of the cable-cam. The encoder only tells you
where you are within a revolution, but it doesn't tell you how many
revolutions you did. The extension is done by comparing the current
encoder position with the previous one, taking the difference (which can
be positive or negative), and adding it to the previously computed
absolute position. Something like this:

int32_t absolute_position;

void update_absolute_position(uint8_t encoder_position)
{
    uint8_t old_position = absolute_position;  // extract LSB
    int8_t delta = encoder_position - old_position;
    absolute_position += delta;
}

Beware of the types of the variables. The type of delta, for instance,
ensures that the result of the subtraction is wrapped the correct way to
yield a number between −128 and +127. Thus, the sign will tell you which
is the shortest path (clockwise or counterclockwise) from the previous
to the current position.

Note also that you have to call this function frequently enough: more
than once per half revolution. Otherwise it won't know which direction
the wheel turned. If your loop() runs fast enough (you don't use
delay(), right?), you just have to call this function once in
loop(). Otherwise you would have to setup a timer interrupt to ensure
the updates are frequent enough.

Lastly, you have to define the limits:

int32_t left_limit = INT32_MIN;
int32_t right_limit = INT32_MAX;

// To set the left limit to the current position:
if (user_pressed_the_relevant_button()) {
    left_limit = absolute_position;
}
// and likewise for the right limit.

and condition the maximum speed on the distance to the closets limit.
Assuming you store the speed as a signed number (the sign being the
direction), you would constrain it to always be between a negative
min_speed and a positive max_speed, which could be updated as
follows:

// Slow down if close to a position limit.
if (absolute_position - left_limit < BREAKING_DISTANCE) {
    min_speed = map(absolute_position,
        left_limit, left_limit + BREAKING_DISTANCE,
        0, -ABSOLUTE_MAX_SPEED);
} else {
    min_speed = -ABSOLUTE_MAX_SPEED;
}
if (right_limit - absolute_position < BREAKING_DISTANCE) {
    max_speed = map(absolute_position,
        right_limit - BREAKING_DISTANCE, right_limit,
        +ABSOLUTE_MAX_SPEED, 0);
} else {
    max_speed = +ABSOLUTE_MAX_SPEED;
}
speed_to_apply = constrain(requested_speed, min_speed, max_speed);

Note that this makes the speed limit a linear function of the position.
You may want to look into easing functions to have a smoother breaking.


My software serial code won't work at > 4800bps

At 1MHz and 9600 baud, you have a total of 104 clock cycles available to run your interrupt routine in.  A quick count up of the assembly instructions generated comes to more than that (around 126 at first glance), so you can't fit it into the time.

As a result, your baud rate will actually be lower than 9600, and the chip will be completely starved of clock cycles for doing anything in your main loop.


Can we write text file to SD card that can also be read in windows?

Notepad in Windows will show the raw data in a file - in all its hideous glory. However, there are things to make sure of:

Make sure that what you write to a file is ASCII characters. By that I mean do not simply write a byte or word value, convert it to a string first:

byte value;
...

value = Sensor.read(); // Return a value from 0-99
Card.write(value);

The above code will write a byte of 0 to 99 to the file - but you probably don't want that! The byte 32 is a space; 65 is the capital letter A; and 97 is the lower case letter a. Say what?

Every byte is represented by a different character in Notepad, so you need to convert the byte 97 into TWO bytes - first the byte (character) 9, and then the byte (character) 7. How do you do that?

One easy way is to use the following:

byte value;
char buffer[8]; // Define once for temporary use

...
value = Sensor.read();
sprintf(buffer, " %d", value); // Store value in buffer as chars - with a leading space
Card.write(buffer);

The above will write one (or more) characters into the file depending on the value you want to print. If your existing data was just a series of 0 bytes, your old code would have been nothing but NULLs. This will (at least) print 0 0 0 0 0 0 0 0 0 0


In RH_ASK.h is:
RH_ASK(uint16_t speed = 2000, uint8_t rxPin = 11, uint8_t txPin = 12, uint8_t pttPin = 10, bool pttInverted = false);

So the argument has a default value specified here.  If you don't specify it, it assumes that default.


How to convert this sketch to keep only one if-else statement?

First find the duplicated code.

E.g. the fragment

  int lightSensorValue = analogRead(ldrPin);
  Serial.print(lightSensorValue);

  if(lightSensorValue < LightSensorThreshold){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

is repeated three times.

Then find within the duplicate code fragments, the differences, which are:

the pin number
the value to check against.
the two texts

Then make a new function containing one duplicated code fragment, and replace the differences, by variables which you pass in the function as arguments:

void checkSensor(int pin, int sensorLimitValue, char* okText, char* warningText)
{
  int sensorValue = analogRead(pin);
  Serial.print(sensorValue);

  if(sensorValue < sensorLimitValue) {
    Serial.println(okText);
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  else {
    Serial.println(warningText);
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  delay(500);
}

And call respectively:

checkSensor(ldrPin       , LightSensorThreshold, " - light"   , " - dark");
checkSensor(rainSensorPin, RainSensorThreshold , " - it's wet", " - it's dry");
checkSensor(smokePin     , thresholdValue      , " - Smoke"   , " - No Smoke");

I switched the green/red values, because I assume when the value is lower than the limit, the green LED should be on, and otherwise the red LED.

Btw, why not use smokeSensorThreshold instead of thresholdValue to keep it consistent with the other duplicated code fragments?


Sending multiple channels with bluetooth

The BT module will connect as a SPP (serial port) device, and then pass the serial data to and from the arduino and whatever you choose to connect to (that supports SPP).

There is only one channel, and in any case only one set of TX and RX wires that will be connected to your arduino, but this does not stop you from sending as much data of as many different types as you want. You are only limited by the BAUD rate and how much time the message will take to send.

For complicated data transfers you will need to write the code for a protocol so both sides can make sense of what the other says. You are free to do whatever you can think of here, although if you need to make a complicated protocol you might get some use out of the answers to this question:

Communication Protocol Best Practices and Patters


Is programming the ATTiny85 possible in 1.5?

You can download a version of arduino-tiny for IDE 1.5.x from here.


Check the datasheet and I think you will find you need 3 amps peak.  It requires this peak current when you make a call or send a text/sms.

Use a 5A power supply and that should solve the problem.

I have never tried it but "super capacitors" might work, providing the extra power when its needed, it depends how long you need the 3A for.


If you need inspiration what to do with the Arduino, google Simple Arduino projects and search a bit. You will find a lot of interesting things.

If you want to build a keylogger for a normal computer keyboard, then you can start with an old PS2 keyboard and this library: PS2Keyboard Library

From a quick glance on the PS2 protocol, it seem to have the same electrical functionality as the I2C protocol (both lines have a pullup resistor to 5V and the connected controllers are open collector, so that an inactive device doesn't disturb communication on the bus). With this I would say, you have to tap the Data and Clock lines with the library. Maybe you can also power the arduino directly over the bus power lines.

Maybe this video is also interesting in this context: Hardware Keylogger with Arduino UNO

As the USB protocol is far more complex than PS2, I wouldn't recommend a USB keylogger as a starter project. (Though it seems possible when using the right shield for the UNO). You can also use an USB to PS2 Adapter for your USB keyboard to get it working without buying a new keyboard. If you still want to make a USB keylogger, I think other Arduino variants can also work as USB hosts, which would make things easier.


Switch setting 'running' state boolean doesn't hold

Thanks to @Manjenko's comment I was able to see my error.

Here is my solution:

boolean running = true;
int swReading;
int swPrevious = LOW;

void setup() {
  pinMode(swPin, INPUT);
  digitalWrite(swPin, HIGH);;
}

void loop() {

  swReading = digitalRead(swPin);

  if(swReading == LOW && swPrevious == HIGH) {
    running = !running;
  }
  swPrevious = swReading;

  if(running) {
    ...
  }
}


This page explains that the ATmega2560 could drive up to 800mA: Arduino Playground: Arduino Pin Current Limitations
There are limitations for groups of pins, so you have to be careful.
The 800mA is a lot in my opinion. I wonder how hot the chip will become.

What kind of leds do you use ? Normal 20mA leds ? Or is 10mA leds also possible ? 30*20mA = 600mA, but 30*10mA is only 300mA. The 300mA seems a lot safer to me.

With Charlieplexing the leds are not 'on' all the time. However, with the Arduino Mega 2560 you have enough pins, and you could just lower the current through the leds.
Turning them on for a short time (without Charlieplexing) is the same as turning them continuous on with a lower current.

The most common way to drive 30 leds is with a led strip. For example a led strip with neopixels. That led strip has to be powered seperately.

My advice is to lower the current for the leds to 10mA and hope that the ATmega2560 doesn't get too hot.

[ADDED] 300mA is still a lot. Start with 5mA per led for a total of 150mA when they all are on at the same time. Many modern and good quality leds are bright at 5mA.


Issues using HC-06 Bluetooth module with arduino

I assume this wiring is correct, right?

Rx > Tx
Tx > Rx
Gnd > Gnd
Vcc > 3.3V

Almost. The Arduino's TX should be reduced to 3.3V using a 10k/20k potential divider.

  How do I read the serial input? I've been using

if(Serial.available() > 0)
       phoneInput = (char) Serial.read();

You should read and digest this.

  What datatype is the Serial.read() returning to my variable before I cast char on to it?

An integer. It holds either 0-255 representing the ASCII code for a character, or -1 if there is nothing in the buffer to read.

  I get errors uploading the code to the board (avrdude: stk500_recv(): programmer is not responding), until I remove the pin connected to the Rx on the arduino, is there a cleaner solution to uploading the board without unplugging wires?

That will be because you are using pins 0/1 to communicate with the bluetooth which you can't do because those are used to communicate with the PC.


Is it possible to make normal pins act like ground pins?

No, it's not going to work - even worse, you risk frying your Arduino -, for the following reasons:

The Arduino data pins can't source (neither sink) enough current for that to work.
The inductive kickback of the motor could fry Arduino pins.

The right way to do what you want to do is using an H-bridge controlled by your Arduino data pins. There are lots of Motor Driver PCB modules for Arduino (most of them based on the inefficient L298 driver IC, which you should ignore and look instead on those based on the TB6612FNG driver IC or similar, because it would be a far better solution) that implement this function.


Can I drive an LM334(Z) from an Arduino with AnalogWrite()?

If you don't need super high accuracy, using a MOSFET's ohmic region, plus a smoothing filter on the output of your PWM (analog out), could be a solution.


Can't get 4 digit 7 segment display to show different values

You have a common cathode display and all your cathodes are tied to ground through resistors. You have no way at all of separating out the different digits.

You cannot directly drive such a display with a shift register like that - you need a more direct connection to the Arduino (it needs to be high speed) and rapidly switch each cathode on and off in sequence to display each of the four numbers one after another.

Also the resistors should be in the 8 anodes, not the 4 cathodes.


Using Atmel Studio with Arduino Starter Kit (Uno MCU)

There are many tutorials on programming Arduino boards (or any other AVR MCU) with Atmel Studio:

Creating new project:
https://asensar.com/blog/2013/how-to-setup-atmel-studio-for-arduino-development/

Configuring Avrdude for firmware upload:
https://asensar.com/blog/2013/how-to-integrate-avrdude-with-atmel-studio/
http://www.instructables.com/id/How-to-Load-Programs-to-an-Arduino-UNO-From-Atmel-/

Please see this post too:
Atmel studio 7 - my own libraries

Nothing to afraid of, just don't mess with lock fuses (relevant only if you decide to play with ISP programmer and arvdude/avrdudess). Use Arduino USB virtual COM port connection for firmware uploading, just like in Arduino IDE.

With Atmel Studio you don't have rich libraries available like in Arduino platform, instead you will have to program MCU, its peripherals (and other devices connected, if any) by directly accessing MCU registers. This requires some knowledge on MCU hardware (but it is a natural choice if you want to learn that). Eventually you can build your own wrapper libraries similar to one in Arduino.

Check Procyon AVR library too - much better choice than digging Arduino library sources (a bit old but still relevant, I always recommend it as a starting point for AVR library development:)
http://www.procyonengineering.com/embedded/avr/avrlib/


HC-05 bluetooth module not accepting AT commands

###### Try This : Your Code Updated With Possible Fixes  ######

After examining your code and comparing it to my working code I believe I have found a definitive answer.  I'm altering your code so you can copy it and try it.  I'll add comments where I've changed it.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(15, 14); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  Serial.println("Enter AT commands:"); // a prompt in Serial Monitor
  // Deleted while loop, unnecessary

  // set the data rate for the SoftwareSerial port
  // notice that your comment on previous line says SoftwareSerial port
  // but you are setting the Serial3 port -- this is where we use mySerial
  // Serial3.begin(38400); // commented your line of code
  mySerial.begin(38400);
}

void loop() { // run over and over
  //if (Serial3.available()) { // we don't use Serial3 any more
  if (mySerial.available()) {
    //Serial.write(Serial3.read());
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    //Serial3.write(Serial.read());
    mySerial.write(Serial.read());
  }
}

I am confident that if you use this newly modified code it will solve your problem.  I should've noticed this earlier.

Here's the rest of my original answer.

I have struggled with this myself.  As a matter of fact it took me a few months of owning some HC-05s before I finally dug up an answer.  It's been a while since I worked with it so I'll do my best to explain what to do.

Arduino Nano

Also, I use an Arduino Nano to do the programming of the HC-05.

This Setup Lets You Alter HC-05

Once you wire it up and run the program (included here) you will be able to send any of the HC-05 commands and they work great.  You can change the name of the device, the 4-digit pass-code and everything.

Crude Snapshot, But Enough To Build Simple Circuit

I also have a crude snapshot* of the circuit I used (at the time just for documenting it for my own memory) but I think we can work you thru it.  and I know those wires are all crammed together and it almost looks like they are in the same breadboardholes but they are actually hooked up properly.  I was so excited it finally worked I snapped the pic too fast.

*see image below

Here's the code I use:

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  //pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  //digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor

  if (BTSerial.available())
    {
     //Serial.println("bt available...");
    Serial.write(BTSerial.read());
    }

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Does Your HC-05 Have the Button?

Okay, so the first thing is to check to see if your HC-05 has the little button on it?  If it does that has to be held when you apply power to the circuit.  The HC-05 will blink and then it will be in COMMAND mode and you can let go.

If No Button

You can see that mine has the button.  That is why the first two lines the setup() method are commented out.  I don't need D9 to go high (it is not connected to the pin) because mine has the button. If yours has the button (most likely does) then you don't even have to worry about it.

Looking Back At Your Question

Now that I look back at your sample code it could be that you're not aware that you have to hold that button when you power up.  Or you don't know that you need to connect that wire to keep the HC-05 in command mode.

Pins For TX / RX

That's probably the problem you are having, because everything else looks the same -- except you are using 15 and 14 for TX / RX.  I am using D10 and D11 for mine and I remember something about those pins in the back of my mind so if yours still doesn't work, try switching to those and try using my code.

I remember the first time I finally got this working and I was dancing around the room. Good luck and I hope you are dancing soon.  :)


Can I simulate a clock without an RTC connected?

TimeLib.h has a virtual clock that can be updated and corrected from multiple sources, including an RTC chip or an NTP server on the internet (assuming an internet connection).

It doesn't need that clock source, though, but it will drift with time. Once you have set the clock correctly it will keep close to the right time (assuming no reset or power loss of the Arduino). Not perfect (because the Arduino's main clock isn't perfect) but close enough for many simple applications.


I am getting an error while trying to set up the U8g2 library

I figured out what I was doing wrong. I was copying the name from the Constructor Reference and immediately inputting the arguments in parentheses. I needed to put u8g2 after the constructor name and then put the arguments. Thanks!
The corrected code is as follows:
#include <Arduino.h>
#include <SPI.h>
#include <U8g2lib.h>

//Constructor
U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0,A5,A4);


Help me determine the power consumption/rating of the circuit below?

It's not a simple matter of "calculating the power". Instead you need to:

Calculate (or obtain) the current consumption of each individual sub-module or component
Calculate (or obtain) the current consumption of the main MCU for each power state it operates in
Calculate the current consumption of static items such as voltage dividers and power LED

Then:

For each unit examine the percentage of time it spends in different power states. From that create an hourly average current for the unit.

And finally:

Sum up all the average hourly usages to get a final AH value for the whole circuit.

Most of the current values can be obtained either by calculation (e.g., Ohm's Law for resistive dividers and LEDs, etc), or from the datasheets for the devices you have attached.

Note that this will still only be an approximation, because (amongst other things) you have multiple power sources which will cause different drains on the system depending on which source is being actively used (different monitoring circuitry and components switched it), and that (I assume) is influenced by the weather.


You haven't provided enough information for anyone to easily help you. Assuming that you took your code from GitHub myAHRS_plus_i2c.ino you can look further down the file to find the definition of read_rev_id(). It simply reads the revision number from the AHRS chip and displays it on the console. Since this is all that it does you could leave out the call to read_rev_id(). But if you are going to use it then be aware that it contains an obvious bug. The second read() should be to I2C_SLAVE_REG_REV_ID_MINOR.

//READ REVISION ID
int read_rev_id()
{
    uint8_t id_1 = 0;
    uint8_t id_2 = 0;
    read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_1, 1);
    read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_2, 1);
    Serial.print("READ REVISION ID= "); Serial.print(id_1); Serial.println(id_2);
}


H-bridge with 2N2222 transistors - input voltage is chopped

You have discovered the standard problem when building an H-bridge. If
you want to drive it with a voltage lower than its output voltage, then
you cannot directly control the high-side transistors.

There are several solutions to this problem. The simplest and most
reliable is to buy an already built H-bridge. If you really want to
build it yourself, then you will need extra transistors to drive the
high side.

Below is an example using only NPNs. It's a half-bridge which behaves
like an inverter. You would use two of those to build a full bridge.

simulate this circuit – Schematic created using CircuitLab

Here, the leftmost transistor is used to drive the high-side one.
I didn't label the resistors, as their values will depend on how much
current you want.

This is not the only possible schematic, and probably not the best.
There are many other options, including NPN/PNP combinations,
Darlingtons and MOSFETs.


Broken serial connection corrupting Arduino values

You could consider writing/reading the value to/from the EEPROM.
http://arduino.cc/en/Reference/EEPROM
This allows the board to be reset, or even turned off, and retain the value previously set.  What you would be doing is saving the value to the internal memory of the Arduino.  This is resettable and persistent over a "reboot".
Granted, there is a limited number of writes you can do, but that number is high enough (~100k) that you will probably wear out the fan before the EEPROM sector dies.

Syntax
EEPROM.write(address, value)
EEPROM.read(address)
EEPROM.update(address, value)

For objects:

EEPROM.put(address, data)
EEPROM.get(address, data)


and an external 5V DC power supply

OK, assuming you are putting 5V into the barrel jack this is exactly what you expect to happen.

From the Arduino Uno specifications you are supposed to supply a recommended 7V to 12V. Your supply of 5V is too low.

The barrel jack first goes through a M7 protection diode which would have about a 0.7V forward voltage drop, and then through a NCP1117ST50T3G voltage regulator which has a dropout voltage of (typically) 0.95V at 100 mA.

Thus you have:

5V input - 0.7V - 0.95V = 3.35V

That is what you are finding.

Solutions

If you have a proper, regulated, 5V DC supply you can put that directly onto the 5V pin of the Arduino. Better get the wires around the right way because you are bypassing the protection diode!
Get a DC supply in the range 7V to 12V and put that into the barrel jack.
Another simple idea is to just get a wall-wart that is used for charging phones via USB and run a USB cable into the Arduino USB port.

Empirical test

I put 5V into the barrel jack of my Uno and read 3.33V on the 5V pin, which is pretty-much what you got. I measured a 0.77V drop over the M7 diode.


How do I make specific tones with a piezo buzzer?

It's very hard to know from your question what you are having trouble with.  I have a piano and I can hit the keys, but it takes me a long time to hit them in the right order and with the right timings to create a new symphony.

Anyway, if creating the sounds is the problem, have you looked at the Tone library?

Different alarms have different sounds.  I once heard an alarm which sounded like the start of Fuer Elise, so probably the notes were E and D#.  That would make their frequencies about 330Hz and 311Hz:

void loop()
{
    tone(pin, 330, 250);
    delay(300);
    tone(pin, 311, 250);
    delay(300);
}

The sound you linked to sounds to me like it starts on a C, and slides up gradually one octave.  One octave higher is double the frequency, so this code should do that:

void loop()
{
    const int startFreq = 523;  // C5 is 523Hz

    // Start at the given freqency, and increase gradually by
    // one octave (double the frequency)
    for (int freq=startFreq ; freq<= (startFreq*2) ; ++freq)
    {
        tone(pin, freq, 10);
        delay(3);
    }
}


In general, once an embedded processor's interrupt fires, the interrupt routine clears the interrupt.  Usually inside the interrupt routine.  Failure to clear the interrupt normally inhibits further interrupts.

That said, in the Arduino paradigm, this is "taken care of" by the Arduino Timer library described here.  In the example code:

/*
 *  Timer1 library example
 *  June 2008 | jesse dot tane at gmail dot com
 */

#include "TimerOne.h"

void setup()
{
  pinMode(10, OUTPUT);
  Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
  Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}

void callback()
{
  digitalWrite(10, digitalRead(10) ^ 1);
}

void loop()
{
  // your program here...
}

...you can see that the example does not actually contain "the" Timer interrupt routine but rather a callback() routine which the Timer library calls when the Timer interrupt occurs.  Code to clear the Timer interrupt is missing and assumed to be in the Timer library.

Consider this if you are writing you own interrupt routine instead of using the Arduino's Timer library.

I'm going to have to call foul on myself.  Clearing interrupts in their own interrupt routine is very common.  But looking at this page, where the Atmel timer hardware is directly controlled (that is, the normal Arduino Timer library is not being used) and the real interrupt handler exists in the sketch, I see where this is not done.  So, for the Atmel, there must be at least one timer mode where the timer interrupt does not have to be clear for the interrupt to happen again.

If you are using the Arduino's Timer library consider this warning from the Timer's library web page linked to above:

  Be careful about trying to execute too complicated of an interrupt at
  too high of a frequency, or the CPU may never enter the main loop and
  your program will 'lock up'.

Finally, hardware timed interrupts are normally reserved for operations which are time sensitive and occur much faster than executing code can handle.  For events that happen on the order of seconds, most applications setup 1 timed interrupt to count off a convenient interval.  Say 1 second.  Code is used to keep count and call the proper functions at the intended time.


How to multitask with interrupts on Arduino?

There is no real multitask on Arduinos. The Arduino can only do one thing at a time.

But, you can do things sequentially, one after another, so fast, that a human will think, that it happens simultaneously. This involves a non-blocking coding style, which needs no interrupts

Every delay in your code (at least the long onces) need to be removed. if you want to do timed things, you should use the coding principle from the BlinkWithoutDelay example, that comes with the Arduino IDE.
Also no function should wait for something to happen. Think of a function, that waits for a command from the serial interface. Blocking code would wait indefinitely, until a command was received, preventing any other code from execute. Instead the function could exit fast, when there is currently no command to process, leaving time for the other code to execute.

The whole principle relies on the loop() function executing very fast, so that your code can still be reactive. This works for most of the situations. Only sometimes you need to react that fast, that you need interrupts. Your usecase doesn't seem to belong to the interrupt needed faction.


What changes I have to take care while coding from Atmel Studio instead of Arduino IDE?

Atmel cpp projects do not currently provide an option to upload using Arduino bootloader. Atmel only provides upload using hardware programmers.

The bootloader is deleted when you upload using a hardware programmer either from Atmel Studio or from the Arduino ide.

The underlying Atmel toolchain is not very different from the latest Arduino toolchain however Atmel does not know about the Arduino hardware/cores. You have to copy the Arduino core sources to your Atmel project if you want to compile for Arduino compatibility but that still does not give you bootloader upload.

It is not clear from your question if you have the Arduino sources in your cpp project already. If you do have the sources in your project then you can use avrisp mkII or other programmer to upload but the Arduino libraries might be an issue for you if you are using them.

There is another option in Atmel Studio however it might not be what you require ...

You can install the Visual Micro plugin for Arduino from the Atmel Gallery and work with standard Arduino sketch projects inside Atmel Studio.

The Visual Micro plugin provides full Arduino compatible sketch build and bootloader upload in Atmel Studio. Because of the nature of Arduino, the Visual Micro plugin automatically manages the include paths and Atmel project properties so that intellisense works in projects that contain .ino source code files. If the project does not contain .ino files then Visual Micro sleeps (does not interfere with cpp projects)

The plugin also provides other features such as a serial usb debugger, library manager, board manager, Arduino examples etc.

More about Visual Micro is here

Tutorials are here

Debugger overview is here

Update:

There is no difference in program execution between uploading using a physical hardware programmer or using a usb cable via bootloader.

The Arduino libraries sources can be more complicated to include/compile in a project because they often include additional folders with private source code. This is more of an issue with older Arduino libraries that have a sub folder called \utility.


Can BUS Shield on Arduino Leonardo - Can't init CAN

Had this problem myself. Found this fixed it

Change the following line...

_delay_us(10);

To...

_delay_us(50);

In the MCP2515.c file in the library


How to implement brown out detector arduino ESP32?

The ESP32's on-board BOD is mainly intended to inhibit operations that might cause corruption if they happened with too low a voltage.  There is a very unpredictable amount of time for the code in the ESP32 to do anything but effectively halt.
If that's what you want, then you have enabled it in your code above.
If you want to detect a power outage, for example, and log something, then you need two things:

A reliable detector that the power has failed.
A battery or capacitor-based circuit that will continue the ESP32's power for long enough for you to do what you need to do.

So when "1" happens you set a GPIO pin on the ESP32 which triggers your interrupt and you do what you need to do while the power remains stable.


How to read a timer's value once stopped?

Here, below is a code which is you looking for. When you pressed a button then a timer is started and when you released it then a timer is stopped. And you can also see that time also means how long button is pressed.

const uint8_t button_pin = 2;

void setup()
{
    pinMode(button_pin, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop()
{
    static int last_button_state = HIGH;
    static unsigned int push_count;
    static unsigned long last_press_time;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if (last_button_state == HIGH && button_state == LOW) {
        push_count++;
        last_press_time = now;
    }

    // Report when the button is released.
    if (last_button_state == LOW && button_state == HIGH) {
        unsigned long push_duration = now - last_press_time;
        if (push_duration < 10) {  // discard bounce
            push_count--;
        }
        else {
            Serial.print(F("pushes: "));
            Serial.print(push_count);
            Serial.print(F(", duration: "));
            Serial.print(push_duration);
            Serial.println(F(" ms"));
        }
    }

    last_button_state = button_state;
}


Testing a single byte write

I ran some test code overnight to try to get to the bottom of this. Somewhat surprisingly perhaps, I got up to over 11 million writes before a read-back failed:

Current count = 11514199
Writes per minute: 17550
....................
Current count = 11538199
Writes per minute: 17550
....................
Current count = 11562199
Writes per minute: 17549
...................
Failed readback!
Expected: FF
Got: 7F
Current count = 11585314
Halted.

So, 11.5 M writes. Still, as pointed out on the AVR Freaks thread, the guarantee of 100,000 writes to EEPROM gives you a data retention time of 20 years. Possibly if you exceed that limit, the data retention time will go down. It isn't particularly practical for me to test whether or not the EEPROM will still be valid after 20 years. ;)

Interestingly, the next day (as I write this) the EEPROM seems to have recovered and is now still writing and reading back OK. So it would appear that after 11 M writes you may sometimes get a bad read-back.

On the AVR Freaks thread they seemed to get somewhere between 5 M and 8 M writes before failure.

A number of hours later (2.4 hours), the same byte failed again, after a further 2,559,219 writes!

Current count = 14033314
Writes per minute: 17549
....................
Current count = 14057314
Writes per minute: 17549
....................
Current count = 14081314
Writes per minute: 17549
....................
Current count = 14105314
Writes per minute: 17549
....................
Current count = 14129314
Writes per minute: 17549
............
Failed readback!
Expected: FF
Got: 7F
Current count = 14144533
Halted.

Somewhat more quickly the third failure after a further 149,703 writes:

Current count = 14312533
Writes per minute: 17550
....
Failed readback!
Expected: FF
Got: 7F
Current count = 14318236
Halted.

And another failure (in 2.3 minutes) after a further 41757 writes:

Starting.
Current count = 14318236
Waiting for pin 2 to go LOW.
Started.
....................
Current count = 14342236
Writes per minute: 17551
..............
Failed readback!
Expected: FF
Got: 7F
Current count = 14359993
Halted.

Testing the adjacent byte

Now that I got a failure fairly quickly on the somewhat overworked byte, I adjusted the code to write to the next one up (1021) which would be in the same 4-byte "page".

Four hours later, the adjacent byte has been written to 4.36 million times without any errors, so this would appear to support the idea that each byte of EEPROM can be written individually without affecting its neighbours.

Next morning

The adjacent byte (address 1021) finally failed after 12,161,565 writes. So the proposition that each byte can be individually addressed, and has an individual lifetime, seems to be supported.

Current count = 12120000
Writes per minute: 17562
....................
Current count = 12144000
Writes per minute: 17562
..............
Failed readback!
Expected: FF
Got: 7F
Current count = 12161565
Halted.

Code

Main sketch

// EEPROM tester

// Author: Nick Gammon
// Date: 22 August 2015

// Connect a jumper from GND to pin D2 when ready to run.
// Remove the jumper for a clean wrap-up (saving the current count into EEPROM)

// Single flash, repeated every half second: ready to go
// Two flashes, stopped on request
// Three flashes, error
// Occasional flash: working

#include <EEPROMAnything.h>
#include <EEPROM.h>

const unsigned int WRITE_COUNT_ADDRESS = 1010;
const unsigned int TEST_ADDRESS = 1020;
const unsigned int ITERATIONS = 200;
const unsigned long MAX_DOTS = 20;
const byte TESTS [] = { 0x55, 0x00, 0xFF, 0x66, 0xAA, 0x11 };
const byte ACTIVATE_PIN = 2;
const byte LED = 13;

unsigned long dots = 0;
unsigned long writeCount;
unsigned long startTime;
unsigned long initialCount;

void showCount ()
  {
  Serial.print ("Current count = ");
  Serial.println (writeCount);
  } // end of showCount

// flash the LED the required number of times
void flashLED (const int times,
               const unsigned long interval = 100,
               const unsigned long delayTime = 500)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (LED, HIGH);
    delay (interval);
    digitalWrite (LED, LOW);
    delay (interval);
    }  // end of for each iteration
  delay (delayTime);  // delay between iterations
  }  // end of flashLED

// check our memory agrees with what we expect
void checkMemory (const byte target)
  {
  byte found = EEPROM.read (TEST_ADDRESS);
  if (found != target)
    {
    Serial.println ();
    Serial.println ("Failed readback!");
    Serial.print ("Expected: ");
    Serial.println ((int) target, HEX);
    Serial.print ("Got: ");
    Serial.println ((int) found, HEX);
    showCount ();
    EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
    Serial.print ("Halted.");
    Serial.flush ();
    while (true)
      flashLED (3);  // three flashes
    }
  }   // end of checkMemory

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

  // get write count from previous run
  EEPROM_readAnything (WRITE_COUNT_ADDRESS, writeCount);
  initialCount = writeCount;

  // if all 1 bits, variable was never initialized
  if (writeCount == 0xFFFFFFFF)
    writeCount = 0;

  // tell them we are starting
  Serial.println ("Starting.");
  pinMode (2, INPUT_PULLUP);
  pinMode (LED, OUTPUT);
  showCount ();

  // wait for them to unplug pin 2
  Serial.println ("Waiting for pin 2 to go LOW.");
  while (digitalRead (ACTIVATE_PIN) == HIGH)
    flashLED (1);  // one flash

  Serial.println ("Started.");
  startTime = millis ();
  }  // end of setup

void loop ()
  {

  // write to EEPROM, checking each write
  for (unsigned int i = 0; i < ITERATIONS; i++)
    {
    for (unsigned int j = 0; j < sizeof (TESTS); j++)
      {
      EEPROM.write (TEST_ADDRESS, TESTS [j]);
      writeCount++;
      checkMemory (TESTS [j]);
      }  // end of doing each test pattern
    }  // end of loop of x ITERATIONS

  // save the current write count so we can pick up the count next time
  EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
  Serial.print (".");
  dots++;

  // confirming we are working
  flashLED (1, 10, 0);  // flash once, for 10 ms, no extra delay

  // newline, show counter
  if (dots >= MAX_DOTS)
    {
    Serial.println ();
    dots = 0;
    showCount ();
    unsigned long writes = writeCount - initialCount;
    unsigned long timeTaken = millis () - startTime;
    float writesPerMinute = float (writes) / float (timeTaken) * 60.0 * 1000.0;
    Serial.print ("Writes per minute: ");
    Serial.println ((int) writesPerMinute);
    }  // end of needing a newline and counter output

  // check if user wants us to stop by disconnecting the jumper from Gnd to D2
  if (digitalRead (ACTIVATE_PIN) == HIGH)
    {
    Serial.println ();
    Serial.println ("Stop request detected.");
    showCount ();
    Serial.print ("Halted.");
    Serial.flush ();
    while (true)
      flashLED (2);  // two flashes
    }
  }  // end of loop

EEPROMAnything.h

#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
{
    const byte* p = (const byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        EEPROM.write(ee++, *p++);
    return i;
}

template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
{
    byte* p = (byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        *p++ = EEPROM.read(ee++);
    return i;
}

The code is designed to wait until you connect pin 2 (digital pin 2) to ground before starting. This is to stop it executing immediately after being uploaded, before you start the serial monitor. So, upload the code, open the serial monitor, and then connect Gnd to pin D2, and watch the results.

Error correction

If the concern is that the EEPROM reads may deteriorate, once could use Reed Solomon error correction to recover. That is the method used for correcting bad reads on compact disks, and also QR codes. It can recover from a number of errors (you choose the level of error correction you want - the more error correction, the more memory it takes).

My tests so far have shown that failure involves single bits (as did the AVR Freaks tests) so this may well be a way of extending EEPROM life and reliability.

Testing of some Reed Solomon code that I found, would appear to indicate that adding the encoding and decoding would take around 4800 bytes of program memory, plus around 600 bytes of RAM (512 bytes needed for the internal tables, plus some extra work space). In addition you need 256 bytes of RAM for the code block. Those figures could be reduced by using less bits per "symbol". For example, if you stored 4-bit symbols (such as BCD numbers) then the memory requirements would reduce somewhat.


There is no way you can make the Watchdog timer longer on Atmega 128. It is max 1.8 sec if you set all 3 bits of Timer Prescaler.

For Atmega 328 the max watchdog time is 8 sec and longer time can be achieved using  watchdog interrupt and count up (or down) until you want a reset and then force the reset by setting the shortest watchdog timer.

Atmega 128 doesn't support watchdog interrupt, so the trick with interrupt can't be used.


Can you use a RF remote with nRF24L01 and Arduino?

The nRF24 operates in the 2.4GHz frequency and implements a proprietary protocol so, even if I don't have much information on your particular drone/controller, I strongly doubt there's a chance you can use the nRF24 module to talk to your drone.