text:
Array of Strings and Callbacks
I am trying to create an array of structs that contain pairs of Strings and Callbacks the problem I am having is assigning the callback function. I have the following code:
#define UI_ROUTINE_ITEMS 10

struct MenuItem{
    String label;
    typedef void (*callback)();
};

class MenuSystem{
   MenuItem routineMenu[UI_ROUTINE_ITEMS];

   MenuSystem(){
      routineMenu[0] = {"Test", &Test::TestCallback};
   }
}

class Test{
   void TestCallback(){
      Serial.println("Callback called");
   }
}

When I try to compile this I get:
error: no match for 'operator=' (operand types are 'MenuItem' and '<brace-enclosed initializer list>')

I know this is a Syntax issue I just can not figure out how this should be done. I have looked at several examples but I can't figure out how to do this with Classes without using free/malloc, what am I doing wrong?

EDIT

I finally got this working, the problem was that the function that I was trying to call was not static and the declaration in the structure was not quite right. Below is the corrected example:
#define UI_ROUTINE_ITEMS 10

#include <Arduino.h>

struct MenuItem{
    String label;
    void (*callback)(void);
};

class MenuSystem{
   MenuItem routineMenu[UI_ROUTINE_ITEMS];

   MenuSystem(){
      routineMenu[0] = {"Test", &Test::TestCallback};
   }
}

class Test{
   public static void TestCallback(){
      Serial.println("Callback called");
   }
}

Several issue with this code. First, use public/protected/private for classes. Second, use a const char* instead of String or even better str_P. It is the usage of String that is giving the compile error. Third, the Test::TestCallback function reference is not possible. It is a member function. To correct that either have an instance or define the callback function as static.
You could define an abstract MenuItem class with the string and a virtual member function. A Menu class would hold a collection of MenuItems. All the static data should be put in program memory.
There is a Menu system in Cosa. Please see the example sketch. This implementation follows the MVC design pattern.
Cheers!

That was what I was missing, I forgot that in order to pass a reference like I wanted it needed to be static. I knew it was something simple. Thanks for getting me on the right track, unfortunately I can not figure out how to get the Cosa libraries compiling correctly in eclipse.

A pointer to a member instance function is possible:
void (Some_class::*Some_fnc_ptr)();

And in order to call different classes than just "Test" you'd have to play some games with templates and probably virtual functions.  It would get pretty involved, but doable.

Your system works in pure C too:
typedef struct _MenuItem
{
    const char *label; // or String if you like
    void (*callback)();
} MenuItem;

void testCallback()
{
    Serial.println("testCallback() Called");
}

MenuItem menu_system[10];
void setup()
{
    menu_system[0].label    = "Test";
    menu_system[0].callback = testCallback;

    ... # more menu definitions with callbacks
}

void loop()
{
    unsigned int user_menu_selection;

    ... # some menu code, user selection in <user_menu_selection>

    menu_system[user_menu_selection].callback();  // TODO: error checking
}

It might be a good idea to store any static Menu Strings into PROGMEM.

In pure C I would use __flash const instead of PROGMEM: the compiler knows how to properly dereference a __flash pointer, whereas with PROGMEM you have to explicitly call one of the pgm_read_*() functions.

I know that you've resolved your dilemma, but I just wanted to show you a trick: personally, I hate the pointer-to-function mechanism that everyone uses, when there's a perfectly good alternative.
Here's a function that takes an int and returns a char:
char SomeFn(int i);

Here's a typedef describing that function as a type:
typedef char Fn(int i);

Looks pretty similar, huh? What's the point? Now that you've got a type, you can use that instead:
void SetCallback(Fn *fn);

SetCallback takes as a parameter a pointer to a function of type Fn. The * is necessary, and (to me) makes more sense than trying to barrel the pointer-ness inside the type itself - which is what leads to the parenthesis overload. You can call it like this:
SetCallback(&SomeFn);

What could be easier? If SomeFn was a static member of a class, you could just as easily use that:
SetCallback(&Class::SomeFn);


text:
Eclipse add library
I am completely lost here, I have no idea what I am doing wrong. I am using Eclipse Mars using the Eclipse C++ Arduino extension. I am also using the COSA library, this is where the problem comes in. I can use all of the core COSA libraries but I can not figure out how to include the other libraries that are supplied with COSA specifically the ST7920.h file that is located in the libraries folder. Does anyone have any experience with this?
I have tried setting the path using the Project->C/C++ General->Preprocessor include paths and setting it there to no avail.
One thing that I am concerned about is in these separate libraries they are including files that are in other libs using only the header file, for example in the ST7920.hh file it has:
#include "Cosa/LCD.hh"
#include <HD44780.h>

I need to configure things so that the HD44780.h file needs to be found also. That file is located at "../HD44780/HD44780.h". How do I tell the compiler to search the "libraries" folder for files?
Also I tried to simply add the libraries folder as a linked folder in my project, that also did not work.
the only code I have is the #include  and the compiler come back with that it can't find the file.

FWIW I have stopped using Eclipse Arduino plugin and replaced my whole environment with Netbeans 8 (note: I also use Cosa core and several of its libraries). Although it took me quite some time to configure from scratch, now I have a working setup that works just fine.

Netbeans integration was not straightforward but it worked well once done. I did not use any specific plugin for it.

I would advice to use the arduino eclipse plugin and not use the eclipse C++ arduino extension.
The eclipse C++ arduino extension is still very much in development.
The Arduino eclipse plugin has been around for years and contains far more features.
If you use V3 (that is still the nightly at the time of writing) you can use the boards manager and the cosa json file to import the cosa boards.
Importing a lib is a matter of typing
#include "libname"

and saving.

If you are using Linux I would recommend looking at the makefile based build script for Cosa (See Cosa/build). After configuration building from any IDE is more or less a simple command. No Makefile is required. The script cosa will do all the work.
$ cosa BOARD ACTION

such as
$ cosa uno avanti

which will build a sketch for Arduino Uno, upload and start a serial monitor. This can be used from any IDE. I use GNU Emacs, M-X compile (F2), with the command.
The way the Arduino pre-processor works each referenced library needs to be included in the sketch. For a sketch that uses ST7920:
#include <HD44780.h>
#include <ST7920.h>

I am on Windows not Linux, is there a Windows version of the script? It seems to me that I should be able to simply add the Libraries folder to Eclipse somewhere to point it to the right folder.

You should be able to configure Eclipse to add include paths for the necessary libraries. This is basically what the pre-processing in the Arduino build is doing (i.e. finding and adding include paths for the compiler).

Right that is my point exactly, I just don't know how this is done, everything that I have tried to link the libraries does not work, I have tried importing the entire libraries folder as a linked folder. I tried adding both the libraries folder and the ST7920 folder as include folders, library folders etc.

I tried to install the regular Arduino IDE and installed Cosa through the additional boards manager and the extra libraries were listed in the libraries. I was able to compile it through the Arduino IDE. Can you think of anything that I might be missing with Eclipse? This really sounds like a very good library and really want to get this working as it is perfect for my current project.

source: Stack Exchange

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

authors: Алексей Кладов

sort: votes


text:
Reversed Input Voltage Arduino Mega timeout communication with programmer error
On the barrel connector I accidentally reversed the input voltage to an Arduino Mega. The center post received ground while the outer connection received +12DVC, basically I have the Arduino -12VDC. I have since fixed this problem. When I power the Arduino with the USB I am able to program the Arduino without a problem. When I power the Arduino with the +12VDC the program still runs (confirmed by programming the blink sketch). If I have the +12VDC connected and try to program the Arduino then I get the timeout communication error.
Do I just need to re-burn the bootloader? The Arduino's symptoms match those listed here when both cables are connected: Arduino Mega timeout communication with programmer error
Is there anything else I should verify? Or is the Arduino always going to be damaged?
Also as a note I did the same thing to an Arduino Uno (same rail going to both) and the Uno has no problems when both USB and power are connected.

Don't reprogram the bootloader.
If you can upload sketches that is unnecessary.
It will probably be fiddly to identify and fix what has failed, but since you can reprogram it via USB it is still 99% working.
I suggest you get one of those USB charging wall-warts that provide 5 V, and just plug that into the USB port if you want to run it away from the PC. You know that the USB power part works.

Chances are you have blown up the circuitry that performs the switching between barrel jack and USB power sources.  As a result the USB interface chip isn't getting power when it should.
In short: "It's dead, Jim!"

It's still functional as long as I unplug the power connector before programming. It seems like it should be a small fix if I can identify the issue.

There's an op-amp and a P-channel MOSFET.  You may need to replace one or both of them.  First though diagnose the problem with a DMM.

Agreed. Trace the power with the schematic in one hand and a multimeter in the other. There's a reverse-polarity protection diode (D1) as well. 12 V shouldn't have blown that. Still, worth checking out.

The Mega has a reverse polarity protection diode (D1) on the board, so you plugging in the wrong polarity barrel didn't damage anything.
So your current problem in unrelated to this.

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


