text:
safety for power electronics
I'm quite new to Arduino. I have build a number of projects successfully, like potentiometers, serial communication, DAC, sensors, motors etc.
I use a laptop to power my Arduino project and Atmel Studio to program and upload to the Arduino. I have created a project with 2 motors and I have successfully used a separate power supply (a transformer) to power the motors.
Now I want to continue my experiments but I'm afraid of the possibility to cause any problem to my laptop.
When I made the circuit with the 2 power sources (laptop for the Arduino, transformer for the motors) I had to connect the 2 grounds together.
So my question is that:
Can someone explain me or point me to some information about power electronics so to be absolutely sure that I won't cause any problem to the laptop?
Should I use optocouplers, or diodes etc? Is there a way to avoid the 2 grounds connection? What is the reason to connect both grounds (of the 2 power supplies) in the first place?

Connecting the grounds together is required since without that there would be no circuit for the current to flow through.  Take this simple block diagram for instance:

In the top diagram there are two complete circuits - the green one (Arduino's 5V power) and the blue one (device's 12V power).  The communication between the Arduino and the Device can't happen because there is no circuit (red).
In the bottom diagram the red circuit has been completed by joining the grounds together.  That means that the current has some way to get back to where it came from (which current always has to do) so the signals you send can actually get through.
To avoid having to connect the grounds together you need something called Galvanic Isolation.  This involves using some method that is not electricity to connect the two circuits together.  That could be using light in the form of an opto-coupler, or magnetism in the form of a transformer, or even something even more physical like a relay.  In that situation you have an arrangement like this:

The ground connection that was part of the red circuit above has now been sliced in half (red and orange now) and the isolation device is responsible for passing the signal from one side to the other.
Galvanic isolation is highly desirable when:

You are controlling a different type of current (e.g., using DC to switch AC)
You are working with voltages considerably higher than your drive voltage (e.g., switching mains)
You have different ground potentials (e.g., you have a long distance connection)

Galvanic isolation is also useful for long cable runs. For example, MIDI uses optocouplers. With a long cable, you might get earth loops.

@NickGammon Isn't that what point 3 in my answer says?

Oh yeah, sorry. Well I'll let it stand because it mentions MIDI. I didn't quite pick up "long distance connection" as "long cable run". Plus I threw in the "earth loops" keywords. :)

@NickGammon Can't hurt ;)


text:
Can we connect 4 4-digit 7 segment LED Displays to a single Arduino board?
Can we connect 4 4-digit 7 segment LED Displays to a single Arduino board ? Is it possible without another component in between ?

There is an awfull lot to find about this on the internet... I suggest you check it out first. Try searching for IO extenders, shift registers etc. You'll find a lot of theory explained in led cube tutorials also. As @victor said, you're going to need a lot of pins if you don't use another component. So you'll be better off using external components.

Actually, this is dependent on the datasheet. Assuming it's 7 segment + dot, it will require 8 independent pins to control each of the segment. All of segments are connected to a common anode/cathode which can be connected to a pullup/pulldown.
If we have 4 digit, that means we need 4*8=32 pins, which is a lot for any microcontroller. However, if you map out the internal circuit, you'll find that the segments are multiplexed. (You can do this by touching the pins with a wire connected to a pullup resistor, and another wire connected to ground.
Generally, you'll find that all the segment pins are multiplexed together in such a way that if all anodes/cathodes are enabled, all of the digits show the same display.
So how then can we make use of this information? Here's an idea:
How about turning on each of the digits one at a time (by controlling the common anode/cathode), but doing it quickly?
An example sequence would be as follows:
Set the segments for digit 1, enable the corresponding common anode/cathode for 5ms. Turn off.
Set the segments for digit 2, enable the corresponding common anode/cathode for 5ms. Turn off.
Do the same for digit 3 and then 4.
Repeat.
Controlling in this manner means you only need 8+4 pins=12 which is available on an arduino uno. Refreshing at 4*5=20ms will hardly be visible to our human perception, thanks to persistence of vision.
My answer is really just a starting point. If you spend some time, you can try to put in other smarts which are suited for your application, using even less pins. You should try this as an exercise. ;-)
Edit:
As a precaution, it's important to limit the current running through each of the LED segments so that they can live a long and happy life.
Assuming a forward voltage of 2V, adding a 1k resistor at the common anode limits the current to 3mA. This means adding resistors for all 4 anodes.
The same could work for common cathode displays, as long as the reverse breakdown voltage is not exceeded.
As with all things you find on the net, don't take my word for it. You should do the maths to check.

You need 4*4+7 = 23 pins in common cathode configuration or 4 +7*4 = 32 in common anode and arduino uno only have 20 output/input pins so if you don't want to use any external component you are going to need an Arduino mega.
Anyway, the best idea is to use a max7219 matrix led driver. look for it in google.

You could charlie-plex it.. that would dramatically reduce pins but would require more components than just the displays and arduino.

source: Stack Exchange

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

sort: votes


text:
Arduino: how can I stop while() when bluetooth send a data?
I have learned Arduino for a month, and I want to bulid a car with 2 modes,
Remote and Auto. Auto mode needs to have while() loop, so it can receive data from sensors. When I choose Auto mode via bluetooth, it keeps looping and it won't stop when I choose the Remote mode. Here's the part code:
char mode;

void loop()
{
    while(serial1.available())
    {
        char control = serial.read();
        if(control == 'r') mode = 'r';     // r stand for Remote Mode
        if(control == 'a') mode = 'a';     // a stand for Auto Mode

        if(mode == 'r') remoteMode(control);

        while(mode = 'a')
        {
            int IR = analogRead(A10);
            float U1cmMsec,U2cmMsec;
            long U1microsec = u1.timing();
            long U2microsec = u2.timing();
            U1cmMsec = u1.convert(U1microsec, Ultrasonic::CM);
            U2cmMsec = u2.convert(U2microsec, Ultrasonic::CM);

            robot(U1cmMsec, U2cmMsec,IR);

            /*
            Here is the code to stop while() that I don't know how
            to program.
            I have tried:

            if(serial1.read() != 'a') break;

            But it will stop while(), because it will waits for
            bluetooth send data to arduino board.
            And if I take this line off, it will keeps while() and
            nothing can stop it.
            So, what am I supposed to do?
            */
        }
    }
}

Your problem is with this line:
while(mode = 'a') {

What you are saying there is not what you think you are saying.  You are confusing = (assignment) with == (comparison).
You are basically saying "While I assign 'a' to the variable 'mode' and 'a' is not 0 ...", which of course will always be true.
Instead you want:
while (mode == 'a') {

or, "While the variable 'mode' contains the letter 'a' ..."
Now you just need to program in some way of changing the value of mode within your while loop.
You can read more on while loops here:

http://hacking.majenko.co.uk/the-while-loop

The while(serial1.available()) can be turned into an if: the loop function is already executed in a loop, as the name hints :-)
And unnest the inner while.
here it is at high level, which is probably easier to understand:

void loop() {
  static char mode; /*notice the "static"*/
  if (character_available())
    update_mode();
  if (mode == 'r')
    do_one_iteration_in_remote_mode();
  else if (mode == 'a')
    do_one_iteration_in_auto_mode();
}

Just make sure that you do not loop inside neither do_one_iteration_in_remote_mode() nor do_one_iteration_in_auto_mode().

I have replaced both 'mode' and 'control' (they were identical) with a single variable, btChar. At the end of setup(), wait for a transmission to be received before entering the main loop.
Once the main loop begins, a while loop executes until the serial receives a new transmission. Once it is received it is read, btChar is updated and the main loop starts again.
char btChar;

void setup()
{
/* AT THE END OF SETUP() */

// Wait in setup for first BT transmission

    while (!serial1.available())
    { /* do nothing */ }
    btChar = serial1.read();
}

void loop()
{
    while(!serial1.available())
    {
    // Program will stay in this 'while' loop until
    //    a new BT character is recv'd

        switch(btChar)
        {
            case('a'):
            {
            // do the 'auto' stuff
                break;
            }
            case('r'):
            {
            // do the 'remote' stuff
                break;
            }
            default: // this 'block' is not essential
            {
            // you end up here if neither 'a' nor 'r' was received
            }
        }
    }
    btChar = serial1.read();
}

You can adapt the setup while-loop further to make sure that the main loop doesn't begin until the a correct character is received - change the line to:
while ((!serial1.available())&&(btChar != 'a')&&(btChar != 'r'))

Using a switch-case statement within the main while-loop is not essential, and I included it out of interest more than necessity. You can use if statements instead, with one for 'a' and one for 'r'. However, in the event that you have a third or fourth (or more-th) mode then a switch-case statement, in my view, looks easier to read.

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


text:
Arduino with 12 bit DAC (MCP4725) Not Working
I have an Arduino Mega AT2560 and need to have real DAC. I purchased the Sparkfun 12 bit DAC, however I don't think it is working properly.
I am using the Arduino wire library to communicate with the DAC. When I write 0, I am expecting to see 0v from the DAC's OUT pin. However, I see some seemingly random constant voltage. In reverse, when I write 4095 to the DAC I see the same voltage as when I write 0. I expected to see 5v.

Can someone verify that I hooked it up correctly?
Can someone verify the code I am using?

#include <stdint.h>
#include <stdio.h>
#include <Wire.h>

#define MCP4725_ADDR 0x60 // [0000 0110]
/*
* 12 Bit DAC MCP4725 gives a range of 4096 possible values.
*
*/
void setup() {
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(MCP4725_ADDR);
  Wire.write(64);            // cmd to update the DAC [0100 0000]
  Wire.write(4095 >> 4);        // the 8 most significant bits...
  Wire.write((4095 & 15) << 4); // the 4 least significant bits...
  Wire.endTransmission();
}

Full scale should be 4095, not 4096.  In hex, 4095 id 0x0FFF, and 4096 is 0x1000.  You do have a range of 4096 possible values, from 0 to 4095.

I updated the code and tried with 4095 and still am not getting 5v.

Why are you left-shifting in the third "write" line? Does your communication protocol communicate in 4-bit chunks or 8-bit chunks?

I am using basically the same operations from the Sparkfun example: https://learn.sparkfun.com/tutorials/mcp4725-digital-to-analog-converter-hookup-guide?_ga=1.73644763.897386268.1444309037

The system uses 8 bit bytes of data.

Sorry I'm late -- I realize this question was asked 8 months ago, but it doesn't look like you fixed it, and I figure others can always benefit (or you might even, if you still want to try).
Your code looks correct (I compared it to the Sparkfun example, and also to the datasheet for the MPC4725).
However, it does look like you're using the wrong address for the part.
(The actual value for the address is not given in the Sparkfun example -- at least, I couldn't find it).
Your line:
#define MCP4725_ADDR 0x60 // [0000 0110]

is wrong in two places:
1) 0x60 is 0110 0000, not 0000 0110
2) According to the datasheet (section 7.2), the address should begin with the device code %1100, and then the address gets appended. So assuming an address of A2 = 0, A1 = 0, and A0 = 0 (default), the value for MCP4725_ADDR looks like it should be 0xC0 or %1100 000x.  If you soldered the address line to Vcc instead of ground, the address should be 0xC2 or %1100 001x.
The x in the address line represents the read/write bit.  If you're trying to command the DAC, it should not be asserted, so the addresses above are correct. If you're trying to read the current value, it should be asserted, which makes your address 0xC1 or 0xC3.
If you have the address wrong, even though the rest is correct, the part will ignore it, so that's probably the issue you're seeing.
Hope this helps someone!

