text:
Arduino UNO with NRF24l01 + touch screen
I have an Arduino UNO, a NRF24L01 as receiver (receive data from elsewhere), and this touch screen from Adafruit for display and control.
The Adafruit TFT is a shield so it fits the UNO perfectly.
I wonder if this TFT shield can share SPI pins with NRF24L01?
Given that I use pin 10 (=SS) for TFT and pin 8 (=SS) for NRF24L01, with set (SS, low) to toggle between two slaves (TFT and nRF24)?
Somehow it doesn't work once I start to share SPI pins (11, 12, 13) between two slaves.

Did you check the schematics for the TFT? https://cdn-learn.adafruit.com/assets/assets/000/013/453/original/adafruit_products_tftshieldv2.png?1388769644. Looks like pin 8 is already in use.

The TFT you mention is much more than just a TFT, it seems to include a touch screen and also a SD card reader. Depending on what parts you use, the list of pins available may differ.

I think you'll need to show more of what you've done so far (NRF24L01 wiring, code for your sketch, debug traces...) as of now, it is rather difficult to answer your question with the little description you made of your problem,

You also have to ensure any libraries that also use SPI are capable of operating with multiple SPI devices on the same bus. Another thing you have to look out for is with certain SPI devices is that they lock up the bus making it impossible to use more than one device on the bus. There are a lot of variables you need to define before we can help you more. So, what TFT library and what nRF24 library are you using?

Why not use SoftwareSPI with the NRF24L01? IIRC, the maniacbug and tmrh20 NRF24 libraries both support it. It would also prevent the issues mentioned by Avamander.

@ Mikael Patel : I checked with manufacture and they said only pin 9, 10, 11, 12, 13, Vdd, gnd pins were used if I dont need SD card. @ jfpoilpret: You are right, It is a touch screen that I tried to use to get data from three different RF devices. I will share more info. @TisteAndii : I am not sure what you refer to. SOftwareSPI? sounds interesting.

Look, you are making a big mess here. How about registering as one user, rather than making post after post as user27030, user27141, user27142, user27143, user27144 and user27145? That makes it very hard to follow.

Please use the Post answer button only for actual answers. You should modify your original question to add additional information. I've deleted all your "answers". Slow down and edit your original question to add further information. This isn't a forum, and answers are not for adding more details. Format code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.


text:
Arduino Nano and WS2812
I am new to electronics and especially Arduino-based products. I am currently trying my hand at using 5 segments of WS2812 RGB LEDs and using a Nano to control them. I included the picture below for the pin numbers.
If I wanted to run 5 groups of LEDs and use a library like the Adafruit Neopixel or Fastled to control the leds, what would be the best way of wiring them up to the Nano?
I am under the impression that the positives should all be connected to pin 27, the 5v pin, with a 1000 µF 25V capacitor. The ground wires will all be connected together to pin 04, Ground. The data pins will be wired to pins 6, 8, 9, 12 and 13 and each will have a 470 ohm 1/2W resistor on each pin.
I am unsure whether any of the other pins can be used for data pins. The input voltage will vary since this is used on a multi-rotor that I am building. The battery voltage will vary from 12.6V all the way down to maybe 9 volts. I was thinking of using a step down adjusted to 12V to keep the voltage at or under 12v and that will be connected to pin 30. I would love to hear if there are any better ways of wiring this project up.
Also would it be a better idea to power the LEDs from a 5V dedicated source and just use the Nano for the data pin connection? I will only be using roughly 30-40 WS2812s.

Regarding “The data pins will be wired to pins 6, 8, 9, 12 and 13 and each will have a 470 ohm 1/2W resistor on each pin”, note that WS2812s typically are connected together in strings, with the DO (data out) pin of each upstream unit connected to the DI (data in) pin of the next unit downstream. Thus, there is no need to allocate five Arduino IO pins; one is enough.
For further background on WS2812 mechanisms, see for example Is it possible to infer the length of a neopixel string using 1-wire protocol?, and see discussions and diagrams at adafruit.com and sparkfun.com.
Regarding use of an efficient step-down switching-supply voltage regulator set for 12 V out, if you use an adjustable regulator you might as well set it lower than that, for example at 8 or 9 volts. Typically, the regulators on Arduino boards that convert Vin to +5 or +3.3 V are linear regulators rather than switching regulators, so every unnecessary extra volt (above the dropout limit) proportionally increases the amount of wasted energy.
In typical use, a WS2812 draws 20 to 60 mA current, supposing up-to-five-volt power. Thus, a string of 30 to 40 of them will draw at least 0.6 A, in most cases, and up to 2.4 A, if all are on at top brightness. In either case, an external power supply would be de rigueur. You would connect the external supply's ground to the Nano's ground; the +5Vs need not be connected together.
Edit: Addressing questions from comments
Re “if one data in will control the entire array of LEDs, it should be connected to D13”, I'm not aware of any reason for that idea, and indeed would recommend against it. On many Arduino models, D13 drives an LED. While the Uno uses a buffer amplifier to drive the LED, the Nano just has a 680 Ω resistor in series with an LED. I'd not load it further.
Wiring each of several strips in its own chain seems quite reasonable. Yes, you could wire all the DIs of 30 or 40 WS2812 units in parallel. However, parallel inputs would require 30 or 40 wire runs, vs. the simple wiring chain the WS2812 is intended for. Note, per its spec sheet the WS2812 DI load is ±1 µA max, so one '328 IO pin could drive hundreds of them. But input capacitance, up to 15 pF each, probably precludes driving thousands in parallel.
If performance is an issue, possibly use short chains (up to several dozen units long) in parallel, rather than one long chain of hundreds of units. The spec sheet says, “When the refresh rate is 30fps, low speed model cascade number are not less than 512 points, high speed mode not less than 1024 points.” (Low speed refers to 400Kbps signalling; high speed, 800Kbps).
Note, paralleled chains improve refresh rates only when multiple chains are used to show the same pattern. Otherwise, each chain being refreshed separately is no faster than refreshing the same number of units in series. The library that drives a chain of WS2812s hogs the whole processor each time it sends a chain of data. Also note that scan rates of 400 Hz are mentioned in the spec sheet. It is likely to be futile to try to exceed that by paralleling units.
Summary: If you have a dozen or so units on a rotor arm, I'd wire them in series. If it's more convenient to keep each arm's wiring separate from that of other arms, then do so. If each arm will show the same pattern as other arms, you could wire the chain inputs (the first units in each chain) in parallel, else would use separate driver pins.

Thank you for that link.I wish I would have found that before posting.You guys and gals must be sick of new users asking the same questions over and over.The project I am in the process of trying to understand and put together has been done a million times and there are tons of videos but they never seem to go into the wiring or provide a schematic.The led strips I will be using can be wired in a chain but that will really complicate the project a bit because the strips are placed  at the 10 2 4 6 and 8 oclock positions on a clock and they are on each arm of a multi rotor.

I could run the wire to each strip in a chain but the wire will do an entire loop around the multirotor so that will be a hassle.I can do the strips in pairs of two and just use 4 instead of five.I read the link and from what I came to understand is if I wire all the strips together even though they aren't in a chain just wire the data in pin together they will all act in the same manner according to the code used?That will be just fine if that is how they will work?IWould it be wiser to just wire the power side of the leds directly to the regulator and not use the Arduino for power at all.

I am also under the impression that if one data in will control the entire array of led's it should be connected to D13?I am unsure if that is correct since I was under the impression that each pin on the Arduino can be assigned to do a wide range of things based on the code?

source: Stack Exchange

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

sort: votes


text:
smoke came out of Arduino Nano
I was working with Arduino and Xbee with LED, circuit LED  + Servomotor
and doing testing for 5 hours (not continuously).
Then once I omitted the Servomotor circuit and I connected flex sensor, which required connecting 10k Resistor and connect it the laptop as usual, smoke came out of the board (from USB side).  I disconnected it immediately, but now the board doesn't light up and the 5V gives 1.5V.
Is there any chance to fix the board?
I discovered that the B2 diode cracked in the middle, the picture is showing a  good Arduino Nano.
I found a very similar in this post about dead NANO

If you can identify which components have fried they can be replaced. Or you just get another board.

I don't know unfortunately, I really don't know what cause it.

I figured out that the chip B2 (next to the USB) exploded and cracked

B2? Are you sure you don't mean D2? I don't know what a "B?" is other than a battery, and it's not that.

Although I don't see a D2 on the schematic, only a D1. Tell you what - maybe a close-up photo of your board showing the broken component would help...?

Please add a photo to help us understand.

I attached  a picture for the backside of arduino nano

Answer edited, I did not understand you had a Nano

If my understanding is correct, the flex sensor was connected between 5V and GND.
This acted like "short circuit" and should not have burned the AVR, but only the power supply side. If you have a multimeter and some soldering skills it should be possible to fix the board.
Supposing you have an genuine arduino UNO, here is a schematic but it may not be the right version

Remove the MCU
Check voltage between GND and XUSB is 5V (if not either your USB port is burned or you have a short on the board or a component)
Check voltage between GND and USBVCC is 5V (if not, replace the fuse)
Check voltage between GND and +5V is 5V (if it's still 1.5V as you mentioned, try replacing transistor T1 but I do not understand why it would burn. If it's 5V replace the MCU)

EDIT for Arduino Nano
I did not understand you had a nano board (schematic)
The component "B2" you mention is the diode D1 (MBR0520). It burned because of the short circuit you created and nothing else should be defect. It acted like a fuse. Simply replace it and it should be fine.
If you are VERY CAREFULL not to overload the nano with external circuitery and never bring external 5V you could just remove it and make a little solder bridge (waiting for replacement part)

The circuit is correct (as I think), but here is was I just noticed, B2 chip is cracked. I don't know what I can do to it

soldering a bride over the diode?  do yu think I can use USB port normally after that?

Yes a bridge over the diode should work but plese be carefull if you do that. The diode is only here to protect USB port if external power is applied (or as fuse as you demonstrate ^^) and a short will work. BUT DO NOT APPLY EXTERNAL POWER SUPPLY IF YOU DO THAT

external power is power by battery right? .. because I read somewhere that it may affect the Laptop's port as well if I shorted the diode and connected the NANO by USB. do yu hav idea about this?