text:
Cheapest Arduino GPRS or 3G solution
I am looking at creating a fleet of low power, Arduino driven devices.
I would need some kind of GPS on them all (or could triangulate through phone network?) plus a connection to the internet - just for HTTP POST requests. GPRS or GSM would do but 3G would be better.
What are the best (price is a major factor because I'm trying to do a fleet) GSM, GPRS or 3G modules that I can use with Arduinos? As I said, I need their location so one with GPS built in would be great.
EDIT:
The amount of devices in the fleet will change, so the entire network needs to be dynamic which is why having a GPRS/GSM module on each one would work so well.

I've seen people start with a cheap smartphone.

@Gerben any recommendations?

From what I remember it was an FirefoxOS phone. I think Alcatel One Touch Fire or something. I'm unable to find the related article.

So you need position awereness?
Does this count for the complete fleet, or every single arduino in the fleet?
What accuracy are you looking for? 100m, 10m, 1m, 10cm?
What do you want to achieve with the POST requests? They shouldn't be used for the communications between arduino (I believe).
GSM-modules aren't that "low-power" when connecting to the network (around 2A peaks are possible) though yea, they won't draw 2A all the time.

@FuaZe Each arduino. <= 1m would be great. The POST requests are just for updating a web server.

"From numerous tests the typical GPS receiver will achieve an accuracy of 1-5 meters." This is tested on Iphone 3's actually according to this:  http://communityhealthmaps.nlm.nih.gov/2014/07/07/how-accurate-is-the-gps-on-my-smart-phone-part-2/
If you want to use the GPS to avoid the fleet clashing into eachother, you should use other sensors.
But how do you want to achieve communication between the arduino's then?

@FuaZe I'm not planning on using it to avoid collisions, just for seeing their location.

You could consider making one of the arduino's the "fleet leader", this way only one arduino needs to have GSM/GPS

Ah good idea but the thing I forgot to mention is that they amount of devices in the fleet will change which is why it needs to be dynamic.

Not many possibilities (for the phone part, I suggest a GPRS/3G shield), but not wanting to discourage you, if you are thinking about "a fleet", forget about:
low power (the phone radio needs power, some say you need > 1A for both Arduino plus the shield, depending on your distance to the antenna). you must add the GPS part. Even if you communicate just a fraction of the time, you need instant power for feeding the radio.
low price (gprs shields are not cheap, starting at some 25€, and gps shields about 20€). and don't forget that you need a SIM card with a data plan for every unit....

Depending on what are you trying to achieve, I'd try with less expensive (RF communications, for example) to avoid carrier costs and hardware costs, at the price of a more complex development. If you want to publish to a web service, you can always make your minions transmit to a centralized Raspberry PI, for example, that would take the task of bridging with the Internets, or your mastermind...:-D

Can you give me a link to one for 25€? I started with thinking about a RF network with a Pi as the gateway but it'd need meshing and RF isn't cheap either.

look for "gprs shield arduino" at ebay or aliexpress. They can be used with the RPis without problems, as they work with the MCU or RPi via serial port using AT Commands.

would this be ok? http://www.ebay.co.uk/itm/SIM900-GPRS-GSM-Shield-Development-Board-Module-For-Arduino-High-Quality-/271621338401?pt=LH_DefaultDomain_3&hash=item3f3de4b521

According to the product description, yes. You just need to power it with an appropriate power source (I suggest a 2A one) and link it with your RPi via a serial connection. Look for "SIM900 AT Command reference"

2A?! It has a big orange capacitor on for that (or so it says)?

You might be best off with a phone battery of some sort. GSM modules require immediate and big power spikes. A big ass capacitor is often a good choice (or even multiple) as they can respond to the power need very fast. Keep wires/traces short and low resistant.

Though esp8266's can cost ~35$ for 10pcs, which would be the price of one GSM module. You're going to have to do some tradeoffs though.

If you are finding Cheapest and working module you can you SIM800L less then 4$.

aliexpress.com/item/Free-Shipping-Smallest-SIM800L-GPRS-GSM-Module-MicroSIM-Card-Core-BOard-Quad-band-TTL-Serial-Port/32708504554.html

You can find many other cheap alternative but they does not work properly.
Sim800 have good support and you can find many examples to use this with arduino.
Many other model also available in market as per your requirements.

BUT you need to supply it with at least 2Amps.

a few new ones have hit the scene recently. There's one by the folks that made the particle board (the electron supports 2G and 3G). There is also a kickstarter by sixfab that made one for the pi-zero footprint (but it's a standard raspberry pi GPIO and also has USB connection support or you can bread-board it to an arduino). They make a more expensive plate on standard RPi footprint that supports laptop-style WWAN modules (bought separately) so it can do 3G or 4G/LTE.
One of the better one's I've seen recently is actually part of the AT&T offerings (I believe avtel is the one that put the packages together for them). If you google AT&T IoT starter kit, they have four different offerings, with the lowest being $59. (it's apparently used as just a modem and can be connected via gpio style pins or via usb) It comes with a sim with 300Mb and 300 SMS messages good for up to 6 months from date of activation.
There are a few higher end chips coming out with LTE and 4G support also from Simcom (the makers of the Sim900 based devices core chip). Boards I have seen built on their LTE based devices run in the $80-120 range so, unfortunately they don't qualify as cheap.
As of yet, I haven't seen anything with 3G or higher under the $40 mark though. Most of them start above $50 and go up. Maybe by the time 2G is completely phased out, LoRa will be well saturated?

Welcome to Arduino Stack Exchange.  Be sure to take the tour at https://arduino.stackexchange.com

May I suggest reformatting this a bit?  Use the edit button and break up the concepts into separate paragraphs.  It is hard to read so much all at once.  TNX.

Updated Information (November 2024):
As of November 2024, advancements in IoT and cellular technology have introduced several cost-effective and efficient modules suitable for Arduino-driven devices requiring GPS and internet connectivity. Below are some notable options:

SIMCom SIM7600 Series:

Description: The SIM7600 series offers 4G LTE modules with integrated GPS, providing reliable internet connectivity and accurate location tracking.
Features:

Supports LTE CAT1/CAT4, ensuring widespread network compatibility.
Integrated GNSS (GPS, GLONASS, BeiDou) for precise positioning.
Compatible with Arduino via UART interface.

Pricing: Modules are available starting around $50, making them a cost-effective choice for fleet deployments.
Example Product: SIM7600CE-T 4G (LTE) Arduino Shield.

Quectel EC25 Series:

Description: The EC25 series provides LTE modules with GNSS capabilities, suitable for IoT applications requiring robust connectivity.
Features:

Supports LTE CAT4 with fallback to 3G/2G networks.
Integrated GNSS for location services.
Arduino compatibility through UART or USB interfaces.

Pricing: Modules are priced starting at approximately $45, offering a balance between performance and cost.

u-blox SARA-R5 Series:

Description: The SARA-R5 series features LTE-M and NB-IoT modules with integrated GNSS, optimized for low-power IoT applications.
Features:

Supports LTE-M/NB-IoT with 2G fallback.
Integrated GNSS for accurate positioning.
Low power consumption, ideal for battery-operated devices.

Pricing: Modules are available starting around $40, making them suitable for large-scale deployments.

Considerations:

Network Compatibility: Ensure the selected module supports the cellular bands and technologies available in your deployment region.
Power Consumption: For battery-powered devices, consider modules with low power modes to extend operational life.
Integration: Verify that the module is compatible with Arduino, either through direct support or available libraries.
Cost: While initial module costs are important, also consider data plan expenses, especially for a large fleet.

By selecting modules that balance cost, functionality, and power efficiency, you can effectively deploy a fleet of Arduino-driven devices with reliable GPS and internet connectivity.

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


text:
Arduino countdown timer for repeating actions
I have tried to find simple library for triggering timer after some time.
The idea is to retry network connection (RF24 network library).
I have following code now
while(!mesh.write(message, headerType, memSize)) {

}

This code will try to send packet until success
But I need to give up after for instance 10 seconds
I wanna to have something like this
bool timerTriggered = false;
Timer myTimer = new Timer(10000);
myTimer.setCallback(countedDown);

void countedDown() {
   timerTriggered = true;
}

And start timer before network request
myTimer.start();

while(!mesh.write(message, headerType, memSize) || !timerTriggered) {

}

Please suggest the best way to implement this.
Thanks.
EDIT
I have found problem as far as delay(); uses timer internally it conflicts with libraries or simple timer.
The solution is to use Alarm.delay(400); instead.
Maybe someone knows better solution ?

To expand on the other answer and combine it better with your situation:
Just check the current time in your while loop:
unsigned long startTime = millis();
while((!mesh.write(message, headerType, memSize)) && ()millis() - startTime) < 10000)) {
}

That is, while it's not transmitted properly, and the difference between now and when you started transmitting is less that 10 seconds, keep trying.
There is no need for any special libraries or asynchronous timers - it can all be done by examining millis().

Something like this would work as a non-blocking, general purpose timer:
unsigned long startTimestamp;
unsigned long timestamp;
const unsigned long timer_length = 10000; //10 seconds

startTimestamp = millis();
timestamp = startTimestamp;

while ( (timestamp - startTimestamp) < timer_length)
{
    // keep doing thing

    timestamp = millis();
}

// stop doing thing now


text:
How to change i2c address for mpu9250?
I'd like to connect 12 mpu9250 sensors to one arduino board.
I can't find documentation on how to change the addresses of mpu9250 boards. (i read through the reference ). Some tutorials talk about changing addresses for other device so i assume it is possible for mpu9250. I found this map of registers but can't figure out how to change the address.
I realize that mpu9250 might be too specific, so general guidance on how to solve these problems would be highly appreciated.
mpu9250 is similar to more popular mpu9150 and mpu6050. It is also known as GY-9250

http://www.wiimoteproject.com/general-discussion/2-nunchuck-with-arduino-help/msg8262/?PHPSESSID=e189911faffb53447fd2497bc3b87581#msg8262

Page 23 of the manual you linked:

The MPU-9250 always acts as a slave when communicating to the system processor.
  The LSB of the of the I2C slave address is set by pin 9 (AD0).

It seems you can only choose between two addresses as listed in the table on page 12.

fair enough, I just thought it would be logical to allow user to change the address

Might be a little late, but you can string more than two of these on one I2C bus, with a little ingenuity.
You connect the AD0 pin of each MPU to a different I/O pin of the processor, then take low the address of the one MPU you want to talk to.
Then that MPU has one address, all the others have the other address, and being slaves will not respond.
Provided you don't have more than one MPU selected at once, works a dream.

A very cunning suggestion, I like it!


text:
upload.tool not used in custom boards.txt?
I've created a custom board in boards.txt and changed the upload.tool to a nonsense value, and yet when I do an upload the IDE still calls avrdude.
For example, In boards.txt I've changed the line...
tile.upload.tool=avrdude

...to...
tile.upload.tool=nogood

...and added these lines to platform.txt...
# NOGOOD programmer

tools.nogood.cmd="dir"
tools.nogood.program.pattern="dir"
tools.nogood.upload.pattern="dir"

...and reloaded the IDE and hit upload.. and it still runs AVRDUDE.
(Note that my board ID is tile)
I've verified that I am editing the correct boards.txt by changing the cores key to nogood and this does generate an error.
Is boardid.upload.tool not the right place to change the recipe called when upload is hit?
How/where does the boardid.upload.tool=toolname key in boards.txt get mapped to the tools.toolname.upload.pattern key in platforms.txt?
I am using Arduino IDE version 1.8.3.
The custom boards.txt is in the directory Arduino\hardware\Move38\avr.
This full custom platform package is here...
https://github.com/bigjosh/Move38-Arduino-Platform
Thanks!