SparkFun's example at https://learn.sparkfun.com/tutorials/mcp4725-digital-to-analog-converter-hookup-guide says: #define MCP4725_ADDR 0x60  //For devices with A0 pulled HIGH, use 0x61 and the same page says "we’ve broken out the address selection pin (A0) to a jumper pad. By default, this pin is pulled LOW to GND" so that indicates 0x60 is correct.

Remember that the (usual) I2C address is composed by a 7 bit identifier and one bit which indicates whether the master is asking for a write or a read operation. The 7-bit address is 0x60; the byte sent on the bus will be 0xC0 or 0xC1, depending on the operation. Arduino's function expects the 7-bit address and the datasheet provides the byte to be transmitted..

you want to make sure that there are pull-ups on the SCL/SDA lines;
you want to make sure that the address is correct. some routines use 7-bit notation for that, and others use 8-bit notation for that. end of the day, you want the transmission to be 0xc0 | (A2:A1:A0:R/W). so check the write.write() and see what it expects. I suspect that it expects 0xCx, rather than 0x6x.

having said that, here is your code running on an uno, with the dac configured as per sparkfun spec.

so I think it is fair to say that the code is ok but something happened on your end that prevented it from working.


text:
How to change the usb name of Atmel 32u4?
I want to change my Arduino Leonardo's name that Windows shows me when it's plugged in.
I know that i have to change its firmware to change the name but I cant find firmware for it on the Internet.
On Arduino Mega, I have changed it with a downloaded firmware via flip, but I can't change the file because it's a .hex.

you can change the hex, if you're brave enough

Start looking here for the actual implementation https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/caterina/Descriptors.c and at the Makefile for a start towards building from source.  You may be able to modify the .hex (the strings appear to be fixed length and padded with spaces) but will need a tool which fixes the checksums - possibly you can objcopy to a flat binary and back to hex.

The Arduino '32U4 bootloader, Caterina, can be found under hardware/arduino/bootloaders/caterina. It requires LUFA in order to build.
With the technical part aside, note that you are not allowed to use the USB IDs assigned to Arduino LLC with products you intend to distribute under another name. You will need to acquire your own vendor ID from the USB-IF if you want to do so.


text:
What type of sensor could I use to determine the mass of a small object (under 1 kg)?
I'm building a robot that needs to pick up a piece of material and then determine its mass. My robot will retrieve the material using a scoop at the ended of a mechanized arm. Once the material is in the scoop, the arm will tilt upwards until the material slides down the arm and into the chassis.
I hope to weigh the material while its in the chassis, but I'm not sure how to do this. I've found that load sensors are useful for taking masses, but I'm not clear on how they're implemented. For example, I've found load beam cells, but how would I implement one in my design? Does it require a metal plate of some sort (like a weighing pan) on top of it like a laboratory scale? The sensor must be able to communicate with an Arduino.
My robot needs to be under 6 lbs and have a footprint of 35 x 35 cm. Thanks!

The problem is that there are cheap kitchen scales with obscure electrical output decoded and compensated in specialized circuitry you would need to re-engineer from scratch and then there are expensive load cells and sensors with documented output.  An intermediate might be a USB postage scale, at some price premium and probably suggesting something more than an Arduino to host it.

Just a little brainstorming:
If you have a spring, then you can easily calculate the physical force (mass) needed to stretch the spring to a certain extent. The law is called:
 Hookes's Law
 - you could then just measure the increase in distance between the initial position and the position with load. Use a servo or any distance measure.

I wouldn't really use a servo as a distance measure?
You could use any distance sensor below it or a potentiometer that will turn based on the position of your weighing pan.

Servo for the angle though. I was thinking faster, than I typed. But yes a potentiometer does the trick as well.

I like the distance sensor and potentiometer ideas. Could you please elaborate on the pontentiometer idea? How would I rig one up to turn based on the position of the weighing pan?

it depends on how your weighting pan is linked to the robot. if you have a schematic drawing, I could wrap my mind round it.

A load beam cell would be good.  Put it as one leg of your robot, and calibrate it with the arm in a particular location dangling over the cell.   You'd need the beam load cell, and an instrumentation op amp, or HX711 (https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide) to do the interfacing.
Also good would be the cells from a bathroom scale as the four feet -- you could hook them up like https://electronics.stackexchange.com/a/199907/30711 or https://electronics.stackexchange.com/a/199470/30711
One thing cool about using the robot feet for measurement is that you could calibrate for more sensitive measurements while reaching far from the base, and rougher measurements closer.  You could also calculate how far you could reach without toppling over.


text:
How to program an offbrand arduino uno?
So I recently bought this off brand arduino uno from betemcu.cn.
it says its r3 compatible.
Can I program this thing with the arduino coder or do I need to use something else? whenever I try uploading the code it says "problem uploading to board"
what settings or program should I use to code this?

Ask betemcu.cn for docs?

You installed the serial driver, right?

Try uploading program using ICSP.!

Have you tried changing the type of board in the Arduino interface ? For your board I would try the Arduino Uno setting. Also check that the correct serial port is selected (yes I know you connect via USB, it's a virtual COM port I'm talking about).

The issue is probably that you need a driver for the onboard CH340G USB-to-serial bridge.
The Baite Electronics Arduino clones are generally of good quality and work well.
There are some differences between them and Arduino-brand Arduinos. Two notable ones are a different voltage regulator and (probably the issue here) a different USB-to-serial bridge IC.  The Arduino brand products use an FTDI IC and Baite uses, in this case, the CH340 USB bridge IC.
The product is described on this webpage and you will see that they say

UNO MEGA328P CH340G for Arduino Compatible

The CH340G relates to the USB interface IC.
Until about a year ago the USB driver in windows worked with most common USB ICs as well as with FTDI ICs.  However, FTDI changed their system so that the Windows driver will now only work with FTDI brand ICs. So it is now necessary to load a driver into the PC (whether Windows, Linux or other O/S) to suit the CH340.
If you email them Baite will provide a link to the CH340 driver, but they do not usually provide it on their website (reason unknown to me.)
Or, you can obtain a driver from numerous websites.
A web search on eg:  driver ch340 baite arduino
turns up many pages.   How good or how safe any of these is is TBD.
This page claims to provide a Windows 7 CH340G driver and install instructions
This YouTube video describes how to install a driver and provides a link to this page which lists a number of drivers.
This page discusses the issue

betemcu.cn/Baite (is there a difference?) should pay you for offering support on their products!

@RespawnedFluff I know you've heard me say it before but, for others: I have no relationship with Baite except as a satisfied customer. I've bought a few orders from them - maybe $200 overall more or less. I've been happy with the product, the price and the responsiveness. Their documentation is essentially nonexistent - which seems strange considering how easy it would be to provide basic data. Even the driver non provision is strange - they will provide (afair) a temporary link if you ask (which I did at one stage). I have heard various tales about Arduino clones which work poorly  ....

.... or not at all or are of generally low quality or poorly made. Anything I've bought from them (that has actually got used :-) ) has worked as expected. Others' experiences with them may be different and I have no involvement whatsoever in their dealings with anyone except me.

@RespawnedFluff Re Baite/Bete - the photos that Corey supplied seem to be an essentially exact match for the ones on their website and the PCB silkscreen contains both Baite as a company name and betemcu.cn as a website. So one and the same it seems.

Re: "I know you've heard me say it before". Actually, I haven't. And I didn't mean to sound like you were dishonest, hiding something, or anything remotely dubious like that. I'm sorry if I came across that way, and I probably did given the length of your reply. Cheers.

@RespawnedFluff No - no problem - I just talk too much :-). You raised a valid point which I thought was worth addressing for others. I usually add some sort of disclaimer in such posts but didn't do soon that occasion - my bad.

Just install your driver. Some might install automatically. Then try to upload the sketch using arduino IDE.


text:
PC <-> Xbee <-> Another Xbee Communication
I have this application where I want to send commands from the PC to an Arduino, remotely, and receive an answer back.
The hardware configuration I'm using to achieve that is the following:
PC <--> Arduino with an Xbee <--> Another Arduino with another Xbee

It's just half-duplex communication. Everything seems easy, but there is a problem.
Each Arduino has an Xbee Shield with an Xbee module connected to it.
Reading the documentation of the ArduinoXbeeShield, an excerpt caught my eye:
"With the jumpers in the Xbee position (i.e. on the two pins towards theinterior of the board), the DOUT pin of the Xbee module is connected to the RX pin of the microcontroller; and DIN is connected to TX. Note that the RX and TX pins of the microcontroller are still connected to the TX and RX pins (respectively) of the FTDI chip - data sent from the microcontroller will be transmitted to the computer via USB as well as being sent wirelessly by the Xbee module. The microcontroller, however, will only be able to receive data from the Xbee module, not over USB from the computer.
With the jumpers in the USB position (i.e. on the two pins nearest the edge of the board), the DOUT pin the Xbee module is connected to the RX pin of the FTDI chip, and DIN on the Xbee module is connected to the TX pin of the FTDI chip. This means that the Xbee module can communicate directly with the computer - however, this only works if the microcontroller has been removed from the Arduino board. If the microcontroller is left in the Arduino board, it will be able to talk to the computer normally via USB, but neither the computer nor the microcontroller will be able to talk to the Xbee module."
That means I will not be able to build what I want with this configuration?
I already tried, but didn't work.