@O2M I'm electronic and software engineer, shorting the diode if you connect nothing else than 1 USB port to your Nano is no risk at all for the PC and the Nano. Diode is here to prevent current flowing into the USB port if you connect external power (battery or other). Your short circuit experience with flex sensor shows that the diode also protects the computer USB from overcurrent by burning (this protection is only side effect, the diode could be shorted instead of open). Thus shorting the diode should only be a temporary solution to confirm nothin other is broken and it should be replaced

very helpful information, thank you so much:) i'll solder it temp. till I receive  a new diode

The Nano has mainly surface-mounted devices on it. You need to be quite skilled to remove faulty ones and replace them, without special equipment.
By the time you have identified which one needs replacing, removed it (no easy task if it is the processor) and replaced it, it would be easier and probably cheaper to just buy a new board.
You may well have fried the main processor (Atmega328P) which I see with a quick search is selling for around $7 to $8 in one-off quantities, whereas you can buy the entire Nano for around $13 for a genuine one, or around $9 for a clone. It just won't be worth the trouble.

hello sir, the  problem is that the circuit seems correct and there is no short circuit anywhere, i'm really afraid to by a new one and burn it as well since i'm going to build the same circuit again. Can you identify whether the cause of burning is by the circuit or no? The flex sensor required 10K-R and lilypad Xbee board both connect to the 5V.  The board orginaly was working fine as I said, but once I removed Servo and I connected the flex Sensor circuit this what happened.

I figured out that the chip B2 (next to the USB) exploded and craked

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


text:
Problem with Software Serial: no response
I am using an Arduino Uno board with IDE 1.6.7.
I have tried to implement a tweaked version of the basic example (SoftwareSerial example) from the Software Serial library. The code is attached.
It should blink the light and print the message on the serial monitor. But I am not getting anything.
In fact, I also tried the example as it is. It did not work either.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(8, 9); // RX, TX

void setup() {
    pinMode(13,OUTPUT);
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }
    Serial.println("Goodnight moon!");
    // set the data rate for the SoftwareSerial port
    mySerial.begin(9600);
    delay(1000);
}

void loop() { // run over and over
    mySerial.println("hell");
    if (mySerial.available() > 0) {
        digitalWrite(13,HIGH);
        Serial.write("working..");
        delay(3000);
        digitalWrite(13,LOW);
        delay(2000);
    }
}

You are misunderstanding what "available" does. It doesn't tell you how much you sent, it tells you how many bytes are in the receive buffer.

I am checking if the buffer has some data not the quantum . If this condition is positive , the LED with pin 13 should blink. Simultaneously , a  message should be sent to serial terminal . Please let me know if the logic is wrong.

You just say "It does not work", but you could at least provide traces of what you can see on the "normal" serial console and what you see on the other serial console, what you type as input, how you connected TX/RX to your terminal. Without this information, there could be a dozen reasons why your setup does not work.

Can we see a schematic of your wiring, if you have any wires running around?

It would be extremely helpful if you can describe your setup,like your wiring and how you're sending the messages....

So what is connected to soft serial Rx (pin 8 ) ?
Just connect pin 8 and 9 so that the data you sent through pin 9 will be received in Rx and satisfies the if condition.
If this works, the problem is with your device connected to soft Rx

Do you have it connected right? Wire as follows: Tx of one device goes to Rx of the other. Tx does NOT go to Tx. Rx does NOT go to Rx. You must criss-cross them.

SoftwareSerial cannot transmit and receive at the same time.  So even if you connected pin 8 to 9 with a wire, your sketch will not receive what was transmitted.  That's a guess without your wiring diagram.
NeoSWSerial can simultaneously transmit and receive.  It is a drop-in replacement for SoftwareSerial.
However, AltSoftSerial is even better, and it only works on pins 8 & 9.  Use that instead!
This answer compares all 4 serial types, including HardwareSerial.

I built two scetch for testing. One for Arduino Nano no1 and another for Arduino Nano no2. They are tested and working, not only written to this page.
No2 is sending "hello" and No1 is listening and sending it to PC via Serial.
The speed (1200bps) is slow, but so it is easier to see what is happening.
Connect Pin10 of no1 to Pin11 of no2 and gnd to gnd.
Connect the Nanos to the USB-ports of the PC and set a monitor program (1200, 8N1) to listen no1.
This seems to be a good way to test Serial.print, Serial.println and Serial.write commands. You will be surprised.
/*No1:/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
  Serial.begin(1200);
  Serial.println("Testing");
  mySerial.begin(1200);
}
void loop() { // run over and over
 if (mySerial.available()) //If this is missing, you get fast repeating carpage
{
    Serial.write(mySerial.read());
    Serial.print(".");
 }
}

/*No2:/
#include <SoftwareSerial.h>
 SoftwareSerial mySerial(10, 11); // RX, TX
 void setup(){
  mySerial.begin(1200);
}
void loop(){
    mySerial.print("Hello");
}

if(mySerial.available()>0)

mySerial.available() returns the number of bytes available in your serial receive buffer. Unless you are sending commands via serial in pins 8 and 9, this will remain 0 and you will never enter the if statement.
Also, you have two declarations for serial here:

Serial.begin() initialized the built-in UART USB module. Here you will be able to send/receive commands with a program such as Putty.
SoftwareSerial mySerial(8, 9); // RX,
mySerial.begin() initializes serial communications with pins 8 and 9 on the Arduino board. This would be if you wanted to send/receive commands with digital I/O instead of, or in addition to, the UART USB module.

Thanks for the quick response . However , I am sending bytes to mySerial Port via the following command in the loop: mySerial.println("hell");
Should it not initialize mySerial ?

The fact you send something out to TX does not mean it wshall be echoed back to RX, it all depends on how you connected TX and RX and how you setup your serial terminal (if you use one).

The serial portia initialized but there is nothing in the receive buffer unless you are sending data to your arduino from your computer over putty or telnet etc

Just remove the if statement and the code should make the LED blink at the very least

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


text:
How does Arduino IDE for OSX work without drivers?
My Arduino IDE works right out of the box without me having to install any USB to UART drivers. I know the Atmega16U2 on the UNO is acting as UART bridge, but this means that OSX recognizes it on a hardware level, which doesn't make sense since no drivers were installed - unless there is some sort of standard here that the Atmega16U2 implements?
The reason why I ask this is that I have a project where I want to connect an ATMega328p to a client mac which may not have access to 3rd party drivers, so having serial work natively with screen would be ideal. If the Arduino IDE can implement serial monitor without any additional drivers then it means I can too.
Does anyone know how this is implemented?
Thanks!

Sounds luke you want a CDC/ACM implementation.  Maybe you can meet your goal with just a 32u4, leonardo style?  There are lots of Arm parts with built in USB too.  Or you can do it the same way an Uno does.

Windows 8.1 is the last version of any common desktop system that requires CDC/ACM (that is what the Arduino's USB port is) drivers.
OS X is based on BSD which, like Linux, has had CDC/ACM drivers built in since (pretty much) the dawn of time. It is only really Windows that has had the concept of drivers for anything that isn't vendor specific and/or complex (such as video cards, or devices that don't adhere to published standards).
Even Windows 10 now has the drivers for CDC/ACM built in (it's only taken Microsoft 20 years or so to catch up with the rest of the OS world).


text:
Controlling Relay Using Serial Monitor
I tried to make a program that can control a 4 channel relay (with LEDs as indicators) with a serial monitor. First time I tried to program it using a char command to make it turn on only, it worked. Then I tried to make it off only, it also worked, but when I tried to combine them, to control it to On or Off in the same program, it didn't work.
this is my code
#define CH1 2
 #define CH2 3
 #define CH3 4
 #define CH4 5
  void setup(){
 Serial.begin(9600);

pinMode(CH1, OUTPUT);
pinMode(CH2, OUTPUT);
pinMode(CH3, OUTPUT);
pinMode(CH4, OUTPUT);
digitalWrite(CH1,HIGH);
digitalWrite(CH2,HIGH);
digitalWrite(CH3,HIGH);
digitalWrite(CH4,HIGH);
 }

 void loop (){
  if (Serial.available()) {

char ser = Serial.read();

 switch(ser){
 case 'on1':

 onPin1();

 break;

 case 'on2':

 onPin2();

 break;

 case'on3':

 onPin3();

 break;

 case 'on4':

 onPin4();

 break;

 case 'off1':

 offPin1();

 break;

 case 'off2':

 offPin2();

 break;

  case'off3':

 offPin3();

 break;

  case 'off4':

 offPin4();

 break;

   }

 }
 }

 void onPin1(){
    digitalWrite(CH1, LOW);
 }
  void onPin2(){
   digitalWrite(CH2, LOW);
 }
   void onPin3(){
   digitalWrite(CH3, LOW);
 }
  void onPin4(){
   digitalWrite(CH4, LOW);
 }

  void offPin1(){
   digitalWrite(CH1, HIGH);
 }
   void offPin2(){
   digitalWrite(CH2, HIGH);
 }
   void offPin3(){
   digitalWrite(CH3, HIGH);
 }
   void offPin4(){
   digitalWrite(CH4, HIGH);
 }

with that code, I got "duplicate value", maybe because the pin is double-called. But when I tried to make it in separate swicth case condition, no error but couldn't respond to the command char

This is C++, so the single quotes are used for character literals. If you want string literal, you have to use double quotes. However, string literals can't be used in switch.
And you can't definitely use it like that if you are reading only one character.
However you can use single characters for this:
#define CH1 2
#define CH2 3
#define CH3 4
#define CH4 5

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

  pinMode(CH1, OUTPUT);
  pinMode(CH2, OUTPUT);
  pinMode(CH3, OUTPUT);
  pinMode(CH4, OUTPUT);
  digitalWrite(CH1,HIGH);
  digitalWrite(CH2,HIGH);
  digitalWrite(CH3,HIGH);
  digitalWrite(CH4,HIGH);
}

void loop (){
  if (Serial.available()) {
    char ser = Serial.read();
    switch(ser){
      case '1':  onPin(CH1); break;
      case '2':  onPin(CH2); break;
      case '3':  onPin(CH3); break;
      case '4':  onPin(CH4); break;
      case '5': offPin(CH1); break;
      case '6': offPin(CH2); break;
      case '7': offPin(CH3); break;
      case '8': offPin(CH4); break;
    }
  }
}

void onPin(int8_t pin) {
  digitalWrite(pin, LOW);
}

void offPin(int8_t pin) {
  digitalWrite(pin, HIGH);
}

Or you can toggle the relay states.
Test strings as commands are little bit harder to use as you have to read whole command (or use state machine). Following example is little bit unnecessary hard but it's working...
constexpr uint8_t     channels = 4;
constexpr uint8_t ch[channels] = { 2, 3, 4, 5};

template <uint8_t pin, uint8_t val> void setChan() {
  digitalWrite(pin,val);

  Serial.print("setChan: "); Serial.print(pin);  Serial.print(' ');  Serial.println(val);
}

using action_t = void(*)(void);

action_t  on_actions[channels] = {
  &setChan<ch[0],LOW>,
  &setChan<ch[1],LOW>,
  &setChan<ch[2],LOW>,
  &setChan<ch[3],LOW>
};

action_t off_actions[channels] = {
  &setChan<ch[0],HIGH>,
  &setChan<ch[1],HIGH>,
  &setChan<ch[2],HIGH>,
  &setChan<ch[3],HIGH>
};

void setup() {
  Serial.begin(57600);

  for (auto pin : ch) {
    pinMode(pin, OUTPUT);
  }
}

String command = "";
action_t action = nullptr;

void loop() {
  if (action != nullptr) {
    action();
    action = nullptr;
  }
}

void serialEvent() {
  if (Serial.available() > 0) {
    char inChar = (char)Serial.read();
    if ((inChar == '\r' || inChar == '\n')) {
      if (command.length() > 0) {
        Serial.print(command);
        if (command.startsWith("on")) {
          uint8_t channel = command.substring(2).toInt()-1;
          if (channel < channels) {
            action = on_actions[channel];
          }
          Serial.print(" On="); Serial.print(channel+1);
        } else if (command.startsWith("off")) {
          uint8_t channel = command.substring(3).toInt()-1;
          if (channel < channels) {
            action = off_actions[channel];
          }
          Serial.print(" Off="); Serial.print(channel+1);
        }
        Serial.println();
        command = "";
      }
    } else {
      command += inChar;
    }
  }
}

I have learned about switch case purposes, I i do like that, but I need to use specific "text" instead of single text 't'. How to do that? @kiiv


text:
uSDaemon in Linino / Arduino Yun Mini hogging the syslog
There is an annoying problem with Linino One / Arduino Yun Mini as the syslog (logread) is full of messages from uSDaemon, complaining about missing files.
ls: /sys/bus/scsi/drivers/sd/*/block/sd?: No such file or directory
handle umount errors
check umount
(and so on, three lines every two seconds, so every other meaningful information is pushed out of the syslog pretty soon)
If I disable the uSDaemon with
/etc/init.d/usd disable
the syslog is OK, but is there any functionality actually lost if uSDaemon is not running, beside being unable to read from a non-existing uSD card reader?