If you leave the protocol unset in the boards.txt, then the current version of the Ardunio IDE (1.8.12) will then use the program recipe rather than the upload recipe in platform.txt. The program recipe can use the {protocol} key to get the programmer selected in the IDE menus.
Relevant source in Arduino IDE SerialUploader.java...
if (usingProgrammer || prefs.get("upload.protocol") == null) {
  return uploadUsingProgrammer(buildPath, className);
}

From https://github.com/bigjosh/Move38-Arduino-Platform#programmers:

Since there is no bootloader in a tile, all code must be programmed rather than downloaded.

When you do an "Upload Using Programmer", the tool is specified in the {programmerID}.program.tool property in programmers.txt. The {boardID}.upload.tool value is only used for a standard upload.
Since programmers.txt is not in your hardware package, this makes it very inconvenient to customize. What's worse is that the platform.txt associated with the selected programmer is used, rather than the one in your hardware package, for "Upload Using Programmer". For this reason, some popular hardware packages include their own copies of all standard programmers. The downside of this is it really clutters up the Tools > Programmer menu if you have multiple of these packages installed.

Ugg. So ugly. Thanks for the authoritative answer - these are hard to come by in Arduino land! :)

For future lookers, it does not seem like the {boardID}.upload.tool in platform.txt is always used for a standard upload. For example, it does not seem to be used if an upload.speed is not specified in boards.txt (even if the specified tool does not have a baudrate). It also does not seem to be used on OSX sometimes.

Custom tools for the Arduino build process are documented in the Boards Manager Package Index spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification#tools-definitions
So it would seem that it i not possible to use custom tools with a manually installed board since there is no package index file.

This problem does not appear to be limited to only custom tools, it also seems to happen with built in tools like avrdude. :/


text:
XBEE WiFi S6B RSSI for Smartphone localization
I am building an early prototype, proof of concept, network monitoring tool.  A big part of it uses localization of a Smartphone.  It seems that the best way to do this is using RSSI from multiple points.  I plan to do this using several Arduino Fios with Xbee WiFi (S6B) cards.
My current setup has a network running from my smartphone (it is running DHCP) with a laptop monitoring all the traffic on the network.
What I need is for my Fio Xbees to dump the RSSI of the "access point" (Smartphone) onto the network so my laptop can pull the data.
Thus, to/from is not important as far as the packet is concerned, I just need the data dropped on the "wire" for my laptop to later parse, which is good because Serial.print* sends out a broadcast to 255.255.255.255:fffff.
I can make my devices broadcast any integer, but when I go into AT mode nothing aside from the initial DHCP handshake gets put on the wire.  Any ideas?
void setup() {
  Serial.begin(9600);
  Serial.flush();
  delay(1000);//enter AT mode start
  Serial.print("+");//AT
  Serial.print("+");//AT
  Serial.print("+");//AT
  Serial.flush();
  delay(1000);//enter AT mode finish
  while(Serial.available()>0){
    Serial.write(Serial.read());
  }

}

void loop(){
  Serial.println("ATDB");

  while(Serial.available()>0){
    Serial.write(Serial.read());
  }
  delay(750);//3/4 a sec
}

Note, Serial.println("ATDB"); should cause the xbee to drop the RSSI on the wire; see
XBee_WiFi_AT_Commands.pdf
at digi.com.
The three "+"s at the start are how you move the device into AT mode; see
Digi_International_90002124_G.pdf at mouser.com.
Once again what I am trying to do is get the collected RSSI information dropped onto a wifi connection from multiple xbee WiFi S6B equipped Fios.

You are reading from the device then echoing back the characters, still in AT mode. You need to save the rssi response, exit AT mode, then send the response, otherwise the device will interpret it as another AT command.

Just incase anybody stumbles onto this page googling, I am posting my solution below (I think it will work for any xbee radio)
Basically for some reason the RSSI values are getting nulled out before I can read them, both in my API mode tests and AT commands.  I'm not convinced that there is not some way around this in API mode at least, but it is irrelevant for my current purpose.
What I did was wire pin 6 on the xbee to a digital pin on the Arduino (I used 7) then use a pulse detector to find the period of the wireless signal coming in.
int pin = 7;
unsigned long period;

void setup(){
  Serial.begin(9600);
  pinMode(pin, INPUT);
  Serial.println("Getting started");
}

void loop(){
  delay(100);
  period = pulseIn(pin, HIGH);
  Serial.println(period);

}

It is not perfect, but for now it works, might help someone else in the future.


text:
2 way communication between Arduino with XBee and Computer
I have an Arduino Uno with a Wireless SD Shield and XBee S1 and a PC with another XBee S1 connected to it. What I'm after is for me to be able to send a message from my computer and receive a message back from the Arduino (For now let's just say if the Arduino receives a "1" I want it to send an "A" back)
Here is the code I have been practicing with (courtesy of SparkFun)
#include <SoftwareSerial.h>
SoftwareSerial XBee(0, 1); // RX, TX

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

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

(I have changed the pins from 2,3 to 0,1 as the latter is on the Arduino itself)
I have set my Xbees up and have been able to get them to talk to each other when both connected to separate PC's, but I am having trouble getting the Arduino to send information to the other XBee. When I try and send data from the Arduino IDE both RX and TX Led's flash.
Could anyone steer me in the right direction?

I have changed the pins from 2,3 to 0,1 - change it back, no wonder it doesn't work. You can't have HardwareSerial and SoftwareSerial on the same two pins. It doesn't make any kind of sense.

Pin 0 and 1 are the Hardware Serial of Arduino you cannot use it as the software serial and I also used that code once use pin 2 and 3 its issue regarding the configuration of your XBEE? Check your XBEE configuration XCTU

You don't need to declare an extra (software) serial port because the wireless shield connects the Arduino TX and RX on pins 0 and 1 directly to the TX and RX of the Xbee. So, Serial.available, Serial.read and Serial.write directly addresses the xbee. Just leave out the software serial from your code and it should work.


text:
How to detect Arduino serial port programmatically on different platforms?
I am trying to write a little program that needs to detect Arduino ports automatically. I have tried many methods but haven't found any reliable way.
I can see that the Arduino IDE can detect it, by showing /dev/cu.xyz (Arduino Uno) or COM6 (Arduino Uno) etc.
How could I detect if the device connected to the serial port is an Arduino or not? Preferably without pre-flashing the Arduino with specific firmware.
I found this Python version, which uses serial.tools.list_ports.comports() here,  but it didn't work when I tested it on Windows and MacOS.
The best I can get is by using go-serial's USBManufacturer, I can get 'Arduino (www.arduino.cc)'.
I also found this post, about the same question, but without any solution.

When I connect an Arduino Uno to my Linux box, lsusb says “ID 2341:0043 Arduino SA Uno R3 (CDC ACM)”. I don't know how to do that on other OSes though.

I agree with Edgar Bonet - if you can enumerate the USB ports you can work out which one has an Arduino on it, just like the IDE does.

Yeah, maybe usb info is all we can get since serial ports don't have any more info. The ports' Description and USBManufacturer could be used. Thank you guys.

A little more information about what you are trying to do would be helpful.

Quite late for the party! Just leave it here for anyone looking for a solution on windows.
The proper way is to read the device list from registry.
First location is

HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM

A better location is here

HKLM\SYSTEM\CurrentControlSet\Services\usbser\Enum

You have the list of Arduino devices there. Mine is Arduino Leonardo. Genuine Arduino UNO uses the similar chip and it should be in there as well.
To get the port, just copy the first device (index 0) and plug into this location

HKLM\SYSTEM\CurrentControlSet\Enum

So it is like this

HKLM\SYSTEM\CurrentControlSet\Enum\USB\VID_2341&PID_8036&MI_00\9&88cb209&0&0000

So you have friendly name and port number of the serial device. Then just write some code to read these registry locations.
In C
#include <windows.h>
#include <wchar.h>
#define MAX_VALUE_LENGTH 255

void getUSBSerialList()
{

    HKEY hKey;
    //check if we can read registry
    INT dwRegOPenKey = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\usbser\\Enum"), 0, KEY_READ, &hKey);
    if(dwRegOPenKey != ERROR_SUCCESS) return 0;

    DWORD type=REG_DWORD, size=0, USBser_count = 0; // a place for RegQueryValueEx to write back to
    DWORD dwRes;

    //read count of usb devices
    dwRes = RegQueryValueExW(hKey, _T("Count"), NULL, (LPDWORD) &type, (LPBYTE) &USBser_count, &size);
    if (dwRes) return 0;

    if (USBser_count)
    {
        for (INT i=0, dwRes = ERROR_SUCCESS; i<USBser_count; i++)
        {
            WCHAR achValue[MAX_VALUE_LENGTH];
            WCHAR buffer[MAX_VALUE_LENGTH];
            ZeroMemory(buffer, sizeof WCHAR  * MAX_VALUE_LENGTH);

            swprintf(achValue, L"%d",i); // read value name "0", "1"...
            dwRes = RegQueryValueExW(hKey, achValue, NULL, (LPDWORD) &type, (LPBYTE) &buffer, &size);

            // Plug that value into "SYSTEM\\CurrentControlSet\\Enum\\"
            HKEY hKey2;
            swprintf(achValue, L"SYSTEM\\CurrentControlSet\\Enum\\%s",buffer);

            INT dwRegOPenKey2 = RegOpenKeyExW(HKEY_LOCAL_MACHINE, achValue, 0, KEY_READ, &hKey2);
            if (dwRegOPenKey2) return 0; // check if this key exists

            // From here read friendly name
            dwRes = RegQueryValueExW(hKey2, _T("FriendlyName"), NULL, (LPDWORD) &type, (LPBYTE) &buffer, &size);
            if (dwRes) return 0;

            // or read COM port
            swprintf(achValue, L"%s\\Device Parameters", achValue);
            dwRegOPenKey2 = RegOpenKeyExW(HKEY_LOCAL_MACHINE, achValue, 0, KEY_READ, &hKey2);
            if (dwRegOPenKey2) return 0;

            dwRes = RegQueryValueExW(hKey2, _T("PortName"), NULL, (LPDWORD) &type, (LPBYTE) &buffer, &size);
            if (dwRes) return 0;
        }
    }
}