Basically with your shield you have two options:

Communicate between the MCU and the XBee at the cost of not being able to communicate between the PC and the MCU.
Communicate between the PC and the XBee at the cost of having to remove the MCU from the board completely.

Neither of which are particularly ideal.  The first option is completely out since that rules out all PC communication.  The second option turns the Arduino into just a USB->TTL Serial adapter - and a rather expensive one at that (you can get them on eBay for like $2).
What you want is to re-wire the system using jumper wires (messy, I know) so that the TX and RX pins of the XBee connect to other pins on your Uno then use SoftwareSerial to communicate with the XBee.  That will leave the Arduino's TX and RX pins free for communicating with the PC.
Alternatively invest in a different Arduino that has more hardware UART interfaces, like a Mega2560.

With Mega I solve the problem completely?

@stdio.h With a Mega you can manually wire the XBee to a different pair of UART pins instead of 0 and 1.  That way you can communicate between the MCU and PC and the MCU and XBee.


text:
Error in my Arduino code " error: expected unqualified-id before ‘if’ "
I cant seem to find this error is:
elevator_bug_2.ino:38:1: error: expected unqualified-id before ‘if’

Here is the code:
// these constants won't change. They are the
// lowest and highest readings you get from your sensor:
const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 600;    // sensor maximum, discovered through experiment

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the sensor:
  int sensorReading = analogRead(A0);
  // map the sensor range to a range of four options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // do something different depending on the
  // range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability
}

if (Serial.println("dark") == true)   // LINE 38
{

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}
}

Check where the function loop() ends. Seems likes there is a } too many or a function declaration is missing.

C is procedural language and code is compiled. You cannot put code beyond procedure as you try to do in mentioned if. Remaining code following this point is nonsense. Do you mean you can put second loop() based on if condition ? I recommend to start learning programming C before using Arduino. In C you can do such a idea using preprocessor directives IF, ELSE, ENDIF.

As Tma mentioned earlier, C is a procedural language. That means that all the code must be part of a defined function. So in your code you have the functions void loop() and void setup(). Wich are two functions you must always have in an arduino sketch, but you can also define others. What you cannot do is having two functions with the same name and type in C like you have there, because there is no way to tell them apart from each other. You have two functions called loop and setup...
One basic thing about Arduino code that you must know is the way it runs your code. Every arduinos sketch must have a setup and a loop function. Then when you start the program, it wil first execute the code in your setup function ONCE and then start at your loop function. The name of the loop function already indicates that it will LOOP all the code inside it, so when your program reaches the end of loop() is starts again at the top of loop(). Your program will never reach any point below loop, because you need to specifically call a function to redirect your program to another point. I think the best way to learn Arduino is to study some C first.


text:
Arduino Bootloader availability
When I look at arduino and arduino-like boards featuring ATMEGA328 chip, I see that they either use a micro controller or a FTDI chip to program the ATMEGA through Arduino board pin 0 and 1.
This only works because there is a bootloader available on the chip. Is the bootloader present by default or do I need to install it.
What I mean is can I just buy 10,000 ATMEGA328 from ATMEL, put them on boards and program them through UART or do I need to first flash them with a bootloader?

You can ask Atmel to pre-program chips if you're going to buy 10K of them.

@pjc50 Is it from experience? I have a doubt they will do that even for 10K, as it means setting up a process.

Some distributors of programmable ic's will program them for you... it does cost extra.

Not from experience, but http://www.atmel.com/images/atmel-42215-production-programming-of-atmel-microcontroller_ap-note_at06015.pdf / https://electronics.stackexchange.com/questions/38990/preprogrammed-atmel-microcontrollers

Just to be clear; the bootloader is not requires to upload or run code on the chip. It's just there, so you can program the chip using serial, instead of ISP (or OneWire or parallel).

The bootloader is the feature supplied with the Arduino board, but not a chip itself. If you want to clone Arduino (fully or partially), you will have to burn the bootloader yourself.

Is it possible to find the bootloader online, so that I can ask the contractor (the one that will manufacture the boards and put the CMS on them) to burn the bootloader at the same time?

The bootloader is supplied with the Arduino IDE. Also I believe you can find the files on their website (even the sources).


text:
Arduino read from Server periodically
I have an arduino attached with a RGB-Shield. I want to query my server for the RGB values periodically. I basically got it working using the Ethernet Shield but it takes too long to get the value (~500ms}. I really want to read the values from my server really really fast in an endless loop.
Can you give me any hints on how I can improve my code?
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192,168,1,151);
IPAddress ip(192, 168, 1, 177);
EthernetClient client;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Ethernet.begin(mac, ip);
  }

  delay(1000);

  if (client.connect(server, 80)) {
    client.println("GET /rgb.php HTTP/1.1");
    client.println("Host: 192.168.1.151");
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();

    ... read from Server

  }

  if (!client.connected()) {
    client.stop();
    if (client.connect(server, 80)) {
      client.println("GET /rgb.php HTTP/1.1");
      client.println("Host: 192.168.1.151");
      client.println("Connection: close");
      client.println();
    }
  }
}

you may use mqtt protocol, it support push notifications instead of polling and it's way lighter

Yeah I thought about that, but I could not imagine that push is faster than polling. Is it?

You could try with a direct TCP connection (in this way you skip the HTTP layer) but you need to prepare also a small TCP server (in any language comfortable to you) that accepts the client connection, sends the data, waits the ACK and close the connection.

I would start with this section:
if (client.connect(server, 80)) {
  client.println("GET /rgb.php HTTP/1.1");
  client.println("Host: 192.168.1.151");
  client.println("Connection: close");
  client.println();
}

How many messages does the Arduino Ethernet library send for this block? Actually due to the implementation of the Arduino Print and EthernetClient class it sends 7 messages (no joke!). It does not collect this into a single message/frame.
The first optimization is to print a single string and send that as one frame.
  #define CR "\r\n"

  client.print("GET /rgb.php HTTP/1.1" CR
               "Host: 192.168.1.151" CR
               "Connection: close" CR
               CR);

Cheers!

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


text:
Measuring acceleration in g's
I am using adxl335 accelerometer with Arduino uno r3 to measure acceleration due to gravity along x axis. I am using 50 ms delay and printing to serial.
I have two questions, which are;

Can I measure fractional values, like .8 in acceleration due to gravity?
when I shake the accelerometer up down along x axis, I don't see any variations in 'g'?

I am using analog pins and 3.3V power supply from Arduino to power the sensor.

If you read the datasheet you can quickly find that the output of the device is 300mV per g.  That means:

Read the analog value
Convert it to millivolts
Divide it by 300

The result is the g value.  If you do it using floating point then yes, you get fractions of a g resolution.
For instance:
float mv = analogRead(0) / 1023.0 * 5000.0;
float g = mv / 300.0;

If the analog channel has 1024 steps, that's 5/1024 = 0.0048828V per step, or 4.8828mV per step.  Divide that by 300 and you get a resolution of 0.01628g
As for not seeing variations in X when you shake up and down, maybe that is because you really want to look at the Z axis, not the X. X is left/right, Y is forward/backward and Z is up/down.  It's all in the datasheet - it makes for good reading, I suggest you take a look.

Thank you very much, it worked, I looked at the data sheet but it turned out to be that I was directly dividing the analogRead by 300. As for the variation in g it turns out that I wasn't shaking too hard and the code was wrong. Thanks again


text:
Converting ASCII value to String
I have this code.
String incoming;   // for incoming serial data

void setup() {
    Serial.begin(9600);  // opens serial port, sets data rate to 9600 bps
}

void loop() {

    // send data only when you receive data:
    if (Serial.available() > 0) {
            // read the incoming byte:
            incoming = Serial.read();
            String mysrr = String(incoming);
            // say what you got:
            Serial.print("I received: ");
            Serial.println(mysrr);
    }
}

A few of you will recognise this as an Arduino example.
However, when I run it ( I sent it the message "hi"), I get this in the serial:
I received: 104
I received: 105

Why is this happening?

Serial.read() returns an int not a String. https://www.arduino.cc/en/Serial/Read
Use an int for incoming (as the example). Or even better use a char and skip all the strings.
Cheers!


text:
avrdude: stk500_recv(): programmer is not responding + avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x47
So I'm following a beginners arduino book and I made a blinking program and now I've coded another program but when I try to upload it, avrdude(whatever that is) gives me the errors in the title and repeats them 10 times.
I have tried this so far:

Restarting my windows 8
Pressing the reset button on my arduino uno R3

My guess is that since it worked the first time, my blinking program must be clogging up the space in my arduino.How can I fix this problem. Or if my guess is right, how can I get the blinking program out of arduino and go home to my bots folder?
My IDE is arduino 1.6.7 and my port is CPU1. and lots of people mention tools>serial port but there isn't a "serial port" button on my IDE.

Since there are no accepted or up-voted answers to this rather old question I'm going to link to my post here about problems with uploading.

I had the same exact problem and fixed it, just by molding the two reset pins on the arduino together. Just check if they are properly connected as the error probably is caused by that.

If that doesn't work, check the LEDs on the board. When you are uploading a sketch both RX and TX should be lightning up.

There is a gap between my reset pins. How do I mold  them together?

Just search a little bit around Google.
A simple solution is pressing the restart button after the program is compiled, then, upload it.
Or restart the Arduino while the Arduino is uploading the program.
If the problem remains, try to burn again the bootloader of your arduino.