text:
BASCOM-AVR stk500_2_ReceiveMessage(): timeout: -1
Arduino Uno R3
Windows 10
Bascom AVR
The ON is alright.
The LED flickers now and then.
The RX and TX flickers when I press the program button on Bascom but then disappears almost immediately.
Hello. I have been having this trouble since yesterday. It always appears whenever I click the program button on Bascom. I feel so stupid having to Restart my PC and checking the Device Manager again and again. I am still new to this.
The COM Port is correct and everything else matches. I do not know how to solve this. Please help, I have already watched tutorials but they all assume you have great background in programming which I don't.
So I hope you can use easy terms.
Thank you.

I know next to nothing about Bascom, but Arduino Uno R3 does not use an STK500v2 bootloader.  It uses one that avrdude refers to as "arduino", basically a modified STK500(v1) protocol.  The arduinoisp.ino sketch also implements stk500v1.  So if you're using UNO "as a programmer", that is with arduinoisp.ino, it would also not be STK500v2.  STK500v2 has been used in some of the larger arduino "Mega" boards.
So if you have a choice of programmer, it would be "arduino" or perhaps "stk500(v1)" at 115200 baud.  If you are choosing an arduino board, it sounds like you have an Arduino Mega type board selected rather than the UNO.  If you are using arduinoisp.ino sketch, it would be stk500v1 at 19200 baud.

Have you tried a different USB cable?
I was having trouble flashing and the cable turned out to be the issue.


text:
Setting up Huzzah ESP8266
I am trying to set up a Huzzah ESP8266 and can not get it to work. I have scoured the internet for help and to no avail. I have the board loaded with a baud rate of 115200 and am transmitting at  80 MHz. When I try and upload the sketch it successfully uploads and after a second or two it sends me this error.

Sketch uses 222,209 bytes (21%) of program storage space. Maximum is
  1,044,464 bytes. Global variables use 31,576 bytes (38%) of dynamic
  memory, leaving 50,344 bytes for local variables. Maximum is 81,920
  bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Here is my code:
 void setup() {
pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
 void loop() {
digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the    voltage level
                                // but actually the LED is on; this is     because
                                // it is acive low on the ESP-01)
delay(1000);                      // Wait for a second
digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

Does anyone know what I'm doing wrong or can anyone help me out.

Did you select the port of your ESP8266 in the Tools > Port menu? Please select File > Preferences > Show verbose output during > upload, upload the sketch, and then update the error message in your question with the full verbose output.

espcomm error messages usually mean that your sketch is -not- uploaded correctly. Are you sure you selected "Adafruit HUZZAH ESP8266" in the arduino IDE? It should be in the list.

Also, does the HUZZAH actually have a usb to serial chip on the board, or do you need an external one? If so whichone are you using? Some FTDI? I can't check myself atm., behind a firewall :)

Have you contacted your seller/supplier? Adafruit actually has very good support and they sure know their hardware and possible faults.

If you´re working with a development board, they (usually) come with tow buttons: Reset and Flash. If this is the case before start to upload your code you must press the Flash button, this error is common when the Flash button it's not pressed.
If you're working with an ESP8266-01 (this is the "naked" esp8266) you must read this tutorials: GreatScott vid on youtube, and for the connections: a good Hackster.io tutorial.
Hope you can make it run!!!

When using a serial cable (4 wires, only works on windows), you need to press the 2 buttons in the sequence described here (https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide): gpio0 down, reset down, reset up, gpio0 up. The red led should be dim now. This means the huzzah is ready to bootload.


text:
Arduino Text Scrolling on 16x02 I2c on NodeMcu (ESP8266-12)
I have managed to get my 1602 I2C LCD working on a NodeMCU devkit. I can display text parsed from the web but I am not sure how to set it to autroscroll if message is greater than 16 characters. I tried the lcd.ScrollDisplayLeft() but it doesn't work. I figured I would have to do it manually and it is a matter of getting string length and then looping the characters.
This is what I have so far:
#include <ESP8266WiFi.h>
#include <Wire.h>  // This library is already built in to the Arduino IDE
#include <LiquidCrystal_I2C.h> //This library you can add via Include Library > Manage Library >

LiquidCrystal_I2C lcd(0x3F, 16, 2);

const char* ssid = "ssid";
const char* password = "pass";
const char* host = "api.thingspeak.com";

int find_text(String needle, String haystack, int from) {
  int foundpos = -1;
  if (haystack.length() < needle.length())
    return foundpos;
  for (int i = from; (i < haystack.length() - needle.length()); i++) {
    if (haystack.substring(i, needle.length() + i) == needle) {
      foundpos = i;
      return foundpos;
    }
  }
  return foundpos;
}

void setup() {
  Serial.begin(115200);
  delay(100);
  lcd.init();   // initializing the LCD
  lcd.backlight(); // Enable or Turn On the backlight
  delay(200);

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  lcd.setCursor(0, 0);
  Serial.print("Connecting to ");
  lcd.print("Connecting");
  lcd.setCursor(1, 1);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    lcd.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Connected!!");
  delay(1000);
}
int value = 0;

void loop() {

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");

  }

  // We now create a URI for the request
  String url = "/apps/thinghttp/send_request?api_key=345345345345345";
  Serial.print("Requesting URL: ");
  Serial.println(url);
  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Fetching Data..");
  delay(10000);

  // Read all the lines of the reply from server and print them to Serial
  while (client.available()) {
    String line = client.readStringUntil('\r');

    int start_loc = find_text("<b>", line, 0);
    int end_loc = find_text("</b>", line, 0);
    if (start_loc > 0 && end_loc > 0)
    {
      lcd.clear();
      Serial.println("data:  ");
      lcd.print("data: ");
      lcd.setCursor(1, 1);
      for (int i = start_loc + 3; i < end_loc; i++)
      {
        Serial.print(line[i]);
        lcd.print(line[i]);
     }

  Serial.println();
  Serial.println("closing connection");
  delay(2000);

}
  }
}

Inspecting the library code, it is apparent that the method called only sets up a command bit field and it is actually the display that performs the operation.
So, you might check if your LCD is capable of performing the scrolling operation.
This web page contains a tutorial on how to use the scrolling feature.  In this code example from that page:
void loop() {
  // scroll 13 positions (string length) to the left
  // to move it offscreen left:
  for (int positionCounter = 0; positionCounter < 13; positionCounter++) {
    // scroll one position left:
    lcd.scrollDisplayLeft();
    // wait a bit:
    delay(150);
  }

...you can see that it is not automatic.  That you need to call the method each time you want to scroll (in this case) one position to the left.


text:
How do I use two PulseIn() functions simultaneously in Arduino?
I want to connect multiple Ultrasonic sensors to my Arduino board. For that, I need multiple pulseIn() functions to work at the same time. How can I do that?

You can't. pulseIn() is a blocking function that waits for a pulse to arrive before returning.
Instead you will either have to use interrupts or (where available) Input Capture peripherals.
However, using multiple ultrasonic sensors at the same may not make sense. Unless you take great care with your physical design you will get interference between the two.  Echoes from one bouncing around will trigger the other.  For this reason it is normal to not trigger both at once, but to use them sequentially, in which case pulseIn() is still perfectly fine to use.


text:
How to correctly code a LED STRIP?
I recently bought a 5050 RGB 12V 3A LED strip and I set it all up with my Arduino and run this code (from adafruit website), everything is good:
Example Code
Once you have the strip wired up, it is easy to control the color of the strip by using PWM output, for Arduino you can use
#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
}

void loop() {
  int r, g, b;

  // fade from blue to violet
  for (r = 0; r < 256; r++) {
    analogWrite(REDPIN, r);
    delay(FADESPEED);
  }
  // fade from violet to red
  for (b = 255; b > 0; b--) {
    analogWrite(BLUEPIN, b);
    delay(FADESPEED);
  }
  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
  // fade from yellow to green
  for (r = 255; r > 0; r--) {
    analogWrite(REDPIN, r);
    delay(FADESPEED);
  }
  // fade from green to teal
  for (b = 0; b < 256; b++) {
    analogWrite(BLUEPIN, b);
    delay(FADESPEED);
  }
  // fade from teal to blue
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
}

I tried to find a way to achieve the same effect but only with two colors...red to yellow..red fade to yellow and fade to red and so on..
EDIT:
Thanks to @majenko I achieved this...Fade from Red to Yellow and back on:
    for (int r = 0; r < 256; r++) {
        analogWrite(REDPIN, r);
        analogWrite(GREENPINPIN, 255 - r);
        analogWrite(BLUEPIN, 0);
        delay(FADESPEED);
    }

    // Fade red down and blue up
      for (g = 0; g < 256; g++) {
        analogWrite(REDPIN, 255);
        analogWrite(BLUEPIN, 0);
        analogWrite(GREENPINPIN, G);
        delay(FADESPEED);
      }

What kind of arrangement are you after? Assuming red and blue are your two colours, do you want "NONE -> R -> R+B -> B -> NONE..." or "R -> B -> R -> B...", or what?

@Majenko R ....fade to B....fade to R...fade to R and so on...

The main difference between what you want and what that code does is that you want to fade both colours at once, but that code is aimed at only fading one colour at a time.
You want to fade R up whilst fading B down, and then fade R down whilst fading B up. The simplest way is with just two loops:
// Fade red up and blue down
for (int i = 0; i < 256; i++) {
  analogWrite(REDPIN, i);
  analogWrite(BLUEPIN, 255 - i);
  delay(FADESPEED);
}

// Fade red down and blue up
for (int i = 0; i < 256; i++) {
  analogWrite(REDPIN, 255 - i);
  analogWrite(BLUEPIN, i);
  delay(FADESPEED);
}

One fade value (i) per loop, and a little bit of maths to turn 0-255 into 255-0 for the value you are fading down.

For Red->Yellow->Red you just need to keep red on and fade green on and off.  You already have code to fade green on and off in your original program:
  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

  // fade from teal to blue
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

Couple that with setting the red and blue to on and off respectively, and you have:
#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);

  analogWrite(REDPIN, 255);
  analogWrite(BLUEPIN, 0);
}