In C#, just use Registry object to do so
int usbser_count = (int)Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\usbser\\Enum", "Count", -1);

I haven't done it in C# but I think it's easier than in C.
What if yours is arduino clone that use CH340 instead of atmega16u2, it won't appear in the registry location above. It will show up here instead:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CH341SER_A64\Enum

You can do the same for other type of USB serial devices like CP210x (on some ESP32 dev boards)

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\silabser\Enum

Or even get a list of WinUSB devices (such as ST-Link v2)

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WINUSB\Enum

Here is a solution:
On Windows, Arduino IDE comes with a tool named listComPorts.exe, which will list all COM ports and their USB info like VID & PID. There is also a file named arduino.inf in drivers folder contains all known device types and their VID&PID etc, and we can look for the connected device.
On *nix, the IDE take advantage of libusb and no such a tool, and it's easy to find a tool to list usb info on these platforms.
This go package mentioned in the question is a good choice, which also uses libusb and could build on all platforms. (On windows, you have to install mingw to build the C code, cygwin & msys don't work, I tried TDM-GCC and it works. You also have to add LDFLAGS: -lsetupapi (in serial.go) to successfully link the code.) After list all serial ports, you can search for 'Arduino' to determine the port. 'CH340' is also a keyword to search as many modified boards use this chipset.
New version of the IDE don't have listComPorts.exe, they all uses libusb. I find this tool from version 1.6.5.

You can start the Arduino IDE wait unit the port is detected-which are stored on the hard drive by the arduino IDE;exit the IDE; then read through that file with your custom Windows (or whatever OS you're using -to get your answer. This answers your question you wrote above.

This is not applicable as the program is to run on machines without Arduino IDE, and the detecting process should be AUTOMATICALLY.

That wasnt clear to me from your question -which is why I wrote "This answers your question you wrote above."

The arduino IDE is open source so you can get the part of the code that does that COM detection-this will require some work on your part-and use it in your own program

So as far as I can understand that does answer your question

OK, I am trying to find the related part from the source code. Thank you anyway.

Here is snippet of C# code based on answer by SimonVu14. It looks through the named keys and gets ports for both Atmega and CH340 chips. If you expect to have just one Arduino connected to the computer, you can just go with the first one found. Otherwise you'll need to invent something to figure out which one is yours (which usually involves opening port, sending some predefined request and expecting some predefined response), or give user option to select via UI.

    private readonly string[] _arduinoKeys = {
        @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\usbser\Enum",
        @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CH341SER_A64\Enum"
    };

    /// <summary>
    /// See https://arduino.stackexchange.com/questions/30808/how-to-detect-arduino-serial-port-programmatically-on-different-platforms/80887
    /// </summary>
    private IEnumerable<(string name, string port)> EnumerateArduinos()
    {
        foreach (var arduinoKey in _arduinoKeys)
        {
            var countObject  = Registry.GetValue(arduinoKey, "Count", null);
            if (countObject is not int count)
            {
                continue;
            }

            for (int i = 0; i < count; i++)
            {
                var enumObject = Registry.GetValue(arduinoKey, i.ToString(), null);
                if (enumObject is not string enumKey)
                {
                    continue;
                }

                var friendlyName = Registry.GetValue($@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\{enumKey}", "FriendlyName", null);
                var portName = Registry.GetValue($@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\{enumKey}\Device Parameters", "PortName", null);
                if (portName is string port && friendlyName is string name)
                {
                    yield return (name, port);
                }
            }
        }
    }


text:
I2C Read Operation in TCA9539
I am using this TI device TCA9539 (http://www.ti.com/lit/ds/symlink/tca9539.pdf) with the pins A1 and A0 tied to ground resulting the write address to 0x74.

I don't have any issues writing to this device address and perform the necessary functions, however when I try to read registers using Arduino read functions, getting NACK there. Is 0x75 correct read address?
For second question:
Based on the device spec for read operation:

Reading from a slave is very similar to writing, but requires some additional steps. In order to read from a slave,
  the master must first instruct the slave which register it wishes to read from. This is done by the master starting
  off the transmission in a similar fashion as the write, by sending the address with the R/W bit equal to 0
  (signifying a write), followed by the register address it wishes to read from. When the slave acknowledges this
  register address, the master sends a START condition again, followed by the slave address with the R/W bit set
  to 1 (signifying a read). This time, the slave acknowledges the read request, and the master releases the SDA
  bus but continues supplying the clock to the slave. During this part of the transaction, the master becomes the
  master-receiver, and the slave becomes the slave-transmitter.
  The master continues to send out the clock pulses, but releases the SDA line so that the slave can transmit data.
  At the end of every byte of data, the master sends an ACK to the slave, letting the slave know that it is ready for
  more data. When the master has received the number of bytes it is expecting, it sends a NACK, signaling to the
  slave to halt communications and release the bus. The master follows this up with a STOP condition."

This is the code I am trying to use,
Wire.begin();
Wire.beginTransmission(0x74); // start i2c transmission as write addr
Wire.write(0x01)              // the register i need to read from
Wire.beginTransmission(0x75); // start i2c transmission as read addr given

I believe the device I2C read and arduino library functions for read is not making sense to me. Has anyone used this device for read?

You have misunderstood, how the Wire library works. It is doing all the things with the direction bit for you.
Write Operation:

Wire.beginTransmission() takes a 7-bit address as a parameter. The direction bit is automatically and internally set to write operation.
Wire.write() writes a value to the library-internal buffer, but is not doing anything on the actual I2C bus
Finally you call Wire.endTransmission() to finally do the write operation on the actual I2C bus. Prior to this function call the library doesn't do anything on the bus. So you have to call it, so that the data can reach the slave device

Read Operation:

For reading from a slave device there is an extra function: Wire.requestFrom(). It takes the (7-bit) address and the number of requested bytes as parameters and it returns the number of bytes, that were actually read from the slave device (is important if the slave is sending less data, than requested). After a call to this function, the read bytes are now lying in the library-internal buffer.
To get the received bytes from the library-internal buffer, you have to use Wire.read(). Again it does not do anything on the I2C bus. It just reads from the internal buffer.

So for your code you need to send a command byte to the slave, that says, what registers of the slave (determinded by the lowest three bytes, as the datasheet says) you want to access next. After that you can either send more bytes (in order to write the chosen registers) or you can start a request, so that the slave will send you the current state of the selected register.
Look at this images from pages 23 and 24 of the datasheet:

These are showing exactly, what you have to send. Note that the address byte is automatically send by the Wire library, so you don't have to do it. I will put it in code for you:
Write operation:
Wire.begin();
Wire.beginTransmission(slave_address);
Wire.write(register_address);
Wire.write(new_register_data);
Wire.endTransmission();

The register address is documented in the datasheet. In this case it is the register with address 0x01 (Though this makes no sense, since this is a read-only register).
Read operation
Wire.begin();
Wire.beginTransmission(slave_address);
Wire.write(register_address);
Wire.endTransmission();
if(Wire.requestFrom(slave_address,1) > 0 ){
    byte data = Wire.read();
}

Here we first do a write operation to tell the slave, what register we want to access. Then we request the data in this register with Wire.requestFrom(). To transfer from the internal buffer to our program is done with the Wire.read() function (but only, if there was actually something received).

For the address of the slave device: This depends on how you have set the pins A0 and A1. You can find a table with the corresponding addresses at page 21 of the datasheet. Note that these are NOT including the data direction bit. When you are using the Wire library, you don't have to bother about it.

If this solved your problem, please mark the answer as correct, so that others can see it directly. Thank you

Done, answers accepted!

The arduino i2c libraries expect a 7 bit slave address, not 8 bit address + r/w bit, and will manage the read write bit internally based on if you do a write or read.
So begin transmission 0x74
Write 0x01
End transmission
Begin transmission 0x74
Read n
End transmission

You have to end the first transmission before starting the read. The actual I2C action is done when endTransmission() is called.

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


text:
Getting error while uploading a sketch through Ardunio IDE
I recently used the Ardunio board and powered with the AVR pocket programmer along with the AVR ISP cable and it worked just fine and no issues were experienced. However now that i switch back to the default method of powering Ardunio board with USB, getting this error while trying to upload the sketch.
There are forums available on Arduino platform but no definitive resolution.
The board is recognized by the IDE.

Did you put the bootloader back on after wiping it with the ISP programmer?

No i didnt. Do i need to put burn the bootlloader through USB cable or through the AVR ISP programmer?

Through the ISP programmer. The USB cable won't work until you put the bootloader back on.

Reinstall the bootloader using your ISP programmer.
Installing a sketch using ISP first wipes the chip clean, and that includes the bootloader. Without the bootloader the USB interface won't be able to communicate with the main MCU.

I have marked your answer as accepted and it worked ... thanks!!


text:
How to connect GPS Neo-6M module to GSM Shield SIM900 V2?
I'm doing my final year project, My project is based on "Arduino Real Time Gprs/Gsm & GPS Tracker". So Now I have purchased the hardware components such as:

Arduino UNO R3
GSM Shield SIM900 V2.0
Ublox GPS Neo - 6M Module

I'm a begginer to this project, I have a doubt connecting these components together. I have stack the GSM Shield with the Arduino Uno but I don't know how to connect the GPS module to the GSM Shield (How to wire the components). because as you see my pic you might see on the top of the GSM shield there are no female headers except one which comes for the display.

So do I need to implement a female header on the GSM Shield and solder it to conncet the GPS module?

Can't I connect the GPS module to the GSM Shield's UART Pins?
Please Help me Guys :)

For your program, I'll highly suggest to use softwareSerial. It pretty much emulates the serial communication on other pins (NOT PIN 0 & 1). Then connect it like if you would normaly connect an UART device to your Arduino on the 2 other pins that you chose (NOT PIN 0 & 1). This should make it easy to prorgam your Arduino while having the GPS and GSM module connected to your Arduino.
The shield can cause problems if it uses Tx and Rx on pins 0 & 1, WHICH ARE THE PINS NOT TO USE IF YOU USE SOFTWARE SERIAL, so you might as well connect it with jumper wires. Take the TXs from both of your module and connected to whatever GPIO you want and do the same to the RXs, NOT ON PIN 0 & 1.
Once again, softwareSerial is NOT ON PIN 0 & 1.


text:
HC-06 Bluetooth RX & TX voltage (3v3 || 5v)
I acquired a HC-06 Bluetooth module, and understand that the voltage on the pins must be 3v3 and therefore requires the use of a voltage divider to lower the Arduino's 5v to 3v3 like this.

But the page where I purchased the product says the following:

interface level 3.3V, you can directly connect a variety of SCM (51, AVR, PIC, ARM, MSP430, etc.), 5V microcontroller can also be directly  connected, it can not pass without MAX232 MAX232!

Does this mean I can connect without using a voltage divider?
What does "it can not pass without MAX232 MAX232!" mean?

About the MAX232, I have a Dwengo (similar to Arduino) and to use the HC06 I have to disconnect the serial port(=RS232) else I short circuit my HC06.
After some googling, MAX232 is simply the name of that chip which is required to convert your TX/RX from your bluetooth module to something usable by Arduino.
Source: http://en.m.wikipedia.org/wiki/MAX232

Some chips that run on 3.3v have 5v tolerant inputs. But it doesn't look like the BC417 does (looking at the datasheet).
So just add the voltage divider.


text:
When I connect the Vcc and GND of my circuit to my Arduino, it is powered off?
When I connect the Vcc and GND of my circuit to the 5v and GND in my Arduino, it is powered off and stops working. What is the reason and how shall I fix it?

Reference: Serial to Parallel Shifting-Out with a 74HC595

It sounds like you're short-circuiting the power supply. Can you show a diagram of the circuit you connected?

@PeterR.Bloomfield : Ok sure

That diagram is from the shift register tutorial at Arduino.cc, so I think it's safe to say it's OK. You've most likely made a mistake in the wiring. You'll need to check all your connections to ensure nothing is hooked-up wrongly.

@PeterR.Bloomfield : how does short circuit happens to a power-supply any way ?

A short circuit means the Vcc line (+5V) has been connected directly to GND (or through something with very low resistance). The result is that almost all available current flows through that route, meaning there isn't enough power available to run anything else. Be aware that a short circuit can permanently damage your equipment, so it's important to fix it.

@AbdelrahmanTarief: Maybe the series resistor value before the LED is too low and therefor the LED is drawing too much current, more than the AVR can source?

@Phataas : Thanks man the problem is solved

@AbdelrahmanTarief: Share your solution?

@Phataas i will remember the solution and post it , its 3 months ago

Note: if you are changing something have the power off.
The first thing to try is unplug the IC. If it powers up after the IC is removed it is Possibly the IC is bad; However measure the Voltages on the proto board where the IC is inserted, be sure Pin 16 is +5V when referenced to pin 8.  Check the data sheet for the correct pinout, I do not know what IC you are using. If the voltage is correct it is pointing more to a bad IC.
The final check for the IC is to insert the IC and remove the ground lead to the LEDs.  If the system comes up then the problem is not enough power to drive the LEDs as is. If it does not come up replace the IC.  Even a momentary reverse voltage or a ESD (Electro Static Discharge) incident will damage the IC, we know is is going to fail, we do not know when.
Be sure your resistors are at least 300 Ohm or higher, with that resistance the LEDs when all on will draw a total of 80mA. If you want to do the calculations try this link: "http://www.onlineconversion.com/ohms_law.htm".
If you want to check the LEDs, remove the IC and connect +5V one at a time to the wire that goes to the resistor from the IC.
Good Luck,
Gil


text:
Run code via NRF24L01+ command "dynamically"?
I'm trying to make a home automation setup but I'm having a bit of trouble.
I want to be able to send commands of varying sizes to my arduino, separated by "|" and after receiving it completely it runs code corresponding to the command.
Example:
input "RCP=10001|CMD=D|VAL=120"
would result in an array like:
String cmd[][] = {{"RCP", "10001"}, {"CMD", "D"}, {"VAL", "120"}}

with the amount of 'variables' being... well, variable.
The code would continue checking if the RCP (recipient) ID corresponds with the ID of the current client and then run code based on the following variables.
But I don't think that's important info for the code which separated the string.
This string would be sent through an NRF24L01+ (That code already works)

Is the data always going to be triplets of RCP/CMD/VAL?

No, I'd like to be able to add like: VAL1, VAL2, or RESP=1 or something like that. Is this possible?

I've read this twice, but I can't find any question.

My apologies Gerben, I should've been clearer. But it has already been solved. Thanks for commenting anyway. :)

Why not use a library like RF24Mesh that does all this for you.

You're right, that is a more sensible way to go. Thanks for the heads up! Got the example working today and I'll be rewriting the current functionality to work with RF24Mesh. Again, thanks! :)

What you are asking is very tricky at best. Your average Arduino doesn't have enough memory to start storing arrays of Strings.
Instead you will need to "distil" the information as it comes in and store the distilled information.
If the possible keys are all known beforehand then you can assign a number to each possible key - say RCP is 1, CMD is 2, VAL is 3, etc.  If the values are all numeric or can be represented by a number, then convert those to the corresponding number and store those.
Also the Arduino is not good at working with dynamic memory allocations - again because of lack of memory.  If you can decide on a reasonable maximum number of messages to store then you can pre-allocate the memory for them.
For instance it may be good to define a structure which is the content of a message:
struct message {
    uint8_t key;
    uint16_t val;
};

Then make an array of that structure - one slice per possible command, say 10 of them:
struct message messageQueue[10];

That would take a total of 30 bytes in memory - each entry being 3 bytes (1 for the key, two for the value).  Now you can set the keys and values to the correct data as it arrives.
Depending on how you want to deal with the messages as they come in - add them to the end of an existing queue, or always starting the queue from empty every time a new message arrives - you might want to implement a circular buffer.  This is basically how the Serial port on the Arduino works - in involves having two pointers to locations in the array - one where you are writing to, and one where you are reading from. As you write to the array the writing pointer moves along - if it reaches the end it starts from the beginning again.  As you read from the array the reading pointer moves along too.  If the two pointers are together then the array is empty. If the writing pointer would end up where the reading pointer is, the array is full.  Take a look in the Arduino source code (HardwareSerial.cpp) to see how it's implemented.
As for parsing the string as it comes in - if you have it as a single String already then it's a case of looking through it for the | characters and splitting out each portion in turn, then doing the same with each portion looking for the =. Then you can interpret what is in the key/value pairs and decide what to store in the array.

Thank you very much! So it boils down to the fact that Arduino's have a small amount of memory and thus aren't suitable for dynamic memory allocation like a higher level language would be? I think I'll be able to think of a reasonable max amount of commands. The reason I wanted to have it dynamic was that newer version of my "master" might want to send more commands, but I could implement a type of version check on the client so the master knows if he is capable of those commands. Again, thanks :)

The lowest (RAM) memory footprint would to act on the information as it is received, and so basically avoid storing commands at all, except for a small (provided by Arduino anyway) circular buffer between the serial port and main-loop parsing.


text:
ATTiny85 Serial communication with Bluetooth Module
For a simple project I would like to use a ATTiny85 connected to a HC-06 Bluetooth Module so it can talk to my Android phone.
I wrote a code for my Arduino Uno and worked as expected. When I changed the code to use on my ATTiny85 I got an error saying that 'Serial' was not declared in this scope and assumed that the ATTiny does not support Hardware Serial.
I need to read a String when received and sleep the MCU when not receiving. I went to use SoftwareSerial and was not able to get a String, just the first char.
I approached it in some was, like defining a char string[10]; as global and string[i] = mySerial.read(); i++; inside the loop, but it keeps not working. Whether it is the sleep, or my work to read data, I couldn't make it work.
Can someone provide a way to put a ATTiny85 to sleep, wake up to receive a String through Serial and sleep til the next data through Serial, please?
To sleep I'm using
void sleep() {
  GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT3);                   // Use PB3 as interrupt pin
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep

  // woke up
  cli();                                  // Disable interrupts
  PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear Sleep Enable bit

  sei();                                  // Enable interrupts
}

ISR(PCINT3_vect) {

}

And my loop is something like
char inputString[10];
int i = 0;

void loop() {
  sleep();

  if (serial.available() > 0) {
    char inputChar = serial.read();
    if (inputChar == '2') {    //Char to break
      //Do something and reset i
    } else {
      inputString[i] = inputChar;
    }
    i++;
  }
}

Thanks to all.

You could easily overflow your buffer here. It’s a fixed 10 bytes, but nothing checks to see if you’ve filled it. You might be just trashing the memory by writing outside of the array.

Hello,
I think you should do this:
char inputChar = '';    //this in global
while (serial.available()) {
    inputChar = serial.read();
    if (inputChar == '2') {    //Char to break
        //Do something and reset i
    } else {
        inputString[i] += inputChar;    //= to +=
    }
    i++;
}


text:
Configuring Accelerometer on BNO055 sensor
I'm using the BNO055 9DOF Adafruit sensor to measure the acceleration/orientation. How can I change the configuration of the accelerometer from 4G (default) to 16G?
What I already know:
The datasheet : https://cdn-shop.adafruit.com/datasheets/BST_BNO055_DS000_12.pdf
From point 3.5.2 from page 27, I need to change xxxxxx01b to xxxxxx11b in the configuration file (that is the library). I use https://github.com/adafruit/Adafruit_BNO055 but I could not find any information on what to change and where in the .h file.
Any ideas?
Thank you

This was partly discussed as an issue on the library's github

https://github.com/adafruit/Adafruit_BNO055/issues/48

Here's how I understand it:
The library doesn't configure the registers you want. I don't see a reference to writing to the ACC_CONFIG register (address 8). Not even defined in the header.
The sensor has two register-pages (0 and 1) [refer page 50]. I.e. if you select page 0 then the register at address X means something, at page 1 it means something else.
We want to write to ACC_Config at address 0x08 on Page 1.
Page 77 tells us that, regarding writing to the register: "Write: can only be changed in sensor mode, see section 3.5.2"
In code, you could hack something in there:

https://github.com/adafruit/Adafruit_BNO055/blob/master/Adafruit_BNO055.cpp#L115

After changing to the sensore mode, you could then write to the register as
//values taken from section 3.5.2 page 27
#define BNO055_ACC_CONFIG_2G (0) //0B00
#define BNO055_ACC_CONFIG_4G (1) //0B01
#define BNO055_ACC_CONFIG_8G (2)  //0B10
#define BNO055_ACC_CONFIG_16G (3)  //0B11

//bandwidth definitions
#define BNO055_ACC_BW_7_81_Hz (0)
#define BNO055_ACC_BW_15_63_Hz (1)
#define BNO055_ACC_BW_31_25_Hz (2)
#define BNO055_ACC_BW_62_5_Hz (3)
#define BNO055_ACC_BW_125_Hz (4)
#define BNO055_ACC_BW_250_Hz (5)
#define BNO055_ACC_BW_500_Hz (6)
#define BNO055_ACC_BW_1000_Hz (7)

//powermode definitions
#define BNO055_ACC_PWRMODE_NORMAL (0)
#define BNO055_ACC_PWRMODE_SUSPEND (1)
#define BNO055_ACC_PWRMODE_LP1 (2)
#define BNO055_ACC_PWRMODE_STANDBY (3)
#define BNO055_ACC_PWRMODE_LP2 (4)
#define BNO055_ACC_PWRMODE_DEEP_SUSPEND (5)

#define BNO055_ACC_CONFIG_ADDR 0x08

//Select page ID 1 to write to the right register
write8(BNO055_PAGE_ID_ADDR, 1);
//build the config value with bitshifts
//see page 77
//use all standard values except 16G parameter
uint8_t acc_config = (uint8_t)((BNO055_ACC_PWRMODE_NORMAL << 5)
                   | (BNO055_ACC_BW_62_5_Hz << 2)
                   | BNO055_ACC_CONFIG_16G);
//write new accelerometer config
write8(BNO055_ACC_CONFIG_ADDR, acc_config);

//change back to page ID 0 (or whatever was before there)
//Otherwise we read sensor data from the wrong page with entirely different meaning
write8(BNO055_PAGE_ID_ADDR, 0);

Since I don't have that sensor here I have no way to test it. So this is just the basic idea. You can also read registers with read8, with which you can verify that before you write anything to the register, it has some standard (or expected) value. E.g., ACC_CONFIG should read as 0B00001101 = 0x0d. And after you write a value there you should be able to read the same value back, otherwise the chip didn't let you execute the write and you have to investigate why.
Yes, you mostly have to do the hard work by yourself. Changing from 4G to 16G might also have the implication that some other calculations on the raw data has to be done different, however I am not sure of that.


text:
"avr/io.h: No such file or directory" while compiling for board Generic STM32F103C series
I'm trying to compile FastLED library for my STM32F103C using Arduino 1.8.5 IDE, but getting this error:
In file included from C:\Program Files
(x86)\Arduino\libraries\FastLED/led_sysdefs.h:32:0,

                 from C:\Program Files
(x86)\Arduino\libraries\FastLED/FastLED.h:44,

                 from
C:\Projects\ioSmartHome\arduino\ColorPalette_stm32\ColorPalette_stm32.ino:1:

C:\Program Files
(x86)\Arduino\libraries\FastLED/platforms/avr/led_sysdefs_avr.h:12:20: fatal
error: avr/io.h: No such file or directory

 #include <avr/io.h>

                    ^

compilation terminated.

exit status 1
Error compiling for board Generic STM32F103C series.

I just have no idea why it's trying to include this file which isn't existed for this platform. Any idea?

Did you select the correct board in the IDE?

More specifically, for a variety of historical reasons, if FastLED can't determine the hardware platform/board being built for, it falls back to avr - and this particular STM chipset isn't directly supported in FastLED at the moment - there's a fork running around that has added support for it, but I haven't had a chance to pull it back into the main library.

<avr/io.h> is a header file used to interface the IO registers of the AVR micro-controllers. Most Arduinos are AVR-based, and some Arduino libraries assume an AVR core. This seems to bee the case with the FastLED library you are trying to use.
Your microcontroller, however, is an STM32, with an ARM core. It is not an AVR, and it will not work with code that assumes you have an AVR core.


text:
Drawing amperage with Arduino code
I'd like to preface this by saying I'm a complete beginner, but I have learned a ton already on this project, and I feel like I'm almost there.
I'm using an Arduino Uno and an Adafruit motor shield. I am working on a project for mechanical engineering and I need lots of amps for lots of torque for my mechanism. I'm including my code although I know it doesn't work, I haven't had the chance to debug it yet, and I'm really not sure if I'm on the right track.
So I know that it's possible to draw more amperage than is strictly allowed from the Arduino. What I don't know for sure is how to code it. Attached is my preliminary attempt.. I kind of assumed that the maximum speed would be the maximum allowable speed of the motor, regardless of the Arduino's capabilities, and scaled the output MAXampDrawSpeed as a function of that. To be specific, my motor can draw up to 20 amps, which would be too much for the Arduino to handle, so I scaled it down accordingly, with 255 being that maximum 20 amp output. I'm not sure if I'm on the right track there.
So the other problem is - the TA for my class made a simplified code reference file, sort of predefining a lot of the things that I manually defined in my code (or tried to at least). I didn't realize this, and when I asked him a question, he sort of shot me down and said "you should use my reference code" -- but his code doesn't compile for me. I had some problems with libraries (I fixed them!), but this isn't a library. It's a reference file, like the tabs up at the top. But it won't even compile for me. My feeling is that I may have annoyed him with my many many stupid questions up until this point and he's just kind of like "girl, get it together"... So the question there is -- am I almost there with my track or should I figure out what's wrong with his code and try to fix it his way so that I can ask him questions without being such a bother to him? And also is that likely to be a hindrance on drawing the extra amperage that I really really want? I am prepared to use heat dissipation methods as are necessary, and any advice you could give me there would also be appreciated.
If you need any more information, about my mechanism or anything I'd be glad to share that as well. I'm parallel mounting one motor to the four dc motor mounts on my Arduino in order to draw maximum current in that way as well. I have two switches controlling the output, one of the switches will engage the program for the maximum distance competition and the other for the accuracy competition.
So again, this code isn't right. I haven't even started on debugging it, because I didn't want to waste my time. Maybe you'll be able to follow my logic. I know there aren't many notes. If you need me to add notes for clarity I would also be glad to take the time to do that.
Thanks!
#include <Stepper.h>
#include <AccelStepper.h>
#include <Servo.h>
#include <Adafruit_MotorShield.h>
#include <Wire.h>
#include "Arduino.h"

#define STEP_TYPE_1   SINGLE
#define STEP_TYPE_2    SINGLE
#define STEPS_1    200
#define STEPS_2    200

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
Adafruit_DCMotor *DC4 = AFMS.getMotor(4);
Servo Servo1;

void setup() {
  digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
  int i = analogRead(A0); //Reads the value on the analog pin and saves     this as variable "i"
  AFMS.begin(); //Initializes the motorshield board
  int motorPin1 = 1;
  int motorPin2 = 2;
  int motorPin3 = 3;

  pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
  digitalWrite(A0,HIGH);
  pinMode(A1, INPUT);
  digitalWrite(A1,HIGH);
  pinMode(A1, INPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  Servo1.attach(9);
}

void loop()  {
  int distancepin = 0; //Just integer quantities, i like to have too     many of them
  int accuracypin = 0;
  int inPin1 = 0; //switch pin values
  int inPin2 = 0;
  int MAXampDrawTime = 75;
  int MAXampDrawSpeed = 178;
  int NORMampDrawTime = 225;
  int NORMampDrawSpeed = 61.2;
  int DrawTime = MAXampDrawTime+NORMampDrawTime;
  int ServoTime = 450;
  long previousMillis =0;
  long intervalMAXamps = 100;
  long intervalNORMamps = 400;
  DC1->setSpeed(MAXampDrawSpeed);
  DC2->setSpeed(MAXampDrawSpeed);
  DC3->setSpeed(MAXampDrawSpeed);
  DC4->setSpeed(MAXampDrawSpeed);
  inPin1 = digitalRead(A0);
  inPin2 = digitalRead(A1);
  if (inPin1 == HIGH){
    unsigned long time_zero = millis();
    unsigned long current_time = millis();
    digitalWrite(1,HIGH); //turn motor on to maximum draw amperage
    digitalWrite(2,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(4,HIGH);
    while((millis()-time_zero)<(400000)){
      if( millis() >= (time_zero+NORMampDrawTime)){
      DC1->setSpeed(NORMampDrawSpeed); //set motor on to normal draw     amperage
      DC2->setSpeed(NORMampDrawSpeed);
      DC3->setSpeed(NORMampDrawSpeed);
      DC4->setSpeed(NORMampDrawSpeed);
      digitalWrite(1,HIGH); //turn motor on to normal draw amperage
      digitalWrite(2,HIGH);
      digitalWrite(3,HIGH);
      digitalWrite(4,HIGH);
    }
    if ( millis() >= (time_zero+DrawTime)); {
      digitalWrite(1,0); //turn off motors
      digitalWrite(2,0);
      digitalWrite(3,0);
      digitalWrite(4,0);
    }
    if (millis() >= (time_zero+ServoTime));{
      Servo1.write(0);
      delay(400);
      Servo1.write(90);
    }
  }
}
if (inPin2 = HIGH);{
  int MAXampDrawTime = 75;
  int MAXampDrawSpeed = 59;
  int NORMampDrawTime = 225;
  int NORMampDrawSpeed = 20;
  int DrawTime = MAXampDrawTime+NORMampDrawTime;
  int ServoTime = 250;
  unsigned long previousMillis =0;
  unsigned long intervalHIamps = 100;
  unsigned long intervalNORMALamps = 400;
  DC1->setSpeed(MAXampDrawSpeed);
  DC2->setSpeed(MAXampDrawSpeed);
  DC3->setSpeed(MAXampDrawSpeed);
  DC4->setSpeed(MAXampDrawSpeed);

  unsigned long time_zero = millis();
  unsigned long current_time = millis();
  digitalWrite(1,HIGH);
  digitalWrite(2,HIGH);
  digitalWrite(3,HIGH);
  digitalWrite(4,HIGH);
  while((millis()-time_zero)<(500)){
  if( millis() >= (time_zero+MAXampDrawTime)){
    DC1->setSpeed(NORMampDrawSpeed);
    DC2->setSpeed(NORMampDrawSpeed);
    DC3->setSpeed(NORMampDrawSpeed);
    DC4->setSpeed(NORMampDrawSpeed);
    digitalWrite(1,HIGH);
    digitalWrite(2,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(4,HIGH);
  } else( millis() >= (time_zero+DrawTime)); {
    digitalWrite(1,0);
    digitalWrite(2,0);
    digitalWrite(3,0);
    digitalWrite(4,0);
  }
  if (millis() >= (time_zero+ServoTime));{
    int  time_check = millis();
    while (millis() - time_check < 400000) {
      inPin1 = digitalRead(A0);
      if (inPin1 == HIGH ) {
        Servo1.write(0);
        delay(400);
        Servo1.write(90);
      }
    }
  }
}
}}

If you exceed the limits of the equipment you run the risk of damaging it.  Is it not possible to use an alternative power supply for the motor, and use the Arduino just as a controller.

Firstly your formatting is horrible, but that's probably just the this editor, if it isn't please fix it.
In loop() you are wasting time if you are re declaring constants, move them outside the loop.
Why have you got 4 on switches?  Could you not gang them altogether? Join the wires and use just one pin?
you are repeating blocks of code, break these out into functions, this means less code to debug. I.e. SetMotorSpeed.
If (inPin2 = HIGH)

This will always be true, because an assignment is C\C++ always returns true, you meant ==
You TA is being paid to help you, don't be afraid to p##s them off, it's there job to get p'd off at students, and their choice.  At least you are doing it by asking questions not d##king around.  That said the most likely cause of you problems with his example is missing libraries or IDE version differences.  Or even library versions, if you add the first 5 errors as a comment I might be able to point you in the right direction.

You reeeally don't want to draw current through your controller board.  It's best to use a transistor power circuit, or 741 op-amp, or relay.  Keep your power delivery separate from your control system.

I'm going to echo what Matt said but you have way too many constants declared like variables.
A constant in C should be done like this
#define MYCONSTANT 666

right at the top of your code and outside of any setup loop or main function
Also think about the integer types you are using remember that Arduinos are 8 bit processors only use longs (32bit) where you really really have too and especially do not declare a constant as a long or int the way you have inside your loop.
This
int NORMampDrawSpeed = 61.2;

is just wrong you are saying that an int is a float, which it cannot be.
I personally avoid using floats altogether in Arduinos but if you must then declare it as a float or a constant (if it is a constant)
float NORMampDrawSpeed = 61.2;

or
#define NORMampDrawSpeed 61.2

be very careful when doing arithmetic with floats and ints because it will always return a float unless specifically typecast
better still since your new to programming just don't use them
And yes as Matt said write your own functions for stuff you need to do a lot such as
void setMotors( byte on_off ){
    for( uint8_t i=1; i <= 4; i++){
        digitalWrite(i,on_off);
    }
}

declare this function above the setup function an use it to turn all your motors on or off (1 or 0) like
setMotors(1);

Sorry but I have to disagree, constants should be done as
static const int MyConstant = 666;
And they should have the smallest scope possible, i.e. as close to the point of use as you can.
But that's just style, so it doesn't matter which way Team One goes as long as she is consistent.

Well Ok what you call style is just wasteful IMO. Do it like that and it uses up 1 or more RAM locations which cannot be optimised use a define and the pre-processor inserts a value into the program memory which would have been taken anyway by your const. So do it that way and you lose RAM and program memory.

You don't have to take my word for it either see  here link

No, your right, to much time spent on Window programming with unlimited resources.  (I still like the look of my way better though :) )


text:
DCMotorTest from the Adafruit site – got fatal error exit status 1
New to Arduino, I plugged in DCMotorTest from the Adafruit site and got this error message: a fatal error exit status 1
/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tock");

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tech");
  myMotor->run(RELEASE);
  delay(1000);
}

My error message was:
Arduino: 1.6.7 (Mac OS X), Board: "Arduino/Genuino Uno"

/Users/student/Downloads/Adafruit_Motor_Shield_V2_Library-master/examples/DCMotorTest/DCMotorTest.ino:11:34:
 fatal error: Adafruit_MotorShield.h: No such file or directory
 #include <Adafruit_MotorShield.h>
                                  ^
compilation terminated.
exit status 1
Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

Did you install the Adafruit_MotorShield.h library? 2. If you did, did you do it without the IDE running, or restart the IDE afterwards?

Based on the error report it seems that you have just opened the example program from the downloaded folder. In order to add library files (which includes the header files, c++ source code, etc.) you have to move the Adafruit_Motor_Shield_V2_Library-master folder to the libraries folder.

Documents > arduino > libraries

If no such folder exist, then create a new folder and name it libraries.
To check weather the libraries have been installed, open arduino IDE goto

file > example and check weather the example programs are added (you will see "adafruit" in the list)

Now, restart the arduino IDE and things should get going.
Note:
Do not use "-" and do not include space while naming a folder, as the compiler may throw up error. Instead you are free to use "_","$". Name of a folder should always start with a letter.
For more detail visit https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use/how-to-install-a-library


text:
Connect Digital monitor to Arduino?
I need a small display with ~ 5 digits.
The display needs to show number of visits to my site in real-time.
(Every time someone visits it needs to increase by one).
I thought to create an app, that fetches server stats every 10 seconds, and checks new number of visitors.
Do you think it is better to do with Arduino or Raspberry Pi?
Do you know of a digits monitor that can be connected to it?

A 7 segment display (they come from tiny to huge) or SPI Character or Graphic display fits with an Arduino.  But once you add networking a pi is a better conceptual fit though has a lot of practical complications.  A simple Android tablet may be considered, too.

For the complexity of the pulling of the data from a specific API, I would suggest to use i2c screen from adafruit and a python script running on raspberry pi.
this will save you time on coding eth interface and just mostly copy and  paste some simple code to communicate to the display

@max246 I came in to write pretty much the same thing, so you should post that s an answer

Trivial edits to a question that isn't specific enough for the site and has been abandoned by its asker are not going to redeem it - they just undeservedly bump it back to the top of the queue.  If the poster won't nail down their requirement, this should be closed.

It all depends on how used to you are with using pi or arduino. What you want can be done in both ways.
The displaying of count is common for both. It can be done using a 16X1 LCD display, 5 different 7 segment LED connected via decoders or a graphic display module. Interfacing all these with Arduino will be relatively simpler than Pi.
For the fetching of data and sending it to your device for displaying it. You can use ESP8266 Wi-Fi module with arduino and pull the data. Which is not as simple as it sounds but it is not impossible too.
For pi, (like @max246 said) you can run a python script and use another api to get the data.

For the complexity of the pulling of the data from a specific API, I would suggest to use i2c screen from adafruit and a python script running on raspberry pi. this will save you time on coding eth interface and just mostly copy and paste some simple code to communicate to the display
This is one module that I used and it is simple to use: https://www.adafruit.com/products/1270

authors: Вкотором Тио


text:
How to rotate 3 servo motors when 6 led lights are lit using EMG signals
I am completely new to arduino and trying to do a school project where i will be able to more 3 fingers with the help of a servo motor using EMG signals.
Right now i am able to read the signals. I just want to modify the code in such a way that when all 6 lights are lit on my emg reading device the servo with rotate by 90 degree. And when all leds are off the servo motor will go back to its initial position, that is will rotate back by 90 degree.
I badly need help over here. Here is the code:
 #define NUM_LED 6  //sets the maximum numbers of LEDs
#define MAX 45     //maximum posible reading. TWEAK THIS VALUE!!
int reading[10];
int finalReading;
byte litLeds = 0;
byte multiplier = 1;
byte leds[] = {8, 9, 10, 11, 12, 13};

void setup(){
  Serial.begin(9600); //begin serial communications
  for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
    pinMode(leds[i], OUTPUT);
  }
}

void loop(){
  for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
    reading[i] = analogRead(A0) * multiplier;
    delay(2);
  }
  for(int i = 0; i < 10; i++){   //average the ten readings
    finalReading += reading[i];
  }
  finalReading /= 10;
  for(int j = 0; j < NUM_LED; j++){  //write all LEDs low
    digitalWrite(leds[j], LOW);
  }
  Serial.print(finalReading);
  Serial.print("\t");
  finalReading = constrain(finalReading, 0, MAX);
  litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
  Serial.println(litLeds);
  for(int k = 0; k < litLeds; k++){
    digitalWrite(leds[k], HIGH);
  }
  //for serial debugging, uncomment the next two lines.
  //Serial.println(finalReading);
  //delay(100);
}

Thanks :)