"Searching around a little bit arround on google" is not particularly helpful, as googling is probably what led the OP to SE in the first place! ;-) If you could provide a useful link or two (which you have done), along with a quoted summary of the info provided in each link (in the case of future link death) that would be great, or better still, if you have encountered this issue yourself, feel free to provide your own solution (which you also have done)... :-)

You're probably trying to connect through the wrong port.
I had this problem due to the mac suddenly making the /dev/cu.USB port option unavailable for selection through the arduino software interface under tools/port, and then not knowing what I was doing I just tried to connect through the wrong port and got this error.
After rebooted the mac, voila the /dev/cu.USB port option was suddenly available again under tools/port, we selected it and were able to successfully upload again.
I don't know why the mac or arduino software does this, my sense is that  something must get confused during upload sometimes, especially if you disconnect and reconnect the usb for some reasons, or turn on the 9v power on the arduino board while uploading.

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


text:
Link to an project for remotely turning off light switch?
I want to build a contraption using an arduino that allows me to turn off my light from across the room. I plan to use a solenoid to move the lights switch up and down. I'm sure I'll have some specific questions later on but to start with, has anybody made or seen a similar project? All I'm really looking for is a link to a project (unless you're willing to give advice/suggestions). Thanks!

Light switches are made with a variety of actuators. You will have to share what type you intend to control because that will impact the remote triggering mechanism. (I will show examples in an answer due to not being able to add pictures here).

Using a solenoid to control a manual switch is possible for sure, but very uncommon, so I guess you won't find references easily. A solenoid capable of moving switches may consume a lot of power, so most engineers will replace the combination switch/solenoid by a relay. Controlling a relay is a very common task, with many references available. But as a relay contains a solenoid, you may find helpful hits there, too [http://www.electroschematics.com/8975/arduino-control-relay/].

MicroBot Push: a robotic finger for your buttons...

https://www.indiegogo.com/projects/microbot-push-a-robotic-finger-for-your-buttons#/
The Robotoic Light Switch

http://hackaday.com/2015/11/06/the-robot-light-switch/
Wifi controlled light switch

https://hackaday.io/project/5141-wifi-controlled-light-switch

This isn't exactly what you asked for, but may be a better idea.
Light switches are electrically just switches.  Either two points are connected or they are not.  In this case they are meant to be mechanically actuated by humans.
Instead of making a electrically controlled contraption that mechanically activates the existing switch, you could more easily use a electrically-activated switch directly.  Such things are called relays, and are quite common and readily available.  You can easily get a relay that can be actuated from 5 V that can switch 120 or 240 Vac at a few amps.
Put the relay in parallel across the switch if you want the switch to be able to override the light on, and in series if you want the switch to be able to override the light off.
To allow both the relay and the switch to toggle the light on/off independently, each needs to be a SPDT (single pole double throw) switch or relay.  Actually, you'll have a hard time finding a relay that isn't at least SPDT.  Ordinary wall switches aren't, but ones meant for multiple switches to control the same light are, like you often find at the top and bottom of the same set of stairs.

I fully agree that this is a better idea and I considered it but decided to go with mechanical actuation for a few reasons. First, I want more experience with mechanical projects, not just electrical. But also I want my device to be easily removed or switched. Assuming the switch type is the same, I want to be able to move it to any random light switch and have it working in seconds. My goal is to create a mechanical one for now (something that just works) and in the future, design a better system like the one you suggested.

Various types of light switch actuators. Which is it?

I apologize, I should've been clear about that in my initial question. Pretty much all the switches I intend to use are the same and standard, corresponding to your first picture.

@JamesM. - Good to know. By the way, "standard" really does not apply because if it did there would be only one picture.


text:
Modbus master arduino code is throwing weird errors on upload
I am using the following https://code.google.com/p/simple-modbus/ arduino master library code. In order to communicate with my industrial drive.
All seems right but I am getting some weird errors. I am using the arduino master code as it is. With just the difference in modbus_construct.
Here is the error I am getting
 This report would have more information with
 "Show verbose output during compilation"

enabled in File > Preferences.
Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
In file included from SimpleModbusMasterArduino.ino:29:

C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:131: error: expected ',' or '...' before numeric constant
In file included from C:\Program Files\Arduino\hardware\arduino\cores\arduino/HardwareSerial.h:28,
                 from C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:215,
                 from SimpleModbusMasterArduino.ino:29:
C:\Program Files\Arduino\hardware\arduino\cores\arduino/Stream.h:57: error: expected ',' or '...' before numeric constant
In file included from SimpleModbusMasterArduino.ino:29:
C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:222: error: expected ',' or '...' before numeric constant
SimpleModbusMasterArduino:37: error: 'Packet' does not name a type
SimpleModbusMasterArduino.ino: In function 'void setup()':
SimpleModbusMasterArduino:45: error: 'packets' was not declared in this scope
SimpleModbusMasterArduino:45: error: 'READ_HOLDING_REGISTERS' was not declared in this scope
SimpleModbusMasterArduino:45: error: 'modbus_construct' was not declared in this scope

SimpleModbusMasterArduino:49: error: 'modbus_configure' was not declared in this scope SimpleModbusMasterArduino.ino: In function 'void loop()': SimpleModbusMasterArduino:56: error: 'modbus_update' was not declared in this scope
Here is my code:
#include <SimpleModbusMaster.h>

/*
   The example will use packet1 to read a register from address 0 (the adc ch0 value)
   from the arduino slave (id=1). It will then use this value to adjust the brightness
   of an led on pin 9 using PWM.
   It will then use packet2 to write a register (its own adc ch0 value) to address 1
   on the arduino slave (id=1) adjusting the brightness of an led on pin 9 using PWM.
*/

//////////////////// Port information ///////////////////
#define baud 115200
#define timeout 1000
#define polling 200 // the scan rate
#define retry_count 10

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 2
#define LED 13

// The total amount of available memory on the master to store data
#define TOTAL_NO_OF_REGISTERS 8
#define TOTAL_NO_OF_CONSTANTS 1

// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  PACKET1,
  //PACKET2,
  TOTAL_NO_OF_PACKETS // leave this last entry
};

// Create an array of Packets to be configured
Packet packets[TOTAL_NO_OF_PACKETS];

// Masters register array
unsigned int regs[TOTAL_NO_OF_REGISTERS];

void setup()
{
  // Initialize each packet
  modbus_construct(&packets[PACKET1], 1, READ_HOLDING_REGISTERS, 0x3000, 8, 0);
  //modbus_construct(&packets[PACKET2], 2, READ_HOLDING_REGISTERS, 0x3000, 8, 16);

  // Initialize the Modbus Finite State Machine
  modbus_configure(&Serial, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);

  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();
  Serial.println(regs[0]);
  //regs[0] = analogRead(0); // update data to be written to arduino slave

  //analogWrite(LED, regs[0]>>2); // constrain adc value from the arduino slave to 255
}

Your issue is that you define constants, such as timeout, which are widely used in Arduino library as parameter names. After preprocessing your definitions, correct code in "Arduino.h" such as
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);

becomes
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long 1000);

No wonder the latter line fails to compile.
You will need to find unique names for your defines, or use constant variables instead.


text:
Problems with Windows 8.1 install of Arduino IDE
I have replaced my Arduino, thinking it would solve the problem, but I still get it. Whenever I try to upload code, I get the error messages programmer is not responding and not in sync. Then I heard Arduino had drivers required. But my Windows 8.1 didn't recognize Arduino Uno. It was put in the other devices area as an unknown device in the device manager. The update driver button is greyed out. I get the message:

The drivers for this device are not installed (code 28). There are no
  compatible drivers for this device. To find a driver for this device,
  click update driver.

That's the greyed out button… When I look at driver details, it says 'No driver files are required or have been loaded for this device.' For the not in sync/programmer not responding error, I've tried restarting the board before uploading, restarting whilst uploading, you say it, I've done it. How can I fix this so I can finally follow my dream to be an engineer/programmer?

Have you tried, maybe, installing the drivers...?

Sorry but from what I read it said that windows should automatically recognise arduino UNO. But thanks, I'll download the drivers

Windows 10 can. All other versions require the Arduino CDC/ACM drivers.

Getting started with a new toolchain can be quite a challenge…
I'm not a Windows guy, but it looks like there are drivers that need to  be installed to get things working with the Arduino. I'm guessing that what is going on here is that Windows is looking locally for drivers and not finding them (or any indication that drivers are needed). I think the button was grayed out because it couldn't help – not because help wasn't needed.
Here are a few sources that I found by searching on:

arduino driver windows 8.1

[SOLVED] Arduino drivers for Windows 8.1 64bit
Windows 8.1 (64bit) USB-serial driver for Arduino?
Installing the Arduino IDE – Windows 8.1 & 10
Install Arduino Drivers on Windows 8

While we're at it, it is worth mentioning that "out of sync" error message from avrdude are very common. A bit of searching here will find you some good resources on solving them as well – deal with the drivers first, then see if errors persist.

the IDE comes automatically with the drivers, how do I install them? Everyone online says 'click update driver and select those drivers' but , as you know, my update driver button is greyed out.


text:
How do I install Arduino drivers?
I need to install my Arduino drivers, but Windows 8.1 doesn't seem to like Arduino, and it greys out the update driver button. Therefore I can't select the drivers from the drivers folder in my Arduino IDE folder.
There are drivers that need to be installed. But Windows 8.1 greys out the update driver software button. Also, it refers to Arduino Uno as an unknown device. How do I install the Arduino drivers and make Windows let me install the drivers?

Are the drivers signed?

What do you mean?

Try right-clicking on the .inf file and selecting "install".

Have you tried following the Windows 8 instructions at https://learn.sparkfun.com/tutorials/installing-arduino-ide/windows ?

Have you tried following the Windows 8 instructions at http://dawdevel.blogspot.com/2012/12/arduino-uno-on-windows-8-without.html ?

Which .inf file Majenko?

What Arduino is it?  Is it a genuine one, a clone or a fake? Where did you get the drivers from?  Do you know what version they are?  Are they on CD/DVD or downloaded?

I've fixed the problem now :). The drivers needed administrator rights for modification and I'm not admin so I asked my admin to allow me to update the drivers

