text:
New to Arduino: Should I learn C, C++ or both (C & C++)?
From what i've researched here is my thoughts on both

C++
I heard that you can create libraries using C++ in arduino. And you can use the Arduino IDE to do that stuff.  Here is the proof

http://arduino.cc/en/Hacking/LibraryTutorial
Notice that it uses the C++ syntax.
I also see arduino projects on github written on C++
https://github.com/search?l=C%2B%2B&q=Arduino&type=Repositories&utf8=%E2%9C%93

C

I heard that you can use AVR GCC and code it without the arduino ide. And I heard it's much faster than the arduino language because it's more closer to the metal. But I think it's harder to set up because you need a programmer into the Atmel chip, which is much more costlier compared to directly plugging in the arduino using the USB to printer cable. And you also need to download a bunch of stuff to get coding in pure avr gcc (win-Avr GCC, atmel studio etc.).
Which one should i learn C or C++? I prefer the easy to debug route. Or is it beneficial if i learn both?

The basic syntax of C and C++ is very similar, to the point that C code can typically be compiled directly as C++. You'll also find C standard functions (such as printf and malloc) can be used from C++ programs.
The major difference in the core language is that C++ has a lot of extra stuff such as classes and templates. Conventionally, C++ also has a huge standard library which doesn't work on C. However, that's not usually available (nor really appropriate) for Arduino programming, so you don't need to worry too much about it unless you migrate to e.g. desktop programming.
Basically, it's probably sensible to learn C first, because the same knowledge works in C++. You can then move on to the C++-specific stuff, such as classes.
As a side note, the Gnu Compiler Collection (GCC) actually covers both C and C++. It's what the Arduino IDE at Atmel Studio use under-the-hood for all their compilation. It's even possible to work directly with GCC but still upload programs to Arduino via USB.
It's also worth noting that programs compiled within the Arduino IDE aren't necessarily going to run any slower than programs compiled some other way (whether C or C++). The main difference is whether or not you use the Arduino functions. Since they are general purpose, they're not necessarily doing things the most optimal way. You could get more efficiency in theory by manipulating the microcontroller's special registers directly, which is you can do from within the Arduino IDE as well. It's usually very tricky for a beginner though, so it's probably not something you want to attempt until you're more comfortable with C/C++.

Granted, as you said it's mostly unrelated to embedded programming, but I'm not sure I'd use the word 'huge' to describe the C++ standard library.  Sure, it's a covers a lot more ground than the C standard library, but compared to virtually any other popular programming language, it's quite spartan.

Arduino supports c++, but does not support many of the standard libraries.
The vast bulk of the functions in the Arduino IDE are c functions.
You can do almost everything in c, except for a few advanced items.
Due to the limited c++ libraries it will be difficult to learn c++ on Arduino; indeed it is not the ideal platform to learn c, as most of the tutorials will not work (because there is no I/O on Arduino).

Several standard Arduino libs are C++, the first that comes to mind is Serial, but there are others!

@jfpoilpret I never said the libraries were not c++, but all the advertised functions are callable in c. This is a question by a beginner who is unlikely to be overriding the serial class (or any other).

For starting out? I would say neither. The arduino IDE is based on a programming language called processing. Which you can look at. Honestly, if you have done any programming in the past you will be fine for the basics. The advanced stuff might make you look at working with c++ files. But there is nothinging overly complex there. A lot of the add-on hardware that you can purchase comes with existing arduino libraries. Use these as a baseline.