And what is the problem?

Why not use a linear  servo with EMG feedback on pulse rate?

Apart the problem you have (that the constants are not defined), what you are asking can be easily solved by looking at the servo library.
The servo library tells you that

You have to include the servo library header: #include <Servo.h>
You have to add a variable to hold the object: Servo myservo;
You have to attach the object to a pin: myservo.attach(SERVO_PIN);
Finally you can move the motor to any position (0 <= x <= 180) with the syntax myservo.write(val);

In your code, then, you have the variable litLeds which tells you how many leds are there. Particularly if you have 6 (or more) leds light you will move to 90°, while with 0 (or less - even if this is meaningless) you reset to 0. So the complete code is
#include <Servo.h>

int finalReading;
byte litLeds = 0;
byte multiplier = 1;
byte leds[] = {8, 9, 10, 11, 12, 13};
Servo myservo;

void setup(){
    Serial.begin(9600); //begin serial communications
    for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
        pinMode(leds[i], OUTPUT);
    }
    myservo.attach(SERVO_PIN);
    myservo.write(0);
}

void loop(){
    for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
        reading[i] = analogRead(A0) * multiplier;
        delay(2);
    }
    for(int i = 0; i < 10; i++){   //average the ten readings
        finalReading += reading[i];
    }
    finalReading /= 10;
    for(int j = 0; j < NUM_LED; j++){  //write all LEDs low
        digitalWrite(leds[j], LOW);
    }
    Serial.print(finalReading);
    Serial.print("\t");
    finalReading = constrain(finalReading, 0, MAX);
    litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
    Serial.println(litLeds);
    for(int k = 0; k < litLeds; k++){
        digitalWrite(leds[k], HIGH);
    }
    if (litLeds >= 6)
        myservo.write(90);
    else if (litLeds <= 0)
        myservo.write(0);

    //for serial debugging, uncomment the next two lines.
    //Serial.println(finalReading);
    //delay(100);
}