The IDE package usually ships with the driver(at-least the latest one).
Go to Program Files in C: and find the Arduino folder and you should find a folder named Drivers. Inside you will find an application named dpinst-x86. Run it and you should be good to go!

Often reinstall the latest arduino IDE with Windows Administrator rights helps (use right click execute as administrator).

If the arduino is undetected in PC go to control panel-device manager - connect the arduino and some COM port will appear click it and troubleshoot make sure your PC is connected to internet and then you will be able to see your com port in arduino ide.


text:
"Update driver software" not showing. :(
I've followed tutorials installing arduino drivers for a while, but this is getting in my way:

The all-important "Update driver software" button isn't showing? Can anyone explain this and how I can fix it? Many thanks!

Simple solution: Upgrade to Windows 10 and you won't need the drivers. Ditch Windows 8, it's the most dire piece of *&$"!^ ever created. Even worse than Windows ME.

What arduino are you using official/unofficial? Using any tools to connect the arduino to the pc? I would recommend to reinstall arduino. And or try connecting the device to another USB port

I'm using arduino UNO R3 , I'm using USB to connect my arduino. I'll try another port

Thanks, but I'd get tonnes of new problems if I upgrade to windows 10. Lots of software I have has admitted to glitching a lot on windows 10.

But I am considering upgrading to windows 10.

do you know any other solutions?

Upgrade to Linux and you won't need any drivers either.


text:
İs there any way different way than GND's Arduino
İ'm making  a project on my arduino uno when i figured out i had no more GND left to finish the circuit. İs there any other way to optimize, use pins as input maybe. İ tried whit other websites, however, they weren't much of a use. Can you show an example also.
Thank you sooo much in advance,
Dario

Can't you just connect multiple GND wires to one GND on the board?

No, two wires don't fit into one slot

connect them outside...

Dario,
There are only 3 ground pins on the Arduino Uno, but don't be afraid to "breakout" these pins with wire. It doesn't matter if you connect multiple component grounds together, as long as they are connected to ground with no resistance between them, the circuit will close.
Strip board and pin headers will help you here, try this: http://www.instructables.com/id/Home-Made-Arduino-Prototype-Shield/


text:
arduino and gsm module receive
Can you help me with the codes? I have gizduino(arduino clone), i used the codes in receiving sms from the internet but what i receive is a symbol "y" with two dots at the top. Whats wrong?
My gsm is set to suart.
// Example 55.4

#include <SoftwareSerial.h>
SoftwareSerial SIM900(2,3);

char incoming_char=0;

void setup()
{
  Serial.begin(19200); // for serial monitor
  SIM900.begin(19200); // for GSM shield
  SIM900power();  // turn on shield
  delay(20000);  // give time to log on to network.

  SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  // blurt out contents of new SMS upon receipt to the GSM shield's serial out
  delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop()
{
  // Now we simply display any text that the GSM shield sends out on the serial monitor
  if(SIM900.available() >0)
  {
    incoming_char=SIM900.read(); //Get the character from the cellular serial port.
    Serial.print(incoming_char); //Print the incoming character to the terminal.
  }
}

You are most likely using the wrong baud rate. Try 9600, 57600 and 115200. Are you sure of that power up procedure? Is there any evidence that the module is on?

Most probably you are using sim900 or sim800 module. These modules would be either fixed to a certain baudrate like 9600 or 115200, OR the module might be at auto-baud mode.
In auto baud mode you need to send AT\r to the modem after the modem is switched ON so it can know what baud you are using.
Please check the following...

GSM Modem/Module not responding to AT commands after firmware Upgrade??
Serial port AN


text:
Unable to initialize W5100 using Arduino Pro Mini
I am unable to initialize a W5100 module using an Arduino Pro Mini. I try setting the MAC and IP addresses but read invalid values thereafter.
Here is the Arduino program along with the output:
void setup() {
    uint8_t mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    uint8_t local_ip[] = {192, 168, 1, 100};
    Ethernet.begin(mac, local_ip);
    printMacAddress(); // OUTPUT: FF:FF:FF:FF:FF:FF
    printIpAddress(); // OUTPUT: 255.255.255.255
}

void printMacAddress() {
    uint8_t mac[6];
    W5100.getMACAddress(mac);
    Serial.print(mac[0], HEX); Serial.print(":"); Serial.print(mac[1], HEX); Serial.print(":");
    Serial.print(mac[2], HEX); Serial.print(":"); Serial.print(mac[3], HEX); Serial.print(":");
    Serial.print(mac[4], HEX); Serial.print(":"); Serial.print(mac[5], HEX); Serial.println();
}

void printIpAddress() {
    IPAddress ip = Ethernet.localIP();
    Serial.println(ip);
}

I read in some blog posts that the Arduino may initialize before the W5100 initialization is completed so others recommend manually resetting the W5100 after Arduino initialization.
So I connected the W5100 reset pin to the Arduino digital output 4 and reset the W5100 during setup using the following code.
const int W5100_RESET_PIN = 4;
pinMode(W5100_RESET_PIN, OUTPUT);
digitalWrite(W5100_RESET_PIN, LOW); // Activate reset pin by asserting low
delay(5); // Wait for 5 msec
digitalWrite(W5100_RESET_PIN, HIGH); // Deactivate reset pin by asserting high
delay(300); // Wait for W5100 to initialize[/code]

I observed the W5100 resetting because the module LEDs flashed off and back on each time I manually reset the Arduino. However this does not fix the W5100 mac/IP initialization issue.
How should I troubleshoot this issue?
Here are pictures of the assembly.
https://i.stack.imgur.com/cjnHE.jpg
Here is an overview of the W5100 module.
http://arduino-info.wikispaces.com/Ethernet

One of the Ethernet examples shows you should test the result of the begin function call, like this:
// start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

Try displaying the return value from begin to see if that initialization succeeded.

Thanks for your comment Nick.  Calling Ethernet.begin(mac) returns non-zero and it fails to configure DHCP.  I also tried configuring IP manually and this fails as well.


text:
arduino pro mini downloading?
I purchased the arduino pro mini atmega328 and equipped it with FTDI breakout board with USB, a battery charging board, Wireless transmitter and a wireless receiver.  I'm assuming they can all be connected.  My question is, how do I download programs to the arduino board?  And where might I find specific programs to download?

Have you done any research at all? Google will find all of your answers.

https://www.arduino.cc/

The Arduino Pro Mini has a row of connections at the small end that align with the connections on the USB-to-Serial board you have.  They are marked GND - VCC - RXI - TXI and should be in the same order as the connector on the FTDI board. I think that the pin marked GRN on the Arduino will align with the connector marked DTR on the USB-to-Serial board, but please make sure that VCC aligns with 5V!
With the FTDI board plugged into the Arduino, you can plug your computer into the FTDI board's USB port and when you run the Arduino IDE programming tool, that USB port should say that it's connected to a serial port.  Pick the "Arduino Pro or Pro Mini" as your board, then pick your processor (most likely the "ATmega328 (5V, 16MHz)" and finally your port (that serial port you found).
Now when you upload your Arduino program to the Arduino, it will know the board your have and the port to use.
As for programs to use, start simple and get the onboard LED to blink.  From there, you'll have the basics down for creating a program and getting it to the Arduino.  You'll find tons of example programs (called sketches in Arduino land) that will help you connect all your fun wireless gizmos!
As noted above - Google is your friend.  There are many places to go for examples and help.  Start with some of the commercial sites like Adafruit and SparkFun. Their staff really supports the Arduino community with how-to videos, libraries, examples, etc.


text:
What is preventing my code from checking the number of pushbutton values for a correct/wrong answer?
My code is supposed to generate a random number and then display it in binary using four LEDs. After you press it, it waits for two seconds before checking your number of pushbutton presses to see if they equal the random number, and it turns the green/red LED on accordingly and restarts the loop.
It doesn't do that, and also it counts multiple pushes if you keep the button pressed in, since it reads the pushbutton as being "on".
Code:
//VARIABLES:
const int ledPin1 = 2;
const int ledPin2 = 3;
const int ledPin3 = 4;
const int ledPin4 = 5;
const int buttonPin = 6;        //push button
const int ledPincorrect = 8;   //green LED that switches on for correct answer
const int ledPinfalse = 9;    //red LED that switches on for wrong answer

int randomNumber = 0;
int buttonState = HIGH;
int buttonPushCounter = 0;             //counter for button presses
int lastButtonState = HIGH;             //previous state of the button
int getal;
int i;                              //for the ConvertBinary function, i serves as a variable for the LED's
unsigned long Timer;               //Timer, switches on after buttonstate = LOW, and after 2 seconds the game restarts
long lastDebounceTime = 0;         // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
int ledState = HIGH;
int remember;

void setup()
{
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(ledPincorrect, OUTPUT);
  pinMode(ledPinfalse, OUTPUT);
  Serial.begin(9600);
  randomSeed(analogRead(0));
  buttonState = digitalRead(buttonPin);
  Timer = millis(); // unsigned long Timer = millis();

}
void loop()
{
  if (randomNumber == 0) {
    Serial.print("lets start with random");
    getal = random(1, 16);
    Serial.print("random is: ");
    Serial.println(getal);
    randomNumber = 1;
  }

   int remember = getal;
   for (int i = 2; i < 6; i++) {
   remember = remember / 2;
      if (remember % 2 == 1){
       digitalWrite (i, HIGH);
      }
     else ((digitalWrite(i, LOW)));
    }

    // reading the button state

    // read the state of the switch into a local variable:
    int reading = digitalRead(buttonPin);

    if (reading != lastButtonState) {
      lastDebounceTime = millis();
      if (reading == LOW) {                    // if (reading == LOW) ????
        buttonPushCounter++;
        Serial.println("on");
        Serial.print("number of button pushes:  ");
        Serial.println(buttonPushCounter);
        Timer = millis();
        lastButtonState = buttonState;

      } else {
      // if the current state is LOW then the button wend from on to off:
      Serial.println("off");
    }

      if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      lastButtonState = reading;
    }

    if (Timer >= 2000UL) {
      if (buttonPushCounter == getal) {
        digitalWrite(ledPincorrect, HIGH);
        digitalWrite(ledPinfalse, LOW);
        digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      randomNumber = 0;
      buttonPushCounter = 0;
      }
      else {
        digitalWrite(ledPinfalse, HIGH);
        digitalWrite(ledPincorrect, LOW);
        digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      randomNumber = 0;
      buttonPushCounter = 0;
      }
}

    }
}

}

Have you tried using serial communication to get some debug information out of your sketch? I see you've got some Serial calls in there, what does your output look like?

@Martin Carney
lets start with randomrandom is: 1
number of button pushes:  1
number of button pushes:  2
number of button pushes:  3
number of button pushes:  4
number of button pushes:  5
number of button pushes:  6
number of button pushes:  7
This is from one button press

Sounds like you have a debounce problem. I'd recommend making a simple sketch (e.g. with just one button and one LED) just to get your debounce code working the way you expect it to, then bring that over into your program as a whole.

Let us start with the simplest issue in your code:
Timer = millis();
...
if (Timer >= 2000UL) {
...
}

After 2000 ms this is always true (for about 49 days)?
Cheers!
Please format your code if you expect anybody to take the time to read it and help.


text:
Arduino Hardware Issue
I have two Arduino Uno R3 boards and both of them now seem to have an issue. There's a micro sized 8 Pin chip near the dc power port. This seems to get incredibly hot (i managed to get a blister from touching it) and the "L" Led seems to stay dimly lit even when the reset button is pressed.
The Arduino Uno was working fine during operation and only started giving me this problem recently, i cant seem to find any visible short or loose terminal on the board.
I can see that the reset function is being used as my LCD does reset.
Would anyone have a reason for this mysterious issue?

This chip seems to be the dual op-amp labeled LMV358IDGKR in the Uno R3 schematic.

How are you powering the Arduino when this condition occurs?

I had something similar before because I tried to attach a fan to it. Are there any short circuits or something that would take a huge amount of power?

post a picture of your UNO board

There are two issues here:

The "L" LED lighting. On the R3 Uno this is driven by an op-amp and if pin 13 is "floating" the op-amp may, or may not, turn the LED on. So this is normal.
The 8-pin chip near the power plug getting very hot. This is definitely not normal. You must be consuming a lot of current to do that. You could try measuring it. A Uno running an "empty" sketch should be consuming around 50 mA. Note that this chip is the op-amp mentioned in my first point. Possibly you have damaged it. Did you connect an LED (or motor) or similar to pin D13? If so, what current-limiting precautions did you take?

Try running an empty sketch (or the Blink sketch) with no hardware connected to the board, to see if it still happens.
Try measuring the power consumption, if possible, with a meter measuring the input through the 5V pin, if you have a 5V power supply you could use for this.
Are these genuine boards, or cheap clones from eBay?

Did my answer help or not? Stack Exchange is recycling this as an unanswered question. If it helps, please indicate this. If not, please state in what way it was not helpful.


text:
First time set up- permission denied to usb port- ubuntu 14.04
I just plugged my arduino in and the light is on, but the blink test failed to upload. here is my error:
Arduino: 1.6.7 (Linux), Board: "Arduino/Genuino Uno"
Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

https://www.arduino.cc/en/Guide/Linux#toc9

@IgnacioVazquez-Abrams - can you turn that into an answer? We are trying to get our percentage answered up. :) Maybe with a bit of copy and paste, so it isn't link-only.