The arduino text-editor uses C(++). "Processing" is a horrible abortion of a wrapper on Java (it's still java, just much worse). None of this is original, and there are no new languages involved.


text:
ESP8266 cannot create TCP connections to this particular server
EDIT: I have created an issue about this here: https://github.com/esp8266/Arduino/issues/4593

I have this server: 185.205.210.197
(Check that it works: http://185.205.210.197/)
And I have this code in my ESP8266:
#include <ESP8266WiFi.h>

#define HOST "185.205.210.197"
#define PORT 80
#define WIFI_SSID "SSID"
#define WIFI_PSW "PASSWORD"

const char* ssid = WIFI_SSID;
const char* password = WIFI_PSW;

void setup () {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(5000);
    Serial.println("Connecting to Wifi...");
  }

  while(!pingServer()) {
    delay(3000); //Send a request every 3 seconds
  }
}

void loop() {}

bool pingServer() {
  WiFiClient client;

  if (!client.connect(HOST, PORT)) {
    Serial.println("connection failed");
    return false;
  }

  Serial.println("connection success!");
  return true;
}

The expected result: Connection success, but got connection failed.
If I try connecting with my PC, it works, only with ESP8266 it doesn't.
Tapping with Wireshark I suspect that there is a problem with ESP8266 TCP packets, here I leave them for you to analyze:
PC TCP connection request (which works):
000030006b081c001a48ea4c0000000010009e098004dba400000000800401009e090b221f000000c603000004000000880254009801a7ad45b7000af5f4e90c000af5f4e90c603c0000aaaa0300000008004500003c000040003706cb37b9cdd2c5c0a82b490050df312dfea1498c6ac92aa0120000079c00000204058c0402080a336f35554aeb0fe90103030700ead7d1
ESP8266 TCP connection request (which receives no response from server):
000019006f080000952a9f520000000012049e098004daa1000801a200000af5f4e90c2c3ae80f137f000af5f4e90c5000aaaa0300000008004500002c00030000ff06431dc0a82b70b9cdd2c5c00100500000196d000000006002086040f80000020402189ccdd933
What I've also checked:

The ESP connects fine to other servers.
There is no firewall blocking the connection between ESP and the server.
I've tried this in different networks and conditions, the error persists.
Other computers can connect to the server, so ESP should be able as well.
Tried with different ESP8266 boards to rule out hardware malfunctioning.
I am using NODEMCU V0.9 board (original firmware) with Arduino IDE and this ESP8266 library.

How to replicate:

Using the latest Arduino IDE and ESP8266 library.
Check that the test server works at http://185.205.210.197:80/ (just open this link basically and see that is running nginx).
Copy and upload the code above to your ESP8266 (NODEMCU or similar).
Open the Arduino IDE console/monitor and confirm that no connection is established to port 80.
Rage in admiration for such a strange bug.

I've opened an Issue for this: https://github.com/esp8266/Arduino/issues/4593

Not a cookie cutter answer, I did a quick test and my ESP8266 does connect to you nginx. Of course you do not accept the params from my fridge, but this is what I see in the log.
7007 :
7010 :

For online documentation and support please refer to
7012 : nginx.org.

7015 : Commercial support is available at
7018 : nginx.com.

7020 :
7022 :

Thank you for using nginx.

7024 :
7026 :
7028 : HTTP : closing connection

You should be able to see that on your side as well.
I am using letscontrolit/ESPEASY  https://github.com/letscontrolit/ESPEasy
And their code to connect looks like
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  if (!ControllerSettings.connectToHost(client))
  {
    connectionFailures++;
    addLog(LOG_LEVEL_ERROR, F("HTTP : connection failed"));
    return false;
}

  boolean connectToHost(WiFiClient &client) {
    if (!checkHostReachable(true)) {
      return false; // Host not reachable
    }
    byte retry = 2;
    bool connected = false;
    while (retry > 0 && !connected) {
      --retry;
      connected = client.connect(getIP(), Port);
      if (connected) return true;
      if (!checkHostReachable(false))
        return false;
    }
    return false;
}

I am using generic HTTP for my controller which here: https://github.com/letscontrolit/ESPEasy/blob/503fd3555e010b08b48fb2dc18290ef120005308/src/_C008.ino
You could try the connect to function to see if that works for you.

Thank's for helping. I am going to try that. Meanwhile this might be a library problem indeed, I opened an issue in the official esp8266 lib repo: https://github.com/esp8266/Arduino/issues/4593

source: Stack Exchange

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

sort: votes


text:
Assembly on the Arduino: IO registers
Question: What registers do I use to access the IO on the Arduino Uno when I am using assembly for programming?
Background:  I was interested in practicing my assembly language skills on the Arduino (I thought it would be easier to turn LEDs on/off than to worry about console IO).  From doing a preliminary search, I have found that the AVR toolchain can be used to program the Arduino.  Yet, I don't quite know how to find the corresponding registers for the IO pins.

The datasheets for the AVR microcontrollers are reasonably good to read. Just Google for the exact controller on your Arduino (eg. ATmege328) and find the "Complete" datasheet on the atmel.com website. Don't download the "Summary", it doesn't include a lot of information. Download the datasheet from atmel.com, that is the only location with the most recent documentation.
There are three registers used in basic IO (check the chapter called "I/O-Ports"):
Where n is a port identifier, a letter ranging from A, B, C, ... depending on the number of IO pins your controller has. Each bit in each register represents a single GPIO pin (yes, you need some basic knowledge on binary to fully understand this).

DDRn, Data Direction Register: This basically configures a pin for either input (0) or output (1).
PORTn, Port n Data Register: When a pin is set as output, the related bit toggles the output pin high (1) or low (0). When configured as input, this enables a weak pull up resistor on the output pin.
PINn,  Port n Input Register: Use this register to read the current level on a pin that is configured as input.

This. Step 1: Stop thinking of it as an arduino. It's not. It's a ATmega MCU on a PCB. 2. Read the datasheet. 3. No really, read the datasheet.

Ah... that is exactly what I needed.  I think I spent so much time looking for Arduino-targeted tutorials, that I forgot I was simply programming an AVR controller, and could use its datasheet.

Check this out: http://arduino.cc/en/Reference/PortManipulation
Also: http://arduino.cc/en/Hacking/PinMapping168
As for other ports and pins, check put the datasheet for your controller, they're really useful to people who can understand them! :)

Link only answers are not useful for the site, as we are not trying to establish a repository of links. Moreover, link only answer are useless if the link ever goes down in the future. It would be better to summarize or paraphrase the content within the answer itself so that users can find what they need here itself or at the very least gain sufficient context so as to be able to find solutions themselves.

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


text:
Question different ways of connecting L298N motor driver board to arduino and motors and powering them
I read few posts and tutorials on this topic but none of them kind of answered my questions.  I bought this L298N motor board and i have two motors that are rated 3V

Now i am trying to understand how to connect it to arduino and power the motors.
For example i have a 12V (8x 1.5v AA batteries) I can connect to VCC and GND then enable ENA with a jumper and connect PWN port from arduino to INA. This way i can control the voltage that is coming out from OUTA and OUTB  I can bring down the 12V to 3V.
Now the question is can i use the +5 (regulated voltage) on the driver board and connect it to arduino Vin and GND to ground to power the arduino? Is that viable solution.  I actually tried it and it works.  I am worried that it is not enough voltage to properly power the arduino.  It's suggested to connect 7v - 12v to Vin.  I am also going to connect a red lab ble shield on top of arduino that is powered by 5v
Another question is if i use 12 volts battery and step it down to 3v with PWN is that going to heat up the L298N chip?

Another option is connecting 9V battery to arduino and then using Vin and GND to power the motor shield and the motors.  The problem there if motor draws more then 1Amp that wouldn't be good for the arduino.  Also if i would switch to 9v+ motors then it wouldn't work.
The third option is to have two separate power sources. 9V for arduino and 5v+ for powering the motors.  Does it make sense to use two power sources?
This project seems like a good way to learn about arduino and electronics
Update
NEOMART Brand New Original High Quality Chips L298N
http://www.amazon.com/gp/product/B00E58EA90/ref=oh_aui_detailpage_o04_s00?ie=UTF8&psc=1
Product Details
1. driver chip: L298N Dual H-Bridge Motor Driver IC

drive section terminal supply area Vs: +5V ~ +35V; such as the need to take power within the board, the supply area Vs: +7V ~ +35V
drive section peak current Io: 2A
logical part of the terminal supply area Vss: +5V ~ +7V(can take power within the board +5V)
logical part of the operating current range: 0 ~ 36mA
Control signal input voltage range:
Low:-0.3V ≤ Vin ≤ 1.5V
High: 2.3V ≤ Vin ≤ Vss
enable signal input voltage range:
Low: -0.3 ≤ Vin ≤ 1.5V (control signal is invalid)
High: 2.3V ≤ Vin ≤ Vss (control signal active)
Maximum power consumption: 20W (when the temperature T = 75℃)
Storage temperature: -25℃ ~ +130℃
Driver Board Size: 48mm*43mm*33mm (with fixed copper pillar and the heat sink height)
Other Extensions: control of direction indicators, the logic part of the plate to take power interface.

Update 2:
I wanted to clarify regarding using 12 volt battery and having 2 motors that I think max voltage is 3 volts.  If i use PWN and step down the voltage to 3 volts will L298N produce a lot more heat to step the voltage down?
Probably in this case would be the best just to get two separate power supplies 9 volts for arduino and 4.5 volts for the motor drive to supply 3 volts for each motor.  Unless i get better motors that support 6v - 9v then i can use the 12 volts battery for both arduino and motors.
As far as the motor drivers, I thought they are used to prevent the noise and power spikes from motors?  I guess you still have to consider it either way.
Thanks in advance!

Can you post a link to the datasheet of that board?

I couldn't find the data sheet for it.  Everyone on amazon complained about it. I updated the answer with the link to the amazon page and some schematics but its pretty small picture.

Found these 2 links: http://www.dx.com/p/l298n-dual-h-bridge-dc-motor-driver-for-robot-smart-car-green-154444#.U-Ppevl_tK0 gives useful info of the board itself, while https://www.sparkfun.com/datasheets/Components/General/L298N.pdf is the datasheet of the IC L298N

@Yan - there is an error in your question, "12V (6xAA batteries)" must be incorrect. 6 x 1.5V AA batteries, ordinary 'dry' cells, would be 9V, and 6 x 1.2V rechargeable ( e.g. NiMh) would be 7.1V. So do you have more than 6 batteries, or is the voltage lower than 12V?

Here is a link to a robotoid page which describes a way to use it.
Here is a link to funnyrobotics which explains how to use it.
I am confident that you could use a search engine to find more examples.
One trick is to use image search. Then look for pictures which look like your photo, and which have extra writing on them. Most people who add labels and writing to the photo are writing to help beginners understand how to use something.
Edit:
That L298N board claims to have a 5V regulator for powering the Arduino, in which case you could use a single power supply, and let the motor board feed the Arduino.
There are two schools of thought on powering the Arduino and motors:

Use two separate power supplies, one for the motor and one for the Arduino.
Use one supply for both the motor, and Arduino.

Using one supply is simple overall. One concern is electric motors can create a lot of electrical noise. If this is not adequately filtered, it might get injected into the Arduino and maybe cause the microcontroller to reset, or become temporarily unstable. The single supply advocates say the power supply to the Arduino should be properly filtered using capacitors and a proper voltage regulator usually, and the problem is solved.
I agree in principle. However, I have seen situations where the transient failure was so brief it looked 'mysterious'. It took time and effort to track it down. Sometimes it was because the motor power supply was underpowered. When the motor 'stalled', for example when changing direction, taking maximum current, the power supply voltage might dip enough to cause the Arduino supply to dip, and reset the chip.
Summary, if you are going to use a single power source for both motor and Arduino, ensure it has plenty of electrical noise filtering, and is a bit over-engineered to cope with the motor stalling. Specifically, it should be able to supply the motors stall current without dipping too low for the Arduino. The 'professional' approach is to have the Arduino monitor the main power supply, and detect that voltage dip. However, that is more complexity, and I suggest you avoid that.
Edit: If you are concerned you might have weird, hard to trace problems, using a single supply, try to design the system so that the Arduino can be 'unplugged' and given its own supply. That should be easy to do with that L298N board as the connections are screw terminals.
Using two separate power supplies should reduce the chances of electrical noise from the motors getting into the Arduino. In some circumstances is it useful to be able to change the motor power supply, or switch it off, without powering the Arduino off.
When the motor voltage is a lot higher than the 5V needed by the arduino, simple techniques to step down the voltage (linear regulators, like the part on that L298N board) convert the excess power to heat, which is quite inefficient. Much above, about, 18V it can generate enough heat to reach quite a high temperature (i.e. 100C) unless it has a good heatsink.
In that case, a simple, cheap solution is to use a second small power supply for the Arduino. An Arduino is likely using under 100mA, so a PP3 would be okay for, maybe, a few hours. A longer term approach is to step the motor voltage down efficiently.
If you use two power supplies, connect the two 'ground' (i.e. or most negative battery connections) together so that they have a common 'ground' reference. That way the Arduino signals will control the motor driver reliably.
Edit:
PWM does not step down voltage. It gives the illusion of less power because the full voltage is only applied for a fraction of each millisecond. When it is on, it is providing (very close to) the full 'motor' voltage. If the 'motor voltage' connected to that L298N board is 12V, then the motor will see 12V.
However, even if the motor is rated at only 3volts, it is unlikely to break only because 12V is applied across it. A 3V motor is as likely to break because it gets too hot, or spun too fast (e.g. the bearings get damaged).
It will likely get too hot under load, or spin too fast if the PWM signal is on for more than, WAG 50% of the time (but there is no warranty with WAG = Wild-A$$-Guess).
If, and only if, your software doesn't run PWM more than 50%, then those motors may be okay. That is a risk I might be prepared to take if the motors are cheap, and replacements easy to get.
Skimming the datasheet, the L298N needs an absolute minimum motor supply of 2.3V+2.5V = 4.8V.
Also, the output switches which control the motor appear to 'drop' a minimum of 1.8volts.
So I think it would be okay with 6V or 7.2V (maybe upto 9V) motor voltage.
IIRC the arduino will work okay with 7.2V upwards, i.e. 6 x NiMh batteries. A higher voltage is just converted to heat by the on-board voltage regulator. I might be tempted to experiment with the L298N boards 5V output, unless you have seen complaints about it.
I am assuming the motors are brushed DC motors (and not steppers or something exotic)
The motor driver will handle switching the current that the motor needs. However, each time the current is switched on or off, the motor will draw current, or generate current (remember it is a motor and also a generator). That could cause the power rail to dip, or even feed current into power or ground. There are diodes on the board to prevent those spikes doing anything awful to the chip, but there is still current flowing through wires.
Further, every rev of the motor, the brushes will break one connection, and make a different connection with the commutator, typically 6 times. (The commutator is the mechanical system that directs the current to flow the correct way round in the motors spinning electromagnet). That creates electrical noise. In some cases so much that you can hear it on an old fashioned radio receiver or analogue TV.
So noise may be a problem. People typically put a 10nF-100nF, relatively high voltage (say 50V), capacitor directly across the motors power connections, at the motor end.
If things get bad, I did a quick search and this blog looked okay, it illustrates ways to use capacitors and inductors to reduce motor noise.
I wouldn't worry too much. Put 10nF-100nF across the motor wires, and see what happens.

Thanks for the reply.  I updated my question and it's 8 AA batteries not 6.  I seen these tutorials and i am able to get the motors running but i am new to electronics and wanted to know the logistics behind connecting motors to the driver and arduino plus stepping down voltage and effect on the driver chip.  Also i don't think any of these tutorials talked about powering the arduino itself.  I am not sure it is assumed that is powered from USB or need a separate power source

Thank you very much!!! This is exactly the information i was looking for which was not included in the other tutorials.  This greatly helps me to continue on with the project.  If don't mind i updated the question with few more questions that i want to ask you.  Either way i am accepting the answer :) Have a great day!

This is a severely underappreciated answer.

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


text:
portd not writing on digital ports 5 and 7
I try to build a function generator (preferably a sine) with an R-2R ladder and a Arduino Leonardo by Borderless Electronics.
For performance reasons one should use portd instead of digitalWrite.
However the signal is not at all what I want (just noise). So upon further investigation I found that the digital pins were never on HIGH. Pin 6 worked flawlessly. Furthermore I have tested the two failing pins with simple test programms and they behaved exactly as I would have expected.
Here is the code I use
 int sine[255];

 void setup()
 {
     pinMode(0, OUTPUT);
     pinMode(1, OUTPUT);
     pinMode(2, OUTPUT);
     pinMode(3, OUTPUT);
     pinMode(4, OUTPUT);
     pinMode(5, OUTPUT);
     pinMode(6, OUTPUT);
     pinMode(7, OUTPUT);

     float x;
     float y;
     for(int i=0;i<255;i++)
     {
          x=(float)i;
          y=sin((x/255)*2*PI);
          sine[i]=int(y*128)+128;
     }
}

void loop()
{
     for (int i=0;i<255;i++)
     {
          PORTD=sine[i];
          delayMicroseconds(10);
     }
}

I tested this with two Arduinos of the exactly same type.
Question: Why are pins 5 and 7 never on HIGH?
Edit: I have simplified everything down to one statement in the loop: portd = x;
I vary x manually
expected findings:
x  ->  #pin that is on high
0  -> None
1  -> 0
2  -> 1
4  -> 2
8  -> 3
...
128 -> 7
actual findings
x  ->  #pin that is on high
0  ->  None
1  ->  3
2  ->  2
4  ->  0
8  ->  1
16 ->  4
32 ->  None
64 ->  None
128->  6
I test this by simply connecting an oscilloscope to the output pins. The behaviour is extremely strange since the pins seem to be in random order, some even missing to portd. Furthermore portd = B11111111, according to the manual, is equivalent to portd = 255; and should set all pins on HIGH. But in my case it sets every pin to HIGH, except pins 5 and 7 are on LOW.

How are you testing the signal? Can you give examples of the actual and expected output from all pins?

Hi Peter. Thanks for your comment, i edited the question and hope it is more clear now.

This is because on ATmega 32u4, which is used in Arduino Leonardo,  pins 5 and 7 are not mapped to port D but to port C and E respectively, as you can see in the ATmega 32u4 - Arduino Pin Mapping.

So you will have to:

either find another port where all 8 bits are available as digital outputs (note that I'm not sure one such port exists)
or split each sine[i] in 2 parts because you will have to work with 2 ports at the same time.

As @jfpoilpret points out, Arduino pins are not always mapped to port bits in a straightforward manner, and it’s crucial to understand the mapping for your particular model.
In fact, the Arduino Leonardo is designed in a way that none of the ports has all 8 bits usable as I/O pins. As far as the microcontroller is concerned, ports B and D each have all 8 bits available, but the Arduino Leonardo/Micro design uses one bit on each port for a LED.
I would also recommend that if you’re using a PORTx register directly, instead of going through the Arduino API, that you also use the DDRx register to set pin directions, instead of trying to use pinMode.


text:
Autonomous Quadcopter power distribution and sensing concerns
I've been programming and testing an Arduino based quadcopter for the past 4 months. Until now I did not need to use an external power source for my sensors. Now I want to use the 'BEC' power from my electronics speed controllers.
Each of the 4 ESCs gives 5V @ 2A. I would set these up in a parallel circuit, which would give me 5V @ 8A (theoretically).
I also want to use a cheap chinese voltage sensor to sense the voltage from my 5000mAh 25-50c 11.1v battery. I'm not sure if it is safe to connect my batteries wires to my sensor with the 125A that it can put out.
My question is whether or not it is safe to have a common ground on Arduino with an 8A power supply AND if it is safe to use a 5V 8A power supply with these sensors.
Here is a problem that I've encountered before:
while powering my IMU off the BEC and sending motor PWM signals, my sketch would run for about 10 seconds then freeze. It was not until I powered my IMU off the Arduinos 5V power that I was able to run the sketch flawlessly. What could have been causing that?
I've made a diagram of my circuit in Fritzing (not actually tested yet due to fear of ruining my sensors). I'm using an Arduino Mega.

I have frequently heard that it is a bad idea to wire multiple BEC's in parallel. My guess is that this is because they will not all output exactly the same voltage. You might want to find out what type of regulator your ESC's use and find out if they can be paralleled.

yes the more I think about it I really dont need 8 amps 2-4 is enough. Thanks:)

I've heard that the BECs on some ESCs don't always output a smooth 5v and it can vary with how much power is being used by the motors. Perhaps that could cause the arduino to crash?

so do you think that a regulator is necessary

A regulator is what a BEC IS. The built-in thing in your ESC is typically a linear voltage regulator, and they are extremely unreliable and should not be used to power critical equipment on your aircraft. Just don't do it. In fact I recommend disconnecting the middle wires on your ESCs, to permanently disable the on-board regulators, as they aren't needed for anything really. Power your Arduino and RC receiver from a separate 5V regulator, preferably switching type (Castle Creations), connected to the main battery.

Your question is quite long. I've broken it up into several parts:

whether or not it is safe to have a common ground on arduino with an 8 amp power supply

Yes. In fact, if you have any electrical connection (even a signal) between those two, you'll need a common ground to ensure integrity of the data being sent.

if it is safe to use a 5 volt 8 amp power supply with these sensors.

I didn't see how much they drew. Without a lot of information, I'm going to say yes. If you don't need that much current, consider removing one of them so you only have 6A or 4A, since 8A is quite a bit if you aren't using it (and you might waste electricity in the conversion process). Make sure to have a thick enough wire for it. A best practice scenario would be to use each ESC separately or use two of the ESCs in parallel (with all  of the grounds connected!). This would isolate the current to either 4A or 2A.

while powering my IMU off the BEC and sending motor PWM signals my sketch would run for about 10 seconds then freeze. It was not until i powered my IMU off the arduinos 5 volt power that I was able to run the sketch flawlessly. What could have been causing that?

I'm not quite sure what would be causing that without seeing the code/circuit for that. The only thing I can think of is the grounds weren't connected and the signal got corrupted.

Thank you for taking time to answer this question you have been really helpful.


text:
Using VirtualWire and RCSwitch in same PRoject
I have the problem, that I want some Arduinos communicate in a wireless mesh network using the VirtualWire library but also be able to receive (and send) codes for my rc sockets using the RCSwitch library.
I have some Arduinos using VirtualWire and some devices using the hx2262 IC for RC-Decoding.
I want to send and receive messages between the Arduinos (each message must be at least 10 bytes long) and also be able to send and receive messages from the hx2262 RC power sockets.
My idea would be to use VirtualWire for inter Arduino communication and RCSwitch for the power sockets. Both work fine as long as I do not put both libraries on the same controller.
Does anyone have an idea to solve that problem?

I finally found a solution: Just use both libraries. The problem I head: VirtualWire uses Pin numbering, RCSwitch uses Interrupt numbering. That was the reason, why it did not work.


text:
Wireless Sensor (IMU) to Arduino
I was doing some research about this subject and I only have more questions than answers.
I want a little IMU sensor (I don't know which hardware I should get) that sends data wirelessly to my Arduino.
The sender part (IMU + sender + battery) should be small (tennis ball size is fine) and the receiving part should be an Arduino.
What should I buy? How can I achieve this? I was looking at a lot of ideas: Xbees, bluetooth, radio receivers, Arduino Nano, etc.
My focus is on the Arduino code, I just need that the IMU sends data at least at a ratio of 10ms.
As a plus I would love to have more than one Wireless IMU sensor connected to my Arduino.

What is the purpose of having the IMU and arduino in different locations in your project? What data are you specifically looking to get from the IMU?

There are in the same location (4-5mts). But its some sort of instrument and i want to avoid the use of cables. Im sending the stream of the Gyro/Accel.

A bunch of ATmega-based quadcopter boards could be an interesting platform as they often now incorporate a six axis chip such as MPU-6050, and use 2.4 GHz radios which are bidirectional.  They are also relatively cheap (replacement parts for toys built around other processors may be even cheaper)

You have not really given enough specifications for any choice of radio to make a difference in your scenario. Any list of products would be very long, overly summarized, and not relevant in a month, So I'll try and outline the thought process I would take in finding the fit for a project I was making.
Radio: Which type of radio to choose will depend on a lot of specific factors, but its more than likely that multiple options will work perfectly. You seem to know the major methods, Xbee, bluetooth, Wifi, and for very long distances, GSM.
You should consider the problem, define what you need by looking at the amount of data per second you want sent, the necessary range, the power you have available in the battery, any region specific laws, and anything else you can think of needing. Also consider if you really need an arduino as the receiver, or if you have a Bluetooth equipped laptop or wireless router on hand that could take that roll for you. Then look around at sparkfun or wherever and find the cheapest, most popular method that fits the bill.
IMU: Many IMU's exist with more or less the exact same features, so I will recommend a similar process. Look at the power consumption, output rate, sensitivity, and communication method you project needs, and find the cheapest and/or best rated item at your preferred electronics retailer that fits the bill. the MPU6000's are popular these days. The altIMUv4 has a magnetometer and barometer included as well. Shop around.
You will most likely want to put an arduino nano/micro/trinket/whatever with the IMU to translate to your communication method. Some radios work with UART serial, but not many IMU's output like this. Those that do cost more because they have a coprocessor on board. Consider if buying a co-processor equipped board will make your sensor processing easier before you discount it for the elevated price. In depth sensor fusion gets pretty hairy, and for some, not having to worry about it could be worth $50.

I followed this recommendation. For each component, evaluate every aspect of it and get the better option available that suits our budget. We finally went for Arduino Fio, XBee Trace Antenna (802.15.4) and the IMU (ITG3200/ADXL345)


text:
Arduino shield stacking
I have an Arduino GSM Shield mounted on an Arduino Uno. Can I stack this GPS shield above Arduino GSM shield? Will there be any pin configuration problem?
In GSM Shield hardware pin’s configuraton are as below:
0 - Not connected
1 - Not connected
2 - GSM Rx
3 - GSM Tx
7 - Modem reset

If there is any problem, how can it be solved? I would be happy if there are any alternatives for the GPS shield.

Addendum
The schematic of the Arduino GSM shield:

The schematic of the SparkFun GPS shield:

Start by finding the circuit diagrams of both shields and lining them in your question.

According to the GPS shield quick start guide (https://www.sparkfun.com/tutorials/173), it seems possible to select different pins for serial communication than the default ones (2 & 3) that conflict with yout GSM shield. So that should be OK.

@jippie - I've added the schematics

Photo by John Boxall
Which pins do they use?
To determine if two shields are compatible, you have to read the specifications of both shields.
The best source for this information is the data sheets supplied with the shields. However there is also this Shield List
Can you reassign pins?
Some shields provide a means to alter which pins are used for communications. This can take the form of a switch or a jumper - either pull-off or solder-bridge type. (the GPS shield in the question has jumpers).
Where the shields do not support pin-reassignment or provides insufficient flexibility, to work-around incompatibilities you can use an in-between shield designed for the purpose.
here is one example:

You hear it all the time in the Arduino community, “will this shield work with my other shield?.” I think we’ve all been disappointed to find that two of our favorite shields compete for control of a digital pin here or a serial pin there. While there are sometimes some clever workarounds from elegant code modifications to aggressive ‘greenwiring,’ Mayhew Labs may have come up with the simplest solution thus far: The Go-Between Shield.

Are any alternatives for the foo shield
I notice that Arduino.cc now point people to the list referenced above. They used to have their own list.
Product recommendations are off-topic here but, obviously, you can search

+1 for the link to Arduino shields references, and for the go-between shield as a generic solution to this kind of issue. However, in this specific case, a go-between shield seems useless as the GPS shield allows changing the TX/RX pins (2 & 3 are just the default pins) quite simply.

@jfpoilpret: Good point. I'll update answer.

From the shield description, the TX and RX of the GPS are mapped on pins 2 & 3, like your GSM, so you'll have to change that.
I'm using Adafruit GPS + flash card shield, which is a bit cheaper (and uses pins 7&8).

But my GSM shield uses pin 7 uses modem reset. Will It create any problems by placing GPS shield on the GSM shield ?

Yes, very same thing. Depending on what you want to do, why not use a breakout plugged on a breadboard ? You'll be able to choose pin assignment.

This answer does not directly address the pin conflict issue, but rather skirts around it.
I have been looking into this same issue for over a month now and have come to the conclusion that the best option is to either purchase, for around $30:

or make, for around $20 (+$60 for the modules)

a shield that uses the SIM908. The SIM908 comes with both GPRS/GSM functionality, and GPS functionality, whereas the SIM900 only has GPRS/GSM. Now, there is no longer an issue with pin conflicts, as instead of two separate shields, only one is required.
The only disadvantage is that if you already have a GPRS/GSM shield, then that purchase will become redundant.
As an aside there is an alternative of a 3G (WCDMA and HSPA) and GPS, using both assisted-mobile (A-GPS) and mobile-based (S-GPS) modes, combined shield, from Cooking Hacks. A bit more pricey though, at $160.


text:
Arduino IDE Unable to detect ZumoMotor.H ( PIXY PET )
recently i trying to make the pixy pet work for my project. (https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/playing-with-your-pet).
I used the given code for the arduino IDE, but i keep on getting this error Arduino: 1.5.7 (Windows 7), Board: "Arduino Leonardo"
sketch_sep17a.ino:27:24: fatal error: ZumoMotors.h: No such file or directory compilation terminated.
This report would have more information with "Show verbose output during compilation" enabled in File > Preferences.
The Code, im using, was given by the official maker of the Pixy Pet. Please have a look. ( https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/the-code)
Thank You.

It looks like you need to install the ZumoMotors library.
There's one available at the following link, although I don't know for sure that it's the same one your Pixy Pet requires:

https://github.com/pololu/zumo-shield

That page includes instructions on how to install the libraries. If you get stuck, there's more help in the official Arduino documentation:

http://arduino.cc/en/Guide/Libraries


text:
Powering LCD Displays without a Breadboard
I hope that this is not a silly question. I may be hoplelessly optimistic in asking, but is there any way to power & display information onto a LCD Display from an Arduino Uno.... Without the breadboard? I am working on a hardware project that has very strict space constraints, and the breadboard is simply not an option.

It will highly depend on the kind of LCD you consider connecting to your Arduino: some LCD displays can be directly wired to the UNO, others need extra components (typically for level shifting) that will need a breadboard, a stripboard or a PCB.

I presume you're looking at this page - the breadboard is merely a convenience, you can just hard-wire the LCD directly - most don't even come with that header plug soldered on.


text:
DC Motor not behaving reliably
Using an Arduino Mega. I have a motor hooked up exactly like the picture below. Using a BC548B transistor, 1N4001 diode, 220 ohm resistor and a 9V battery. I'm driving the motor in code by using PWM analogWrite to value 255. Weird thing is, if hooked up to USB (5V), the motor will only start to move after a certain amount of time, seems like it needs some initial "drive" to get started. If using the 9V battery it starts up quicker, but still not directly, as I would expect. Also, if I set analogWrite to some value less than 255, it will not move at all - is the transistor limiting? Can I change the resistor value to compensate? Thanks for any advice.
int motorPin = 3;
int interval = 10;
int walkingTime = 7.5;
bool walking = false;

void setup() {
  pinMode(motorPin, OUTPUT);
}

void loop() {
  delay(interval * 1000);
  if (!walking) {
    startWalk();
    delay(walkingTime * 1000);
    stopWalk();
  }
}

void startWalk() {
  walking = true;
  analogWrite(motorPin, 255);
}

void stopWalk() {
  walking = false;
  analogWrite(motorPin, 0);
}

First off, you need to ensure the transistor you use fits with the motor you want to drive; you did not mention any spec data about that motor, so it is not possible to answer your question. Second, a 9V battery is never adequate to drive a motor as it is very limited in energy (measured in mAh). Finally, changing the resistor value will certainly not compensate for anything power-related, 220 Ohm is a rather adequate value for this kind of usage.

I don't think there is any diode with PN2222 reference, it seems you confuse with a transistor reference. Typical diode references are 1N100X (replace X with a digit).

Although I don't think the problem is with your code, it might still be useful to post it also so that we can definitely remove any issue with coding.

Sorry for the confusion, it's a 1N4001 Diode. The motor is packed within a plastic enclosure and I can't read any info on it but will try to use a multimeter to find out how much it draws and report back. Will update the question with the code now.

It won't solve this problem, but you really should get a capacitor in there. The motor may have a high starting current, especially if there's a load on it. Adding a capacitor between Vin and GND on the breadboard will help dampen any large current draws being inflicted upon the board. 220uF, rated at 16V minuum is a good starting point. Better still, if the motor is going to be drawing quite a lot of current you should consider connecting the yellow wire of the motor and the blue wire of from the transistor directly to the + and - of the battery, respectively.

Summary:
Your transistor is the wrong way round.
Rotate it 180 degree (so that collector and emitter are swapped) and it should work.
There are much better transistors available for this job, but this one should work when correctly connected.
Swap, test, report back.
The blue wire goes from emitter (right hand lead) to Arduino ground.

Longer:
The transistor is almost certainly "backwards" as above. More on that below, but first some comment on the actual transistor used and a superior alternative.
While it should work better than you describe, the BC548 is not a very good transistor for motor driving. It's maximum collector current is 100 mA. While you do not state the required motor current, within sensible limits a good guide is that the more a transistor can handle the better it will work, all else being equal. A 500 mA rated part would work better. An excellent pair of small transistor for "playing" are the BC327-40 (PNP) and the complementary BC337-40 (NPN). These have guaranteed current gains (effectively current amplification factor) of 250 and typically of 400. They are typically rated at 45V and 500 mA.
The Fairchild versions data sheet here from Digikey have an absolute maximum 800 mA rating. While the part was originally a European one it is widely available in the US and Asia and is usually about the same price as transistors with substantially inferior specs. eg see Digikey pricing below for BC548B and BC337-40 in 1, 10 and 100 quantity. The BC337 costs 1 cent more per transistor in each case. The BC337 comes in 3 versions with suffixes -16, -25 and -40. This relates to the current gain. The -40 part has an average Beta or current gain of 400. This is better (higher) than most alternatives and costs little or no more than the lower gain -16 and -25 parts.
BC548B datasheet here
BC337-40 datasheet here
BC548B pricing
1 10 100 prices are 22 / 20 / 11 cents each.
BC337-40 pricing
1 10 100 prices are   23 / 21 / 12 cents each.
According to that the pinout is CBE (collector base emitter) left to right looking at flat front with pins down. There are occasionally variations between manufacturers (but should not be) but if the datasheet matches your transistor it is "in backwards".
Swap C & E by rotating 180 degrees and report back.
With C&E swapped it acts like an NPN withj very low current gain.
Note: Presumable where you saay digitalWrite you meant analogWrite?

Will try turning the transistor around later today and report back! And yes, I meant analogWrite instead of digitalWrite.


text:
I²C with ATTiny85 at 8MHz using TinyWireM library
Hello fellow Arduino enthusiasts, I am trying to make the ATTiny85 talk I²C with a MMA7660 breakout board I have (it's an accelerometer, this is a follow up question to my previous one).
I would state in advance that the I²C chip works perfectly with Arduino Nano, that I am using the Arduino IDE v1.5.6-r2, using the arduino-tiny core (from here) and that until now I had no special issues working at 8MHz.
The official documentation for the TinyWireM library (at the Arduino playground website) states that:

By default the I2C master library (TinyWireM) is set to run at 1MHz.
  To run at 8MHz, #defines in USI_TWI_Master.h / .cpp must be changed.

I have made the following changes in USI_TWI_Master.cpp:
#define F_CPU 8000000UL // was 1000000UL

I have made the following changes in USI_TWI_Master.h:
#define SYS_CLK   8000.0 // was 1000.0
#define T2_TWI    1.3 // was 5
#define T4_TWI    0.6 // was 4

My guess is that the T2_TWI & the T4_TWI values are wrong. I also tried T2_TWI 40 and T4_TWI 32 (as stated here), and T2_TWI 2 & T4_TWI 1 (as stated here) but no luck. I also tried some other values in between that I thought might make sense but it won't work.
The code I am running is the I²C scanner from here (which as I mentioned works perfectly with the Nano and finds the device), the blow is a modified version for interfacing the TinyWireM library instead of the Wire library:
#include <TinyWireM.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(-1,4);

void setup()
{
  TinyWireM.begin();
  mySerial.begin(9600);
  mySerial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;
  mySerial.println("Scanning...");
  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    TinyWireM.beginTransmission(address);
    error = TinyWireM.endTransmission();

    if (error == 0)
    {
      mySerial.print("I2C device found at address 0x");
      if (address<16)
        mySerial.print("0");
      mySerial.print(address,HEX);
      mySerial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      mySerial.print("Unknow error at address 0x");
      if (address<16)
        mySerial.print("0");
      mySerial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    mySerial.println("No I2C devices found\n");
  else
    mySerial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

As a side note I would say that my logic analyzer was broken recently and I'm sure it would have helped here... Also I am aware of the sound-card hack to be used as logic analyzer, but would prefer to avoid adding more error-prone variables to the system, if possible, for now.
Here is a picture of probing with Saleae logic analyzer of the two channels. The result of the code above is "No I2C devices found":

(Full size picture)
Would appreciate the insights of anyone with experience using ATTiny85 at 8Mhz with I²C successfully.

Did you burn the fuses (upload bootloader) to enable the ATtiny to run at 8MHz?

@imjosh: yes. thanks for bringing it up. I am always using the same ATTiny for prototyping and from time to time I burn the fuses just to be on the safe side :)

I took a look at USI_TWI_Master.h, and I don't think T2_TWI and T4_TWI should be changed at all.  Just SYS_CLK   from 1000.0 to 8000.0.  Have you tried it like that?

Yes. I also tried with the original values. no go.

Are you using an external crystal or resonator?

I am using the internal resonator.

Try using an external crystal or calibrating the internal resonator maybe - https://www.google.com/search?q=calibrate+attiny+internal+resonator

thanks, but currently I'm looking for a solution that does not require external crystal. Also I could not find any reference on how to calibrate the internal oscillator (and not resonator, according to the spec). In addition I find it hard to believe that SoftwareSerial timing is right if the internal oscillator is not accurate enough.

Did you manage to successfully run I²C on ATTiny85 without external oscillator?

Let us continue this discussion in chat.

You have the Pull up resisters in place... both of them?

Yes. Both of them.

Any luck with this issue? I am probably experiencing very similar. My logic analyser says the first byte sent (the slave address) is correct, the rest is nonsense. I tried it on 1Mhz and 8Mhz, correct fuses, fiddling with the T2_TWI/T4_TWI but I am running out of ideas.

Unfortunately no. I also checked with logic analyzer and oscilloscope- and I can confirm output is garbage.

@Omer Looking at this picture from your post, are'nt SDA and SCL signals reversed? SDA looks like clock and SCL looks like data.

I have the same problem as you with a DHTC3 probe. The I2scanner code does not respond OK to the probe address with an Attiny85 while it works with an Arduino Uno. However, I changed the frequency to 8 Mhz and the 2 timers T2_TWI and T4_TWI. And you, have you solved your problem please?

You really just need to scope the signals, even if it's with a DSO Nano-type scope.
Without downloading the datasheets:

I would guess your pull-up is probably too small, but possibly too large (scope it)
Slew rate may be either insufficient or too steep (scope it)
Be aware that the ATTiny runs at "8MHz", and not 8.00MHz. The timing error can be off enough to cause communication issues at high speeds while working well at lower speeds (scope it, and/or start at default and incrementally increase speed by 0.5MHz until it stops working)
MMA may not support a typical protocol feature being used, i.e. 'repeated start', burst transfers, etc. (datasheet register/programming section)

Edit: Both the ATTiny and the MMA should have bypass capacitors near the power pins.

It's kind of easy to miss, but on my last comment to the question I mentioned that I did use logic analyzer and that the results are garbage. It happened with other I2C devices as well, not just MMA. Did you ever got the I2C working with the ATtiny85?

The Tiny family supports both "I2C" and "SPI", although they are not implemented as separate hardware peripherals. Instead, the Tiny has a generic hardware peripheral called the USI, that can emulate both.
Of course, both protocols can always be bit-banged for virtually 100% guaranteed communication with anything you want.

If you feel like it, could you hook up any I2C device up to one and post a capture from your scope?

I discovered that I have an MMA8451Q on my KL25Z. I will try to run it with the Tiny tomorrow and post back the results.

The USI part from Atmel documentation is what giving me hope. Unfortunately I never heard of anyone succeeding with it. I'll update my question with a screenshot of the probing.

uploaded the screenshot.

I know it's an old post, buy my ATTiny85 talked successfully to the BMP280 sensor via I2C using TinyWireM. And no, the SYS_CLK 8Mhz or 1Mhz doesn't make any difference. It works with any T2 and T4 for me - the 5 and 4 default (faster) or 40 and 32 (just slower). My issue was that I've bit-banged the LCD screen and then initialized via TinyWireM the BMP280 sensor... that mix doesn't work.

Just an idea. On adafruit.com there's a product called Trinket which is an ATtiny85 microcontroller board. It can communicate over I2C using their TinyWireM library. Maybe you should  check it out for reference. I hope it helps :)

The owner of the question has already mentioned they are using the library.


text:
Reading several rotary encoders
Have an upcoming project where user input will be based on spinning a large cog and I have several UNOs available
Since rotary encoders need two pins, only a Mega would be able to handle the 7-8 encoders needed. Unless theres a better method of reading them?
Is it worth using an ATTiny85 per encoder and passing all this data to a mega via 1 pin each? This way, I could extend the project beyond 7-8 later?
Or is this idea out the window, because there's a much simpler way?

An Arduino Mega has 54 input pins, which would yield a whopping 27 encoders? Also, reading rotary encoders can be done using interrupts, which is practically zero-overhead (no polling, CPU is only shortly interrupted when an action occursi i.e. CLK has a rising edge). My point is: 1. A Arduino Mega has enough pins, 2. by using an interrupt-capable I2C GPIO expander (e.g. 16-bit MCP23017) you could also do this more efficiently. Sure the question is right?

I meant UNO when writing Mega, thinking maybe a mega. A fantastic should out for the MCP23017 - I will update the question to reflect

rotary encoders need two pins ... not all  ... what kind do you have?

I have a rotary encoder and a MCP23017 here, I'll build a proof-of-concept and come back with an answer later this day.

See https://hackaday.com/2018/04/15/rotary-encoders-become-i2c-devices/ . This person used one chip per rotary encoder. The position would then be retrieved by the Arduino using I2C. So using only 2 pins you could connect up to 127 encoders. Another advantage is that the device can do the debouncing, so your main Arduino does have to deal with this.

Library and schematics are at https://github.com/maxgerhardt/rotary-encoder-over-mcp23017.
To read a rotary encoder (i.e., detect state changes of the knob), there are two possible implementations:

poll the state of the two output pins and check for changes
set up an interrupt which will be called when an output pin changes, then check for changes

Using interrupts is more efficient than always polling the pins, because an action is only executed when an actual change occurs.
Per rotary encoder you would need two pins on your microcontroller. However, we can use GPIO expanders over e.g. I2C or SPI, such as

Microchip MCP23017 (16-bit, I2C)
Texas Instruments PCF8575 (16-bit, I2C), PCF8574 (8-bit, I2C)

Using a port expander over I2C has the advantage being a bus that only uses 2 pins. This means that there can be multiple (up to 127) devices on the I2C bus, and each I2C device can then e.g. provide 16 GPIO pins.
Using an ATTiny85 per encoder and possibly joining them via an I2C bus is also possible, however more expensive and more work.
I've chosen a MCP23017 here because it is interrupt-capable, has 16-bit and I had it lying around. A PCF8574 would have also worked just fine, since it has the same capabilites.
Tests were made using an MCP23017 and a KY-040.

The written library uses a modified Adafruit MCP23017 library and the Rotary library. The Rotary library also handles debouncing by using a state-machine based approach for decoding. The library is a simple header file which defines a RotaryEncOverMCP C++ object, with which a rotary encoder connected to an MCP23017 device can be easily described and managed. It has an example for the polling method and the interrupt method.
For 1 encoder, one can write down schematic like: (interrupt based)

Since one MCP23017 has 16 ports, we can connect up to 8 rotary encoders to one such device.

However the MCP23017 also has three address pins with which its I2C address can be selected. This means we can have 2^3 = 8 such device on the same I2C bus (i.e., connected to the same SDA and SCL lines).
Thus, with one I2C bus, which uses 2 pins, we can have a maximum of 8xMCP23017 and 64 rotary encoders (assuming no interrupts are used, which would need 1 pin for any number of rotary encoders). At the cost of 2 more pins on the microcontroller, we can create another software bit-banged I2C bus, each of which adds again a maximum of 64 rotary encoders.
Assuming D2 to D13 and A0 to A5 are free, on these 18 pins we can have 9 I2C buses with a total of 72 MCP23017 devices hosting a grand total of 576 rotary encoders. Whatever one might need that for.
I've tested this library with one rotary encoder and a MCP23017, but the code is structured in a way that adding more encoders is just adding an entry in an array.

Fantastic. This is exactly the information I was looking for – I've ordered a handful of MCP23017 to get started. I really appreciate the depth you've gone to here

Started working on this today and i've got a setup that is exactly to the specs of the schematic, but nothing is reading on the  console – did you experience a similar problem when writing the answer? and if so, what part should I be checking for

@AndrewLazarus run the I2C scanner scetch first to make sure you can reach the MCP23017. If not, check that the I2C lines, power and RST are connected properly

Thank you! This was good information!

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


text:
Measure small capacitances with ATtiny85 (Digispark board)
I have successfully run the code provided here on an Arduino Nano. If nothing is connected, it will output a very small capacitance (~ 1 pF).
Then I tried to migrate the code to the ATtiny85 (using a Digispark USB Development Board), but I fail to get anything reasonable out of the code. The first analogRead will always give 1023, whereas on the Nano it gives a very small value (again for nothing connected to the input pins).
It's a bit trickier on the ATtiny85 because the pin numbers are different for digital and analog, but I thought I got that right, so what went wrong in the migration?
const int OUT_PIN = 2; // digital pin PB2 is 2, positive pin of C
const int IN_PIN  = 5; // digital pin PB5 is 5, negative pin of C
const int OUT_ANA = 1; // analog read PB2 is 1
const int IN_ANA  = 0; // analog read PB5 is 0

const float IN_STRAY_CAP_TO_GND = 24.48;
const float IN_CAP_TO_GND  = IN_STRAY_CAP_TO_GND;
const float R_PULLUP = 34.8;
const int MAX_ADC_VALUE = 1023;

#include "DigiKeyboard.h"

void setup() {
  pinMode(1, OUTPUT);
  pinMode(OUT_PIN, OUTPUT);
  pinMode(IN_PIN, OUTPUT);
  digitalWrite(OUT_PIN, LOW);
  digitalWrite(IN_PIN, LOW);
  DigiKeyboard.update();
}

void loop() {

    pinMode(IN_PIN, INPUT);
    digitalWrite(OUT_PIN, HIGH);
    int val = analogRead(IN_ANA); // IN_PIN in Nano version
    digitalWrite(OUT_PIN, LOW);

    DigiKeyboard.println(val);
    if (val < 1000) {
      pinMode(IN_PIN, OUTPUT);
      float capacitance = (float)val * IN_CAP_TO_GND / (float)(MAX_ADC_VALUE - val);
      DigiKeyboard.print(capacitance);
      DigiKeyboard.println(" pF");
    } else {
      pinMode(IN_PIN, OUTPUT);
      delay(1);
      pinMode(OUT_PIN, INPUT_PULLUP);
      unsigned long u1 = micros();
      unsigned long t;
      int digVal;

      do {
        digVal = digitalRead(OUT_PIN);
        unsigned long u2 = micros();
        t = u2 > u1 ? u2 - u1 : u1 - u2;
      } while ((digVal < 1) && (t < 400000L));

      pinMode(OUT_PIN, INPUT);
      val = analogRead(OUT_ANA); // OUT_PIN in Nano version
      digitalWrite(IN_PIN, HIGH);
      int dischargeTime = (int)(t / 1000L) * 5;
      delay(dischargeTime);
      pinMode(OUT_PIN, OUTPUT);
      digitalWrite(OUT_PIN, LOW);
      digitalWrite(IN_PIN, LOW);

      float capacitance = -(float)t / R_PULLUP / log(1.0 - (float)val / (float)MAX_ADC_VALUE);

      if (capacitance > 1000.0) {
        DigiKeyboard.print(capacitance / 1000.0);
        DigiKeyboard.println(" uF");
      } else {
        DigiKeyboard.print(capacitance);
        DigiKeyboard.println(" nF");
      }
      DigiKeyboard.println(val); // usually ~ 520 (because we wait until digVal == 1?)
      DigiKeyboard.println(t); // depends on C: ~ 26000 for 1 µF, ~ 2600 for 100 nF, ~ 250000 for 10 µF
  }

  digitalWrite(1, 1);
  delay(10);
  while (micros() % 1000 != 0);
  digitalWrite(1, 0);

}

The reason this doesn't work is that PB5 is pulled high (as it's used as -RESET pin on the board). The code can be rewritten to use only one ADC pin though.


text:
'readPulsioximeter' was not declared in this scope
I am new to Arduino. I am trying to use Pulsioximeter sensor with e-health Platform (http://www.cooking-hacks.com/documentation/tutorials/ehealth-biometric-sensor-platform-arduino-raspberry-pi-medical) on Arduino Uno. Line number 13 is working fine in the example code given in the library and works just fine. But when I try to upload my custom code (setup function definition is given below), I get an error stating 'readPulsioximeter' not defined in this scope. The error doesn't seem obvious to me. Please guide.
Here is the custom code upto setup() function:
#include < eHealth.h >
#include < PinChangeInt.h >
bool configuration = false;
//bool in_it=true;
byte val; // variable to receive data from the serial port
int ledpin = 13; // LED connected to pin 48 (on-board LED)
int A=1;
void setup() {
           pinMode(ledpin, OUTPUT);
           Serial.begin(115200);
           eHealth.initPulsioximeter();
           //Attach the interruptions for using the pulsioximeter.
           PCintPort::attachInterrupt(6, readPulsioximeter, RISING);
           delay(500);
}

 EDIT1:
readPulsioximeter is declared in eHealth.h library which has been included in program. The function has been defined as below in eHealth.cpp file:
    //!******************************************************************************
    //!     Name:   readPulsioximeter()                                             *
    //!     Description: It reads a value from pulsioximeter sensor.                *
    //!     Param : void                                                            *
    //!     Returns: void                                                           *
    //!     Example: readPulsioximeter();                                           *
    //!******************************************************************************
    void eHealthClass::readPulsioximeter(void)
    {
        uint8_t digito[] = {0,0,0,0,0,0};
        uint8_t A = 0;
        uint8_t B = 0;
        uint8_t C = 0;
        uint8_t D = 0;
        uint8_t E = 0;
        uint8_t F = 0;
        uint8_t G = 0;
        for (int i = 0; i<6 ; i++) { // read all the led's of the module
            A = !digitalRead(13);
            B = !digitalRead(12);
            C = !digitalRead(11);
            D = !digitalRead(10);
            E = !digitalRead(9);
            F = !digitalRead(8);
            G = !digitalRead(7);
            digito[i] = segToNumber(A, B, C ,D ,E, F,G);
            delayMicroseconds(2800); //2800 microseconds
        }
            SPO2 = 10 * digito[5] + digito[4];
            BPM  = 100 * digito[2] + 10 * digito[1] + digito[0];
    }

The problem is that you have no function called "readPulsioximeter" in your code. Either define it, pick a different function, or remove that line of code.

readPulsioximeter is declared in eHealth.h library which has been included in program. Please see EDIT1 in the the question.

:) Thanks for your help. I re-defined the function in the program and it worked.

It looks like your missed naming the eHealth object, and that that statement should read:
PCintPort::attachInterrupt(6, eHealth.readPulsioximeter, RISING);
as you did with the initPulsioximeter call. (In otherwords, "which pulsioximeter?").

When I try specifying eHealth.readPulsioximeter, it is shown as unresolved overloaded function type. Problem is that the same line is working in another program but gives error in this program.

:) Thanks for your help. I re-defined the function in the program and it worked.


text:
What is the point of D0-D3 on LCD?
The Arduino LiquidCrystal library has 4 constructors with different arguments:
LiquidCrystal(rs, enable, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)
LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)

The following comments are stated for the constructor arguments:

[...] d0, d1, d2, and d3 are optional; if omitted, the LCD will be controlled using only the four data lines (d4, d5, d6, d7).

What is the point of d0-d3 if they are not needed? Will they decrease the response time?

That type of LCD has two main modes of operation: 4-bit mode which uses 4 data pins (d4-d7), and 8-bit mode which uses all 8 data pins (d0-d7).
4-bit mode has the advantage of requiring fewer output pins on your Arduino. However, it means your sketch needs to send each command/character as two separate batches of 4-bits (one after the other). This is handled for you automatically by the LiquidCrystal library, so you won't need any extra complexity in your code. However, it does mean that your sketch requires roughly double the number of processor cycles to send anything to the LCD.
In contrast, 8-bit mode sends each command/character as a single batch of 8-bits. That simply means it technically runs a little faster.
With that said, a person looking at the display probably won't see a significant speed difference most of the time, as it still goes very quickly. The main impact will be on the microcontroller (the Arduino in this case). If it can use the faster 8-bit mode then it can devote a little more processing time to other things. That can be particularly helpful for timing-critical applications.

With that said, a person looking at the display probably won't see a significant speed difference most of the time, as it still goes very quickly. Which isn’t usually a problem since many modules (especially cheap Chinese ones like the ones on eBay) tend to have low refresh rates, so you can't update them too fast without them turning into a blurry, unreadable mess anyway.

The answer is on the same page as the quote you mentioned (I have highlighted the important statement):

Creates a variable of type LiquidCrystal. The display can be controlled using 4 or 8 data lines. If the former, omit the pin numbers for d0 to d3 and leave those lines unconnected. The RW pin can be tied to ground instead of connected to a pin on the Arduino; if so, omit it from this function's parameters.

It turns out that the Hitachi HD44780 LCD display can work in 4-bit or 8-bit modes.

Yes, it says it can be controlled using both 4 and 8 data lines. But what is the point of using 8 if you only need 4? I mean, isn't there any advantage of using 8 over 4? Why waste 4 data lines if it's of no use?

Using 8 bits mode is a bit faster on Arduino side and simpler (less code). But in general, it is not really worth it, in comparison to sparing 4 output pins.

@jfpoilpret It's worth it if you have four extra output pins...

@annon can you be more concrete about HOW it is worth to use 8 pins mode? Concrete experiment values?

@jfpoilpret As stated in Peter's answer, it gives a little more processing time to the chip. If you have four extra pins, go ahead and add it. If it would require it to be much bigger/more expensive, it's not really worth it.

The presence of those pins is a requirement of the technique that had to be used to interface the LCD to the microprocessors that were available back when the HD44780U controller chip was developed.
Single chip microcontrollers as we know them were still in the future and the LCD had to be interfaced to the 8-bit microprocessor chips of the times using the same techniques as any other 8-bit I/O or memory device which was an 8-bit bus.


text:
Identifying a counterfeit or authentic Arduino
I would like to know how I can identify a fake or counterfeit Arduino board.  For example this product, which is shown below.

I am concerned that it is cheap (about $12 when converted) and I was wondering if it is like a 'legal cheap version' or is it an unauthentic one?  If it is not authentic, would it be legal to purchase it?

It looks like an R3 Uno, but then pictures can be misleading.
However:

Arduino is open source - anyone can make one
Because of that there are many many "clones" of the Arduino
A clone, as long as it's got the right circuitry (and an Arduino is incredibly simple) is as good as the "real thing".

The only problem Arduino have with clones is the use of the Arduino name and logo.  IIRC they don't mind you claiming "Arduino Compatible", but trying to be an Arduino they don't much like.
If it's just their reference designs re-printed (which you can download for free from the Arduino Uno web page) and no further design work has been done, then although it isn't made in Italy by Arduino, it's still an Arduino.
That's the beauty / curse of open source - anyone can make one.
However, that specific one looks like it fits into the "claiming to be an Arduino" category.  It uses Arduino artwork and logos, and tries to make it look like it's an Arduino made by Arduino in Italy, when in fact it isn't.  Legally speaking, they are ripping off the Arduino brand.  Practically speaking, since it's all open source, the actual device (assuming the components aren't counterfeit) should be perfectly fine.
If they were to change the artwork, so it didn't look quite so much like an Arduino, and had something like "Arduino Uno Compatible" on it, then it would be categorized as a clone, and would be fine - you'd know where you were standing.  As it is though, the artwork on it is breaking copyright laws.
The image shown is too low quality to give much information about it, but the two big pointers that it's not made by Arduino are:

The PCB is too blue (real Arduinos are teal)
The polyfuse is the wrong colour (green instead of grey/gold)

@David FTDI hasn't been used on Arduino boards for a number of years now.  They all use an ATMega8U2 or similar programmed with CDC/ACM.

I think it's important to point out that as this board appears to use Arduino logo and branding it is not an "Arduino Clone" it is a "Counterfeit Arduino".

@akellyirl I was actually doing that while you posted that comment ;)