void loop() {
  int g;

  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

  // fade from yellow to red
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
}

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Start LED blink at certain millis() value
I was looking at the blink without delay sketch and I was trying to modify it so the LED would start blinking after 1000 ms. I changed the previousMillis variable to 1000, but the program didn't change. In fact, it doesn't seem to change for any value of previousMillis. I thought that this would change the if statement:
if (currentMillis - previousMillis >= interval)
because 2000ms would have to pass for currentMillis - previousMillis to be equal to 1000ms (interval). What am I missing?

If you initialize previousMillis to 1000 then, initially, currentMillis - previousMillis is −1000. But you are dealing with unsigned numbers, which cannot be negative, so the subtraction wraps around and you get 2^32−1000 = 4294966296.

Thanks, I removed the unsigned from both variables and it works now. However, is there any downside to this? And any better solutions?

“is there any downside to [removing unsigned]?” Yes. millis() will eventually overflow. Unsigned overflow is well behaved, whereas signed overflow is undefined behavior in C and C++. “any better solutions?” You can set an initial interval and change it later.


text:
MPU6050 Measure distance traveled or position
How can I use MPU-6050 with an arduino to measure the distance the robot traveled from it's starting point or just it's current position on the map?
The Robot should be moving in a map same as a 2D array and I need to detect it's position while it is moving and send the data to a station.

You won't - not with any degree of accuracy anyway.
You could attempt "dead reckoning" whereby you estimate the current speed by the acceleration and deceleration over time, and from that get a rough idea about the distance travelled in any one direction, but the accuracy will be so poor and the drift so huge that it would be next to pointless.
Instead you really want to monitor the wheels. Count how many revolutions (or half revolutions, quarter revolutions, whatever accuracy you need) and combine that with the circumference of the wheels to calculate how far you have travelled.


text:
Pass custom element of an array from an inherited class to main sketch
I'm building a base class that creates color patterns using FastLed's CRGB structure. I use the base class as inheritance for another more specific class that modifies a vector of colors (Pixels[]) and at some point I want to pass the color of a specific element from my class to the main sketch. But i'm having some issues with it, since the content of Pixels[] doesn't seem to match what I actually write in there.
Pattern.h:
class Pattern
{
    public:
    CRGB PixelAt(int idx);
    CRGB Pixels[6];
}

Pattern.cpp:
CRGB Pattern::PixelAt(int idx)
{
  // safety check
  if (idx >= 0 && idx < NumLeds)
  {
    return Pixels[idx];
  }
  else
  {
    Serial.print("Index out of bounds: "); Serial.println(idx);
    return CRGB::Black;
  }
}

TestPattern.h:
class TestPattern : public Pattern {
    void Tick(unsigned long millis);
}

TestPattern.cpp:
void TestPattern::Tick(unsigned long millis)
{
    for (int p = 0 ; p < NumLeds ; p++)
    {
      Pixels[p]=CRGB::Blue;
    }
}

Main Sketch:
for (int p = 0; p < NUM_PATTERNS; p++)
{
  // update pattern
  ledPatterns[p].Tick(millis());

  if (ledPatterns[p].Status == Enabled)
  {
    // sum the values of the pixels
    for (int l = 0; l < NUM_LEDS; l++) {
      leds[l] += ledPatterns[p].PixelAt(l);
    }
  }
}

I'm skipping parts of the code to make it easier to read, but I think with this much you should be able to help me make it work. I'm still getting acquainted with C and pointers, which is where I think the problem lies.
So how should I declare and use Pixels[] so that the Main Sketch, the base class and the inherited class all have consistent information?

On the face of it that all looks fine. What is the actual problem you are having though? You have gone through and told us what it is supposed to do, but you have forgotten to tell us what actually happens.

I was not clear when i said "the content of Pixels[] doesn't seem to match what I actually write in there.". I write all the pixels to Blue and when i read them back in the main sketch i get random values.

I figure out something else that is wrong. I have the Tick function in the parent class, but i actually want every child class to overload Tick with its own implementation, which is not happening. When i call Tick in the Main Sketch (also edited that in the main question since i forgot to put it there), the Tick that is being called is the one from the parent class, not the child class, why is that? I thought by default the child function would be called, and not the parent.

@LuisFerreira thats usually caused by changing of object copies. Try to add Pattern(Pattern &) = deleted; and Pattern & operator=(const Pattern &) = deleted; into the Pattern class. And it won't let you copy this object.

@KIIV you mean add those lines in the Header file? I get this compile error if i past them there in the public section:
"error: invalid pure specifier (only '= 0' is allowed) before ';' token"

If you want a child member function to override a parent member function the parent member function has to be marked as virtual.

@LuisFerreira About ticks: if you have TestPattern * patterns[N]; and then you assign pointer to child, you have to use virtual void Tick(unsigned long millis);  and the same in child class.

@KIV In the child class you can use final to say "this will never be overwritten in a further child" which helps the compiler do a better job of optimizing.

@Majenko i want the Tick function to override the parent function since different patterns will have different behaviours . And i want the parent class PixelAt function to be used for all childs, since this code doesn't change from pattern to pattern

@Majenko if you are talking about deleted copy constructor it's basically impossible to override. But, if he's overriding something, it's good idea to add override specifier. If it doesn't actually override anything it'll refuse to compile.

@KIIV I mean in the virtual function. Parent: virtual void Tick(.....); - child: final void Tick(......);