Please note that some defines are missing (e.g. the MAX, NUM_LED and SERVO_PIN)


text:
Reason for warning "avr:build doesn't define a 'build.board' preference" when build.board is explicitly set in boards.txt?
I am trying to set up a custom board under the Arduino IDE, but I can not figure out why I am getting the warning...
Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

I think am following the recommendations and template in the official spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt
My "vendor/maintainer" is move38 and my platform is avr, so the path to the boards.txt is...
Arduino\hardware\Move38\avr\boards.txt

Here is my boards.txt that defines the blink board...
blink.name=Blinks Tile
blink.upload.tool=avrdude
blink.upload.protocol=avrisp
blink.upload.maximum_size=15872
blink.upload.maximum_data_size=1024

blink.build.core=blinks
blink.build.board=AVR_Blink

blink.build.mcu=atmega168pb

blink.c.extra_flags=-Wextra -flto
blink.c.elf.extra_flags=-w -flto
blink.cpp.extra_flags=-Wextra -flto
blink.ltoarcmd=avr-gcc-ar

# set F_CPU to 1Mhz for all boards on this platform
build.f_cpu=1000000L

...which would seem to define build.board as AVR_BLINKS.
I think am following the recommendations and template in the official spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt
...but nonetheless the warning persists.
I am using Arduino IDE version 1.8.3 on Windows.
What am I missing here? Is there something special about the value, format, or position of the build.board key that I am missing here?
Thanks!
More notes
Adding the following lines to a working boards.txt file...
build.name=testname
build.f_cpu=4000000L
build.core=blinks
build.board=AVR_BOARD