I did all the steps and it worked the first time.
Now I try to upload my second program and I get this Message 'avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied' i did this:
roquet@roquet-HP-ENVY-x360-m6-Convertible:~$ sudo adduser roquet dialout The user roquet' is already a member of dialout'.
roquet@roquet-HP-ENVY-x360-m6-Convertible:~$ sudo chmod a+rw /dev/ttyUSB0
roquet@roquet-HP-ENVY-x360-m6-Convertible:~$ ls -l /dev/ttyUSB*
crw-rw-rw- 1 root dialout 188, 0 Jan 20 13:12 /dev/ttyUSB0
roquet@roquet-HP-ENVY-x360-m6-Convertible:~$ but still get the 'permission denie

From the documentation:

Open Terminal and type:
ls -l /dev/ttyACM*

you will get something like:
crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).
Now we just need to add our user to the group:
sudo usermod -a -G dialout $USER

then:
sudo chmod a+rw /dev/ttyACM0

You will need to log out and log in again for this change to take effect.

Note that the preceding is old Ubuntu instructions. On modern distros that use ConsoleKit create the file /etc/udev/rules.d/01-ttyusb.rules containing the following and then reload the udev rules and replug the Arduino device:
SUBSYSTEMS=="usb-serial", TAG+="uaccess"

Great answer. On newer installations you do not have to reload the udev rules. Udev will watch /etc/udev/rules.d for changes. You do have to replug the arduino.

@ppareit what counts as "newer installations"? This doesn't work for me on Ubuntu 16.04 with or without reloading the rules (via sudo udevadm control --reload).

I think it didn't work because the board is identified as belonging to the "tty" rather than "usb-serial" subsystem. Anyway, creating the following udev rule worked for me instead:
SUBSYSTEM=="tty", ATTRS{idVendor}=="(vendor)", ATTRS{idProduct}=="(product)", ATTRS{serial}=="(serial)", SYMLINK+="ttyUSB.arduino", GROUP="adm", where (vendor) and (product) are taken from lsusb and (serial) is taken from the output of udevadm info -a -n /dev/ttyACM0|grep '{serial}'|head -n1.

At least with Ubuntu 16.04, I don't saw this problem on Mint 18.1. Glad to hear that you found a solution!

NAILED IT!!!! UPVOTED.  I have a 17.04 distro and the 1st solution was not persistent!

I followed these instructions and it doesn't work for me. Only thing different my device is on /dev/ttyUSB0. I am using Ubuntu 18 and Arduino Uno.

@CaioCaio: Which instructions? There are two sets.

@IgnacioVazquez-Abrams, I added my user to the usergroup and changed permissions on the /dev/ttyUSB0

@CaioCaio: Did you read the end of the answer, and the comments?

@IgnacioVazquez-Abrams, I did but I had misunderstood it, I read 'proceeding', not 'preceeding', sorry... let me give it a go

@IgnacioVazquez-Abrams, yeah, the second set of instructions didn't work either. My arduino IDE (v1.6) was installed thru Ubuntu software manager, I removed it and then installed it by downloading the IDE package from Arduino.cc (v1.8) and now it works. Thanks for the help!

'sudo chmod ug+rw,o-rw /dev/ttyACM0' or 'sudo chmod 660 /dev/ttyACM0' only gives read and write access to the user/owner (root in the ls output above) and group (dialout in the ls output above), while others are explicitly denied read and write access.

All you need to do is add yourself to the dialout group as described in the answer by Ignacio Vazquez-Abrams. This is done in the terminal by typing:
sudo usermod -a -G dialout $USER

You do not need to use chmod. This gives read/write access to all users and not just members of the group. Before attempting to connect, however, you must logout and log back in. Once you log back in you will be recognized as a member of the dialout group and will be able to open the device.

On Ubuntu 18.04, the only way I found the Arduino IDE installation to work straight out of the box, was using the documentation steps described here:
https://www.arduino.cc/en/Guide/Linux/
No changing groups nor permissions required.