@JarrodChristman The simple answer is to build your own :P

Thanks guys. But what I really want to know is, if I purchase one of these, am I breaking their rights? We are told to purchase one for a small university project and even if it is a counterfeit, it should be enough. But question is, is purchasing it illegal or not.

Purchasing it isn't illegal (AFAIK, IANAL), but selling it is (AFAIK, IANAL).

No, it's a counterfeit. See here - particularly the 'components' section:
http://arduino.cc/en/Products/Counterfeit
Also, as far as I'm aware, Arduino boards are not produced in China but in Italy.


text:
Why can this color sensor not recognize green?
I got this color sensor last week, I've been able to get the sensor to recognize blue and red, but not green. still working on this.
I use the code in the product page.
so anybody have any idea about this issue? Pretty thanks.

Check that you've connected all the Arduino pins correctly to the sensor. In particular, make sure pin 4 on the Arduino is connected to S2 on the sensor.
It's the combination of signals on S2 and S3 which determines which colour is being detected:
S2    S3    Colour
----  ----  ------
Low   Low   Red
Low   High  Blue
High  Low   Clear
High  High  Green

If S2 is always low then you can only detect red and blue.
If the connections are definitely correct, then ensure you haven't made any code modifications which could interfere with it. You may also want to test pin 4 on your Arduino (e.g. using a multimeter) to make sure it's working properly. If necessary, you could use a different pin instead. However, you'll need to modify the #define S2 line in the code to match.

