text:
Hardware network-infrastructure for a fully-arduino-based home-automation project
As already mentioned in another question, I'm spending LOT of time planning the home-automation system for my new house (currently still in the "still building" phase).
Even if started only as a "lights/switch management project", things started getting bigger and bigger and, at the moment, in addition to original requirements, I already have:

A reed switch including cut-detection wires (for a total of 4 wires)  installed on every single window (one switch for single-windows; two switches for dual-door windows);
planned the location of a DHT22 sensor in each room.

In addition to the above, I'm currently evaluating the opportunity to add a single RGB led to have visual-feedback for each push-button (something like: GREEN=>LIGHT/OFF; RED=>LIGHT/ON). More specifically, I'm evaluating the opportunity to replace common/simple pushbuttons with these:

Obviously, such a change will heavily impact the cabling, as:

original simple/pushbutton required only two wires for each pushbutton, with one wire potentially shareable among adiacent pushbuttons (I'll be using "internal pullups", so one wire will be GND)
RGB pushbuttons require six wires (GND and SIGNAL for pushbutton; R, G and B plus COMMON for LED), with only two wires potentially shareable among adjacent pushbuttons (GND and COMMON).

Adding to this that it will be easy to have wall-boxes hosting two, three or even four pushbuttons, and you easily understand that LOTS of cables are required!
Here below I'm attaching a rough schema of what I'm planning to build, in terms of hardware:

where you can see:

ROOM 1, with:

2 x reed switch (up to 8 wires);
1 x DHT22 (3 wires);
a wall box with two pushbuttons/wLED (up to 12 wires);
a wall box with one pushbutton/wLED (up to 6 wires)

ROOM 2, with:

1 x reed switch (4 wires);
1 x DHT22 (3 wires)
a wall box with two pushbuttons/wLED (up to 12 wires)

Also, as for "controlling" the whole system:

two POWER-BOXES, located externally to rooms, where I originally planned to host the "controller" (a MEGA2560) together with needed Relay-modules, and interconnected via an RS-485 bus.

(BTW: actually, I'll have three POWER-BOXES, and not only TWO. But this is a detail, as for the spirit of this question).
Please note that POWER-BOXES (PB1 and PB2) will be located (...as for the original plan) quite FAR from some rooms: up to 10/15 meters, in the worst case scenario. Also, please note that each power-boxes are far up to 10/15 meters from each-others.
Before the real question, let me add another couple of important points:

Even tough I know that some kind of wireless system and/or wireless segment could simplify my overall architecture, I'm a strongly believer that a "wired" system is more reliable than a "wireless" one, expecially in the long-term. As such, as I'm lucky enough to put down lots of "pipes" (to properly distribute cables all around the house), I really prefer a wholly wired system;
As for this question, I'm not interested in the "software" side of the system. This is really an accessory (again, as for this very question). My really_big_problem relates to the "hardware" infrastructure to put in place. That's why I'm posting this question here.

After the all of this, here is the question:
As for your experience and knowledge:

should I stick to original plan, having an RS-485 multidrop-bus interconnecting only the MEGAs, with "signal" cables going directly from room-hardware (pushbuttons, reeds, DHT22, etc.) to the MEGA PINs ....

or

should I add some other Arduinos (a Micro seems a really good candidates) in each room, terminating all the signal-room-cables coming from room-hardware, and speaking with MEGAs via the same RS-485 bus?

In the first case, I'll have a real simple RS-485 bus with a mess of cables; In the second case I'll have a _longer_and_more_complex_ RS-485 bus, with a much manageable network cabling/infrastructure.
Am I right? What are the PROs and the CONSs of above two scenarios? Should I investigate other approaches?
Are there some documentation that can help me picking the right solution?
Thanks in advance to all of those who will spend some (precious) time helping me in this really difficult decision to take!

BTW: if you need further details, please don't hesitate to ask.

I'd put Ethernet shields and Arduinos in each room. Then when you need a more powerful Arduino (or even a Raspberry Pi) you simply connect it to the existing network. It's easier to maintain and expand when some years passes. And, of course, it's very likely you are already wiring the rooms with network wires.

IMHO wiring each button to the central unit (mega) is a real waste of cables, pins and money. Not to mention that that solution is not flexible at all: if you want to add something in some place you will need to pull another wire. IMHO the ideal setup (but I'm just a beginner, so I can be wrong) is having one microcontroller per box: you can use an arduino micro or a simple attiny if the box is really small. Then all these uC are connected through a fieldbus (can be the same RS485 which goes through all the house, can be a "room-wide" rs485, CAN, I2C, Serial, daisy-chain network, ...).

This way you can serially communicate with each box, each box can communicate with the main mega, and most important you will just need to pass a few cables, so extending the network is really easy.Personally I'd use RS485, since it's easier to use than CAN but it's strong enough (in fact, you can use the serial protocol over RS485 transceivers). I'd avoid a global ethernet connection, for both security and performance reasons (security because someone connecting to your net will also be able to see every message, performance because you can't connect an attiny to the ethernet without efforts)

@frarugi87 : thanks for commenting. As for "ethernet security", this should not be a big issue as in such a scenario I will surely rely on a dedicated VLAN. Anyway, the idea of having a fully distributed network, with Arduinos in every box, sounds interesting. I have to check how many nodes can be handled by the framework I'm planning to use.

@DamianoVerzulli well, in any case you will have unencrypted messages going back and forth your network, but yeah, it's just a minor issue. The most important part is that you will need ethernet shields or transceivers (e.g. ENC29J60) for each node, and they will need to handle heavy processing just for the communication, while with simpler field bus (e.g. rs485) you will still need the transceiver (which is cheaper and smaller), but you will need very little computing for the communication (usually it is serial-based, so the peripheral will handle it on its own)

@fabrosell : thanks for commenting. I spent some time, before beginning, investigating ethernet involvement. As the network, initially, looked much like a bus and considering that RS485 was both more cheap and more reliable (not needing an external switch) I'm currently oriented towards RS485. Obviously I'll have ethernet, around the home, but it will be used up to the main "gateway" (one, or probably two of the MEGAs), so to have the whole infrastructure easily accessible by a Raspberry/OrangePI, acting has a web-server/data-collector/etc. Anyway, I'll re-evaluate the ethernet option. Thanks.

I'd go for more, and thus simpler nodes on a single bus. I'd probably add another wire for power too. Because of the long wires, I'd use a slightly higher value for the voltage, and use the regulator on the arduino to get a stable 5v.

@Gerben:  Do you think I'll be able to fit everything (1 x Nano 3.0; 1 x MAX485; up to 3 push-buttons; cabling) inside this wallbox? Should I start planning to design/buy an ad-hoc PCB to reduce/optimize the space?   (BTW: thanks for your time)

@DamianoVerzulli Sure. You can probably even fit in a half-sized breadboard. You can add even more stuff by layering.

short wires are generally better than long ones
I agree, that wired is better in your situation
Maybe you distinguish between two different areas: sensor/actor to controller and controller to controller communication
In many cases you can not chose the sensor/actor to controller communication, because it is given by the device (DHT-22, reed, led push button etc.). Therefore, keep these lines short
RS-485 is good, but is it necessary? It adds drivers to each device. Maybe, I2C could do it,to. You can still use twisted pair cables.

Thanks for commenting. The very first problem I faced was the decide "how" and "with which protocol" interconnect my Arduinos. As: 1) the distance between them was quite large (20 meters or even more); 2) I need to handle "noise", during transmission, as best as possible; 3) the bandwidth required by the whole system is relatively low; I ended up with RS-485 in multidrop configuration (like the one described here. Have you been able to test I2C under similar conditions?

As for RS-485, Nick Gammon in his excellent answer made several really useful tests about cable lenghts, communication speeds and collision/detection/avoidance approaches. Based to them, I ended up deciding that RS-485 was really suited to my needs. Don't you?

As for "short wires are generally better than long ones", such an approach would take me in having an ad-hoc Arduino in every wall-box (this wall-box). I wonder if I'll be able to fit everything inside such boxes (1 x Nano 3.0; 1 x MAX485; up to 3 push-buttons; cabling) and/or if I'll need to design a proper PCB to optimize everything. What's your opinion?

As for two different kinds of networks: "sensor/actor <=> controller" and "controller <=> controller" this is absolutely reasonable and I'm actually investigating this as I've 3 serials on each MEGA so I can definitely have a "secondary network branch" from each MEGA towards the "local" boxes. Also, the software-framework I'm currently evaluating/experiencing, souliss, should play nicely with such an architecture.

Here my additional thoughts in short:

20 meters is, compared with the distance to the moon, quite short ;-). Maximum length of RS-485 is reported to be kilometers with small transmission rates (google: rs485 cable length).
Noise can either be avoided (hardware) or corrected by software (fault tolerant codes, checksums etc.) Generally, software is cheaper.
Short wires does not mean no wires at all. Short wires would e.g. result if you have a controller per room and connect the sensors to it.
There are also small packages of Arduino compatible chips available (ATTiny84/85). And without RS485 you save the space of the controllers...
I2C bus length should work inside a house, if yous is not bigger than the one of Bill Gates...
http://www.esacademy.com/en/library/technical-articles-and-documents/miscellaneous/i2c-bus/frequently-asked-questions/i2c-faq.html
I would not use serial for communication. It is not extensible. Serial is ok for debugging.


text:
How do I correctly use enum within a class?
I am trying to set the status of an object from a private enum and I'm not sure how to get the private member to the public version in the constructor, and I'm pretty sure I should not be using byte in the constructor when it's an enum.
Also, I'm not sure if I should even have the values of the enum inside the header at all. Here is my code:
.h
class CandleRack
{
  public:

    CandleRack(byte candleRackStatus);
    ~CandleRack();
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce *_debouncePushButton;
    byte _pushButtonPin;
    enum _candleRackStatus
    {
      inactive = 0,
      candlesOn = 1,
      rewardAnimation = 2,
      tweetArrived = 3,
      partyMode = 4,
    };
    byte _candlePosition;
    byte _candleStatus[NUM_LEDS];
    elapsedMillis _candleTimeElapsed[NUM_LEDS];
    unsigned int _candleOnForMs;
};

.cpp
CandleRack::CandleRack(byte candleRackStatus)
{
  _candleRackStatus = candleRackStatus;
  _debouncePushButton = NULL;
}

in the sketch
CandleRack MyCandleRack(0);

error:
error: expected unqualified-id before '=' token
_candleRackStatus = candleRackStatus;

Thanks!

Might be more of a programming question as an Arduino question. I've heard that ENUM's are specifically useful when dealing with switch-case statements, since you can define a "default" case.

You can define a 'default' case on a switch statement without needing an enum, but for me it will help the code be more usable as you can give each case a name and not just a number.

SHouldn't CandleRack MyCandleRack(0); be CandleRack MyCandleRack(inactive); or maybe CandleRack::inactive. My C++ is a bit rusty (very rusty). Also, in the interests of program readability the enum would be useful outside the class otherwise you're just assigning a bunch of numbers.

The enum gives the object its properties so my logic tells me it should be a part of the class, it's also a private member so it's properties are hidden from all of the other classes I will be adding. You're right about MyCandleRack(inactive); though.

Hmm, you're true on the default thing. But I can vaguely remember my prof being "mad" at me for using defines instead of enums, since your compiler could check if all enums are handled in your switch-case.

I see two separate issues here.
First of all your enum isn't available as a variable.
By declaring it as a private type within your class the enum can't be used outside of that class.
This forces a user of that class to handle unintended calls like (attention, bug):
CandleRack(255);

which can make code harder to read (and debugging more difficult, since it wouldn't be detected by the compiler).
Second of all you try to directly assign a byte value to an enum type. This will be rejected by the compiler and/or cause runtime errors later (depending on compiler settings).
I recommend that you declare the enum type so that it is accessible directly via the header file:
.h
enum CandleRackStatus {
    inactive = 0,
    candlesOn = 1,
    rewardAnimation = 2,
    tweetArrived = 3,
    partyMode = 4,
};

class CandleRack
{
  public:

    CandleRack(CandleRackStatus candleRackStatus);
    ~CandleRack();
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce *_debouncePushButton;
    CandleRackStatus _candleRackStatus;
    byte _pushButtonPin;
    byte _candlePosition;
    byte _candleStatus[NUM_LEDS];
    elapsedMillis _candleTimeElapsed[NUM_LEDS];
    unsigned int _candleOnForMs;
};

Now you can instantiate your class while using the correct enum type as the parameter.
.ino
CandleRack MyCandleRack(CandleRackStatus::inactive);

Within your implementation you can now directly store the constructor parameter in the private variable, the compiler will make sure it's always of the correct enum type:
.cpp
CandleRack::CandleRack(CandleRackStatus candleRackStatus) {
    _candleRackStatus = candleRackStatus;
    // rest of your initialisiation goes here
}

As an added bonus, there's the possibility to use a couple of C++ language features that will make your implementation easier:

a default parameter value
an initializer (list)

.h
class
{
  public:
    CandleRack(CandleRackStatus candleRackStatus = CandleRackStatus::inactive);
    // [...]
}

.cpp
CandleRack::CandleRack(CandleRackStatus candleRackStatus) : _candleRackStatus(candleRackStatus) {
    // rest of your initializiation goes here
}

One thing I don't understand is why you have Capitalized the name CandleRackStatus. I thought an enum was just a variable and nothing like a class or struct. I think it's confusing to treat it like a class (with naming conventions) ...

last question, when I actually want to change the status of the CandleRack, do I do _candleRackStatus = candlesOn ?

Re: Capitalized, that's a matter of taste and what school of programming you come from. I recommend treating enums like types, because they are. And in most C++ styles types get a capitalized name. See https://google.github.io/styleguide/cppguide.html#Enumerator_Names for reference, also a good read as a whole.

Re: changing the status, the identifier candlesOn is defined within the type declaration of the enum. So in order to access it you would qualify it with the type name: CandleRackStatus::candlesOn. That's called static access and the :: operator works on all type properties that are public and static (see http://stackoverflow.com/questions/10090949/accessing-to-enum-values-by-in-c). So you would change the status using _candleRackStatus = CandleRackStatus::candlesOn.

We've discussed simplification of names before, so if these expressions are too lengthy or confusing, just choose shorter names for types and variables.

How about this refactoring?
class CandleRack
{
  public:
    enum status_t
    {
      inactive = 0,
      candlesOn = 1,
      rewardAnimation = 2,
      tweetArrived = 3,
      partyMode = 4,
    };
    CandleRack(status_t status = inactive);
    ~CandleRack();
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce *_debouncePushButton;
    byte _pushButtonPin;
    status_t _candleRackStatus;
    byte _candlePosition;
    byte _candleStatus[NUM_LEDS];
    elapsedMillis _candleTimeElapsed[NUM_LEDS];
    unsigned int _candleOnForMs;
};

And in a sketch with either the default setting (inactive)
CandleRack MyCandleRack;

or explicit
CandleRack MyCandleRack(CandleRack::candlesOn);

Cheers!

It seems this answer compiles the gist of my answer into a code-only post (see e.g. http://meta.stackexchange.com/questions/148272/is-there-any-benefit-to-allowing-code-only-answers-while-blocking-code-only-ques)

Yes It does a bit. If you could add some of these suggestions to your post I think that would make it a great answer. Especially as this shows how I could use the enum as a public member and not outside of the class - which in my mind, makes it more understandable.

But also thanks to Mikael for this post too, it also helps my understanding of how to use enums.

In this example where is status coming from? status_t status = inactive

status is an alternative naming to your candleRackStatus. Simpler names can increase readability. Since you only pass one parameter, you don't really need to qualify it in more detail than neccessary, so it's probably a good idea to simplify. :) I've updated my answer to explain the use of the enum type and a default parameter value.

Hmm, I find descriptive names more readable and other elements of my sketch will also have a status (even of this object - music status, animation status etc) so I think it's important for me not to rename. I'm also unsure of where status_t comes from, what is the _t ?

source: Stack Exchange

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

sort: votes


text:
Connecting Mac to Adafruit Feather 32u4 Bluefruit LE over serial
The Adafruit board connects fine over USB serial, and fine over Bluetooth to a mobile app, but it will not connect to a Mac serial monitor over Bluetooth.
Is there any way to use the Adafruit's Bluetooth chip as a pass-through, to allow serial communication over Bluetooth from the Mac to the board itself?

Have you checked google for: "Mac bluetooth as COM port"? A lot of interesting articles can be found.

@Sakar did u ever figure this out?

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


text:
The importance of I/O pin DC current
I am thinking about buying Arduino or Raspberry Pi.  I generally know Arduino advantages (fast start-up, low consumption, ADC converters) and disadvantages (low memory, low connectivity, hard programming), but I simply cannot figure out maybe the most important issue: current output for controlling devices.
One of the common cited advantages of Arduino system compared to Raspberry Pi system is that power per I/O pin is much larger.  Arduino Uno allegedly has up to 20 mA @ 5 V per pin and 50 mA @ 3.3 V per pin making quite substantial power of 0.15 W, compared to say typical 10 mA @ 5 V per pin for Raspberry Pi (although there is no official number available).
On the other hand

this power is far too low to control any motors and you still have to
provide shields,
new version Arduino 101 reduced that current to 20 mA and even less for some other Arduino models.

So, what is really the importance (if any) of these higher currents for home projects, compared between different Arduinos themselves and compared to Raspberry Pi?
There is also a question of total current for all pins together, which is also limited, but it is soooooo difficult to get official limits (for both Arduino and Raspberry Pi).
Please give me some insight into this issue, so I can decide.

I have a silly question which might help - how much drive current does your project actually need? Do you have lots of LEDs (which an Arduino might be able to handle directly) or are you driving motors (which all common microcontrollers will need a driver circuit for)?

The problem is that I need microcontroller for learning and playing and I do not want to limit my ideas by bad choice of device in advance.

The simple answer is: It doesn't matter.
Both Arduino and the Raspberry Pi, and every other common microcontroller board, are designed to control things, not provide power to things.
Digital IO pins aren't designed to drive heavy loads. Yes, some (like the Arduino) can provide slightly more current, but that is really unimportant for most projects.
Yes, some boards have more powerful power supply circuits on them so you can draw more current from their power supplies, but again that is largely irrelevant.
The one thing that you seem to be forgetting (or haven't realised) is that the microcontroller board does not have to supply all the power.
The Arduino, Pi, Teensy, chipKIT, whatever, is merely a controller. If your system needs more current it is up to you to provide that current. The Arduino etc merely controls the circuit or device that it is connected to.
It is very common to have multiple power supplies in a large project - each providing different voltages, or being used for different specific tasks within the project.
Just one thing you need to remember: Connect the grounds.

...or use an opto-isolator ;)

@fabrosell ... or a relay ... or an arrangement of motors, pulleys, elastic bands, and small rodents.

Where can I get this small-rodent-isolator? mouser.com?

I mean, you can avoid connecting grounds if you use an opto-coupler.

@gerbem of course. They specialize in them.

So Arduino 101 should't be worse than Arduino Uno in any aspect?

@Pygmalion As long as you're not driving heavy loads, and interfacing things with the correct driver circuits, then there should be no real difference

After doing a lot of study I realized that opto isolators are themselves current hungry devices.  So if you need, say input 20 mA to run opto isolator you are back to square one.  Or are there some low-current opto isolators?

You don't need 20mA to run an optoisolatoe. That value is an upper limit. Check the datashete and look at the pretty graphs to see the switching characteristics. Most will switch from aroud 5mA.

Since RPi provides pathetic total 50mA for all GPIO combined (to use all 17 pins you need at least 17*5mA = 85mA, not mentioning usage of SPI and I2C), it seems that RPi sucks for serious projects.  Do you know by any chance what is total current for all pins for Arduino 101?

Nobody outside of intel knows and they aren't telling anyone.

Oh well.  Arduino and RPi are great projects, but occasionally I get an impression that some details are not well conceived.  They are particularly tight with currents...

My conclusion would be "Both Arduino and the Raspberry Pi are designed to control things, but they did not really provide enough current to safely use all control pins." :)

@Pygmalion That depends on how you define "use". Drive heavy loads - not always. Interface with logic and other similar devices - perfectly adequate.

I partially agree.  But let stop here and not turn this discussion into a flame.

Bottom line is: the controllers are just not meant for supplying power.
They do have the ability to do so, within limits - fairly stringent limits for a controller chip itself, and slightly more generous limits for the on-board power supply. If you really need an all-in-one, you might consider making building your own controller board with a more capable on-board power supply and a number of transistor switches to provide power for the hungrier devices, that can be switched by the MCU chip.
Note that this will not improve the chip's ability to supply power - you can't, by any practical means - but the board can, through the switching transistors.
Figure out your project's power budget, or the budget you'd like to have for your future projects, and design an on-board power supply to exceed that by a healthy margin-of-safety. Likewise, for the individual switched circuits, in order to choose a sufficiently robust switching transistor.
If you prefer an off-the-shelf solution, one of the available motor-driver boards is probably a good choice but it will need to have an independent power supply if there isn't one on the driver board.

I bought a Pi a while back, and found it so tedious to use I put it in my parts drawer and haven't used it since. A Pi is like a small Unix PC - you have to install an operating system, boot it up (which takes time) and then install device drivers etc.
The Arduino (particularly the Uno) boots in under a second, and "just works". It is much easier to use for small to medium projects.
As for the current, as others have replied, you aren't supposed to be powering things, like motors, from the output pins. 20 mA is a nice amount of current to flash an LED, or send data to another device. The output pins are for data not for driving things like motors. If you need more than 20 mA you should be looking at driver circuits, like transistors or MOSFETs.

... hard programming ...

I wouldn't say that. You program in C++. What are you going to program the Pi in? There are many libraries for the Arduino to simplify programming, but you can get down to the "bare metal" quite simply.

I actually did program Raspberry Pi for a research project and I used Python.  I know both Python and C++ and the former is far more user friendly.  Which is a bonus if you want your kids not only to learn electronics but programming too.
Otherwise, yes, I like the fact that Arduino "just works", but it also has extremely small memory, far too small for a serious project.

@Pygmalion Python is beginner friendly. C++ is programmer friendly. Choose which you want to be in the long term.

it also has extremely small memory, far too small for a serious project - it depends on your definition of "serious". I have one right now controlling access to my house. It's been there for a few years now, and works perfectly. It's a microcontroller, not a supercomputer. For projects - ones suitable for a microcontroller - it does a great job.

I did a lot of programming for controlling relatively small science projects and I usually end with a source code of cca 20 kB.  I know that C++ source code is compiled, but this by the rule of thumb only increases the required space.

The AVR compiler is quite good at generating compact code. Especially if you choose sensible data types, like 1-byte or 2-byte types. Once you start using long and float code necessarily bloats somewhat.


text:
Can I hook up two micros to one GPS module?
I've worked with a few different GPS modules. Most of them seem to just pump out data and not really interact with the micro controller.
I have a quadcopter (Cheerson CX 20 Big Sky) It has a gps break out board that looks similar to the one I've worked with before. Is it likely that I connect another micro controller to this board? I want to add a cellular module to my quad.
I know that the answer may be "it depends" but before I start testing and researching I just want to know if it's even likely to work.
If the gps is just barfing out coordinates and not interacting with the main board I think it could work. I could just tap in and "listen" -- is this even a possibility?

You are quite wrong. The answer is not "it depends", but "yes".
You can have any number of devices listening to (receiving) the transmitted data. You can only have one device sending anything back to whatever it is that is broadcasting the data if you need to configure it in any way. That shouldn't be a problem of course if you have one main controller that does that configuration and everything else is just a passive listener.  Just be sure that you don't connect the transmit pins of the passive listeners to anything (unless you want to use them for a completely unrelated purpose to transmit serial data to something else).
The only caveat is that each device you add as a listener will increase the load on the GPS's transmit pin and eventually the slew rate will become too slow and the signal will become distorted. If this ever becomes an issue reducing the baud rate can combat it to a certain extent. For serial though you would need quite a lot of devices for it to become an issue. Two devices certainly won't ever be an issue.

Great! Thanks. This is how I thought it might work but I wasn't certain.


text:
Code problem w/ Uno+GPS+GPRS?
I've got an Arduino Uno, SIM900 GPRS, and the Adafruit Breakout GPS.
Can this code be optimized?
 #include <SoftwareSerial.h>
 #include <TinyGPS++.h>
 #include <Ubidots_Arduino_GPRS.h>
 //Serial Relay - Arduino will patch a
 //serial link between the computer and the GPRS Shield
 //at 19200 bps 8-N-1
 //Computer is connected to Hardware UART
 //GPRS Shield is connected to the Software UART
 #define APN "myapn"
 #define USER ""  // If your apn doesnt have username just put ""
 #define PASS ""  // If your apn doesnt have password just put ""
 #define TOKEN "ubidotsToken"  // Replace it with your Ubidots token
 #define ID "Your_id_here" // Replace it with your Ubidots' variable ID
 // You can send 1 to 10 variable at the same time
 #define ID1 "idHere" // Replace it with your variable ID
 //#define ID2 "" // Replace it with your variable ID
 //#define ID3 "Your_id_here" // Replace it with your variable ID

 TinyGPSPlus gps; // The TinyGPS++ object for interfacing with the GPS
 //Declare indexes, and strings
 char latitude[12];
 char longitude[12];
 float value_1 = 1;
 char var[18] = "Lat: ";
 char var2[18] = "Long: ";
 Ubidots client(TOKEN);
 SoftwareSerial ss(2,3);
 void setup() {

 // the Serial port of Arduino baud rate.
   Serial.begin(9600);

   client.powerUpOrDown();
   client.setApn(APN,USER,PASS);
 //.endC is for _client.end() in Ubidots_GPRS.cpp
   client.endC();
   ss.begin(9600);
 }

 void loop() {

   //handling GPS data parsing
   while (ss.available() > 0) {
     gps.encode(ss.read());}
   //Once a valid location comes up it updates Lat/Long variables
    if (gps.location.isUpdated())
 {
     strcpy(var, "Lat: ");
     strcpy(var2,"Long: ");

     dtostrf(gps.location.lat(),10,6,latitude);
     strcat(var, latitude);

     dtostrf(gps.location.lng(),10,6,longitude);
     strcat(var2, longitude);
   //Added ss.flush();
     ss.flush();
     ss.end();
     Serial.flush()
   //Added client.beginC() for _client.begin(9600) is Ubidots_GPRS.cpp
     client.beginC();
     client.add(ID1, value_1, var, var2);
     client.sendAll();
     client.endC();
     ss.begin(9600);
   }
  Serial.println(var);
  Serial.println(var2);
 }

From this link, I moved the println from inside .isUpdated() to outside the if statement. I was able to get GPS data sent from the unit to my Ubidots account while driving around town. Afterwards I was able to input the data into Google Maps and the route produced was accurate. Do I need flush()?

A simple test: comment  all the code concerned with sending the data over GPRS and run the sketch again. Are the GPS values printed without errors to the monitor?

I commented out .add() and .sendAll(), and the GPS values are being updated without error.

I have edited my post again.

From what you say, everything works. I was going to add a few listen()s in your code but this approach is also alright. If all you want to do is optimize the code, you could save the APN settings permanently to the sim900. Just add client.println("AT&W") at the end of setApn() and use readData() to ensure OK was received. Run the sketch and then you can comment out the setApn() call in setup(). Also provide a link to your updated library with its new functions.

Yes, it does work. Here is the link to my forked repository with the changes I have made so far. The code is in examples/SaveValuesGPS

Optimization is a generic word with plenty of different meanings. Please make it clear what you want: smaller code? Faster code? Code fatser to compile? Code easy to udnerstand or maintain?...

It seems you're using the same hardware Serial port for both your PC and the GPS module. This will result in the GPS module receiving everything you send to the PC with Serial.print() and this may be the cause of your problem, as it could confuse the module and either make it send an endless stream of gibberish and/or making isValid() to always be false. You should instead create a SoftwareSerial instance attached to any 2 digital pins (maybe 2 and 3) like this:
SoftwareSerial ss(2, 3);

and in setup():
ss.begin(9600);  // use your module baud rate

Then at the top of loop(), use this instead:
while (ss.available() > 0)
    gps.encode(ss.read());

Get rid of the recursive call of loop() within loop() since it will cause your stack to rapidly overflow.
If you want data to only be sent when the location values are updated based on recent received data (but not necessarily changed, since you may still be at the same location), you should use if (gps.location.isUpdated()) instead.
Your call of dtostrf() is also wrong. The second argument should be the length of the string to be created (including decimal point) and the 3rd argument should be the number of digits after the decimal point. Something like this should be okay:
dtostrf(gps.location.lat(), 10, 6, latitude);

You can also put this at the end of loop() to check if data is actually being received from the module and processed by the library:
if (millis() > 5000 && gps.charsProcessed() < 10)
  Serial.println(F("WARNING: No GPS data.  Check wiring."));
  while (1){ // infinite loop
    if (ss.available())
      Serial.print(ss.read());
  }
}