@Majenko Or he can make whole child class final:  struct Child final : public Parent { and for the methods I think it should be at the end:  virtual void Tick(...) final override;

After reading comments i got some more clues where to search and indeed the problem was somewhat in the inheritance and how i was calling the functions. This post helped me find the problem.
I forgot to post the piece of code where i was creating the patterns in the Main Sketch, this is how it was initially:
Pattern ledPatterns[NUM_PATTERNS];
ledPatterns[0] = TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
ledPatterns[1] = TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

...
ledPatterns[p].Tick(millis());
...

When i later called ledPatterns.Tick (the function that modifies the values, the function actually being called was the parent and not the child. Thus the unexpected result.
This is how i should have been initializing the patterns, since they are inherited:
Pattern* ledPatterns[NUM_PATTERNS];
ledPatterns[0] = new TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
ledPatterns[1] = new TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

...
ledPatterns[p]->Tick(millis());
...

Sorry for the huge confusion, i thought the problem was in a completely different part of the code


text:
Multi Agent Systems
In my project work, I have 3 robots with their own Arduino boards. Each robot has Infra Red Sensors, whose values I can read using its corresponding Arduino. The main thing however is that each robot must have every other Robots' values. Can anyone suggest me a suitable strategy? I tried using the Processing Software, using which I am able to read all the values from all the robots but sending them back to the robots is turning out to be a problem! It says ports are busy!
Any help would be great!

What do you mean when you say "Processing Software"?  What are you using to read the values from the robots?  Are you using more equipment then the 3 robots you described in your question?

This is just a guess, but I suspect you are using the robots to look for a single IR source.  And that you have not yet considered the need to locate the robots in space disseminate that information among all the robots.

Are you looking for a way for each robot to communicate parameters to its partners? (That sounds like things that are available on several commercially available swarm robots, using IR or optical LEDs and receivers on each robot.)

For example see this robot (Thymio) under "Local Communication". That's an open source robot so you might be able to get a look at the firmware for ideas.


text:
Analog read negative voltage inbuilt protection
I'm trying to read a -10 to +10V analog signal on my Arduino Mega (2560). I've been using a voltage divider to obtain a -5V to +5V signal (with two 10kOhm resistors), which used to work just fine.
I'm wondering if this -5V signal can damage the Analog Input pins of the Mega ?
Thank you in advance for your time !

I'm sorry, but what type of reading would you like to obtain from that signal?Because you'll not be able to read anything negative...

All the IO pins contain a pair of clamping diodes to protect against over-voltage and negative-voltage situations:

As long as the current flowing through one of those diodes doesn't exceed its maximum forward current all will be well and the Arduino won't be damaged. If too much current flows then you will damage the pin.
Since you have 10KΩ resistors, at -5V the maximum current that could flow (assuming a 0.7V drop on the diode) would be (-5 + 0.7) / (10,000 / 2) = -860µA (negative because it's flowing backwards out of the pin from ground to your negative voltage source, not into the pin to ground).
Unfortunately the datasheet doesn't provide a current limit specification for those diodes, but I would expect such a small amount of current to be safe enough.

It’s 860 µA. See my comments to KIIV’s answer.

Current through the clamping diodes shouldn't be more than 1mA according to Atmel's Zero Cross Detection Application Note (AVR182).
EDIT: As Edgar Bonet pointed out you have current about (-5+0.5)/(10000/2) = 0.9mA (tested) in the worst case, there is not much space for mistakes.

+1 for finding that important spec buried inside an obscure application note.

Well, it wasn't me: Max current for AVR IO protection diodes on AVRFreaks. I've seen that thread before so it wasn't so hard.

It should be noted that the voltage divider is Thévenin equivalent to a ±5 V source with 5 kΩ output resistance. Thus the max current is (5 V − 0.7 V) ÷ 5 kΩ = 0.86 mA. This is assuming a 0.7 V drop in the diode.

The pin might not be damaged, but he will never read anything on the negative side of the signal....


text:
How to prevent Wire.requestFrom from hanging?
I'm trying to read data from an Arduino Uno I2C slave via Wire.requestFrom() on an Arduino Uno master. The slave's onRequest handler is simply:

void I2C_Send()
{

  byte myArray[4];

  myArray[0] = lowByte(acount);
  myArray[1] = highByte(acount);
  myArray[2] = lowByte(bcount);
  myArray[3] = highByte(bcount);

  Wire.write(myArray, 4);

}

It seems to work fine for a few iterations, but eventually something happens and the master's requestFrom() call hangs indefinitely. What's causing this and how do I prevent it?
I've tried setting various levels of timeout with Wire.setTimeout(x); but that has no effect.

You are using pull-up resistors and connected ground correctly? How long wires? Might have too large capacitive load and need to reduce the I2C clock frequency. Check the signals with a logic analyzer.

Can you post the master's code?

Did you find an answer...?

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


text:
Receive data from multiple wireless sensors simultaneously
I want to receive data from multiple (2/3) wireless sensors at the 512 Hz data rate simultaneously at a single receiver (bluetooth or any other wireless standard). Is it possible with one receiver or I need  multiple receivers?
I am novice to wireless communication please guide me to any available resources.
Thank you.

It is possible to do this with Zigbee. The API mode in the Xbee modules enables this.
Unlike the AT mode in Zigbee the API mode enables you to distinguish between the packets that you receive from different slaves.
In the API mode, you send each data packet with as a frame with a header which contains start delimiter byte, most significant byte (which tells where the start byte is at), least significant byte (which tells the end of the byte), an API identifier, the data that you want to send and a checksum byte.
This link provides a nice tutorial which shows how to setup Xbees on API mode with an Arduino and Python:
http://serdmanczyk.github.io/XBeeAPI-PythonArduino-Tutorial/
I hope this helps.

Thank you @MayBee for your answer. I went through the link and found useful. Since I am at the design phase right now, I would like to know whether it is possible with wifi or bluetooth? I don't have any power constraints , also I want to know, since data is coming at 512 Hz from each sensor(3 sensors) what type of issues which may occur while synchronizing all the sensors? thank you.

One issue that I faced was that the XBee modules could not handle large data packets in the API mode. Usually, Bluetooth only allows one to one communication but I believe that there are certain modules that will allow multiple slaves. In the case of WiFi, you could perhaps set up an external server and the modules could communicate using that. I have done this for a paid of RNXV WiFly module.  But, you should be able to add more slaves to this without issues. If you want a personal area network with multiple nodes, Zigbee would be the easiest to work with.


text:
ble_write slows down my sketch causing problems (Blend Micro & NRF8001)
I'm working on a prototype which uses the RedBearLabs Blend Micro with the NSC's nrf8001 ble chip, but have ran into a problem that I'm not sure how to solve.
I have two tactile buttons connected to the input pins on the Blend Micro, which are used to increase or decrease counters (integers) in my sketch that is in turn displayed on a OLED screen. When I use these buttons to manipulate the counter in offline mode (meaning that the bluetooth is not connected) I can repeatedly press the buttons very quickly and the counter is increased with every push - but when I connect to my phone and try to push the buttons with high frequency (>1-2 per second) the program is not able to react to every button interaction, causing only every second or third click to be registered.
The only thing that I do differently when I am connected is that I'm sending 5 bytes using "ble_write" (part of the RBL nrf8001 library), which seem to cause this delay resulting in missed clicks. Even sending one byte using "ble_write(X)" seem to slow down the sketch so much that this phenomena occurs.
Do any of you had similar problems and possible ways to solve this? I've been considering batching clicks together until I reach a certain amount and then send them at all once - this however may risk that a button is being pressed at the same time as the ble_write is executed, causing missed click.
Offline click looks like this:
if(digitalRead(A4)) {
while (digitalRead(A4)) {        }
offlineIn++;
localIn++;
totCount++;
sleepTimer = 0;
  }

And the online like this:
if (digitalRead(A4)) {
  while (digitalRead(A4)) {        }
  totCount++;
  localIn++;
  sleepTimer = 0;
  ble_write('0');
  ble_write('0');
  ble_write('0');
  ble_write('1');
  ble_write('1');
}

Thanks!

I've solved it by overclocking my blend micro to 16mhz (done in the Arduino IDE). Not a perfect solution but works. :)

This is a bad solution.  Likely what you have accomplished is to halve delays intentionally put there to properly operate the BLE.  If that works, then you should just be using half delays.

Good point. If I would optimise this I would probably need to look into the libraries used in more detail, but since this actually worked - I'm fine with the results.


text:
No connection with XBee radios on Arduino board
I have two Arduino boards which I've attached XBee radio boards to. One is to send data via Serial.write(num), where num is an integer. The other is receiving that integer via Serial.read. However, when I have both units running, nothing is ever received by the receiving unit. I've tried switching the receiving unit radio board to the USB mode so that I can use the serial monitor to send data to the unit. I've tried sending bytes 01111110, as well as integers such as 77. Nothing ever gets read from the serial monitor. I've downloaded XCTU, but it cannot find either of the radios. What can I do?


text:
Attempt stacking 'CAN-BUS' and 'USB Host' Shields on Mega 2560
I've run into a case of 'In theory it works, but in reality'....
I'm using the CAN-BUS Shield V1.2 from Seeed studio. Many things are written in broken english, so I'm starting to wonder if I can trust all of the information. http://wiki.seeed.cc/CAN-BUS_Shield_V1.2/
The USB Host Shield is a discontinued official Arduino model. https://www.arduino.cc/en/Main/ArduinoUSBHostShield
(I would link to the libraries, but I am unable to post more than 2 links)
CAN-BUS Pins:
AREF
ICSP (SCK, MISO, MOSI)
P9 - CS (SS)
P2 - INT
NC
IOREF
RST
3.3V
5V
Vin

USB Host Pins:
ICSP (SCK, MISO, MOSI)
P10 - SS
P7 - GPX
P8 - INT (actually RES?)
P9 - RES (actually INT?)

The only conflict I see is Pin 9 (CS on CAN, RES on USB). This is where it gets hazy... While the documentation on the bottom of the USBHost page implies that Pin 9 is RES, in the code Pin 9 is actually INT.
So, assuming Pin 9 is actually INT, I re-routed it to Pin 45 on on the Mega and changed it in the UsbCore.h file:
//typedef MAX3421e<P10, P9> MAX3421E; // old
typedef MAX3421e<P10, P45> MAX3421E; // new

Here is a snippet of the code I am running:
#include <PS3BT.h>
#include <usbhub.h>

#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

#include <Bounce2.h>
#include <Time.h>
#include <TimeLib.h>
#include <SPI.h>
#include "mcp_can.h"

const int SPI_CS_PIN = 9;

MCP_CAN CAN(SPI_CS_PIN); // Set CS pin

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

    // THIS WORKS
    if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
    }
    Serial.print(F("\r\nPS3 Bluetooth Library Started"));

    // THIS FAILS
    while (CAN_OK != CAN.begin(CAN_500KBPS))
    {
        Serial.println("CAN BUS Shield init fail");
        Serial.println(" Init CAN BUS Shield again");
        delay(100);
    }
    Serial.println("CAN BUS Shield init ok!");
}

The CAN-BUS Fails to init until I physically remove the USB Host Shield.
If I remove the CAN-BUS code, The USB Host Shield functions normally.
If I remove the USB Host code, the CAN-BUS Shield still DOES NOT init.
I tried to sift through the CAN-BUS init code a little, and I can only assume it's failing to communicate via SPI. What am I missing here?

I think that there is an hardware bug on the USB Master shield:
IC3, the 3-state buffer which converts MISO to 5V, is always active...
The enable pin of this 74LVC1G125 (pin 1) should be connected to the pin ss_3V3.
Then you can stack this shield with another one.

It definitely feels like a hardware bug! I haven't circled back to address this in a while - I'll respond after I try this fix.


text:
Connecting Saleae Logic 8 to MISO (pin 12) on Uno 3 w/ NRF24L01+ halts program
I have an NRF24L01+ with the base module (regulates voltage) connected to an Arduino Uno 3.  I'm using the tmrh20 NRF24 library and am running one of the example programs.  I'm trying to sniff the SPI bus so I have a Saleae Logic 8 hooked up.  As soon as I connect the clip to the MISO pin the Arduino program stops executing.  I'm able to reproduce this 100% of the time.  It seems it is only the MISO pin that is causing the problem.  For the library I am using MISO uses pin 12 on the Uno 3.
Anybody know what is going on?  It seems as if the Saleae is grounding pin 12 when I hook it up.  Not sure why it is only pin 12 that is an issue though.
I can reproduce the same problem when I manually connecting pin 12 straight to GND as well.
I can collect samples without MISO just fine but that of course only tells me half the story.
Any suggestions?
EDIT:
Here are some links and resources for more information.
I'm basically following the instructions from this article:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
The breakout board
http://www.addicore.com/1x-nRF24L01-Adapter-p/ad279.htm
And it's schematic:

Link to the datasheet for the radio itself:
http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01

And some photos of how I have it wired up:

Could you add a link to the NRF24L01+ module you are using and possible schematics? How do you connect ground to the Saleae Logic 8?

Added links.  I connected a few of the ground pins on the Saleae to the ground rail on the breadboard (see photo above).  The ground from the Arduino is connected to the ground rail on the breadboard.

Is the analyzer powered up?  What does that channel read of it read?  Try using a different channel of it.  Also see what size resistor you can connect between the pin and ground without disturbing operation - 100K?  10K?  1K?  Keep in mind your NRF24L01 will only be driving about 3.3v out, an ATmega at 5v has a relatively low Vih for a 5v part, but there won't be as much tolerance for loading as when using a 5v driver.

It seems to be a load issue from the logic analyzer.  I added a pull up resistor between the 5V and the pin.  I still have to have the resistor between the logic analyzer clip and the pin or else it will interfere with execution.  What I see now is that the pin reads high 100% of the time when the clock is not going, and 100% of the time low when the clock is engage.  I don't get any actual values for MISO (0x00 all the time).  The high and low are easily within the logic threshold levels.  I ordered some pots to fine tune the resistors to see if I can find a value that works.  Suggestions?

It would appear from your description that the leads on your logic analyzer distort of the SPI MISO waveform and the Arduino does not read incoming data correctly.
To avoid this, you could place an digital isolator between the Arduino and the Logic 8.
Any decent oscilloscope should also allow you to read the SPI bus.


text:
What is the maximum length an Interrupt Service Routine?
In general, what's the maximum length of instructions that can be included in an Interrupt Service Routine?
The docs say an ISR should be "as short and fast as possible", but that's bit vague.
For example, I have an ISR that gets called for each pulse on an motor's encoder.
void on_encoder_pulse(){
    encoder_change = true;
    count1 += 1;
    count2 += last_call;
    last_call = millis();
}

Will this run without interruption?

What is the maximum length an Interrupt Service Routine?

This depends on the max latency before servicing any other waiting Interrupt Service Routine (ISR).
An AVR ISR will execute with further interrupts disabled until the running ISR is completed. Any other interrupt(s) during the execution will be delayed. Data may be lost if the delay is too long. This depends on the interrupt source and frequency of interrupts.
In general an ISR (for incoming data) should only capture the data that could be lost and delay processing to the main loop function. A good example is the ISR for the Arduino Hardware Serial (USART) handling. Data sent and received are queued.
A traditional method (design pattern) is to have very short ISRs that capture data and push to an event queue. All processing is done in the main loop. This gives short latency and faster response, and reduces the risk of ISRs depending on each other, etc.
Cheers!

In general, on AVR devices, interrupts have been turned off (by hardware) when an ISR (interrupt service routine) begins execution.
Thus, if on_encoder_pulse() is an ISR and is invoked due to an interrupt,  it will run uninterrupted.
An ISR that within itself turns the interrupt system back on before it's done runs the risk of other interrupts being serviced before it completes.
The suggestion that ISR's be “as short and fast as possible” is intended to avoid other interrupts being missed, as will happen if an interrupt source activates multiple times while the interrupt system is off.  Most interrupt sources latch a bit and will be handled when the interrupt system is re-enabled; some don't latch a bit, and won't be seen if some ISR is long-winded.

As already explained by jwpat7, interrupts are, by default, not
interruptible. Thus, if another interrupt fires while your ISR is
running, it will no be serviced until your ISR completes. This delay you
impose on other interrupts is called latency. So your question boils
down to “how much latency can the other interrupts tolerate”.
There is no simple answer: it all depends on the timing requirements
of whatever those interrupts are servicing. For example:

The millis() counter is updated by interrupts. Any latency longer
than 1024 µs (on the Uno) can make it loose tics.
If you are using the serial port to receive data, a latency longer
than one byte time (1040 µs at 9600 pbs, less at higher baud
rates) will make you loose data.
If you are using the Servo library, any interrupt latency will
create jitter in the drive signal, and at some point this may become
visible as mechanical jitter.

Then, if you really need a precise answer, you will have to check the
timing requirements of every piece of hardware and every library you
are using. And then check the latency already imposed by the ISRs in
those libraries, as your latency can come in top of that.
If your program relies on loop() looping fast enough, you should also
keep in mind that interrupts also slow that.


text:
Arduino FFT library - Open Music Labs installation help
I downloaded the zip file of the FFT library from the below link
http://wiki.openmusiclabs.com/wiki/ArduinoFFT
and it now as I implement the example codes, it gives out a message which says
"Error compiling for Mega or Mega2560".
I have an Arduino Mega2560 and I want to know how to use this library for my board for frequency analysis of sound. Any help on this will be much appreciated.

How about sharing the rest of the error message?

E:\Setup files\arduino-1.6.10-windows\arduino-1.6.10-windows\arduino-1.6.10\libraries\FFT/FFT.h:181:3: warning: invalid suffix on literal; C++11 requires a space between literal and string macro [-Wliteral-suffix]
"ldi r16, "STRINGIFY(FFT_N/2)" \n" // prep loop counter
^
E:\Setup files\arduino-1.6.10-windows\arduino-1.6.10-windows\arduino-1.6.10\libraries\FFT/FFT.h:74:10: error: 'prog_int16_t' does not name a type
PROGMEM  prog_int16_t _wk_constants[]  = {
      ^      These are the two types of errors being shown. Is there something wrong with the library? @Majenko

Works only on earlier versions of the IDE. That was the reason for the error.


text:
Arduino Mega 2560 + ESP8266 Problem with GET Request
I have an ESP8266 module connected to my Arduino Mega 2560. My goal is to send a GET request as below to the network:
api.pushingbox.com/pushingbox?devid=vEB39F555B1B8295?tempData=cabbages

If that is successful, I will get the string "cabbages" along with the timestamp inside my Google Sheets. Note that I intend to change the string "cabbages" with many other data once this is working, but for now, just cabbages. Pasting the link above inside a web browser and pressing Enter seems work fine, but doing it automatically from inside Arduino with ESP8266 attached is somehow not as I expected.
After connecting to my home wifi I tried making a GET request to Google.com:
void setup()
{
  Serial.begin(115200);
  Serial2.begin(115200);

  delay(3000);
  Serial2.write("AT\r\n");
  delay(3000);
  Serial2.write("AT+CWMODE=1\r\n");
  delay(3000);
  Serial2.write("AT+CIPMUX=0\r\n");
  delay(3000);

  Serial2.write("AT+CIPSTART=\"TCP\",\"www.google.com\",80\r\n");
  delay(500);
  Serial2.write("AT+CIPSEND=80\r\n");
  delay(500);
  Serial2.write("GET / HTTP/1.0\r\n");
  delay(500);
  Serial2.write("User-Agent: curl/7.37.0\r\n");
  delay(500);
  Serial2.write("Host: www.google.com\r\n");
  delay(500);
  Serial2.write("Accept: */*\r\n\r\n\r\n");
}

void loop()
{
  if (Serial2.available()) {
    Serial.write(Serial2.read());
  }
  if (Serial.available()) {
    Serial2.write(Serial.read());
  }
}

And I get the response as follows, which is actually the Google home page:
AT
OK
AT+CWMODE=1
OK
AT+CIPMUX=0link is builded
Recv 80 bytes

SEND OK

+IPD,1410:HTTP/1.0 200 OK
Date: Fri, 23 Sep 2016 08:49:38 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
P3P: CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Set-Cookie: NID=87=TS-mbT3JjN_vZQurH0M4e1tbNsgmSPF4ALY_ohGFUD6uz76RmbxY41AA_XtC75Wqxfcqu5v1lbLxy-tMa_yrn5-BHrxN7Hn6CeYVnEfG1bBsVd78Y6eHtJ0hOUQPIwaDM0_2wGPO52e7HQ; expires=Sat, 25-Mar-2017 08:49:38 GMT; path=/; domain=.google.com; HttpOnly
Accept-Ranges: none
Vary: Accept-Encoding

<!doctype html><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><link href="/images/branding/product/ico/googleg_lodp.ico" rel="shortcut icon">

<nobr>Search Images Maps Play YouTube News Gmail Drive More »</nobr>

<nobr>Web History | Settings | Sign in</nobr>

<form action="/search" name="f">

 	<input name="ie" value="ISO-8859-1" type="hidden"><input value="en" name="hl" type="hidden"><input name="source" type="hidden" value="hp"><input name="biw" type="hidden"><input name="bih" type="hidden">
<input style="color:#000;margin:0;padding:5px 8px 0 6px;vertical-align:top" autocomplete="off" class="lst" value="" title="Google Search" maxlength="2048" name="q" size="57">

<input class="lsb" value="Google Search" name="btnG" type="submit"><input class="lsb" value="I'm Feeling Lucky" name="btnI" onclick="if(this.form.q.value)this.checked=1; else top.location='/doodles/'" type="submit">	Advanced searchLanguage tools

<input id="gbv" name="gbv" type="hidden" value="1"></form>

Advertising ProgramsBusiness Solutions+GoogleAbout GoogleGoogle.com.my

© 2016 - Privacy - Terms

CLOSED

However, when I try it with the actual URL I intend to use:
void setup()
{
  Serial.begin(115200);
  Serial2.begin(115200);

  delay(3000);
  Serial2.write("AT\r\n");
  delay(3000);
  Serial2.write("AT+CWMODE=1\r\n");
  delay(3000);
  Serial2.write("AT+CIPMUX=0\r\n");
  delay(3000);

  Serial2.write("AT+CIPSTART=\"TCP\",\"api.pushingbox.com\",80\r\n");
  delay(500);
  Serial2.write("AT+CIPSEND=135\r\n");
  delay(500);
  Serial2.write("GET /pushingbox?devid=vEB39F555B1B8295&tempData=cabbages HTTP/1.0\r\n");
  delay(500);
  Serial2.write("User-Agent: curl/7.37.0\r\n");
  delay(500);
  Serial2.write("Host: api.pushingbox.com\r\n");
  delay(500);
  Serial2.write("Accept: */*\r\n\r\n\r\n");
}

void loop()
{
  if (Serial2.available()) {
    Serial.write(Serial2.read());
  }
  if (Serial.available()) {
    Serial2.write(Serial.read());
  }
}

I get the following response:
AT
OK
AT+CWMODE=1
OK
AT+CIPMUX=0
OK
AT+CIPSTART=Accept: */*ERROR
ERROR
ERROR

+IPD,212:HTTP/1.0 408 Request Time-out
Cache-Control: no-cache
Connection: close
Content-Type: text/html

408 Request Time-out

Your browser didn't send a complete request in time.

CLOSED

The code is exactly the same except for the different URLs used, so what is causing the problem here? Why can't I send "api.pushingbox.com/pushingbox?devid=vEB39F555B1B8295?tempData=cabbages" to the internet? Please help! :-/

All those string literals need wrapping in F(...) or you will be overflowing your precious RAM.

But "cabbages" is something I wish to change later. Isn't F(...) only for constant strings?

Yes, and 99.99% of that (all except the word "cabbages" and the content length value) is constant strings.

Hey @Majenko thanks for the tip. But I can't seem to compile right with the F(....) wrapping. :-/

Did you get this issues sorted? I have the same problem, yet I can "GET" to Thingspeak with the same code without any issues? When I copy the URL directly into my web browser it works, however, the timeout error occurs only when I make use of my Arduino the "Serial.print" the GET command. would like your feedback, thanks! EO

I did notice you also changed
AT+CIPSEND=80\r\n
to
AT+CIPSEND=135\r\n
probably you send your request wrong or something?!?
(sorry I post this as answer but I didn't unlock comments yet)

First you must check if the problem is on your side or not.
You call http://api.pushingbox.com and you send parameter which are "pushingbox?devid=vEB39F555B1B8295&tempData=cabbages"
When I glue them together
http://api.pushingbox.com/pushingbox?devid=vEB39F555B1B8295&tempData=cabbages
and copy past this on my browser, I get an error with "Daily limit exceeded" with a status of 429 meaning "too many request".
So maybe there is a problem with the server?

Try changing:
Serial2.write("AT+CWMODE=1\r\n");

to:
Serial2.write("AT+CWMODE=2\r\n");

or:
Serial2.write("AT+CWMODE=3\r\n");


text:
Writing objects to PROGMEM
A few days ago I encountered memory problems (SRAM shortage) on my Arduino. I've read a lot and fixed the problem, now I have around 900 bytes free in SRAM. However, I still have difficulties understanding and using progmem.
The user is allowed to create up to 10 programs (a program in my case is just some object storing the user's preferences). As I don't want to run out of SRAM, I planned to store them in PROGMEM.
Consider the following class:

#define MAX_PROGRAMS 10
#define MAX_PREFS 10

class Program
{
  public:
    Program(String name, Preference* prefs[]); // ctor

    String getName();
    static byte getNoOfPrograms();
    static Program* getProgram(byte idx);

  private:
    const String _name;
    static int _programCtr;

    Preference* _preferences[MAX_PREFS];
    static Program* _programs[MAX_PROGRAMS];
};

One notices that a program can store up to 10 preferences, hence, if the user decides to make 10 programs, each with 10 different preferences, we will definitely run out of SRAM.
Therefore, can I store instances of the above Program class in PROGMEM if I define them as below?
const Program* const pgm PROGMEM = new Program(F("Test"), ...);
// ...
delete pgm;

I presume this is possible since the whole object is const and could never be changed. I actually tried this and had no compiler errors, however, I was stumbled by the fact that the above two lines of code use 22 bytes of SRAM, when I expected it not to use any.
In my case, would it be better not to store the whole object in progmem but only its constant fields, and do the same for all constants in Preference ? (i.e. change const String _name to const char name[] PROGMEM; etc.)

Are you aware that everything you store in progmem is going to be fixed at compile time? I ask because you wish to use progmem to store user defined programs, so that makes sense only if the user defines that programs before compilation occurs... which to me makes the whole thing a nonsense... but I believe it all comes down to what is a program for you...

@RobertoLoGiacco Wow, thanks! This indeed does not make sense if it is to be fixed at compile time, since, the user will make those programs at runtime. Does this imply that i can not avoid to run out of SRAM, apart from limiting the user to less programs and preferences?

Your example only puts the object pointer in program memory. "new" allocates the object from the heap. Please see this example that I put together a few years back. https://github.com/mikaelpatel/Sketchbook/tree/master/ProgramMemory

A more advanced example can be found in Cosa LCD Menu handler. The menu data structure is put in program memory; https://github.com/mikaelpatel/Cosa/blob/master/libraries/Menu/Menu.hh and example sketch, https://github.com/mikaelpatel/Cosa/blob/master/examples/LCD/CosaLCDmenu/CosaLCDmenu.ino

@MikaelPatel Right, i was not sure about dynamically allocating the object or not. Thanks for the examples, they are quiet useful, however, my program instances will be created at runtime. Hence, i think i will have no other option than limiting the user to a few programs..

@HyperZ Or cleaning up your system to a) not use String, and b) tokenize your program and store it as binary code.

It is possible for software running on the ATmega to write to program memory at runtime, and even to erase it in large blocks.  See bootloader sources for an example.

@Majenko Thanks, i cleaned up the whole system such that i don't use the String class anymore in order not to fragment the heap. Now, what do you mean by tokenizing my program and storing it as binary code? :)

I've marked this as a duplicate of Using PROGMEM to store array of structs. The question isn't the same, but the solution is.

Related: Can I write to flash memory using PROGMEM?


text:
How to find gain for this device?
I am doing a project with Arduino to find CO2 in an environment. For this purpose, I bought a breakout board with an MG811 sensor on it. I bought it from eBay and it came with no datasheet. I searched on the internet and found the datasheet for the MG811.
With the help of the datasheet, I also found the formula to convert the input voltage to PPM. But later I realized that the device also has an amplifier on it, which is giving me higher voltages. I searched thoroughly and found the original device on Taobao.
Can someone please tell me how can I determine the gain so that I can convert the values I read to original values?
One more question. On the given web link, I also found that this device comes with a pin called TCM and with Google translate, I found that it shows temperature compensated output. Can you please explain me the use of this pin as well? If it is more advantageous for me, I'll use this instead of the normal analog output pin.

The amplifier is there for a reason, why would you want to convert them back to original values? Can't you just work with the values the device is giving you?

@Len what you said is true but I don't know the extremes of my values so that I can draw a new plot and find a new equation. The company who manufactured the device have tested it and gave a graph to me with which I can find proper equations. For this purpose I want to know the gain.

I assume the values are given in analogue values? If that is the case, you can just use a volt meter to detect which one is changing when the device is exposed to CO² (i.e. from your breath). If you know the gain, just read out the values of the gain and the one the devices gives to the Arduino. Get multiple readings of multiple values, then map the values the Arduino receives to the ones desired or similar to that of the datasheet.

Measure the voltage before the amplifier. Measure the voltage after the amplifier. Divide the second value by the first. There's your gain.

@Majenko do it twice to establish offset

The MG811 spec gives you the range of measurement, but without the values and connections of the surface mount op amp on the board the only way to determine the voltage output for each CO2 concentration is with a Voltmeter and an already calibrated CO2 PPM meter, which you could perhaps borrow from a lab or university.  Once you have the CO2 values and Voltages that correspond, you can build a formula or function to convert the digital values to voltages and then to CO2 concentrations.
The other option is to trace the tracks on the PCB and create a schematic and then post the spec above and the schematic with resistor values included on the electronics Stack Exchange.


text:
Ooops, no LSM303 detected ... Check your wiring!
History
I have an Adafruit 10DOF IMU Breakout which has been working on my Mega for some time. This morning my program did not run so I starting troubleshooting.
Scenario
I eventually plugged the IMU breakout into my Uno with the *out-of-the-box accelerometer reader program from Adafruit. That's when I started seeing
Ooops, no LSM303 detected ... Check your wiring!
And upon close inspection have verified all wires are in the correct spot.

Question
How do I troubleshoot this further? Also, I'm starting to think that my IMU may be fried. How can I test this?

* AHRS out-of-the-box Program from Adafruit:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>
#include <Adafruit_BMP085_U.h>
#include <Adafruit_L3GD20_U.h>
#include <Adafruit_10DOF.h>

/* Assign a unique ID to the sensors */
Adafruit_10DOF                dof   = Adafruit_10DOF();
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);
Adafruit_BMP085_Unified       bmp   = Adafruit_BMP085_Unified(18001);

/* Update this with the correct SLP for accurate altitude measurements */
float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;

/**************************************************************************/
/*!
    @brief  Initialises all the sensors used by this example
*/
/**************************************************************************/
void initSensors()
{
  if(!accel.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP180 ... check your connections */
    Serial.println("Ooops, no BMP180 detected ... Check your wiring!");
    while(1);
  }
}

/**************************************************************************/
/*!

*/
/**************************************************************************/
void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Adafruit 10 DOF Pitch/Roll/Heading Example")); Serial.println("");

  /* Initialise the sensors */
  initSensors();
}