Wouldn't clear just be the color on the other side of the object? Or do you mean when it is out of range?

@AnnonomusPenguin That's the wording used in the datasheet. The device consists of a basic light sensor with a selectable colour filter. Clear means there's no filter, so it will simply detect the brightness of all visible light falling on it. If you apply the red filter, it mainly detects the brightness of red light, and so on. To detect the actual colour of something, you have to take three readings to get the RGB components; i.e. one with each filter applied.


text:
Imbedded loops based on inputs
I'm working on a project with 4 inputs and 7 possible outputs on an Arduino Uno.  Based on any combination of those inputs, I need to run a specific "loop" that will repeat until there is a change in ANY of the 4 inputs.  Specifically:

Input 1 = loop 1
Input 2 = loop 2
Input 3 = loop 3
Input 4 = loop 4
Input 2 and 3 = loop 5
Input 2 and 4 = loop 6
No input = do nothing

So I need to constantly read the 4 inputs and change output loops accordingly.  I have basic Arduino knowledge but am stumped.
This is what I've tried - I have 4 input pins and 8 output pins
int outPin = 0;
int inPin = 0;
int CAR = 0;
int pinRead = 0;

void setup()
{
 for (int outPin = 3; outPin < 11; outPin++);  {  //set pins 3 thru 10 as OUTPUT
   pinMode(outPin, OUTPUT);
  }

 for (int inPin = 9; inPin < 13; inPin++);  {    //set pins 9 thru 12 as INPUT
   pinMode(inPin, INPUT);
  }

}