This site may provide additional details.

Thank you for your input. I have made the changes you suggested. I'm getting errors from serial monitor, but it may be I made a mistake in the one of the changes. `void setup() {
// the Serial port of Arduino baud rate.
Serial.begin(9600);
ss.begin(9600);
client.powerUpOrDown();
client.setApn(APN,USER,PASS);
}`

What errors exactly? did you connect the RX of the gps module to pin 3 of the arduino and its TX to pin 2?

Yes. If I run it with Serial.begin() first in setup() it will work, and with ss.begin() last it will parse data. But within .isUpdated() it will display error when trying to run .add().

What error are you getting exactly? How do you know it parses data? is the gps data changing (as you change your location) and being displayed by the Serial.print()s?

It will get a fix and show the coordinates in the serial monitor. I know there is an error because the .add() is displaying the error string "Error with AT+CSQ" on the serial monitor. It only seems to be working depending on where Serial.begin() and ss.begin() are located in setup().  `void setup() {
// the Serial port of Arduino baud rate.
Serial.begin(9600);
client.powerUpOrDown();
client.setApn(APN,USER,PASS);
ss.begin(9600);
}`

@roe-el Ah, its because there are multiple instances of SoftwareSerial being used. To what pins is the SIM900 connected?

From Ubidot_GPRS.h,  \nclass Ubidots{       private           SoftwareSerial _client = SoftwareSerial(7, 8);               bool httpInit();           char* _token;           bool httpTerm();           char* readData(uint16_t timeout);           void flushInput();           uint8_t maxValues;           uint8_t currentValue;           Value * val;    So 7,8?

@roe-el Edit your code so I can see the changes you've made so far. I will edit some of the library code.

I have edited code the code above.

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


text:
Turning all LEDs on (FAST.LED)
In Fast.Led lib for arduino there is a code to turn off all leds
FastLED.clear ();

Is there also a shortcut to turn all LEDs ON, and with a specific color

What leds/driver are you using?

Arduino nano, FastLed lib and WS2812B leds

I think you could use showColor

You can use fill_solid.
For example
fill_solid( leds, NUM_LEDS, CRGB(50,0,200));

Or
fill_solid( leds, NUM_LEDS, CRGB::Red);

Works fine. While FastLED.showColor() will not behave properly if you add delay after it,


text:
How to get a button state change within a for loop?
I have a for loop inside my void loop() that triggers a piezo.
What I want to happen is when I press a button, it breaks the loop of the piezo, but right now, it's as if it isn't detecting the button press inside my for loop.
Here's my code:
#include <Adafruit_NeoPixel.h>

#define PIN 6
#define TONE 8
const int buttonPin = 2;

long fadeTime = 5 * 1000L; // X minutes
int colorStops = 256;
int delaySpeed = fadeTime / colorStops;
int notes[] = {262,294,330,349};
int switchState = 0;         // variable for reading the pushbutton status

Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, PIN, NEO_RGB);

void setup() {
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input

  strip.begin();
  strip.show();
}

void loop() {
  // read the state of the pushbutton value:
  switchState = digitalRead(buttonPin);

  // Fade in light
  for(int i = 1; i<colorStops; i++){
    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(i,i,0));
    }
    strip.show();
    delay(delaySpeed);
  }

  // Play tone after light fully bright
  for(int i = 1; i<100; i++){
    // Turn off tone on button press
    if (switchState == HIGH) {
      noTone(TONE);
      break;
    }
    tone(TONE, notes[random(0,3)]);
    delay(100);
  }
}

Does switchState = digitalRead(buttonPin); only get called at the start of the void loop and so it can't detect the button change until then? Something else?
Also, in case it's useful, here's my hardware set up...

That'll be because you're not reading the button inside the for loop?

@Majenko Does switchState not just call digitalRead(buttonPin)?

No. switchState is assigned the results of performing digitalRead(buttonPin) at the time it is called - i.e., at the top of loop().

You aren't reading the state of the button within your loop.
You only read it the once at the top of your loop():
void loop() {
  // read the state of the pushbutton value:
  switchState = digitalRead(buttonPin);

You need to replicate that every time you want a new reading from the button - so in your loop you need to add that digitalRead line:
// Play tone after light fully bright
for(int i = 1; i<100; i++){
  // Turn off tone on button press
  switchState = digitalRead(buttonPin);
  if (switchState == HIGH) {
    noTone(TONE);
    break;
  }
  tone(TONE, notes[random(0,3)]);
  delay(100);
}

Or you can do away with the variable altogether and just test the return value of the digitalRead:
// Play tone after light fully bright
for(int i = 1; i<100; i++){
  // Turn off tone on button press
  if (digitalRead(buttonPin) == HIGH) {
    noTone(TONE);
    break;
  }
  tone(TONE, notes[random(0,3)]);
  delay(100);
}


text:
Do I need capacitors for these LEDs?
I have 5 of these NeoPixel LED's.
For these particular LED's, they recommend "use of a 0.1 μF capacitor between + and ground".
Here's what I've got:

The blue's are 100 μF and the little brown ones are...I have no idea. Both were just in this starter kit. Maybe 100 pF?
So, a few questions around this...

Are these actually necessary and why?
Is there any harm in using much higher capacitors than recommended?

Dont know if needed....they arent there on a ledstrip are they? Try and find out...probably you wont kill it. What says the brown capacitor....100N is enough

The little brown ones also have their values printed on them. Do you need a magnifier?

The capacitors are called decoupling capacitors and are used to provide current at very short notice.
The LEDs, when not fully on or fully off, switch rapidly on and off.  This switching needs current to be provided very rapidly at short notice, and batteries and power supplies aren't good at that - so you have the capacitors to act as a little reservoir of power that the LEDs can dip into.
The size of the capacitor (capacitance) can have an effect on how effective they are.  Bigger capacitors respond slower than smaller ones, but store more energy. So you need the capacitor to be small enough for it to respond fast enough. But if you have it too small it won't store enough energy to give to the LEDs and they will be unable to do their job.
0.1µF (or 100nF), aka "104" capacitors are usually reckoned to be a good rule-of-thumb value to use since they are small enough to respond rapidly and yet large enough to store enough power for most small high speed fluctuations.  The exact value though doesn't matter that much, however I would be wary about going below that, and going too high can be troublesome for other reasons as well as their slow response (google: "Inrush Current"). So you don't want to go too high. Around the 0.1µF to 1µF area is where you want to be, with maybe a 10µF for every group of 5 or so LEDs.
I would say 100µF is way too high to have on every LED, but maybe one of those on the breadboard where the power is fed in would be useful to provide a reservoir for larger low frequency demands from the rest of the board.

Are these actually necessary and why?

The datasheet for the WS2812 says a "typical application circuit" should have them:

If the manufacturer recommends it, I would say it is necessary. I'm sure they would be happy to not have to recommend extra parts, but testing would have shown they are necessary. As Majenko replied, putting in 100 µF when you only need 0.1 µF seems way overkill (to say nothing of more expensive).
And don't forget the 150R resistors, eh?


text:
Random Blink LEDs
How can I make LEDs blink randomly?
I found a piece of code, but it is not working for me. I probably need something other than setPixel(), but I don't know what.
I am using the Fast.Led library with Arduino Nano and WS2812B LEDs
void loop() {
    Twinkle(CRGB::Red, 10, 100, false);
}

void Twinkle(uint32_t color, uint16_t Count, uint16_t SpeedDelay, boolean OnlyOne)
{
    FastLED.setBrightness(MAX_BRIGHTNESS);
    fill_solid(leds, random(NUM_LEDS), CRGB::White);
    FastLED.show();
    for (int i=0; i < Count; i++) {
//        setPixel(random(NUM_LEDS),red,green,blue);  //!ORIGINAL LINE OF CODE!
        setPixel(random(NUM_LEDS), color);  //!MY LINE!
        FastLED.show();
        delay(SpeedDelay);
        if (OnlyOne) {
            fill_solid(leds, NUM_LEDS, CRGB::Black);
            FastLED.show();
        }
    }

    delay(SpeedDelay);
    return;
}

What exactly is setPixel()? Does the original code work at all? Remove the statements within exclamation marks and use proper comments for your code. A link to your library would also be nice.

it is not working for me - what is it doing? Nothing blinks? Too many things blink? It isn't random? Aliens kidnap you and do scientific experiments on you? "Not working" doesn't tell us much.

I can't tell exactly whats not working with your code,it would be really helpful if you elaborate more.
But here is some code that I wrote and I think it will get the job done:
//declare our variables:
int myPins[] = {2, 4, 8, 3, 6}; //Enter the number of the pins being used
int RNum = 0;

void loop()
{
    DigitalWrite(myPins[RNum],LOW);
    RNum = Random(0,MAX) // MAX being the number of LEDs connected minus one
    //the above generates a random number
    DigitalWrite(myPins[RNum],High);
}

This will turn on one LED at a time.


text:
Does not name a type error when using makeTime
I am getting a "does not name a type" error when trying to use makeTime() from the Time.h library, code snippet as follows:
#include<Time.h>

tmElements_t tmet;
tmet.Year = 2013-1970;
tmet.Month = 8;
tmet.Day = 28;
tmet.Hour = 18;
tmet.Minute = 30;
tmet.Second = 0;

time_t dateMet = makeTime(tmet);

Alternatively I've also tried time_t dateMet = maketime(&tmet); with the same result. I am no expert so go easy on me but am I missing something small here?
Thanks

You're trying to access the 'properties' (i.e. the members) of the tmet variable in a scope where they aren't accessible (outside of a code block). In this global scope of the program the compiler expects a type name on the left side of a statement (i.e. a variable or type declaration), but tmet's members like tmet.Year aren't types in and of themselves.
There are two solutions. You can move the access to the members of tmet into a code block like the setup function:
#include <Time.h>

tmElements_t tmet;
time_t dateMet;

void setup() {
  // put your setup code here, to run once:
    tmet.Year = 2013-1970;
    tmet.Month = 8;
    tmet.Day = 28;
    tmet.Hour = 18;
    tmet.Minute = 30;
    tmet.Second = 0;

    dateMet = makeTime(tmet);
}

void loop() {
  // put your main code here, to run repeatedly:

}

Or you could declare and define tmet in one statement, which has a different syntax (since you have to provide the content of a tmElements_t in a single line:
#include <Time.h>

tmElements_t tmet2 = { 2013-1970, 8, 28, 18, 30, 0 };

time_t dateMet2 = makeTime(tmet2);

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:

}

Both versions work right away from within the Arduino IDE (i.e. I tested them).


text:
How to control Adruino through Internet
I want to control my Adruino through Internet without Ethernet or wifi shield. So what are the ways I can do?

Guess you need to use a pc, and a program to receive commands and send them along to the arduino by serial.

So can you tell me how to do that.....

You need a backend that will listen for incoming commands. You can start with Django or Ruby on Rails or some microframework. The backend residing on PC should forward commands to Arduino board.

You need access to the Internet. Since you dont want to use an Ethernet or WiFi shield/module, then, for the most part, you are left with:

Using a GSM module with the Arduino to receive data over the Internet
Using a PC as a web server to receive data over the internet and forward it to the Arduino over a wired connection (UART) or a wireless connection (e.g. bluetooth)

The most direct would be the second method over UART. So it could be seen like this: Client/Sending PC -> Over the Internet -> Server/Receiving PC -> Over UART -> Arduino. So you are now faced with 3 main interfaces: Internet->PC for the server and client as well as the PC->Arduino interface on the server/receiver side.
To handle the Internet -> PC interface for the client, the client PC would need to run a program that will connect to the server PC over the Internet (using the server's public IP) and send the Arduino control data. Similarly, the Internet-PC interface for the server PC would require a constantly-running server program that will listen for incoming connections from the client PC and receive the data being sent. Assuming you know Python, with Python you can have both programs up and running within minutes. This site should help with the programs.
Note that port forwarding will need to be implemented on the router on the server side so that packets from outside its local network can get to it, given that its behind a router. This software can help with setting port forwarding rules.
The PC->Arduino interface will require the pyserial package (if you're still using Python). Pyserial can be used to forward the control data received over the internet, to the Arduino over Serial UART. This site should help with using Pyserial for Python 3. Search for other tutorials.
Finally, the Arduino itself must regularly check the Serial buffer for any received characters from the PC. It must then act on the received data, depending on rules you should have established. A simple example would be: 'a' = Write HIGH to pin 13. This means if ASCII char 'a' were received over Serial, the Arduino would interpret this to mean a command to digitalWrite(13, HIGH). You can make use of the built-in serialEvent() to regularly poll the serial buffer. A simple sketch to illustrate this:
void setup(){
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}

void loop(){}

void serialEvent(){
  if (Serial.read() == 'a')
    digitalwrite(13, HIGH);
  else  //any other character turns off the LED
    digitalWrite(13, LOW);
}

This is, by no means, the only way to do this, only very straightforward IMO. For example, you could also upload your control data to some cheap server and have your PC regularly poll that server for any new commands. Of course, this would be greatly simplified if you decided to use a WiFi module, like the cheap ESP-01, directly with the Arduino.

I heard that through Processing IDE we can connect with adruino.  How how it is possible?

@user18794 yeah, i forgot that...you could use Processing to receive data over the web and then send this control data to the Arduino over UART. Check here (https://processing.org/reference/libraries/net/) for more details on using Processing for the web.


text:
I2C Master-Slave Arduino system to control array of steppers
trying to make a system where one master Arduino makes moving 9 steppers 28BYJ-48 by 3 stepper on each slave arduino.
While all the parts on their way to me, wonder to check with professionals.
Maybe I've missed something?
Any suggestions and tips are welcome.
Thank you.

I think your schematic might be wrong there. Only one MEGA is connected to a positive side of a battery.
The MEGA can only run on 7V to 12V. BUT PLEASE DO NOT apply the voltage to the 3V3 or 5V pin.
Microcontroller ATmega1280
Operating Voltage   5V
Input Voltage (recommended) 7-12V
Input Voltage (limits)  6-20V

And also, I would only put in another MEGA when you don't have enough I/O pins.
Digital I/O Pins    54 (of which 15 provide PWM output)

In theory you could use 13 steppers on one MEGA. Try slowly scaling up.
You don't need PWM for steppers, maybe you're confused with servo's?
And why not use one of the stepper-driving MEGA's as the master? (In the first picture, slave 1 isn't even connected to the SDA/SCL lines of the I2C bus.

I don't quite understand the problem. A
 arduino mega would have no problem controlling 9 of these steppers alone. If you are asking about i2c protocol please be more specific about what you need help with.

How much does she more can handle? Can you point me, how it possible, because as my newbie brain think when one stepper requires 4 PWM outputs and mega has only 15, I can drive only 3. Thank you for your help!

These steppers doesn't require any timers really, you can control them with 4 outputs each and control each stepper in code.

Well, 4 pwm outputs, 15 ppm on each arduino.

Why would you need PWM? It's not like doing micro-stepping on a 28BYJ-48 is useful?

If you were to tell us what this system of yours is going to do, we might be of more help.

It is for simultaneously moving steppers, like in kinetic statues. With accelerated moves and so on.

Well first off, if two or more steppers need to go simultaneously just connect them in parallell. These stepper doesent require any PWM or timers really, in normal program loop you need to delay stepping them or else it will stall them(run faster than they can handle), so maybe by using a non-blocking code you could easily run 13 of theese steppers of one mega. or basically any amount of theese steppers you want using shift registers.

@Hans Neve Sorry for my idiotic questions, but what is non-blocking code? loop+setup? What if I want to drive steppers simultaneously but with different speed and direction?

@lenyapugachev : 1) the "non-blocking" concept is something that most arduino developer will experience early in her developer career. If you already have NOT "hit" related problems, than How and Why to avoid delay() is the place where to start :-)   2) no ;  3) unfortunately I have NO experience with stepper-motors but.... my "feeling" is that you need a sort of multitasking and, as such, you definitely need to investigate point 1), that is mandatory in such a scenario :-)

ok, if I get it, yes I will avoid delay(), planning to use something like http://www.airspayce.com/mikem/arduino/AccelStepper/


text:
Atmel studio 7 - my own libraries
I like to use AS7 to make my programs.
I know c and some c++, but how things work from there I'm green.
I would like to know if there is a folder where I can store my own homemade c and h library files where they get to be available for all my projects.
Now I copy all the files into each of my projects and this works but I find it a bit tedious.

You should create your library as a separate project: File->New->Project and select C or C++ static library:

Add your library modules in this project. When building, this will create lib{your_project_name}.a file (in Debug or Release folder) - your library object file you can use in your other projects.
Usually I include in the same solution both the library project and target project (just library project file, sure the library and it's files resides in single place):

ORDO is the library name.
Some check list:

Include the library file in Libraries folder (shown above)
Specify the path to the library *.a file for linker (Toolchain->AVR/GNU Linker->Libraries). Note that there should be different paths for Debug and Release configurations.
Specify the path for library include files (Toolchain->AVR/GNU C or C++ Compiler->Directories)
In some cases, F_CPU definition might be needed for library project too (same as in your project, under Symbols).
When changes are made in your library files, use Build solution (F7) when building, if not - you can use Build project (which will be faster).

Setting project dependencies shall also lead to rebuilding the library automatically when needed (not tested, I usually just hit F7 :).

Thank you for a good answer, I belive i see where to begin now. just as to what to do next, lets say you wanted to make a reusable library for those ds18B20 sensors I see you got there... I have googled around trying to find out how to do this but I cant seem to find any that enlighten me.

I used library from Davide Gironi: http://davidegironi.blogspot.com/2014/09/a-ds18b20-1-wire-digital-thermometer.html - it has no external onewire module, it is basic, minimalistic, doesn't support bus enumeration etc but might be good starting point to implement own.

Nice idea, but what if my own library has Arduino dependencies? I get stuck at this point, because of course requires the Arduino core stuff

Please check AS7 + Arduino + Libraries: How?! and Tutorial: Using Atmel Studio 6 with Arduino projects


text:
Rotary Encoder problem with LCD Display
Program reads rotary encoder correctly without bouncing in this code:
int val = 0;
byte clkPin = 3;
byte dtPin = 2;
bool lastClk;
bool lastDt;
void setup() {
  pinMode(clkPin,INPUT);
  pinMode(dtPin,INPUT);
  lastClk = digitalRead(3);
  lastDt = digitalRead(2);
  val = 0;
  attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
  Serial.begin(9600);
}

void loop() {
}

void clkRise(){
      lastClk = HIGH;
      lastDt = digitalRead(dtPin);
      if(lastDt == LOW){
        val--;
        Serial.println(val);
        }  else{val++; Serial.println(val);}
        }

but when i use lcd to show the result, i get massive bounces (i think) in this code:
#include <LiquidCrystal_I2C.h>

#include <Wire.h>

LiquidCrystal_I2C lcd(0x27,20,4);
int val = 0;
byte clkPin = 3;
byte dtPin = 2;
bool lastClk;
bool lastDt;
void setup() {
  lcd.begin();
  pinMode(clkPin,INPUT);
  pinMode(dtPin,INPUT);
  lastClk = digitalRead(3);
  lastDt = digitalRead(2);
  val = 0;
  attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
  Serial.begin(9600);
  lcd.home();
}

void loop() {
  lcd.print(val);
}

void clkRise(){
      lastClk = HIGH;
      lastDt = digitalRead(dtPin);
      if(lastDt == LOW){
        val--;
        Serial.println(val);
        }  else{val++;}
        }

it increases and decreases by random numbers between 0-5.I use KY-040 R.E. it has built-in 10k pull up resistors.
This is what i use to debounce:
A or B pin of R.E--10k R----------------------------------Arduino INPUT PIN
                         |
                         |
                         =0.1uF C
                         |
                         ---------------------GND

Try adding a slight delay after lcd.print(val);. Something like delay(50);. Also, if the R.E. has in internal pull-up of 10k, the series resistor between the A/B pin should be lower than 10k. Otherwise the maximum voltage is only 2.5V (Vcc/2).

@Gerben i tried delaying, it works better but there are still big jumps like 3-4+

Either increase the delay, or only do the lcd.print if the value of val has changed.

@Gerben it work way better now, but there are still rare jumps. would a schmitt trigger fix this? I took off the 10k resistor that i placed.

I don't know. That's not my area of expertise.

I suspect the problem is that your hardware-debounce capacitive circuit isn't working well enough to accurately debounce the contacts, and that invalid transitions are occurring on the quadrature lines as read by the program.
Note that use of Serial.println() within your clkRise() interrupt handler is problematic, because Serial.println() uses interrupts itself. As far as I know, println() is not reentrant, ie cannot be used correctly from the multiple interrupts that may start before previous println() calls finish their background processing.  The bits of extra delay introduced by LCD code may merely be exposing a problem.
There is no need for either hardware or software debouncing on quadrature inputs.  A correctly-implemented state machine will reject invalid conditions that arise during bounce, or will immediately follow any extra up-tick by a corresponding down-tick, or vice versa.
For some state machine code, see for example answer 16420/3917 and also see answer 18221/3917.  Also see answer 19109/3917.

Çay Öncesi should definitely not be doing Serial.println inside an ISR.

@NickGammon alright. I finished my project. just curious, what is the outcome of placing Serial.println inside an ISR?

Serial.print puts whatever-it-is you want to print into a buffer. It then waits for interrupts to empty the buffer. If the buffer is full already, it waits before putting data into the buffer. Since the buffer won't be emptied inside an ISR, if the serial buffer is full, the program will then block indefinitely.

What I've been doing in my decoder interrupt routines is to set a "valueChanged" flag. Then in the app's main loop, if value changed is true, I use Serial.println() to print it and set valueChanged=false. That way I'm not trying to do serial.print inside an ISR. When I needed more info than that. I created a large (char logBuffer[100]) C string to contain my logged data, and used strcat() to append to that. Then in the app's loop() I print the logBuffer and set it back to empty.

@DuncanC, the general idea of using a buffer like that is ok, but there are several races that can occur -- eg if the ISR adds to the buffer between loop()'s "print the logBuffer" and its "set it back to empty" operations, the added data gets lost.  One can fix the problems using semaphores, or switching between two buffers atomically, etc


text:
How to increase the brightness of a IR transmitter LED?
I have a pair of IR transmitters and receivers, but I have found that the brightness of the transmitter is very low, so that I can't use it to detect an object in front of them.
What should I do?

Please specify the part(nr) you are using.

?
Anyway, how is your Arduino connected? Try using an external power supply (5V) to connect your IR transmitter.

A schematic would help. We have no idea of what transmitters you are using, whether or not you are using driver transistors, and what part numbers you are using. Adafruit has an example which sadly does not have a current-limiting resistor for the LED. However the idea of using a transistor to increase output is sensible.

IR transmitter LEDs are literally just LEDs that emits Infrared Light which is not visible to the human eye.
That being said, IR LEDs behave very similarly to regular LEDs and therefore to increase the brightness you need to increase the Voltage it is receiving, just like you would do with a regular LED.
But the problem with LEDs is that they drain current and that's why we use resistors,to protect our electronics(i.e. Arduino).
So to recieve maximum voltage you can reduce the resistance of the resistor (let's say 220ohm or even 100ohm).
Forgot to mention that the correct wiring of LEDs to an arduino is as follows:
5V pin(or digital pin set to high) -> Anode leg(longer) of LED -> Resistor(connected to shorter leg :3) -> ground pin

That is indeed a correct way. Others are: Anode to +5, Cathode to resistor to I/O pin (LOW pin enables, HIGH pin disables the LED). The resistor can be on the Anode side or the Cathode side of the LED; it is absolutely irrelevant which way it is done.

Actually you need to increase the current not the voltage. Increasing the voltage without changing the resistance has the knock-on effect of increasing the current. Or you can decrease the resistance and keep the voltage the same to increase the current. Either way you are limited to either the IO pin's absolute maximum (40mA) or the LEDs absolute maximum, whichever is lower.

@Majenko True. But I thought that because the resistor and LED are in series then they should Hv an equal current draw. But the you are right because the LED and resistor act like one load and voltage is constant . So the only way to increase power is by reducing resistance.

If you aren't at the current limit of either the IO pin (40mA) or the LED (usually around 30mA) you can increase the current as far as the lower of those.  That can be done by reducing the value of the resistor you are using with the LED or using a higher current drive circuit.
However, just having an LED turned on all the time is not a good way of using it - you are constantly fighting against the background light.
Instead the LED needs to be pulsed on and off using PWM at a very high frequency (typically 30-50kHz) and you need to detect that pulsed light with the receiver.
This is usually achieved by using a high-pass (or band pass) filter and amplifier on the receiver.


text:
Cannot include .h files back one directory
I am working on a project with multiple arduinos. I want my folder structure to be as follows:
/
  libs/
    someSharedFile.h
  arduino1/
    arduino1.ino
  arduino2/
    arduino2.ino

When I include someSharedFile.h in one of my .ino files like this #include "../libs/someSharedFile.h", I get this error No such file or directory.
However, when I move libs/ to arduino1 and include the shared file like this #include "libs/someSharedFile.h" everything works fine.
I am using IDE 1.6.7 on windows 10.

Arduino IDE copies the files to a temp folder. You can see that when you compile in verbose mode.
As such the lib folder is not available.
You should place you libraries in [your home folder]/arduino/libraries

Thanks for your answer. I was trying to avoid that for git integration. Is there any workaround where the libraries and the main code could be in the same repo?

Not that I know of wit the Arduino IDE.

You could use a symlink that's ignored by git. Why do you need to do this?

I am working in a robotics club at school and I want to make it easy for people to get going without having to install a bunch of libraries first.

I would advice a better IDE for a robotics club. These can handle these situations and have far better version control integration. Off-course I advice my arduino eclipse plugin. http://eclipse.baeyens.it/


text:
How do I connect this to my breadboard?
I just purchased this Grove RTC. It includes a cable presumably to connect it to a breadboard and/or Arduino, but the pin holes on this cable are much smaller than those on a breadboard or Arduino.
How/where would I connect this in the case of using an Arduino Uno?

If you want a quick temporary solution, you can probably stick 22 gauge wires in that connector, secure with electrical tape and put the other end in your breadboard.

I would get two jumper wires (with a male plug at each end) chop them into half so you now have four wires, each with a bare end and a plug, strip the wire where it was cut, and solder the 4 bare wires to your socket, and then plug the plugs into the breadboard.

Either use jumper wire, or pull the connectors from the Housing and connect them with male connectors.


text:
Posting Arduino data via ethernet to PHP server problems
I am currently having difficulties sending data from an Arduino using an ethernet shield to a PHP database in MySQL. My problem is that it appears that the server is receiving the data as there is a time stamp when I send it from the Arduino however, the other values it is receiving are incorrect (see images below). The server says the values of "data", and "serial_number" are 0 but they are supposed to be 10 and 24. Along with that the Arduino is saying that the data has been sent successfully. My code for both the server and the Arduino is listed below. Any ideas on how to fix this or what is going on are much appreciated.

Arduino Code:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0x00, 0xAB, 0xBA, 0xBC, 0xDD, 0x02 };
EthernetClient client;
String data;
int t;
int h;

void setup() {
  Serial.begin(9600);
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  }

  Serial.println("still working here");

}

void loop() {
t = 10;
h = 24;

data = "temp1=";

data.concat(t);

data.concat("&hum1=");

data.concat(h);

  if (client.connect("www.smartwater.x10host.com",80)) {
    Serial.println(data);
    client.print("POST /add.php HTTP/1.1\n");
    client.print("Host: www.smartwater.x10host.com\n");
    client.print("Connection: close\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(data.length());
    client.print("\n\n");
    client.print(data);
    Serial.println("Successfull");

  }

  if (client.connected()) {
    client.stop();
  }

  delay(20000);
}

add.php (Server Code)
<?php
    include("connect.php");

    $link=Connection();

    $temp1=$_POST["data"];
    $hum1=$_POST["serial_number"];

    $query = "INSERT INTO `Main` (`data`, `serial_number`)
        VALUES ('".$temp1."','".$hum1."')";

    mysql_query($query,$link);
    mysql_close($link);

    header("Location: index.php");
?>

connect.php (Server Code)
<?php

    function Connection(){
        $server="localhost";
        $user="smartwat_arduino";
        $pass="*****";
        $db="smartwat_Main";

        $connection = mysql_connect($server, $user, $pass);

        if (!$connection) {
            die('MySQL ERROR: ' . mysql_error());
        }

        mysql_select_db($db) or die( 'MySQL ERROR: '. mysql_error() );

        return $connection;
    }
?>

index.php (Server Code)
<?php

    include("connect.php");

    $link=Connection();

    $result=mysql_query("SELECT * FROM `Main` ORDER BY `timeStamp` DESC",$link);
?>

      <title>Data</title>

Stuff

             Timestamp
             Data
             Serial Number

      <?php
          if($result!==FALSE){
             while($row = mysql_fetch_array($result)) {
                printf("
  %s 	  %s  	  %s
",
                   $row["timeStamp"], $row["data"], $row["serial_number"]);
             }
             mysql_free_result($result);
             mysql_close();
          }
      ?>

In your Arduino code, the function call that send the real data within the HTTP-POST call, is this:
[...]
client.print(data);
[...]

When executed, the content of the data variable is sent to the server.
Supposing data is a String object then data.concat() is this function, allowing "... String, string, char, byte, int, unsigned int, long, unsigned long, float, double..." as argument.
So, after the execution, data should contain:
temp1=10&hum1=24
and such content is exactly what is passed, via POST to the /add.php script.
Basically, you're passing two variables, called "temp1" and "hum1". Please keep note of those variable names!
Now let's switch the the PHP script, where you have:
[...]
$temp1=$_POST["data"];
$hum1=$_POST["serial_number"];
[...]

Above two statements, asks PHP to retrieve, via the $_POST function, the content of the two variables data and serial_number.
As such variables are undefined (the variables you passed were temp1 and hum1), PHP consider them like 0 and, as such, assign 0 to $temp1 and $hum1.
I bet that to solve your problem you only need to change above PHP with:
[...]
$temp1=$_POST["temp1"];
$hum1=$_POST["hum1"];
[...]

BTW: please note that what is inside the $_POST call is totally unrelated with the names of the variables you have on the left of the = sign: they are really different things!

Data = 10 is not the characters making 1 and 0 but an ascii character with value
10, your php script doesn't understand that.
Try using itoa function to make character array 1 and 0 for your php to understand.

You get a timestamp from running the php file. That doest mean that there is a number in $data or $serialnmber.
What happens if you fill in a value in your php file instead of the variables $data and serialnumber. If the dbase gets filled, you know that than your variables were empty. If they arent filled something is wrong in your php coding


text:
Writing and reading multiple values through serial
I am currently busy with a project that requires me to use an Arduino and 3 potentiometers (to change background in RGB format) to write values through the serial port and read and separate them in processing.
What I want to do is to be able to use my Arduino to write multiple values to a processing program. I am quite new to coding and its been a while since I worked with my Arduino. I know how to read and write one value, but not multiple values.
Also is there a way to write 20 values?
Thanks in advance!

something like: "value1,value2,value3,value4,value5,value6.."  might do?

The simplest way is to just print them as a single line and separate them with "something". That "something" could be as simple as a space.
Serial.print(val1);
Serial.print(" ");
Serial.print(val2);
...
Serial.print(" ");
Serial.println(val20);

743 234 34 599 2 ... 427 1013 48 2 409

Then in processing you just read the entire line into a String and split it on the spaces into an array.

What would I use to split the values up? Is there a comand or is the spacing interpreted as a type of break?

Well, Processing is Java. So maybe String[] bits = myIncomingString.split(" "); would do the trick...?

Thanks for your help! I finally got it to work and am now able to write up to 18 values (only had 3 potentiometers close so i did a little division to distinguish the values). Aparently when using myPort.read() the diffrent bytes automatically get split up, so all you have to do is read and assign them. Of course after spending all thia time did I realise its basically excactly what the one example in Arduino's IDE does :/


text:
Can we use an alternate RFID reader to read HID cards?
I'm working on a project where I need to read the HID RFID cards. Behind the card it shows as HID 0008p and based on the documentation, it looks like it uses a 125 kHz frequency. I tried using different 125 kHz RFID readers, but I was unable to read the card. What reader should I use?
I used RC522, and also another 125 kHz reader with Wiegand output, both  without any success.
Card Used : HID Proximity Card 0008p
Additional details about the card type : HID DuoProx II 1336
Here is the code i used - This works fine with SWH 5100 reader
But doesn't work with this reader EDK-125 TTL

volatile unsigned long tagID = 0;
volatile unsigned long lastBitArrivalTime;
volatile int bitCount = 0;

#define MAX_BITS 100                 // max number of bits
#define WEIGAND_WAIT_TIME  3000      // time to wait for another weigand pulse.

unsigned char databits[MAX_BITS];    // stores all of the data bits

unsigned long facilityCode;        // decoded facility code
unsigned long cardCode;            // decoded card code

 unsigned char i;

void ISRone(void)
{
  lastBitArrivalTime = millis();
  databits[bitCount] = 1;
  bitCount++;
  tagID <<= 1;
  tagID |= 1;
  Serial.println(bitCount);
}

void ISRzero(void)
{
  lastBitArrivalTime = millis();
  databits[bitCount] = 0;
  bitCount++;
  tagID <<= 1;
  Serial.println(bitCount);
}

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

  pinMode(2, INPUT);
  digitalWrite(2, HIGH);  // Enable pull-up resistor
  attachInterrupt(0, ISRzero, CHANGE);

  pinMode(3, INPUT);
  digitalWrite(3, HIGH);  // Enable pull-up resistor
  attachInterrupt(1, ISRone,  CHANGE);

  tagID = 0;
  bitCount = 0;
}

void loop()
{
  //  See if it has been more than 1/4 second since the last bit arrived
  if(bitCount > 0 && millis() - lastBitArrivalTime >  250)
  {
    Serial.print(bitCount, DEC);
    Serial.print(" bits: ");

 // 35 bit HID Corporate 1000 format
      // facility code = bits 2 to 14
      for (i=2; i<14; i++)
      {
         facilityCode <<=1;
         facilityCode |= databits[i];
      }

      // card code = bits 15 to 34
      for (i=14; i<34; i++)
      {
         cardCode <<=1;
         cardCode |= databits[i];
      }

 //   Serial.println(tagID);
    Serial.println(cardCode);
 //   Serial.println(facilityCode);

    cardCode = 0;
    facilityCode = 0;
    tagID = 0;
    bitCount = 0;

  }
}

Which RFID cards? Link? Which reader? Link? Please read How do I ask a good question?

TisteAndii & Nick Gammon, Thanks for your comments, updated my question with more details.

Don't do serial prints inside an ISR. If you do, all bets are off.

Were you able to figure out how to read the card?I am trying to do something similar. Thanks

See this article about what TTL means https://www.sparkfun.com/tutorials/215

@RamS did you ever find a solution?

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


text:
Arduino Nano ESP8266 software serial problems
I have a problem with my Arduino Nano ATmega328 and my ESP8266 01 module. I have connected the ESP8266 on my Arduino board without FTDI.
I have made the following connection:
I an using a 5V Arduino Nano which of course is 5V. The ESP8266 is a 3.3V device and so I am using a voltage divider to bring the Arduino's 5V down to 3.3V. If you are using a 3.3V Arduino then you do not need the voltage divider.

The wiring is very similar to the FTDI.
Arduino pin 3 to voltage divider and then to ESP8266 RX
Arduino pin 2 to ESP8266 TX
Arduino GND to ESP8266 GND
Pull CH_PD HIGH with a 10K resistor to +3.3V
+3.3V to Vcc

You only need the voltage divider on the Arduino TX pin. The 5V Arduino will read 3.3V as HIGH so you can connect the ESP8266 TX pin directly to the Arduino RX pin.
The problem I had and I can't handle is that when I start up the Arduino Tx and Rx LEDs work continuously so I can't have access to my serial monitor of the Arduino IDE. So with that problem I can't send or receive any command to/from the IDE. Also when I try to upload my program to the Arduino board, I have to disconnect the ESP. If I don't I can't upload it.
Any ideas guys? I would be grateful

I also try to implement code with AltSoftSerial but I have library issues - my laptop does not recognize it (I downloaded it and I put it in the same folder with my code).
  #include <SoftwareSerial.h>

    SoftwareSerial ESPserial(2, 3); // RX | TX
    void setup()
    {    Serial.begin(9600);     // communication with the host         computer

     // Start the software serial for communication with the ESP8266
     ESPserial.begin(9600);

     Serial.println("");
     Serial.println("Remember to to set Both NL & CR in the serial monitor.");
     Serial.println("Ready");
     Serial.println("");}

     void loop()
      {
      // listen for communication from the ESP8266 and then write it to the serial monitor
       if ( ESPserial.available() )   {  Serial.write( ESPserial.read();}  / / listen for user input and send it to the ESP8266
      if ( Serial.available() )       {  ESPserial.write( Serial.read()  );  }}

Well, what did you expect? It seems you're using the same serial port for the PC and the ESP-01. Isnt SoftwareSerial a built-in library?

Yes. Is there anyway to resovle this? I was able to found some solutions using an extra software serial but nothing happened. I am still unable to resolve this.

Post your code.

i have tried different codes but the basic one is the one below :

You say the TX and RX leds onboard blink whenever you send stuff from the serial monitor? Did u set the monitor to "Both NL & CR"? How are u powering the ESP?

Please use the Post answer button only for actual answers. You should modify your original question to add additional information.

I am powering the ESP directly from arduino as i shown above. As i mentioned i am can t send any commands. I have written the reactions i see on arduino and esp ( i also see the blue led of esp blinking --> so the esp try to  send/receive ) . I also put my code above to see what exactly i am trying to do .

Arduino Nano has its tx-rx serial port shared with the FTDI chip used by downloading and serial console. See https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf
This means that if you drive these pins from ESP, it will flash leds, and all communication on these pins will interfere with serial monitor and board programming as well.
You may:

disconnect ESP during program downloading
pick a different board, which has a separate hardware serial port, such as Arduino Micro, Leonardo, or any Pololu A-star 32u4 boards, this way you have a dedicated serial port to control your ESP
wire the tx-rx of ESP to two other pins of your Arduino micro, and use a software serial library to bit-bang serial communication. (Note that serial receiving in software mode may require clever programming - since while your code does something else it can not receive anything).

Basically I ve connected my esp8266 to an ftdi 3.3V logic and it helped my resolve my problems i had. I also use a command to change my esp baudrate to 9600 from 115200. Then i connect my esp back to arduino nano and everything works fine :) ( I think ftdi is the most easy way to get started with an esp module. )

authors: Μάριος Μιχαήλ


text:
Problems with serial communication from Arduino to Bluetooth HC-05
I just purchased some HC-05 Bluetooth devices and I have followed the directions to put the devices in AT command mode by holding EN HIGH when the HC-05 powers up.  When I do this the HC-05 goes into the "slow blink" to indicate it is in command mode.  However, when I send it "AT" I get odd characters in the response.
Note that when I type "AT" I get exactly 4 characters back.  They are just not the "OK" characters I expect.  I also verified that the Arduino IDE serial console is sending both NL and CR characters.
BTW, here is the Mel Patrick HC-05 authored setup program I am running:
https://raw.githubusercontent.com/dmccreary/coderdojo-robots/master/src/bluetooth-remote/hc-05-setup/hc-05-setup.ino

It has been suggested that the data from the HC-05 is only going up to 3.3v and that might be the cause of the problem, since the Arduino is looking for a 0-5 volt signal.
I also note that when I remove the TDX line from the HC-05 that no responses come back.  So I suspect that it is getting the "AT" fine through the RTX from the Arduino to the HC-05.  It is just some problem in the return data format.
Is there a simple transistor circuit I can hookup to shift the levels back to 0 to 5 volts from the 0 to 3.3 volts?
I am also using an Arduino Nano if that makes any difference.
Thanks - Dan

How is it wired? Are you using hardware of software serial? Do you have it set at the right baud rate?

I have wired the RTX and TDX connections correctly and I have set the correct baud rates.  I have another one with similar connections working fine now, but I still don't understand why this device is failing.
I have three theories.  1) The defaults were set wrong in this device and got changed back on reset, 2) or the voltages levels were not working.or 3) I have a bad wire...

Here is the current dialog:
HC-05 BlueTooth Programmer

AT test           a. Set Device Name (a,name)
Version           b. Set Role (b,0)
Address           c. Set Password (c,1234)
Name              d. Set UART (d,Baud,Stop,Parity)
Role              m. Display this menu
UART
State
Password
Device Reset

Blue is what I typed:
1
OK
2
OK
+VERSION:2.0-20100601
3
OK
+ADDR:98d3:31:fb1d15
4
OK
+NAME:t
5
OK
+ROLE:0
6
OK
+UART:38400,0,0
7
OK
+STATE:INITIALIZED
8
OK
+PSWD:1234
OK
a,DAN_ROBOT_1
OK
4
+NAME:DAN_ROBOT_1
OK

are setting the serial monitor to 38400 baud? it s the default speed of AT mode

Strange char in serial monitor cames in 90% of the case from a difference in speed between the Arduino and the Serial Monitor.
In order to have a correct display Arduino (so Serial.begin), Serial Monitor and the HC have to use the same speed. I think as other replied, default speed is 38400.
But, TAKE CARE: as soon as yo change the speed (eg if you change it to 9600), you have to change it on the Arduino and Serial Monitor.

If you use software serial for Bluetooth, you need to set the baud rate and the default baud rate of HC-05 is 38400.
You can change this baud to the desired with AT command.

This is a comment, not an answer.  May I suggest that you flesh out this answer to show exactly how to do these things?

Try setting your baud at 38400. Connect Tx->Tx & Rx->Rx when configuring your module. Tx->Rx & Rx->Tx during execution.

Why do you need to swap the connections over?

I think WaldoK is confused by the fact that, if you connect something on TX/RX on the Arduino, you can't upload the sketch. So maybe he thinks he has to swap the connections when in fact he just need to disconnect while uploading.

Is there a simple transistor circuit I can hookup to shift the levels back to 0 to 5 volts from the 0 to 3.3 volts?

Yes there are level shifting circuits you can use, resistor dividers and all that stuff, but you will be better off using a proper level shifting circuit, something like this:
Level Shifter
I believe there is something to do with the speed of switching between high and low and getting crisp rise and falls of the signal.

Set Baud rate to 38400 in serial monitor.
If you have Arduino UNO with removable Atmega328p - then remove the chip and connect TX of HC05 to TX of Arduino and RX to RX.
Most of the HC05 works perfectly with 5V system (I have one here hooked up to 5V and RX,TX connected directly ( without level shifter) but it's not recommended.

If you are indeed receiving something after the AT command, that means you have the baudrate wrong. Change it from the serial monitor to 38400 or something else.

My experience with these units...

BAUD rate varies so try them all.
Some expect chars in caps and some don't care
Some expect a question mark after the command and some don't e.g AT?
Some require CR and some don't.
Some only stay in AT mode for a second on boot and thus I found I had to set it up in steps, e.g write program to set PIN, then another to set NAME and so on..

Reason for this is that many clones do not have full software and commands installed.


text:
Arduino water pump not working and beeping
I’m new to Arduino and am trying to build a plant watering system without much knowledge on the subject. But my water pump is not working as I expected it to.
I wanted to keep it simple so I bought a Arduino Motor Shield for my Arduino Uno R3. I’m using a motor rated at 3-9V (motor is shown below), I’ve tried two different DC adaptors plugged into the power supply port on the arduino, 12V 1.5A and 12V 2A, even though the motor is rated at 9V, I’ve read that I need a 12V adapter to power the motor shield.
http://www.mabuchi-motor.co.jp/cgi-bin/catalog/e_catalog.cgi?CAT_ID=rs_360sh
The first problem is If I run the motor at full speed, analogWrite(3, 255), it sounds like its going to explode, so I’m trying to run it at a lower speed. But If use values anywhere below 170 the motor will not run and will only make a beeping sound.
Secondly, regardless of the PWM value I run the motor at, the chip gets very hot very quickly.
My question is, why can’t I run the pump at lower PWM values, and why is it getting so hot?
If I bought a 12V water pump and used the same setup, would I not have any of these problems?
EDIT:
an update...
it seems to basically work now. i have a feeling it wasn't working great because I was previously using a powerbar
It will run on max power PWM(255) for about a minute, and then stop working, which is okay. It will stop and then the motor shield lights will start blinking. Does anybody have any guesses what is happening? The motorshield chip is a little hot, so overheating is a possibility. Or is there not enough current ?
video
https://www.youtube.com/watch?v=xdxf3f_Svqs
void setup() {

//  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin
}

void loop(){
  //forward @ full speed, A
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 170);   //Spins the motor on Channel A at a speed. approx 90 is min

  delay(3000);

  digitalWrite(9, HIGH); //Engage the Brake for Channel A

  delay(1000);

}

I’ve read that I need a 12V adapter to power the motor shield. That's incorrect; the product page says 5V to 12V.

the chip gets very hot very quickly - which chip?

Would that be the voltage regulator chip by any chance?

@NickGammon it is the main L298P chip

Of course it sounds like it's going to explode if you're powering a 9V motor with 12V. This could cause a much greater current draw than you would expect as the relationship between voltage and current is unlikely to be linear once you go out of the manufacturer's specifications, which is why the driver gets hot.

@CharlieHanson okay that makes sense, i kind of ignored that. Is there a way I can limit the voltage to my motor, like a sort of resistor before my motor

Yes you can use a resistor, but that will get hot instead. The 'unrequired' energy that is supplied by the power supply has to go somewhere - either as heat in the driver or heat in a voltage-limiting resistor. Your best solution is to change to a 9V supply.

Regarding your motor just making high pitched noise (beeping) I would say that you are not supplying enough power to your motor for it to pull in the load and get rotating, you might try to first get it started by a higher power setting (PWM) and then when it's running see how far down you can set it before it stalls (stops).
I don't belive a 12V pump would work any different.
As to the motor and L298 chip getting hot, this is sort of normal and in some cases would require som way of dissipating this heat. A heatsink might be an option.
If you were to overheat the L298 it will shut down before being destroyed (it should).

Okay thanks, does that mean I should supply more voltage or current ? It just seems strange considering the water pump is rated at 3-9V

Neither, By power you have to take into considerment that you are using PWM. That means that if your motor at 12V would draw lets say for ease of calculation 1A at 100% pwm it would draw 12W (Watt) by lowering your PWM ratio to 50%, your motor will still draw 1A at 12V but only half the time.

The motor runs smoothly and reliably when I connect it straight into the VIN pin using a 9V adapter. But when I drive it through the motor shield problems occur.
Ideally I would want to drive the motor shield/motor with a 9V power adapter so that I can run the motor at max PWM (255), but there isn't enough power if I do that because the motor shield also needs power.

I thought to myself, maybe I'll just run the motor at max power (12V) for the project, I don't need it to be on that long so it's ok. But as I was trying to test that out, the motor stopped responding, the lights on motor shield were blinking and I could hear a ticking sound.
So…… is there any solution to this apparent "electrical noise" ?

Check voltages at 100%, you might have burned the motor.

@HansNever no it's not burnt, it just stops responding after about a minute. if i wait 10 minutes, the motor will run for another minute and then stop


text:
Using Lua in Arduino project
I want to write code for my Arduino in Lua. Where I can find the necessary (pins) I/O lib and examples for Arduino IDE?
UPD: I've got arduino mega with many memory.

You want to code in Lua? And have that code run on the Arduino? Which Arduino do you have in mind?

@NickGammon , that's true, I want to write program for arduino uno.

@NickGammon: ok, now I've got an arduino mega.

It looks like the ESP8266 runs Lua, but I haven't seen it running on an Arduino.

Lua is an interpreted language. That is, the compile phase turns Lua source code into intermediate "pseudo-code" which the Lua interpreter then runs. It doesn't compile into machine code, and therefore there is nothing that could be uploaded to your Uno as a "hex" file.
In any case, with only 2 KB of RAM, it wouldn't be very practical to attempt to run Lua on a Uno. I like Lua personally, but running it on the (AVR) Arduinos just isn't practical.

Lua is a language (a spec of syntax and semantics). Its most widespread implementation is an interpreter, but there is nothing in the Lua language that prevents one from writing a compiler that emits Arduino code (or any other code). I find it actually unexpected that no one has made it yet.

AFAIK, Arduino IDE supports C++ only. You can use other languages to communicate with Arduino from your PC. Take a look at Firmata.

An enterprising person might cross compile Lau to C++ ... Once upon a time our AT&T C++ compiler only emmitted C and the cc command turned that into object coed.


text:
SIM800L project not working
I got a SIM800L, same as the one under this link, Quickstart SIM800 (SIM800L) With Arduino, and played around with an Arduino Nano and Uno. I had a few problems, at the start, not getting it work properly. It turned out that my Nano 5V pin wasn't enough for the SIM unit. It works fine with Uno though.
There is the code I tested the GSM (same link) and got it working somehow, I got simple AT commands and managed to send an SMS. But after I dismantled the connections and the next day I tried again... Nothing. I can see the SIM unit connects to network as the LED blinking slows down to once every 3 seconds but when I type commands in nothing happens in the serial monitor. It doesn't give errors or anything, just nothing happens on the serial monitor.
I did wire it incorrectly, once with the Tx/Rx, but that shouldn't damage the unit, should it?
I tried to upload different programs to my Arduino and they work fine so that shouldn't be the problem. Is there a way to reset the SIM800 unit? Or am I missing something here?

If you turn around the Rx and Tx pins, nothing would be damaged. Try connecting a "USB to serial TTL cable" directly, so you can speak from with terminal from PC (USB) to the device directly.

These modules cannot tolerate a 5v supply.  It is theoretically possible for a carrier board to have a 5v to 4.2v regulator, but there is no indication of the existence of one at your link.   the LM317 mentioned there is extremely unsuitable - insufficient current handling, and too high a dropout voltage.

It looks like it has a 5V pin right at the top left doesn't it?  Also kinda curious - what disqualifies the LM317 from candidacy?

The module needs a good 5v supplier as it might have a peak of 1A or 2A, when it registers to the network or connects to 3G.
You need to make sure that you share the ground between the power supplier and you use some 2 pins on your arduino to connect the GSM module.
Dont try to get a fast baudrate as software serial doesnt work, try with 9600 to start then see if it response to the AT command.
SIM800 is a very simple module, try with an FTDI in case you want to make sure you didnt break your Arduino.
For more help, share your schematic how you have connected the arduino.

While you are correct about the high current requirement, the device cannot tolerate a 5v supply unless there is an appropriate regulator somewhere in the system, which would be less than trivial to select (the link's mention of an LM317 is entirely unsuitable)

Isn't he using a breakout board which has an onboard regulator?

I have put in a lot of time with the SIM808, and I always have trouble delivering enough power to it.  Note that the SIM808 will alert you with an "undervoltage warning" sometimes as a response to AT commands.  I bet the SIM800 would do the same.
As Max above is alluding to - try powering the SIM800L via a separate 5V 2A adapter.  When doing this don't forget to still hook up ground between the Uno and your SIM800L board.
If you accidentally hooked 5V to the VDD pin on your module, you may have damaged it.
FTDI is a tool every embedded dev should have.  Get a few!

Keep in mind that the SIM800/808 cannot tolerate a 5v supply - you hint at this, but it's not clear what regulator you imagine would provide an appropriate connection to such a supply.

You're right.  I didn't make it clear - I am using a FONA 808 shield module which is designed to plug in to an Uno 5V directly

The FONA shield accepts a 5v input, yes, but it is to recharge the required lithium cell.  It is actually the cell rather tha the input which provides the peak power required by the module.  That means that a high current 5v supply is not really required, nor even likely to be taken advantage of, since the charge current is set for a relatively small cell.


text:
RS485: is "Y" multidrop allowed?
I imagine that the proper way to implement an RS485 multidrop bus is the following:

What happens if, in order to save cables, I connect the same 5 nodes above using this other topology?

Will it works?
If no, why?
If "maybe", under which circumstances will it work?

P.S.: yes! I know that MEGA has three Serials and, as such, I could implement two different BUSses (1: Mega<->Mega<->Mega; 2: Mega<->Nano<->Nano), but this will increase the complexity of the software I'm running, as it needs some hacking in order to play nicely with two distinct RS-485 busses;
P.P.S.: This is the bus discussed in this other question

At low speeds and short distances that won't be a problem.
At high speeds (megabits per second) and long distances (hundreds of meters) you may get reflections unless you get the termination just right.

Can you please tell values you think is reasonable to call "short distance" and "low speed" in this context?

@Bacco tens of meters and 115200 baud, I'd call short distance and low speed.

Thanks for your feedback!


text:
Multiplexing potentiometers
Is it possible to have two rotary potentiometers read from a single analog input pin?
The analog input is 10 bits (0-1023), so each pot would have 5 bit precision (0-15).
Least significant bits for pot 1 and most significant bits for pot 2.
A SPI/I2C ADC IC (eg. MCP3008) is an option if this is not possible.
Edit:
The two pots do not need to be read at the same time.
It seems full 10 bit precision could be achieved if I use a digital pin to enable each pot before it is read.

There are a few ways of doing what you want.  One would be to use an analog multiplexer as in this answer: Expanding analog inputs to the Arduino
Another would be to use digital I/O pins to control the power and ground to the potentiometers.  Note that both sides of the pot need to be controlled, not just one, since any connection of one will interfere with the other.
So you will need four IO pins - one for the +5v and one for the GND of each potentiometer.

In this example set D3 to OUTPUT and HIGH, D4 to OUTPUT and LOW, and D5 and D6 both to INPUT.  You will now be reading from the top pot.
Then change D3 and D4 to both be INPUT, and D5 to be OUTPUT and HIGH and D6 to be OUTPUT and LOW.  You will then be reading from the bottom pot.
A bit wasteful of IO pins though.

This is great, and I don't think it's really wasteful of IO pins when you consider that the alternative is adding in a multiplexer which is a bit overkill for cases like this.

Building on @Majenko's answer, I think you could do the same thing, using 1 analog pin (as shown in his answer) and one digital pin.
Rather than using one digital pin for each side of the each pot, you could use one transistor for each side of each pot, and then use one digital pin to switch all 4 transistors on/off at the same time, in the right combination.

It could be done, yes. It's a choice between lots of components or lots of IO pins. If you're going in the lots of components direction you may as well go for an analog MUX and get lots more channels to play with anyway.