Nothing above have helped me. When I have installed from file, from official site, it doesnt even start. Then I have installed Arduino IDE from "linux app store" and was working but have a problem like our friend from top. So I have uninstalled it and installed via terminal    sudo apt install arduinoand now it`s working. Cheers.

Or just use the chown command.
sudo chown <username> /dev/ttyACM*

This worked for me

This question has been asked many times in this site, and the same answer has been giving by another user.  I will cite Chris Stratton on this subjedt: This is a bad idea, in particular on a typical dynamically configured linux with udev or similar managing /dev nodes you will have to do it every time you connect the device. Add your user to the appropriate group instead, which is a lasting fix.


text:
How to write a sketch when adding more devices to an I2C data line?
I am building a weather station, using a battery-operated outside unit, that transmits data from a DHT22 sensor to a unit inside my house.
The inside unit is using I2C communications from my Arduino Uno to my LCD display.
I would like to add a BMP180 sensor which also uses I2C communications.
My question is, how would you write a sketch to incorporate both the BMP180 sensor and the LCD display on to one I2C line?

Have you tried combining code for polling the BMP180 and the LCD yet? There's really nothing special about doing both at once, as long as both libraries are well-written.

What's the problem? If they both have different addresses, read from the sensor, then write to the LCD.

Yes you can connect multiple devices on one I2C bus. Every device on the bus needs to have its own address. Some libraries have the default address included. Some do allow to change it. Others don't. For example the SE95 temperature sensor (page 10) does allow for setting a few bits of the address allowing more than one sensor on a bus.
You can use the Wire library from Arduino to request data from I2C. When you want to pull data from a sensor, you have to send a command depending on the specs than request data from the address.
Example: for the SE95 address 0x4F (you can repeat this for any address you have a sensor on your bus) the SE95 ranges from 0x49 to 0x4F depending on the pin settings:
//Please note that the example is not complete because Wire has to be loaded and initialized
byte address = 0x4F;
byte read1;
byte read2;
Wire.beginTransmission(address);
Wire.write(0x00);
Wire.requestFrom(int(address), 2);
if(Wire.available()) {
  read1 = Wire.read();
  read2 = Wire.read();
}

So depending on the libraries, this would be quite easy.

Like Nick Gammon said, they have different addresses, so there shouldn't be a problem. Connect their SDAs and SCLs together, with the necessary pull-ups.
The libraries you are using should handle the low-level reading and writing. Proceed as though they are any 2 devices connected to your Uno. Print to the LCD as usual, and poll the sensor with library functions.


text:
Atmel SAM MCU (on Arduino Due) only boots after second power up
I am using an Arduino Due as a prototyping board for a microcontroller project. The due has the chip Atmel ATSAM3X8E, with an ARM Cortex-M3 core. I am programming the flash directly using Atmel Studio and SAM-BA over USB, I am not using the arduino tools or bootloader in any way, at least not to my knowledge. I am powering it over the USB port on the arduino.
I am able to program the flash and select flash for boot, but the problem is that the chip never works the first time I plug in the power. But if I cut the power and try again, it boots normally and the program starts. Then if I cut the power and wait a while, I have to power it up another two times before it works. It's like there is some volatile charge or RAM in there that needs to have been powered within the last minute for the chip to boot at power up like it should, but I don't know what. The result is the same if I plug the USB into my computer, or from a phone charger. Also the same whether I use the native or arduino programming USB port to power it.

How about if you press the reset button? after powering it up for the first time?

Then it starts correctly

Floating bootloader pin?

I don't know if there is a bootloader pin.. Can't find anything about that in the datasheet. Here is the schematic for the arduino: https://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf

Edit: Maybe the SHDN pin? I see it is related to some kind of sleep / power save mode, and it is not connected

I did this improvement and worked to me
https://forum.arduino.cc/index.php?topic=256771.30 (#35)


text:
Why the need to use the volatile keyword on global variables when handling interrupts in Arduino?
I am familiar with the keyword Volatile being used to declare variables that are shared among multiple threads on a software application (basically on a multithreaded application).
But why do I need to declare a variable as Volatile when running the code on an an Arduino interrupt? Is the code running in the interrupt executing on different thread? Is there something else going on?

You have to tell the compiler that the variable exists so that optimization algorithms don't remove it entirely from your executable.

"I am familiar with the keyword Volatile". Then forget about it, and read again.

Effectively the interrupt handler is a separate thread from main. Without the volatile declaration, compiler does not know that main must re-read the global (which may have been changed by the interrupt handler).

Is the code running in the interrupt executing on different thread - well sort of, only the opposite. Interrupts are the mechanism, the technique used by OS programmers, to implement threads. So we need to use volatile in multithreaded code because their context has been switched by the OS in an interrupt. We need to use volatile in interrupts simply because interrupts run in a different context.

First, it's volatile not Volatile. I cover these concepts in my page about Interrupts however to avoid giving a link-only answer I'll repeat the relevant bits.

What are "volatile" variables?
Variables shared between ISR functions and normal functions should be declared volatile. This tells the compiler that such variables might change at any time, and thus the compiler must reload the variable whenever you reference it, rather than relying upon a copy it might have in a processor register.
For example:
volatile boolean flag;

// Interrupt Service Routine (ISR)
void isr ()
{
 flag = true;
}  // end of isr

void setup ()
{
  attachInterrupt (0, isr, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  if (flag)
    {
    // interrupt has occurred
    }
}  // end of loop

Critical sections ... accessing volatile variables
There are some subtle issues regarding variables which are shared between interrupt service routines (ISRs) and the main code (that is, the code not in an ISR).
Since an ISR can fire at any time when interrupts are enabled, you need to be cautious about accessing such shared variables, as they may be being updated at the very moment you access them.

First ... when do you use "volatile" variables?
A variable should only be marked volatile if it is used both inside an ISR, and outside one.

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

eg.
volatile int counter;

Marking a variable as volatile tells the compiler to not "cache" the variable's contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.

Atomic access
Consider this code:
volatile byte count;

ISR (TIMER1_OVF_vect)
  {
  count = 10;
  }

void setup ()
  {
  }

void loop ()
  {
  count++;
  }

The code generated for count++ (add 1 to count) is this:
 14c:   80 91 00 02     lds r24, 0x0200
 150:   8f 5f           subi    r24, 0xFF     <<---- problem if interrupt occurs before this is executed
 152:   80 93 00 02     sts 0x0200, r24   <<---- problem if interrupt occurs before this is executed

(Note that it adds 1 by subtracting -1)
There are two danger points here, as marked. If the interrupt fires after the lds (load register 24 with the variable count), but before the sts (store back into the variable count) then the variable might be changed by the ISR (TIMER1_OVF_vect), however this change is now lost, because the variable in the register was used instead.
We need to protect the shared variable by turning off interrupts briefly, like this:
volatile byte count;

ISR (TIMER1_OVF_vect)
  {
  count = 10;
  }  // end of TIMER1_OVF_vect

void setup ()
  {
  }  // end of setup

void loop ()
  {
  noInterrupts ();
  count++;
  interrupts ();
  } // end of loop

Now the update of count is done "atomically" ... that is, it cannot be interrupted.

Multi-byte variables
Let's make count a 2-byte variable, and see the other problem:
volatile unsigned int count;

ISR (TIMER1_OVF_vect)
  {
  count++;
  } // end of TIMER1_OVF_vect

void setup ()
  {
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  if (count > 20)
     digitalWrite (13, HIGH);
  } // end of loop

OK, we are not changing count any more, so is there still a problem? Sadly, yes. Let's look at the generated code for the "if" statement:
 172:   80 91 10 02     lds r24, 0x0210
 176:   90 91 11 02     lds r25, 0x0211  <<---- problem if interrupt occurs before this is executed
 17a:   45 97           sbiw    r24, 0x15
 17c:   50 f0           brcs    .+20

Imagine that count was 0xFFFF and was about to "wrap around" back to zero. We load 0xFF into one register, but before we load the second 0xFF the variable changes to 0x00. Now we think count is 0x00FF which is neither the value it had before (0xFFFF) or now (0x0000).
So again we have to "protect" the access to the shared variable, like this:
void loop ()
  {
  noInterrupts ();
  if (count > 20)
     digitalWrite (13, HIGH);
  interrupts ();
  }  // end of loop

What if you are not sure interrupts are on or off?
There is a final "gotcha" here. What if interrupts might be off already? Then turning them back on afterwards is a Bad Idea.
In that case you need to save the processor status register like this:
unsigned int getCount ()
  {
  unsigned int c;
  byte oldSREG = SREG;   // remember if interrupts are on or off

  noInterrupts ();   // turn interrupts off
  c = count;         // access the shared variable
  SREG = oldSREG;    // turn interrupts back on, if they were on before

  return c;          // return copy of shared variable
  }  // end of getCount

This "safe" code saves the current status of interrupts, turns them off (they may already be off), gets the shared variable into a temporary variable, turns interrupts back on - if they were on when we entered the function - and then returns the copy of the shared variable.

Summary
Code may "appear to work" even if you don't take the above precautions. That is because the chances of the interrupt occurring at the exact wrong moment is fairly low (maybe 1 in 100, depending on the code size). But sooner or later it will happen at the wrong moment, and your code will either crash, or occasionally return the wrong results.
So for reliable code, pay attention to protecting access to shared variables.

I thought volatile would handle the multi-byte types read and write access in the main loop and ISR!
So, I was completely wrong and should turn off the interrupts before accessing them in the main loop, right?! ;-(

That's right. volatile just tells the compiler to not optimize and keep variables in processor registers. It doesn't have any other side-effects (apart from letting the compiler know these variables may change at any time, so volatile variables are never optimized away because they "aren't used"). So yes, as illustrated above, "guard" access to multi-byte variables by turning interrupts off.

Is it safe to remove volatile if we use the final version of getCount()?

I don't understand why the line (sbiw r24, 0x15) uses the value 0x15 instead of the value 20 in the "Multi-byte variable" section. Could it be a mistake?

@ecc Well, one is hex and one is decimal. Of course, 0x15 is 21 in decimal, not 20. However the compiler may have decided to subtract 21 and check if the carry bit was set, instead of comparing to 20. This would be part of compiler optimization. In other words, > 20 is the same as >= 21.

volatile has nothing to do with multithreading per se, and it seems to be among the most miused keywords in that area. It is never a substitute for proper synchronization.
As per standard C, volatile invokes mostly implementation defined behaviour of telling the compiler to not optimize away accesses to the memory a variable resides in, even if the compiler thinks there can't be any other.
This can be useful in the following situations where the compiler is not aware that outside means can change a variable:

memory mapped hardware registers
variables accessed from other threads but checked in a tight loop
variables accessed from interrupt or signal handlers but checked in a tight loop


text:
HC-06 Bluetooth Module on Arduino Nano
I'm working on a project where I need to have Bluetooth capability on my Arduino Nano to send data from a sensor over to the computer. Unfortunately, I'm having a difficult time figuring out how to establish a connection from the HC-06 to the computer.
I've hooked up the HC-06 to my Arduino in a fashion similar to the picture shown below.

I've also been testing it with various code that I've found online that deal with tutorials on the HC-06.  The current code I'm working with is below.
#include <SoftwareSerial.h>
SoftwareSerial BT(1, 0);

void setup()
{
  // set digital pin to control as an output
  pinMode(13, OUTPUT);
  // set the data rate for the SoftwareSerial port
  BT.begin(9600);
  // Send test message to other device
  BT.println("Hello from Arduino");
}
char a; // stores incoming character from other device
void loop()
{
  if (BT.available())
  // if text arrived in from BT serial...
  {
    a=(BT.read());
    if (a=='1')
    {
      digitalWrite(13, HIGH);
      BT.println("LED on");
    }
    if (a=='2')
    {
      digitalWrite(13, LOW);
      BT.println("LED off");
    }
    if (a=='?')
    {
      BT.println("Send '1' to turn LED on");
      BT.println("Send '2' to turn LED on");
    }
    // you can add more "if" statements with other characters to add more commands
  }
}

When I search for a connection on my computer, it finds the HC-06 and I can then attempt to establish a connection.  I enter the pairing code of 1234.  It then says that a connection has been established so I go into the Bluetooth Services tab where it tells me what COM port to use (either COM7 or COM4 depending on which computer I try it on.  I've tried this on two separate computers.)
So, I open a PuTTY session and attempt to connect to the indicated COM port.  About 50% of the time, it says that a connection could not be established to the indicated COM port.  The other 50% of the time, I am able to open a PuTTY session but then nothing happens.  The green LED on the HC-06 continues to blink away no matter what I try to do.
Any help would be VERY appreciated as I feel like I've tried everything I can think of.
Thank you!

You double checked the baud speed used in putty? And a=(BT.read()); has unneeded brackets. Remove the outside ones

Yeah, I'm setting my PuTTy session at 9600 baud.

Your voltage divider looks wrong. You should be dividing voltages from the Nano to the module and not the other way round.

Also why lay SoftwareSerial over those pins? They are already UART pins from what I can see.

I agree with TisteAndii's comment. Your voltage divider is in the wrong place. You are dividing down the 3.3V signal from the HC-06 to be a maximum of 2.269 volts. However the Nano requires at least 3.5V to be considered HIGH.
Plus, you are putting 5V from the Nano into the HC-06 which may damage it.

Try changing the order of the pins on the Software Serial declaration, the correct order is (Rx,Tx), so SoftwareSerial BT(0, 1);
Or, just forget Software Serial altogether and remove the first two lines and change "BT" to "Serial" to use the hardware UART on those same pins which works better.


text:
Can't compile my library because "String does not name a type"
I am writing a small library to move some code out of the arduino sketch and make it reusable. Problem is that it does not compile since "String does not name a type".
This is my code (reduced):
myESP.h:
#ifndef MYESP_H
#define MYESP_H

#include "Arduino.h"

#include <String>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>

class myESP {
    private:
        const char* _ssid;
        const char* _password;
        const char* _host;
    public:
        myESP();
        myESP(char * ssid, char * pwd, char * host);
        String macToStr(const uint8_t* mac);
        String doGet(String data, String sensor, int duration);
};
#endif

myESP.cpp:
#include <String>

#include "Arduino.h"
#include "myESP.h"

myESP::myESP() {}

myESP::myESP(char * ssid, char * pwd, char * host) {
    _host = host;
    _password = pwd;
    _ssid = ssid;
}

myESP::String macToStr(const uint8_t* mac) {
}

myESP::String doGet(String data, String sensor, int duration) {

}

When i try to compile it, I get the following:

/Users/lbedogni/Documents/Arduino/libraries/myESP/myESP.cpp:14:1:
error: 'String' in 'class myESP' does not name a type  myESP::String
macToStr(const uint8_t* mac) {
/Users/lbedogni/Documents/Arduino/libraries/myESP/myESP.cpp:22:1:
error: 'String' in 'class myESP' does not name a type  myESP::String
doGet(String data, String sensor, int duration) {

I have tried to change the order of the imports, change libraries, but still it does not compile.
Any idea?

#include <String> - the IDE automatically includes the String type so you don't need this include.

Your syntax is wrong in myESP.cpp. Change this:
myESP::String macToStr(const uint8_t* mac) {
}

myESP::String doGet(String data, String sensor, int duration) {

}

to this:
String myESP::macToStr(const uint8_t* mac) {
}

String myESP::doGet(String data, String sensor, int duration) {

}

The return type is String and the function implementation should be prefixed with the class name myESP::. Obviously, you also need to fill in the body of the implementation or you'll get more errors because you don't actually return anything.


text:
MQTT Broker on an Arduino
Has anyone here setup an MQTT Broker on an Arduino?  I am looking to use pubsubclient to send sensor data from 12 individual wireless sensors to an Arduino every 250ms.  I know this can be done using a Raspberry Pi, but I am new to all this and am just now comfortable with programming an Arduino.  I also looked at using XBee, but have heard it may not be able to handle the data frequency.  I am only sending 1 byte of data from each sensor each time.  Any help or suggestion is appreciated.

Maybe link to some info on MQTT.  From my limited understanding, MQTT is on top of a TCP/IP stack, so to send one byte per observation, there would need to be quite a few bytes of overhead.

Sending one byte of data over MQTT is incredibly inefficient. You would be better off using a simple serial protocol of some form and forgetting about MQTT to send data between little nodes like this. By all means use MQTT to publish it out onto the internet somewhere, but internally don't use MQTT.

Majenko: when you say to use a simple serial protocol, can you give an example of what you mean?  What hardware would be needed at the sensors to transmit, and at the arduino to receive it? I do not need to publish to the web, just from the 12 unique sensors wirelessly to a single arduino.

One additional piece of info, the physical distance from the sensors to the Arduino is about 10 ft.  I'm sure that plays into how this could be done.  I looked at using RF24, but read that it is limited to just 6 connections communicating in an organized manner.

MQTT is TCP based. A nodeMCU (think of it as a super-Arduino) has a 5 concurrent connections limit. I don't know about Arduino WiFi shields, but I doubt it can handle more than that.


text:
Multiple Wireless Sensors to an Arduino
I am looking for ideas on how to connect 12 sensors to an Arduino wirelessly.  The sensors will be about 10ft from the Arduino.  They need to send one byte of data every 100ms-250ms to the Arduino in an organized manner.

I have investigated MQTT and pubsubclient, but have not found a way to make an Arduino a Broker, and have been told it is very inefficient for my application.
I have looked at NRF24L01, but it appears to be limited to just 6 pipes to receive data in an organized fashion.
I researched Xbee, but have been told that it cannot keep up with the data rate.

Other suggestions are appreciated...  Thank you.

You can do it with an NRF24L01 using just a single pipe.  Simplest would probably  be to actively query each node for data by including a node number in the query packet, but you can also have them identify themselves with a node number, transmit at slightly varied or random intervals, and perhaps put a reading number in each packet too so that they can transmit each reading more than once to generally accommodate any collisions on the occasions where the transmissions from two overlap.

Chris, would you happen to have any example Arduino code to do this, or a pointer to a reference, showing both the client and the server side?  This sounds like it may be the simplest solution...  I did not specifically mention in my original post that each sensor is wired directly to an arduino.    Thank you!

Did you got the things working? I am looking for - how to receive wireless data from four sensors with 512 Hz data rate(for each sensor and simultaneously) ? thank you.

Can any one help me in getting the Arduino code that how I can receive data from 6 sensors simultaneously on single master nrf24lo1...... Thanks in advance

I would recommend the nRF24L01.
You don't need one pipe per node - just one pipe.
Each pipe is effectively an address that a node responds to - having multiple pipes means you can have multiple addresses on one node (like aliases) - but of course you only need one address per node, and hence one pipe per node.
The range is more than adequate (with the antenna version I have managed to get hundreds of meters no problem) and the price is so low as to be negligible.

It might be easiest to send a UDP packet over WiFi.  There is no extra packet overhead for this "connectionless" protocol: no OPEN, no ACK/NAK, no CLOSE, etc.  The incremental cost for additional bytes is very small, so if you decide you need to send 2 bytes, or even 100 bytes, it won't affect the throughput very much.
If you can "batch" the bytes, that would be even better.  For example, could you send 8 bytes per node, once every 800ms-2000ms?  If not, WiFi speeds should allow the single-byte UDP packet to get through without much latency.  Do you know what latency the receiver can accommodate?  You might get lower average latency with batched packets, depending on the network access time (i.e., how long it takes to hop on to the air).
A roll-your own approach would be to use a raw RF transmitter/receiver with something like VirtualWire.  With proper synchronization from the "master", the slaves could each have their own time slot, avoiding collisions (which keeps the network access time low)

WIFI is going to add a lot of register-with-the-access-point type setup overheard before you can do that.  Probably the reason for considering it would not be any inherent advantages (its quite disadvantageous compared to the alternatives) but the ready, inexpensive availability of ESP8266 boards as sensor nodes on which the poster can run Arduino-style firmware.  It can also function as the sensor hub and if needed the AP - either in cooperation with the existing Arduino or potentially replacing it.

Use nRF24L01. To avoid collisions you can query the sensors (as Chris suggested in comment).
The setup would be:
Each sensor would have unique address. Central unit would transmit request and sensor node would respond to it. Central unit would have different address and all sensors would transmit to that address. You can also use data in ack to pack response.

Central node (Addr0) -> Sensor 1 (Addr1): Request
Sensor 1 (Addr1) -> Central node (Addr0): Response, sensor data
Central node (Addr0) -> Sensor 2 (Addr2): Request
Sensor 2 (Addr2) -> Central node (Addr0): Response, sensor data
Central node (Addr0) -> Sensor 3 (Addr3): Request
Sensor 3 (Addr3) -> Central node (Addr0): Response, sensor data
...

Thank you all again.  I am just becoming comfortable with programming the Arduino.  Would you have a link or example Arduino code to do this?   All the examples I have found just show a one-to-one communication.

Essentially all that is happening here is one-to-one communication, it's just that the hub has such an interchange with each node in turn.  One thing you will need to think about though is how long to wait for a reply, before moving on to try the next node.

Ahh...  understood.  What sort of delay/wait time would be typical?  Am I even going to be able to meet my data rate of 250ms?  That is, within 250ms I would need to obtain a reading from all 12 sensors...

There will be plenty of time, it's more a question of what is the best strategy for using it.

So how to connect the sensor? directly via I2C to the nRF24L01 transceiver, with another transceiver at the microcontroller end? Wouldn't you need a microcontroller at each end?


text:
Has anybody seen/created a gps guided vehicle with arduino?
I thought the idea of Amazon Prime air drone delivery was a pretty cool one when it first came out and I started to question whether something like that (an autonomous gps guided vehicle) could possibly be created with the Arduino microcontroller(s). Any thoughts?

Is this your other question just worded slightly differently? If so, it would be better to ask one question, not two almost identical ones.

@NickGammon uh oh, well as you can see im new here and I have no clue what caused me to submit it twice

You might really want to check out LIDAR applications. While extremely expensive, it's a superb way of checking your surroundings. (https://www.youtube.com/watch?v=nDkW_XuXQEM)

GPS is not, by itself, enough to make an Amazon Prime-like delivery drone.  GPS only provides a very rough position (thanks to the US Military imposing a large margin of error on non-military users, or so the urban legend goes (it's actually a difference in transmission systems that makes the difference)). It's good enough for getting you to your destination and working out roughly where you are, but getting to a specific pinpoint location just can't be done.
So you need other sensors as well. Things that can examine the environment and work out where you are in relation to other things. Especially people. Object avoidance is the critical component of any autonomous drone, and unless you can come up with a completely safe and foolproof system the FAA will be down on you like a ton of rectangular building blocks.

Yes, someone (not me) has: https://www.youtube.com/watch?v=3-r2Jk0uA6U
I doubt it would work very well with non-flying vehicles - in the air, a 3 meter margin of error is fine, on the ground it's the difference between the sidewalk and the middle of the road.