Will create a menu entry for a new phantom board called testname, but this is not a real board with usable keys. If you compile while that board is selected, you get the warning...
Using board 'build' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
Using core 'arduino' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

...despite the fact that the key build.board is explicitly defined.

Do you have a board called Move38 in there too?

Which version of the Arduino IDE are you using? Is that your full boards.txt? I can't reproduce the issue with Arduino IDE 1.8.4.

@Majenko There is no board named Move38. There is only one board in the boards.txt and is is the blink board. The Move38 is the "vendor/maintainer" as per the spec and so is the name of the parent directory- the boards.txt path is Arduino\hardware\Move38\avr\boards.txt. Thanks!

@per1234 I've posed a full boards.txt above, and also the (hard earned!) answer. Thanks for offering to help!

It appears that you can no longer set a global property in the boards.txt file. You must set every property individually inside each board ID, even if they are the same for every board in the file. This seems to contradict the documentation that states that...

The other properties will override the corresponding global properties
  of the IDE when the user selects the board.

Further, if any global key is set directly, then both the board specific keys  and the global keys are ignored.
So in my above boards.txt, setting the the global key build.f_cpu at the end of the file seems to cover the blink.build.board key and prevent it from being copied to build.board when the board is selected. Even if you set the global key build.board directly, this setting is ignored.