/**************************************************************************/
/*!
    @brief  Constantly check the roll/pitch/heading/altitude/temperature
*/
/**************************************************************************/
void loop(void)
{
  sensors_event_t accel_event;
  sensors_event_t mag_event;
  sensors_event_t bmp_event;
  sensors_vec_t   orientation;

  /* Read the accelerometer and magnetometer */
  accel.getEvent(&accel_event);
  mag.getEvent(&mag_event);

  /* Use the new fusionGetOrientation function to merge accel/mag data */
  if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation))
  {
    /* 'orientation' should have valid .roll and .pitch fields */
    Serial.print(F("Orientation: "));
    Serial.print(orientation.roll);
    Serial.print(F(" "));
    Serial.print(orientation.pitch);
    Serial.print(F(" "));
    Serial.print(orientation.heading);
    Serial.println(F(""));
  }

  /* Previous code removed handling accel and mag data separately */
  //  /* Calculate pitch and roll from the raw accelerometer data */
  //  Serial.print(F("Orientation: "));
  //  accel.getEvent(&accel_event);
  //  if (dof.accelGetOrientation(&accel_event, &orientation))
  //  {
  //    /* 'orientation' should have valid .roll and .pitch fields */
  //    Serial.print(orientation.roll);
  //    Serial.print(F(" "));
  //    Serial.print(orientation.pitch);
  //    Serial.print(F(" "));
  //  }
  //
  //  /* Calculate the heading using the magnetometer */
  //  mag.getEvent(&mag_event);
  //  if (dof.magGetOrientation(SENSOR_AXIS_Z, &mag_event, &orientation))
  //  {
  //    /* 'orientation' should have valid .heading data now */
  //    Serial.print(orientation.heading);
  //  }
  //  Serial.println(F(""));

  /* Calculate the altitude using the barometric pressure sensor */
  bmp.getEvent(&bmp_event);
  if (bmp_event.pressure)
  {
    /* Get ambient temperature in C */
    float temperature;
    bmp.getTemperature(&temperature);
    /* Convert atmospheric pressure, SLP and temp to altitude */
    Serial.print(F("Alt: "));
    Serial.print(bmp.pressureToAltitude(seaLevelPressure,
                                        bmp_event.pressure,
                                        temperature));
    Serial.println(F(""));
    /* Display the temperature */
    Serial.print(F("Temp: "));
    Serial.print(temperature);
    Serial.println(F(""));
  }

  delay(100);
}