void loop()
{
  for (int CAR = 3; CAR <11; CAR++); {  //set all pins to LOW
   digitalWrite(CAR, LOW);
  }

  // BRAKE

    {while (digitalRead(9 == HIGH) && digitalRead(10 == LOW) && digitalRead (11 == LOW) && digitalRead(12 == LOW)) {
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(10, HIGH);

  }}

  // LEFT

    {while (digitalRead(9 == LOW) && digitalRead(10 == HIGH) && digitalRead(11 == LOW) && digitalRead(12 == LOW)) {
    digitalWrite(0, HIGH);
    delay (200);
    digitalWrite(1, HIGH);
    digitalWrite(3, HIGH);
    delay (200);
    digitalWrite(2, HIGH);
    delay (200);
    digitalWrite(0, LOW);
    digitalWrite(1, LOW);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    delay (200);

  // RIGHT

  }}

    {while (digitalRead(9 == LOW) && digitalRead(10 == LOW) && digitalRead(11 == HIGH) && digitalRead(12 == LOW)) {
    digitalWrite(5, HIGH);
    delay (200);
    digitalWrite(4, HIGH);
    digitalWrite(6, HIGH);
    delay (200);
    digitalWrite(7, HIGH);
    delay (200);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (200);

  // HAZARD

  }}

    {while (digitalRead(9 == LOW) && digitalRead(10 == LOW) && digitalRead(11 == LOW) && digitalRead(12 == HIGH)) {
    digitalWrite(0, HIGH);
    digitalWrite(5, HIGH);
    delay (200);
    digitalWrite(1, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    delay (200);
    digitalWrite(2, HIGH);
    digitalWrite(7, HIGH);
    delay (200);

      for (int CAR = 0; CAR < 8; CAR++); {  //set all pins to LOW
       digitalWrite(CAR, LOW);
    delay (200);}}

  // BRAKELEFT

  }

    {while ( digitalRead(9 == HIGH) && digitalRead(10 == HIGH) && digitalRead(11 == LOW) && digitalRead(12 == LOW)) {
    digitalWrite(0, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    delay (200);
    digitalWrite(1, HIGH);
    digitalWrite(3, HIGH);
    delay (200);
    digitalWrite(2, HIGH);
    delay (200);
    digitalWrite(0, LOW);
    digitalWrite(1, LOW);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    delay (200);
    }
  }

  // BRAKERIGHT

    {while (digitalRead(9 == HIGH) && digitalRead(10 == LOW) && digitalRead(11 == HIGH) && digitalRead(12 == LOW)) {
    digitalWrite(0, HIGH);
    digitalWrite(1, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(5, HIGH);
    delay (200);
    digitalWrite(4, HIGH);
    digitalWrite(6, HIGH);
    delay (200);
    digitalWrite(7, HIGH);
    delay (200);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (200);
    }
  }

  // NOTHING

    {while (digitalRead(9 == LOW) && digitalRead(10 == LOW) && digitalRead(11 == LOW) && digitalRead(12 == LOW)) {

       for (int CAR = 0; CAR < 8; CAR++); {  //set all pins to LOW
         digitalWrite(CAR, LOW); }}
    }
}

What have you done already? Can you post your current code?

Yes.  Added to post above

From your code, there is a conflict for pins 9 and 10, it seems you want to define the as both inputs and outputs!

Please note this gets way harder when you use delay().

When you need repeating behaviour in an Arduino program, putting loops within the loop() function often isn't the best approach. It leads to a lot of confusing logic which is quite hard to get right, and becomes quite unwieldy to maintain.
A more effective approach would be something like a simple state machine. At the start of loop() you would check the input values and figure out which behaviour (or state) you want to execute: BRAKE, LEFT, RIGHT etc.. You might want to store this information in a variable somewhere, e.g. state 0 could be BRAKE, state 1 could be LEFT, and so on.
Next, you simply check what the state value is, and execute the appropriate instructions once. For example:
switch (state)
{
    case 0:
        // BRAKE instructions here...
        break;

    case 1:
        // LEFT instructions here...
        break;

    // etc...
}

There's no need for any while loops because loop() is going to get called all the time anyway. There are two big advantages of this approach. First, you only need all the input conditions in one place, which makes the code easier to manage. And second, it means you can easily have your program doing other things later in loop() because it's no longer stuck in nested loops all the time.

As a side note, it's very important to mention that lines like this are incorrect:
digitalRead(9 == HIGH)

What you're doing here is comparing the number 9 to HIGH, and then passing the result (which is 0) to the digitalRead() function. That means you're effectively only ever checking pin 0. What you actually want to do is pass 9 to the function, and then compare the overall result to HIGH, like this:
digitalRead(9) == HIGH

I've looked at the switch (case) before, but didn't get it.  Based on your reply, I've constructed this-

void loop() {
{if (digitalRead(9) == HIGH && digitalRead(10) == LOW && digitalRead(11) == LOW && digitalRead(12) == LOW)
button = 0;}
{if (digitalRead(9) == LOW && digitalRead(10) == HIGH && digitalRead(11) == LOW && digitalRead(12) == LOW)
button = 1;}
{if (digitalRead(9) == LOW && digitalRead(10) == LOW && digitalRead(11) == HIGH && digitalRead(12) == LOW)
button = 2;}
ETC then,
switch (button) {
case 0: // BRAKE
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);

ETC

Not sure how to format code for comments.  Sorry.

@ASM Google "switch statement" and you'll get a quick description. Basically, it evaluates the value at the very beginning and if it's equal to the first value, then only that code is executed. If it's equal to the second value, only that code is executed (and so on). However, it seems like you need an if statement that's nested since, as far as I'm aware, you can't use the && operator except at the very beginning.


text:
ADXL345 Arduino UNO data_ready interrupt
I would like the sensor values to be updated each 10ms(100Hz) and then run the algorithm and repeat the same process. However, after timing the algorithm it is taking only 2ms, I think the data_ready interrupt is not working as expected. Physical hardware connection is from INT1 of ADXL345 to pin2 of the UNO.
edit:
I have configured the accelerometer to have a data rate of 100Hz. I have set up an interrupt with data_ready to run the algorithm present in the loop each time a new sample comes that is each 10ms. However each sample is coming every 2ms which shows the interrupt is not working and I would like to know why. I have timed the interrupt with the millis(); function before and after calling the interrupt, also I have stored the samples in an array and printed it on the serial interface and the samples were repeated as it was updated every 2ms instead of 10ms. The algorithm I have developed needs the sampling rate to be 100Hz.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
#include <avr/io.h>
#include <avr/power.h>

#define F_CPU 16000000UL

volatile int sensor_update=0;

//-----------------------------------------------------------------------------------     -----------
//Write to ADXL345 registers
void writeTo(int device, byte address, byte val) {
Wire.beginTransmission(device); //start transmission to device
Wire.write(address);        // send register address
Wire.write(val);        // send value to write
Wire.endTransmission(); //end transmission
}

//----------------------------------------------------------------------------------------------

/////////////////////////////////////////////////////////////////////////////////////////////

//ISR function

void interrupt(void){
sensor_update=1;

}

//////////////////////////////////////////////////////////////////////////////////////////////////

void buzz(int targetPin, long frequency, long length) {
long delayValue = 1000000/frequency/2; // calculate the delay value between     transitions
//// 1 second's worth of microseconds, divided by the frequency, then split in half since

  //// there are two phases to each cycle
  //// calculate the number of cycles for proper timing
  long numCycles = frequency * length/ 1000;

  //// multiply frequency, which is really cycles per second, by
  //// the number of seconds to get the total number of cycles to produce
  for (long i=0; i < numCycles; i++){ // for the calculated length of time...
    digitalWrite(targetPin,HIGH); // write the buzzer pin high to push out the diaphram
    delayMicroseconds(delayValue); // wait for the calculated delay value
    digitalWrite(targetPin,LOW); // write the buzzer pin low to pull back the diaphram
    delayMicroseconds(delayValue); // wait againf or the calculated delay value
  }
}

/* Assign a unique ID to this sensor at the same time */
Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12345);

void setup(void)
{
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  Serial.begin(9600);
  //Serial.println("Accelerometer Test"); Serial.println("");

  pinMode(4, OUTPUT);// buzzer output pin

  /* Initialise the sensor */
  if(!accel.begin())
  {
    /* There was a problem detecting the ADXL345 ... check your connections */
    //Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
    while(1);
  }

  /* Set the range to whatever is appropriate for your project */
  accel.setRange(ADXL345_RANGE_16_G);
  accel.setDataRate(ADXL345_DATARATE_100_HZ);
  // displaySetRange(ADXL345_RANGE_8_G);
  // displaySetRange(ADXL345_RANGE_4_G);
  // displaySetRange(ADXL345_RANGE_2_G);

  //Create an interrupt that will trigger when a tap is detected.
  attachInterrupt(0, interrupt, RISING);

  writeTo(0x1D, 0x2E, 0);
  writeTo(0x1D, 0x2F, 0);
  writeTo(0x1D, 0x2E, 128);
  writeTo(0x1D, 0x2F, 127);
}

void loop(void)
{

  if(sensor_update==1 ){
    //When sensor_update is set to 1 in the ISR,the algorithm process the data from the accelerometer being updated every 10ms(100Hz)
     sensor_update=0;//reset
  }
}

It looks like some of your code got cut off; could you add that? also, can you try and give a more detailed description of what you want the code to do? what did you use to time your code?

basically my algorithm needs a sampling rate of 100Hz and that is what I used to develop it in the first place. The interrupt even though configured with this data rate is not working as expected, I am guessing it is an interrupt setup problem.

Should you be manually running the interrupt function in the loop, or should that only run when the sensor causes the interrupt to happen?

I actually just spotted that. After removing the interrupt call from the loop, the interrupt simply never kicks in now. The enable and map registers are set up correctly,could someone confirm that please.

after some troubleshooting: putting pin2 as an input doesn't change anything.
testing if the output from ADXL INT1 is toggling with 1Hz output rate with a multimeter give 0V so the problem is coming from the accelerometer, somehow it is not generating anything.
edit: I have changed the device to 0x53 instead of 0x1D and now the LED is always on, still not toggling tough.

According to the data-sheet:

The interrupt functions are latched and cleared by either reading the
  data registers (Address 0x32 to Address 0x37) until the interrupt
  condition is no longer valid for the data-related interrupts or by
  reading the INT_SOURCE register (Address 0x30) for the
  remaining interrupts.

Therefore, an ISR that just sets a flag will not be called a second time. At the very least, you need to read the INT_SOURCE register. If you are using the SparkFun ADXL345 library, then this would be a call of the form:
ADXL345 adxl = ADXL345();
void setup() {
  adxl.powerOn();
  adxl.setInterruptBitLevel(true); // active low
  attachInterrupt(digitalPinToInterrupt(interruptPin), isr, LOW);
  pinMode(interruptPin, INPUT);
  adxl.singleTapINT(1);
  ...
}

void isr(void) {
  detachInterrupt(digitalPinToInterrupt(interruptPin));
  interrupts();
  byte source = adxl.getInterruptSource();
  ...
  attachInterrupt(digitalPinToInterrupt(interruptPin), isr, LOW);
}

Note that I use a level-triggered interrupt here and re-enable interrupts before calling adxl.getInterruptSource(). The issue is that this call may take some time to talk over the I2C bus. To ensure that there are no reentrant calls, I detach the interrupt first. Without this, the level-triggered mode causes an interrupt loop.
The use of a level-triggered interrupt makes sense because the ADXL won't produce another interrupt until you read from INT_SOURCE. It also avoids the problem of missing an edge detection, which tends to cause subtle bugs that are hard to find.
I was unsure about the soundness of turning on interrupts within the ISR and so asked a question about this - What is the right way to query an I2C device from an interrupt service routine?

Been bashing my head with this one. And have searched the internet for a solution And tried for hours to program a solution.
From my tests the problem seems to be the Register 0x30—INT_SOURCE is populated with triggers. But the INT pin is only triggered when the  Register 0x30—INT_SOURCE is read.
This means that firstly the Arduino can't be woken from sleep by the INT1 or INT2 pins because they don't change unless the Arduino is already awake and reading the Register 0x30—INT_SOURCE
Second problem is to trigger an interrupt INT pin to jump to the ISR interrupt service routine you have to read Register 0x30—INT_SOURCE. And if you are going to do that then you might as well forget the interrupt and just jump into the ISR() and check registers in that. Which is how the example in the Sparkfun_ADXL345_Example for arduino ended up with the  ADXL_ISR(); call in the main loop. To sum up. Unless some one knows away to get the ADXL345 to change state on its INT pins without the need to read Register 0x30—INT_SOURCE, then the device is useless for use with the INT pins. I have given up on it and looking for another device to wake my ESP32 from sleep. Such as the BMI160 - Bosch which looks like a contender and has a arduino library for.


text:
Have Arduino write data to a MySQL database?
Would it be possible to have an Arduino write directly to a MySQL database?
I'm a web programmer, so I'm familiar with how to get records from a MySQL database. I have MAMP installed on my mac, so I have the ability to build an interface, directly in the web browser, that retrives the records from a MySQL database.
What I'm thinking is to connect the Arduino directly to my computer via USB, and write data from the sensors, or the pins, directly to my MySQL database.
I'm using two phototransistor to record whenever something blocks the light. Each sensor records individually a timestamp for when the blocking occur.
Is that possible?

It's possible if you forget about the Arduino directly writing to the database.
Simply put, the Arduino is restricted to a serial connection.  To directly communicate with MySQL you would need a network connection, and then implement the MySQL protocol - a huuuge amount of work.
The normal way is to have an adapter program running on the PC which receives data from the Arduino over the serial connection, then performs any insert, select, etc instructions on the MySQL for you.
There is a "MySQL Connector" available* (https://launchpad.net/mysql-arduino) but of course that requires you to have an active network connection of some form to your Arduino.  Remember that the Arduino (certainly the Uno) is very limited on memory and program space, so having the Arduino connect direct, and doing anything else, might be mutually exclusive.

*Nice find, @SomeHardwareGuy...

You can do that using an Arduino Yun: the Yun has a linux cpu paired with the ATMega32U4, so you can delegate things like accessing a mysql database, either local or remote.
Take a look at this instructable.
There are different ways for delegating logging sensors readings to the linux side and have them stored on a mysql: the easiest is to code a short python script and call it from the sketch using Process.


text:
Ultrassonic sensor
Hi I have this ultrasonic sensor:
http://www.micropik.com/PDF/HCSR04.pdf
I use this code to read distances:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long time = pulseIn(echoPin,HIGH);

My question is this: in the datasheet says that the sensor will send 8 pulses at 40khz. Every pulse will take 0.000025 seconds so 8 pulses would be 200 usec.
So why the delay is only 10 usec if it should be 200usec?

The 10us delay is just your trigger pulse HIGH phase. Refer to the timing diagram on bottom of page two in your datasheet.

The 10 us pulse to the TRIG pin activates the ultrasonic detector. It then sends 8 pulses at 40 kHz, and finally, sends a pulse to the ECHO pin. That pulse sent to the ECHO pin has a pulse-width proportional to the distance of the nearest object.