In my case: I erase the board configurations that was with problem in the file boards.txt.
These configurations appears between #### ... board configurations... #####.

The line in your boards.txt:
build.f_cpu=1000000L

created a separate board entry with the board ID build, thus the error message:
Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

From your comment:
# set F_CPU to 1Mhz for all boards on this platform

and your answer I see that you expected that line to define a global value for the build.f_cpu property but the Arduino IDE has no mechanism for doing this in boards.txt and I don't believe it ever has. You need to define the properties for each board individually in boards.txt, where they will override previously defined properties of the same name. However, you can define default property values for the hardware package in your platform.txt just as you attempted to do in boards.txt.

With the "build.f_cpu" key defined, I do not see a new board named "build" under the boards menu, and all the keys defined for the "blinks" board (which is properly selected from the boards menu) disappear when the "build.f_cpu" key is defined so even if there was a phantom "build" board now defined, why should it suppress some of the selected board's keys? Thanks!

Also, when I read the line "A configuration file is a list of "key=value" properties" in the spec, I expect that I can set any key to any value in any config file. This does not seem to be true - setting global keys in boards.txt does not actually set the global key. The section on boards.txt says that keys can be set on individual boards, not that they can not be set globally. I think either a bug or a documentation issue or both. – bigjosh 1 min ago

"I do not see a new board named "build" under the boards menu". That's because the board is missing a required property. Try adding the line: build.name=bigjosh.

"why should it suppress some of the selected board's keys". What do you mean by keys?

Adding a name does create a phantom entry in the menu, but does not actually create a board with keys. See new added notes above.Thanks!

Key is anything to the left of the = in one of the prefs files (like boards.txt) as per the spec.

That's because you're setting the key incorrectly. Remember, the first part of the key is the board ID. You need to do it like this: build.build.board=AVR_BOARD.


text:
What's the difference between ICSP vs ISP?
I'm not sure if these terms are interchangeable or not. What's the difference between ICSP and ISP? Is it simply the reset? I've shown two configurations in this question I just asked. Are they both ICSP?

From what I've heard, ISP is the term used by Atmel. ICSP is the term used by PIC.

The difference between ISP and ICSP is a hyphen.
ISP stands for In-circuit Serial Programming, and ICSP stands for In Circuit Serial Programming.
Any arrangement that allows you to program a microcontroller while it is in a circuit using a serial protocol can be called ISP or ICSP.

Well, they may the same but, according to Wikipedia, ISP stands for In-system programming

{sarcasm}And of course Wikipedia is always right....!{/sarcasm}  At the end of the day they both refer to the same concept using different wording. Semantics are completely irrelevant when they are just an acronym that refers to a concept, the concept being programming a chip while it is in a circuit using a serial protocol.

I have also seen sometimes «in situ programming». It's the magic of acronyms, they can tell anything you want

According to the Atmega32U4 datasheet:

The device is manufactured using ATMEL’s high-density nonvolatile memory technology. The On-chip ISP Flash allows the program memory to be reprogrammed in-system through an SPI serial interface, by a conventional nonvolatile memory programmer, or by an On-chip Boot program running on the AVR core.

I can't find the word "ICSP" in the datasheet. The quoted paragraph doesn't really explain the acronym. It could be an anagram of SPI. ;)

It seems clear to me that "in system" and "in circuit" are referring to the same thing. The program is serial rather than parallel as it uses SPI (Serial Peripheral Interface).

I've shown two configurations in this question I just asked. Are they both ICSP?

Not really two configurations, because the ICSP header on the board is directly connected to the pins you showed in the other configuration. You may as well talk about using different ground pins as a "different configuration".


text:
Detect if a chair is occupied using Arduino with some sensors
I want to detect if a seat is occupied by a person. This is the answer that I found on Stackoverflow.
However, how accurate is the output of 4 suggested sensors? Will the computing of all these 4 sensor values into one boolean recognize a case when, for instance, a box of 40kg is placed on a seat and some person is just slightly "shaking" that seat with a hand? In those cases Arduino should recognize that a seat is not occupied by a person. Will it work with only 4 sensors or is there any better and more accurate solution (maybe some existing library)? I guess that CapSense-Library is not applicable in my case.

All sensors have their downsides. And will sometimes falsely trigger. You can probably detect some false triggers with additional software. e.g. a load cell that continuously gives the same value would suggest a very inactive person, or a box. Also a box tends to not be not as heavy as a person (though maybe as heavy as a little child). In the original question cost was a major factor. In your case accuracy seems to be more important. Could you maybe elaborate on what it is you need to achieve? CapSense was actually be a suggestion that came to my mind when reading your title.

I guess that CapSense-Library is not applicable in my case. - why not? How about a heat sensor anyway? If the person is not wearing really thick clothing their rear end will tend to warm the chair (and the sensor). However it might take a while to cool down afterwards.

As has been mentioned in the comments there's many ways of sensing, each with its own pros and cons.
Sensing the presence of something is actually twofold.  First you need to know if there is something there, and secondly you need to try and identify what it is that's there and if it fits your criteria.
With passive sensors of the type used by Arduinos it all comes down to a matter of probability.
If you have force sensors, you know when something is there, but you can't work out what is there, only that it weighs a certain amount.
Using capacitative sensors you can get an idea about what the something is made of - how much does it affect the capacitance, etc.
Using ultrasound and/or infra-red beams etc you can get an idea of the kind of size of the object that is in the chair.
So combining them all together you can work out the likelihood that it is a human if:

It weighs enough to be a human
It has a suitable dielectric response to be a human
It is big enough to be a human

Of course, there's always the chance that it's just a big dog, or a sack of potatoes.
So it's all a case of improving that probability by adding more sensors of different types, until you are almost certain that it is a human.  You will never be 100% certain, of course.

I've also been trying to figure out a suitable idea for the same question.

Image processing would be so accurate in this but there are some problems with this approach, since there is a lot of code work and in case we want to implement this system in restaurant people might not agree.
Pressure sensors would work better for the  idea but there are some issues with this approach also. Just as mentioned in the question if there is some kind of a weight in the chair there will be an issue. also there are several chairs for a table in case of a restaurant so if we need to know whether the table is empty or not we will have to check whether all the seats are empty or not. In this case we need to pair the chair to the table using some method. we can also take this approach assuming that the chairs of the table will never change i.e. the same set of chairs remain for the same table.

The best approach for this particular scenario would be the sensors being in the table, or having a set of sensors such as a pressure sensor, thermal sensor, IR and verifying the seat is occupied.

Also there will be an issue if a device is connected to the chair since it needs power to work, once it the battery is drained you will have to charge it too