-- EDIT --
I'm pretty sure the board is dead. The program stops at accel.begin(), mag.begin(), or bmp.begin(); I've tried each individually.

same issues, ordered board from AliExpress. Using this code however, I can report that in my case, the board is not dead an reports some values - it just is not recognized somehow.   int yAxis = analogRead(A4); // Yout pin of accelerometer   Serial.print(",");   Serial.print(yAxis);

@user2305193 Fascinating. Please let me know how it turns out!

Check each of your conditional statement at
if(!accel.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP180 ... check your connections */
    Serial.println("Ooops, no BMP180 detected ... Check your wiring!");
    while(1);
  }

by commenting the others.

I had a similar issue. Turns out it was faulty wiring, probably due to a cheap breadboard (as a noob you would expect perfect connectivity from something like a breadboard! Turns out: not at all!)
Here's how I went about debugging it, using an i2c scanner to debug connectivity (find library + example here).

remove the while(1) loops that halt your program, so the program doesn't 'stop' on error
Use an 'error variable' e.g. fail. Initialize e.g. as fail=0 at start of script so it's global. Add fail=1 for every oops case in initSensors()
in loop(), check if fail==0, if yes, continue with outputting the 10DOF sensor values, if there is an error (fail==1) call initSensors() and the i2cscanner() so you get a debugging view of your connectivity. This would look like below, and will keep calling the debug function until you connected it properly.

Hope this was useful or at least interesting to you, good luck.
Screenshot of i2c scanner:

I this one of many Arduino invented terminology ?
Normally function returns ZERO on success and -1 or positive number identifying the error.
if(!accel.begin())

{
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }

Different functions return different things. Functions that handle buffers supplied by the caller typically return the caller's buffer pointer on success or a NULL pointer on failure, for one of many counter-examples. You can't assume what choices another author made without reading the description or the code itself. The author of this library wrote the .begin() function to return a bool; TRUE on success, and FALSE otherwise. It is not uncommon.


text:
writing and uploading sketch as cpp file
I want to use only *.cpp files and no *.ino anymore. I read a lot of stuff about how to upload c++ instead of arduino sketches. But still I was not able to find a step by step guide how to do it.
Actually I am developing my sketch within Spacemacs (Emacs) and uploading it with Arduino-Makefile (https://github.com/sudar/Arduino-Makefile)
When I now want to start a new project with only *.cpp and *.h files to use classes etc. how would I start? Does anybody has the time to describe a rough step-by-step without the trivial stuff?

.ino files are C++ files. You could just rename your main C++ file with the .ino extension and compile it with the IDE or Sudar's Makefile. If you are not using the Arduino core library, a much simpler Makefile could do it.

yea but what about these loop() and setup() functions. I know I could write a main() function instead but well...there must be some kind of conventional interface so the microcontroller knows what to start running. Or are those two "arduino" functions wrapped by a main() function which just calls setup once and calls loop() in a while-loop?

If you're moving to a standalone project then why do you care what the Arduino libraries do? If you need the Arduino libraries then why are you moving to a standalone project?

I never said I want to skip the arduino library. Still want to use it but not in a ino file

See my post about How the IDE organizes things.
Also see my page about how to avoid the quirks of the IDE sketch file pre-preprocessing.
You can certainly manage without .ino files. As Edgar Bonet says, they are really C++ files with certain pre-processing (see link above).

but what about these loop() and setup() functions

Effectively, the Arduino IDE supplies a main function that looks like this:
int main ()
  {
  init ();    // initialize hardware, including timers and timer interrupts
  setup ();   // user setup
  while (true)
    loop ();  // stuff to be done repeatedly
  return 0;   // this will never be executed
  }

(It's slightly more complex, to allow for USB where applicable, but that is the idea).

But still I did not found the step by step guide how to do it.

I'm pretty sure there are a lot of example "make" files around which show the idea.
I have an example here.


text:
Results for GP2Y1010AU0F Dust Sensor
I am using Dust Sensor GP2Y1010AU0F
I downloaded the code from the manufacturer here:
http://www.waveshare.com/wiki/Dust_Sensor
/*********************************************************************************************************
*
* File                : DustSensor
* Hardware Environment:
* Build Environment   : Arduino
* Version             : V1.0.5-r2
* By                  : WaveShare
*
*                                  (c) Copyright 2005-2011, WaveShare
*                                       http://www.waveshare.net
*                                       http://www.waveshare.com
*                                          All Rights Reserved
*
*********************************************************************************************************/
#define        COV_RATIO                       0.2            //ug/mmm / mv
#define        NO_DUST_VOLTAGE                 400            //mv
#define        SYS_VOLTAGE                     5000

/*
I/O define
*/
const int iled = 7;                                            //drive the led of sensor
const int vout = 0;                                            //analog input

/*
variable
*/
float density, voltage;
int   adcvalue;

/*
private function
*/
int Filter(int m)
{
  static int flag_first = 0, _buff[10], sum;
  const int _buff_max = 10;
  int i;

  if(flag_first == 0)
  {
    flag_first = 1;

    for(i = 0, sum = 0; i < _buff_max; i++)
    {
      _buff[i] = m;
      sum += _buff[i];
    }
    return m;
  }
  else
  {
    sum -= _buff[0];
    for(i = 0; i < (_buff_max - 1); i++)
    {
      _buff[i] = _buff[i + 1];
    }
    _buff[9] = m;
    sum += _buff[9];

    i = sum / 10.0;
    return i;
  }
}

void setup(void)
{
  pinMode(iled, OUTPUT);
  digitalWrite(iled, LOW);                                     //iled default closed

  Serial.begin(9600);                                         //send and receive at 9600 baud
  Serial.print("*********************************** WaveShare ***********************************\n");
}

void loop(void)
{
  /*
  get adcvalue
  */
  digitalWrite(iled, HIGH);
  delayMicroseconds(280);
  adcvalue = analogRead(vout);
  digitalWrite(iled, LOW);

  adcvalue = Filter(adcvalue);

  /*
  covert voltage (mv)
  */
  voltage = (SYS_VOLTAGE / 1024.0) * adcvalue * 11;

  /*
  voltage to density
  */
  if(voltage >= NO_DUST_VOLTAGE)
  {
    voltage -= NO_DUST_VOLTAGE;

    density = voltage * COV_RATIO;
  }
  else
    density = 0;

  /*
  display the result
  */
  Serial.print("The current dust concentration is: ");
  Serial.print(density);
  Serial.print(" ug/m3\n");

  delay(1000);
}

My results seems rounded or always returning in certain 'steps'.
(below are my results)
Is there a rounded error in the code or something else that could be going on?
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 124.10 ug/m3

Its because the resolution of the analog read is 10 bits or 1024 discrete values.
In your code the density is basically calculated as:
density = (((5000 / 1024.0) * analog_value * 11) - 400) * 0.2

You can calculate the resolution as:
(5000 / 1024.0) * 11 * 0.2

and you get 10.7421875, which matches your observation.
If your filtering (calculating the average over last 10 values), would calculate and return a float, you would get smoother values.


text:
How to control MKR1000 from outside your local network
I want to send an HTTP command to MKR1000 from outside my local network.
So far, all the googled resources point to getting the local IP (example 192.168.0.10) of MKR1000 and sending a command like http://192.168.0.10/H to it and then parse it.
How do I send a command to MKR1000 from outside its local network?
I should clarify that I want this to be a consumer product and can't have the end-user fiddling with their routers for port forwarding etc.

Google "port forwarding" along with the make and model of your router.

I want it to be a consumer product and don't want every end user to be fiddling with their router. Edited my question accordingly.

Well you can't. Simple fact: devices on an internal network, regardless of how you may wish it, are not accessible from outside. Only the user can configure their router to forward access to it.

But a lot of consumer IOT products (e.g. NEST) are controlled from your mobile device from anywhere?

No they aren't. An external service is controlled from your device, and the IoT device queries that same external service.

What you really want is something like MQTT

I see, so I need a server. Mobile device writes to server and MKR1000 keeps querying the server to get commands? I think Firebase will work nicely BUT this continuous query on MKR1000 side will be battery and data consuming.

Depends how "continuous" you really need.

The only way I can think of to achieve this would be to port forward your router, and forward port 80 (http) to your MKR1000. You can check out https://portforward.com/ for instructions on that.
If you don't want to port-forward, you'd have to have the MKR1000 connect to a centralized IOT server somewhere, and have the user go through the server to access the MKR1000. That's how other iot devices such as nest cameras do it.

You now can try this UPnP_Generic library to do the auto-portforwarding for you without manually touching the router.

Many of us are manually port-forwarding in Internet Gateway Device (IGD, Router) in order to provide access to local Web Services from the Internet.
This library provides the easier way to automatically port-forward by using the Simple Service Discovery Protocol (SSDP), running on nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, ESP8266/ESP32, using ESP WiFi, WiFiNINA, Ethernet W5x00, ESP8266/ESP32 AT-command WiFi supporting UDP Multicast.
The SSDP provides a mechanism whereby network clients, with little or no static configuration, can discover network services. SSDP accomplishes this by providing for multicast discovery support as well as server based notification and discovery routing.
The SSDP is used for advertisement and discovery of network services and presence information. It accomplishes the task without assistance of server-based configuration mechanisms, such as Dynamic Host Configuration Protocol (DHCP) or Domain Name System (DNS), and without special static configuration of a network host. SSDP is the basis of the discovery protocol of Universal Plug and Play (UPnP) and is intended for use in residential or small office environments.
This UPnP_Generic library is created to automatically update your IGDs with the requested port-forward information, using one of the many available boards / shields. See Currently Supported Boards.
The time between checks to update the UPnP Port Mappings is configurable to match your use case, and is set in the examples at 10 minutes. The LEASE_DURATION is also configurable and default to 10hrs (36000s). The Virtual Server Name can also be specified in the sketch and is shown in the IGD, e.g. NRF52-W5X00 or ESP8266-WIFI as in the following picture:

The UPnP_Generic code is very short, can be immersed in your Projects and to be called in the loop() code.