message:
EEPROM library throwing errors

I've included <EEPROM.h> in my sketch and am trying to run a simple sketch that just does EEPROM.write(0,4); followed by a println of EEPROM.read(0);  However, it won't compile.  It keeps telling me there is an error, and that I'm making a "request for member 'write' in something that is not a structure or a union".  I'm using the Mega ADK.  What am I doing wrong?  I've also tried to go to sketch->include libraries and include the EEPROM library directly, still no joy.  This is Arduino 1.6.13 on Windows 8, if it matters.

body:
The problem had to do with data types.  I was using an unsigned int as follows:

    unsigned int addr = 0;
    EEPROM.write(addr,5);

However, EEPROM.write requires an int, not an unsigned int, and this caused a compiler error.


sender: user

message:
teensyduino with teensy LC: cannot include multiple files in sketch

I'm trying to get a rather large sketch working with a teensy LC.  I'd like to break it into headers and C files, but the multi-file sketch fails to compile.  When I put everything into a single, monolithic sketch, it runs fine.  I've #included the h files where they are needed, using single quotes, and have confirmed that my h files are in the same folder as my sketch.  Is there an additional step to go through specific to teensy?  I've managed to do this tons of times using a standard arduino.

Here is a basic sketch:

 This is the main sketch file:

       #include "tst.h"
    void setup() {
      // put your setup code here, to run once:

    }

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

This is tst.h

    void doNothing();

This is tst.c

    #include "tst.h"
    void doNothing()
    {
      int i = 0;
    }

I get the  error "undefined reference to doNothing() in function loop"

sender: assistant

body:
> I get the error "undefined reference to doNothing() in function loop"

The C++ compiler cannot find doNothing(). This is mainly due to the incomplete header file and mix of C and C++.

Two things are needed to avoid this type of problem; 1) protect the file from multiple includes (in the same compile), 2) make the function visible to the C++ compiler as a C function (without name mangling).

tst.h:

    #ifndef TST_H
    #define TST_H

    #ifdef __cplusplus
    extern "C"{
    #endif

    void doNothing();

    #ifdef __cplusplus
    } // extern "C"
    #endif
    #endif

Cheers!


message:
HTTP request not sending

so I have a wifi shield and I am sending a web request, but its not going through. I know it's not the server because the other function of the program works properly. My code is available on [pastebin][1]

  [1]: http://pastebin.com/w9W3RGPi

**EDIT:**

The request that is not working is on line 318

body:
You are lacking a space:

    client.println((String)"GET /msg.php?action=send&ID=2&message=" += currentMessage += "HTTP/1.1");
                                                                                ^

Your HTTP is running in to the content of your message ending up with a corrupt request. Also you are doing appending within your strings (`+=`) when you don't need to (`+` is all that is needed). In fact, you don't even need that - just do multiple prints and reduce the hammering your heap is getting. Oh, and don't forget to use `F()`:

    client.print(F("GET /msg.php?action=send&ID=2&message="));
    client.print(currentMessage);
    client.println(F(" HTTP/1.1"));


message:
Arduino IDE on Linux - directory not found

I have Ubuntu 14.04 installed on a chromebook through crouton. I'm trying to install the Arduino IDE. I figured out that I needed the 64-bit version of the IDE and downloaded it. Then, I started following the instructions given - I found the downloaded file, which was named `arduino-1.8.0-linux64.tar.xz`, opened it (this opened a new window in a program called Xarchiver, which listed the subfolders and files), and saw the `install.sh` file. When I right-clicked, there was no option to run it from the terminal, so I went back to the terminal and did `cd Downloads` and then tried to cd into the downloaded file. However, it said that there was no such directory. I listed the files in Downloads, and the downloaded file came up, listed in red.

How can I run the `install.sh` file? What am I doing wrong? Any help would be appreciated.

body:
You need to extract the archive file first.

    $ cd ~/Downloads
    $ tar -Jxvf arduino-1.8.0-linux64.tar.xz


message:
Collection of functions for arduino IDE

I am having troubles creating a collection of functions to be used in Arduino sketches and libraries. What I want is not a class, but simply a group of functions which do not require an object to be called; general utilities that can be helpful in any Arduino sketch, like an average of analog reads, or a little statistical tool.

Suppose I write a file called Utilities.h    (I am not sure .h is the right extension to use in this case):

**Utilities.h**

    #ifndef Utilities_h
    #define Utilities_h
    #include <Arduino.h>

    void utility1(...){
    ...
    }

    float utility2(...){
    ...
    }

    //and so on

    #endif

I then save this file in `../Arduino/libraries/Utilities`. Whenever I want to use my utilities from this file directly in a sketch I type `#include`the full path to the file (`#include <Utilities.h> `  won't work).

The real problem is if I want to use this collection of functions in a library, like in the following example.

**myClass.h**

    #ifndef myClass_h
    #define myClass_h
    #include "full path to Utilities.h"

    class myClass{
     private:
      int a;
     public:
      myClass();
    };

    #endif

**myClass.cpp**

    #include "myClass.h"

    myClass::myClass(){
     a = utility2(...);
    }

Whenever I try to `#include <myClass.h>`  in my sketches and compile, I get 'multiple definition' error messages for the functions on my  `Utilities.h`.

So to summarize, my question is: how can I create a collection of functions that can be used both in a sketch and in a library for Arduino?

body:
You need to "split" your library.

Placing full functions inside a header file (`.h`) is bad form and causes the exact problem you are seeing. Every time you include the header file you create an entirely new copy of the function. This can only work if the functions are `static`, which means that they exist, and are contained entirely within, the function in which the header is included in. All outside access to them is completely cut off and they become "local" to the file. That means you can have multiple copies of them in one program. However that is wasteful of space since you are duplicating your code.

Instead you need to have the code itself in a `.cpp` file, which gets compiled separately and then linked with your sketch at the end of compilation, and just pointers to the functions you have written in your `.h` file.

Utilities.h:
-
    extern void myFunction();

Utilities.cpp:
-
    void myFunction() {
        blah blah
    }

The `.h` file just contains a *prototype* for the functions which tells the compiler that "This function is defined elsewhere. Find it later on when you link."

It's only the `.h` file that is included in libraries and sketches, etc, so only the prototype that is duplicated between files. The `.cpp` is compiled separately and thus only compiled the once, so you don't get the code duplicated.

One caveat with this is that your sketch must include the library you have written so that the IDE knows to look for `.cpp` files within it to compile. And you must use `#include <Utilities.h>` for it to be able to work that out. Using a full path rather than just `<Utilities.h>` means that you break all portability and the IDE may not know to look for `.cpp` files in there, or even where to actually find it when compiling.  Note as well that the IDE needs to be restarted after creating a new library, which is why it may not be able to find it in your experiments.


message:
Where can i get a current Websockets Library for Arduino that will work with the Ethernet Shield

I'm trying to get a simple WebSocket client working on an Arduino Mega with an ethernet shield. I tested the ethernet on the Arduino and it's working fine. I've tried a few of different WebSocket libraries the example sketches fail to connect. I've tried them with echo.websocket.org and with two different express instances ( one running WS and one running SocketIO ). But the WebSocket connection seems to fail.

https://github.com/billroy/socket.io-arduino-client

https://github.com/krohling/ArduinoWebsocketClient

is there a preferred  library for the most recent WS standard that anyone has used with sucess recently?

body:
I have debugged both these libraries using wireshark, sending a message to a node.js ws server in my computer, and there really is some sort of problem in the handshake. The package is sent by the client and received by the host, by the connection with the ws server is never established.

Was anyone able to use them?
Is there any alternative (besides Johnny-Five)?


message:
Why does an `.ino` file have to be in a folder of the same name?

I'm trying to organise a very complicated project and I want to put all the actual code in a folder named `src` (source), but I want to keep the main `.ino` file as `main.ino` (it will also be in `src`). Then when I try to open the code, the IDE says that `main.ino` has to be in a folder named `main`.

**Why is this?**

I fully understand the error message, but why does the file naming in Arduino has to be so. Is there a way to change that?

body:
AFAIK, that is a quirk built into the Arduino IDE. The best workaround I can think of is a file structure something like:

    ArduinoWorkspace --- /myproj/ ----+ /src/ --------+ myproj.cpp
                                      + myproj.ino    + sensor.h
                                                      + sensor.cpp
                                                      + (more files)

, where myproj.cpp just `#include`'s main.cpp. This should leave your project files "clean" such that they should work in a more typical environment as well.

Update:

I borrowed the name "main" from your question, but on reflection, "main" is a reserved name, specifically, every C or C++ program has a main.c or main.cpp as its top level code, provided by the system if you don't provide one. So I avoided using that as the folder- and project-name (but feel free to try it) and I've updated the diagram. What you do need is a project folder and a .ino file within it, of the same name. The .ino file could

    #include <src/anything-else-you-like>

, e.g., your top level code file, thus pulling everything else. You may need for your .ino to `#include` each of the files in the `src` folder, if it the compiler doesn't figure out on its own, that that's where your other files are.

BTW, if you do use the name main.cpp for your top file, it will have to call the setup() and loop() functions (and serial event function, if you use that). It's probably best to leave the name 'main' alone, let the system provide the same main every Arduino program gets by default, and write your project code the typical Arduino way -- starting with setup() and loop().


body:
When you have a project made up of a number of `.INO` files, how is the IDE supposed to know which is the "main" one? During compilation the IDE concatenates all the `.INO` files together into one monolithic file. It does this starting with the "main" one and then appends each of the others alphabetically to the end.

It is done this way so that your includes and global variables, which you should put in your "main" `.INO` file, are at the start of the finished program.

In order to do this the IDE has to know which of the files is the "main" one. And the way it works that out is by finding the one which is named the same as the folder the sketch is in.

In [UECIDE](http://uecide.org) I take it a step further and turn the whole folder into a *compound document* so you no longer have to enter a folder and open a `.INO` file to open a sketch - the actual folder itself is the whole sketch project. Again this kind of folder is identified as having a `.INO` file within it that is named the same as the folder.


message:
I keep on getting a stray '\302' in program error.How do I fix it.This is in arduino uno

#include <LiquidCrystal.h>

    int trigPin = 13;  //sensor's trigger pin connected to pin 13
    int echoPin = 7;  //sensor's echo pin connected to pin 11
    float pingTime;  //time for the ping to hit the target and back
    float ss;  //we will calculate the speed of sound
    float td = 13; //target distance.

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

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

      Serial.begin(9600);
      pinMode(trigPin,OUTPUT);  //TRIG AS OUTPUT
      pinMode(echoPin,INPUT);  //EHO AS AN INPUT

      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.println(ss);

    }

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

      digitalWrite(trigPin,LOW);  //set trig pin low.
      delayMicroseconds(2000);
      digitalWrite(trigPin,HIGH);
      delayMicroseconds(100);
      digitalWrite(trigPin,LOW);
      pingTime = pulseIn(echoPin,HIGH);  //measure ping time traveltime in microseconds.
      ss= 2*td / pingTime;  //gives us speed in inches per microseconds.
      ss=ss/63360*1000000*3600;  //gives us speed in miles per hour.
      Serial.print("The speed of sound is ");
      Serial.print(ss);
      Serial.println(" miles per hour");

      // Turn off the blinking cursor:
      lcd.noBlink();
      delay(3000);
      // Turn on the blinking cursor:
      lcd.blink(0);
      delay(3000);

    }

body:
The culprits are the no-break spaces (U+00A0) you sometimes use in your
indentation. Each of them, when encoded in UTF-8, is represented by the
pair of bytes `0xc2 0xa0` (or `0302 0240` in octal). You should indent
with _regular spaces_ (U+0020) instead.

Specifically, you have no-break spaces as the first characters of each
of the following 8 lines:

    lcd.begin(16, 2);
    // Print a message to the LCD.
    lcd.println(ss);
    [...]
    lcd.noBlink();
    delay(3000);
    // Turn on the blinking cursor:
    lcd.blink(0);
    delay(3000);


body: Beware when you copy code from sites which have formatead fonts in their content. As you copy and paste these font-formatead codes, chances are that you copy the font's formats as well. Once you paste these formatead fonts on your code, the text editor from the Arduino IDE will not recognize the special characters used on the font's formatting; thus, it will not show them on your screen. However, the compiler will read them and will strive to compile them as if they were part of your code. Since the compiler does not "understand" these special characters, it will warn you about their existence by identifying them as "stray" pieces of code. This is why some code-related sites, such as GitHub, gives you the opportunity of copying RAW CODE, so you do not copy the formatead fonts that some developers use to showcase their much appreciated contributions. I sincerely hope this works for you. Best regards.


body: Just try to removes extra spaces that are outside the scopes (curly braces `{` and `}`) and it'll work fine.


message:
Arduino beginner question

I just got a new pro-micro Atmega32U4 board, and installed the current Arduino IDE (1.8) and cannot get it working.

There is no entry for a pro-micro, so I chose Leonardo as it uses the same chip.

When I choose upload, the two red LEDs blink fast, but I get an error from avrdude, saying that it cannot upload the code.

The board is probably from a Chinese web shop ($6 clone). There are no buttons on the board.

My questions are:

* Is there already a bootloader on the chip, or do I have to program one? How do I check this?

* How does it know that it must receive an upload, instead of running the flash program?

* Which board should I choose in the IDE?

This is the error:

> Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

[It looks exactly like this one.][1]

  [1]: http://eud.dx.com/product/open-smart-atmega32u4-development-board-pro-micro-for-arduino-844452853

Update: I did everything the manual said. I can choose the pro-micro now. Still the same error message. How do I check what state the bootloader is in?

body:
There is an extensive guide written by SparkFun explaining how to work with Arduino Pro Micro: [Pro Micro & Fio V3 Hookup Guide][1].

There are specific drivers for the board, so make sure you have them installed. There are also board files for the IDE, which allow you to select the Pro Micro in Arduino software.

  [1]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide


body: I'm answering my own question. It works now. You must reset it (maybe twice) before you can upload software to it. I soldered a few wires to it for this. That did the trick.


message:
Should I use LLC to power sensors on grid pcb at 4mtr wire length distance?

I have setup a grid pcb that further distributes power and receive signal from sensors, I know low voltage can detroit if not damage sensors , so I am thinking to put [BD-LLC][1]  to distribute power output to 6 sensors connected to PCB shown below.
[ignore 24 volt power that feeds solenoid it is separate and comes from power adapter not from mega though the wire has same red colour] the 5 volt wire connecting to main connector from other connector is not visible.
[![rear view][2]][2]

[![front view][3]][3]
And I have Arduino Mega from which I am drawing power 5 volt (using digital multimeter I found it's 4.98 volt). And all sensors are connected to this 5volt parallely.
So the question is should I put this[ BD-LLC][1] on above PCB to distribute correct power output to sensors ?

  [1]: https://learn.sparkfun.com/tutorials/bi-directional-logic-level-converter-hookup-guide
  [2]: https://i.stack.imgur.com/YS9mJ.jpg
  [3]: https://i.stack.imgur.com/EKO43.jpg

body:
Transmitting power over longer distances requires careful consideration. The actual voltage you will get at the remote end depends on two major factors:

* The resistance of the wire, and
* The current draw of the remote device

If you regulate your 24V incoming power down to 7V for the Arduino and then send the Arduino's 5V over 4m of wire to power your remote board the actual voltage the board will receive depends on the amount of current the board draws.

If this current is tiny then the voltage drop for the wire will be small and can largely be ignored. For instance, you quote about 3Ω resistance for 4m of wire, which to me seems incredibly high (32AWG which is like hair thin is only ~0.5Ω/m), but anyway.  If your board draws 100mA, over your 4m wire, which is actually 8m when you take into account the length of the ground wire ("There and back again - an electron's tale.") you would drop (2*3Ω)*0.1 = 6*0.1 = 0.6V, so your 5V would turn to 4.4V by the time your board sees it. Not only that but the ground wire would be offset at the board end by 0.2V, which may impact LOW logic level detection.

So ideally you need to both minimise and mitigate that voltage drop. And both can be done using a *buck* regulator at the board and powering it from the 24V supply instead of 5V.

By using a buck regulator you massively reduce the current over the wire (for 24V to 5V you could be looking at around a quarter of the current or even less, depending on the efficiency of the regulator) which reduces the voltage drop on both the power and ground wires. It also guarantees that the board runs at 5V regardless of the current draw of the board.

Here's a diagram:

[![enter image description here][1]][1]

For digital sensors this loss of voltage could cause damage if any incoming logic signals are above the absolute maximum for the sensor (which is usually a function of the supply voltage, say Vcc + 0.3V). For analog sensors it will affect the values you are reading, since the voltage emitted from the sensor is often a function of the supply voltage, and if that is not what you expect it to be your calculations from the ADC values will be incorrect.

----

To answer your original question "can I use a LLC to distribute power" the answer is "no". The LLC can allow you to interface logic signals between two different voltage levels, but not affect power at all. And further more it requires that you have both voltages availabe for the LLC to operate, and you don't have both voltages, you only have the 5V minus the wire's voltage drop available, so you can't use it to mitigate any offset in the logic levels either.

  [1]: https://i.stack.imgur.com/4bvYA.png


message:
I have 4 motors connected to their own ESC (that is connected to a power distribution board), how do I connect this to Arduino uno? (Drone)

I am currently working with a bigger drone that I want to connect with an arduino uno.

The motor and ESC that are already soldered together and connected are these: https://hobbyking.com/en_us/mt1806-brushless-combo-include-esc-5030cw-ccw.html

I have also connected it to a power distribution board where I succesfully can connect my 3s lipo battery.

What is currently missing is where I should put the 3 pins on each ESC onto the arduino board. So there are 12 pins in total.

The color on the 3 wires on each ESC are: yellow, red and brown.

Yellow is the signal if i am not mistaken and those should be connected on the PWM pins where I control each motor in the code.

When it comes to the red it is + power and should I ignore to connect these pins? I would like for my battery to power both the motors and the arduino so of course I would prefer to connect it to the arduino uno if it is possible.

body:
Here are just some clarifications for you:

- Signal pins don't ***have*** to be connected to PWM pins. ***AFAIK***, any digital pins should work.
- **All** grounds togheter! Glad you got that right!
- Connect VCC of ESCs directly to the power supply.
- Connect power supply to VIn of Arduino (not 5V because you are going to grill it!)

---

**Uptdate**

- Yes, you can probably solder all the VCC wire of the ESCs togheter.
- By power supply, I meant connecting it directly to the battery.

---

- To power the Uno, connect the battery+ to the VIn pin of the UNO.


message:
Switch a 12V 3.3A component from an Arduino

I need turn off and turn on component from an Arduino UNO.

[![Block diagram showing the power source, the component and the Arduino][1]][1]

How can I do that? I am thinking about some transistor (IRF 530N) but I am not sure about it.

Please give me a beginner advice how to implement such a switch.

EDIT: Is this realy good for my problem?
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/vsjRk.png
  [2]: https://i.stack.imgur.com/HtQyU.png

body:
A relay, as pictured, is a good choice. It provides complete galvanic isolation and switches the power properly.

Another option is to use a MOSFET that can handle enough current (an N-channel switching the ground as a *low side* switch, or a P-channel switching the power which is itself switched by an N-channel, as a *high side* switch).


body:
I've just bought a few STP16NF06L fets for this very purpose, N channel MOSFET.

The key part of that part number is the L at the end. This indicates low (or Logic) gate threshold, which means it will switch on fully at 5v gate drive, unlike most fets which are sort of conducting at 5v but need 10v to reach their specification (like an IRF530N).

The 16 and the 06 are 16 amps and 60 volts respectively.

You can get about 25 of them for the same price as a UNO, depending on supplier, in the UK [here for instance](http://cpc.farnell.com/stmicroelectronics/stp16nf06l/mosfet-n-ch-60v-16a-to220/dp/SC11129)


message:
Value declared but not coming up as declared

void setup() {
    // put your setup code here, to run once:
    const int buttonPin2= 2;
    const int buttonPin3= 3;
    const int buttonPin4= 4;
    const int buttonPin5= 5;
    int total=0;
    int wait=0;
    int buttonState = 0;
    pinMode(buttonPin2, INPUT);
    pinMode(buttonPin3, INPUT);
    pinMode(buttonPin4, INPUT);
    pinMode(buttonPin5, INPUT);
    }
    void loop() {
    int wait=5000;
    while(wait>1)
      buttonState = digitalRead(buttonPin2);
      if(buttonState == HIGH){
        total=total+1
        wait=0
      }else{
        int wait=wait-1
      }
    int wait=5000
    int buttonState = 0;
    while(wait>1)
      buttonState = digitalRead(buttonPin3);
      if(buttonState == HIGH){
         total=total+2
        wait=0
      }else{
        wait=wait-1
      }
    int wait=5000
    int buttonState = 0;
    while(wait>1)
      buttonState = digitalRead(buttonPin4);
      if(buttonState == HIGH){
        total=total+4
        wait=0
      }else{
        wait=wait-1
      }
    int wait=5000
    int buttonState = 0;
    while(wait>1)
      buttonState = digitalRead(buttonPin5);
      if(buttonState == HIGH){
        total=total+8
        wait=0
      }else{
        wait=wait-1
      }
    int wait=5000
    Serial.begin(9600)
    while(0=0)
      Serial.println(total)
    }

body:
There are many errors in this code. Below I have high-lighted some of them. Please check your C/C++ language reference(s).

    void setup() {
    // put your setup code here, to run once:
    const int buttonPin2= 2;
    const int buttonPin3= 3;
    const int buttonPin4= 4;
    const int buttonPin5= 5;
    int total=0;                        <--- not used in setup()
    int wait=0;                         <--- dito
    int buttonState = 0;                <--- dito
    pinMode(buttonPin2, INPUT);
    pinMode(buttonPin3, INPUT);
    pinMode(buttonPin4, INPUT);
    pinMode(buttonPin5, INPUT);
    }
    void loop() {
    int wait=5000;
    while(wait>1)                             <--- missing block { ??
      buttonState = digitalRead(buttonPin2);
      if(buttonState == HIGH){
        total=total+1                         <--- missing semi-colon ;
        wait=0                                <--- dito
      }else{
        int wait=wait-1                       <--- local declare not used
      }
    int wait=5000                             <--- illegal redeclare + semicolon
    int buttonState = 0;                      <--- illegal redeclare
    while(wait>1)                             <--- missing block ;
      buttonState = digitalRead(buttonPin3);
      if(buttonState == HIGH){
         total=total+2                        <--- missing ;
        wait=0                                <--- and so on.
      }else{
        wait=wait-1
      }
    int wait=5000
    int buttonState = 0;
    while(wait>1)
      buttonState = digitalRead(buttonPin4);
      if(buttonState == HIGH){
        total=total+4
        wait=0
      }else{
        wait=wait-1
      }
    int wait=5000
    int buttonState = 0;
    while(wait>1)
      buttonState = digitalRead(buttonPin5);
      if(buttonState == HIGH){
        total=total+8
        wait=0
      }else{
        wait=wait-1
      }
    int wait=5000
    Serial.begin(9600)
    while(0=0)
      Serial.println(total)
    }

Start with something much simpler and learn to master the language. Cut-and-paste programming will not help achieve any goals you might have with this sketch. You are simply wasting your time *<:)#


message:
which spi mode shall i use given this timing diagram

I need some help to ensure my understanding of how this is supposed to work.

I want to know given the attached serial timing diagram which spi mode should I use?

Based on my newly found knowledge I believe it should be mode 1
https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino

Is this correct?

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/aWCF7.gif

body:
We can see from your diagrams that the starting state of the clock line after the CS goes active is low indicating a CPOL of zero.  Also, we see that data changes after the falling edge of the clock indicating the CPHA is also zero.  This infers, according to [this reference][1], that the SPI mode is zero.

  [1]: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase


body:
If you look at the diagram you showed, it makes sense to use mode zero.

[![SPI mode][1]][1]

Clearly you need mode 0 or mode 1 because the clock is normally low.

Now looking at the change of the data vs the clock, it makes sense that you sample on the leading edge (mode 0) - the red lines - because the diagram shows that the data is held steady for a while after the clock changes (from low to high).

It wouldn't make sense to sample on the trailing edge because immediately after that (the blue line) the data changes.

  [1]: https://i.stack.imgur.com/Ufpv6.png


message:
How many bluetooth modules can be interfaced with Arduino UNO?

At most how many bluetooth modules(HC-05) can be interfaced to Arduino UNO?<br>

body:
Two. One on the hardware UART (TX/RX pins with the `Serial` object). One on `SoftwareSerial` on any two pins you choose.

Any more than that and you will need more hardware UARTs.


message:
Can I design Arduino Mega 2560 circuit without adding ATMega 16?

I want to make Arduino Mega 2560 board.
As the reference files are given on Arduino Site, I don't want to add USB communication on the board.
So can I remove part of ATMega 16?
Will it cause any kind of problem in working of board?
And if It will fine to remove ATMega 16 part, How much part of schematic to be change?

body:
Yes, you can omit the ATmega16U2 and its accompanying parts. That is, the whole right block of schematic in [this sheet](https://www.arduino.cc/en/uploads/Main/arduino-mega2560_R3-sch.pdf).

The resulting board will work perfectly fine, it will simply no longer have a built-in programming interface, nor a built-in USB-serial interface. You will likely want to buy an FTDI cable and an AVR programmer, if you do not already have these.


message:
Microcontroller software shutdown with transistor 2N4401

I am trying to understand why connecting, say, an Arduino digital pin 4 to a `2N4401` pin 2 as well as `5V` PSU to `2N4401` pin 1 and Arduino `VCC`  to `2N4401` pin 3, won't keep power.

When shorting pin 1 and pin 3 on the `2N4401` the MCU is powered on and in-software pin 4 is set to `pinMode` `OUTPUT` and `HIGH`which should allow the `2N4401` to let power flow to the MCU for as long as power is available even when the short circuit between `2N4401` pin 1 and 3 is cut.

Instead what happens when the short between pin 1 and 3 is cut, the MCU is turned off instantly.

It's as if the transistor isn't reacting to the pin 4 MCU signal at all.

Could anyone explain why this is happening?

I'm sure I lack a lot of knowledge here and I want to know how I could utilize a `2N4401` to make a SW shutdown system.

Why `2N4401`? Why not a MOSFET?
MOSFET's circuits that do SW shutdown are available, but no transistor base SW shutdown circuits are to be found anywhere, and the `2N4401` is all that I have right now.

**Update**

[![enter image description here][1]][1]

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

    void loop(){
      digitalWrite(4, HIGH);

      delay(3000);

      digitalWrite(4, LOW);
    }

  [1]: https://i.stack.imgur.com/Rescn.png

body:
Your question is rather confusing, but some problems are evident just from looking at the schematic:

The schematic is crap.  I have no idea what you're trying to say with the dotted line between the - terminal of the the battery and the processor GND pin.

The line going thru the middle of the transistor is apparently meant to be the connection to the base, but this is sloppy at best.

It took me a while to realize you have the positive power connection at bottom and the ground at top.  Don't do that.

All these things make your schematic hard to read.  Now that I've had to waste time deciphering the schematic, I'll be more brief once we get to talking about the circuit itself.

You say the transistor is a 2N4401, which is NPN, but you show a PNP.  Huh?  Which is it?

There is no base resistor.  The E-B junction looks like a diode to the driving circuit.  When the digital output tries to go low, it will be held one diode drop below power.  That could damager the digital output or collapse the power supply.

Update

You have edited the schematic to show a NPN, but now you have a chip trying to drive itself thru a emitter follower.  The switch also does nothing at all since both its ends are already shorted together.


body:
This is what you appear to be wanting... A manually operated contact (S1 in your "diagram") momentarily shorts out the NPN transistor and applies power to the Arduino. In that short time the contact is active, you want a transistor to by pass this switch and keep applying power to the Arduino so that should the contact go open circuit, power remains on the Arduino.

The main problem, assuming my guess about what you want is correct, is the use of an NPN transistor as an emitter follower; whatever voltage you apply to the base will be about 0.7 volts lower on the emitter so, when the contact opens, the emitter voltage drops to about 4.3 volts to keep the NPN turned on but, that in turn leads to a drop in base voltage and quite rapidly you end up with nothing on the emitter.

You need a PNP transistor that can be turned on much more effectively with an NPN pulling the PNP base towards ground. In other words you need two transistors to do what you want: -

[![enter image description here][1]][1]

This one is shown at 5.5 volts on the power rail but 5 volts will be fine. It is also shown using a p-channel MOSFET instead of a PNP because the MOSFET will act as a much better "short" when activated.

Here's one that shows a PNP transistor - ignore the 12 volts - it will work on 5 volts: -

[![enter image description here][2]][2]

The "lamp" is where you connect the Arduino (aka PIC in the circuit). You will be better off with a p-channel FET though but, just in case you decide to use the PNP version you might need to lower R3 to maybe 470 ohms to provide enough base current to pass sufficient collector current to power the Arduino.

You also need to have S1 wired across the "pass" transistor - at the moment you have it connected back on itself and therefore does absolutely nothing. Note that this has been fixed in the question now!

  [1]: https://i.stack.imgur.com/IK5Pl.jpg
  [2]: https://i.stack.imgur.com/b7C9n.gif


message:
How do I do a register read?

Below is the sketch I'm using with the TI 32-bit adc ADS1262. I've been trying to achieve maximum resolution by setting the MODE2 register gain to 101, which is 32V/V. The default PGA setting is 000 or 1V/V. The line I set the gain is: "PC_ADS1262.ads1262_Reg_Write(MODE2, 5<<4 | 2);" I think it is probably set for the 32V/V, but I was wanting to do a register read to make sure where it is actually set at. I do not know how to do the register read, any suggestions?
The ADS1262 datasheet page 85 shows a RREG read register command, but I simply do not know how to use it. BTW, with the adc connected to a 10mV voltage the best results I get are 0.00997589244 volts or 0.00997589149 volts. It jumps between those two voltage readings. So the increment is 0.00000000095 volts. That's pretty good precision, but its not 32-bit. [ADS1262 datasheet][1]

     example.ino
     this example gives differential voltage across the AN0 And AN1 in volts
     Hooking-up with the Arduino
     ----------------------
    |ads1262 pin label| Pin Function         |Arduino Connection|
    |-----------------|:--------------------:|-----------------:|
    | DRDY            | Data ready Output pin|  D6              |
    | MISO            | Slave Out            |  D12             |
    | MOSI            | Slave In             |  D11             |
    | SCLK            | Serial Clock         |  D13             |
    | CS              | Chip Select          |  D7              |
    | START           | Start Conversion     |  D5              |
    | PWDN            | Power Down/Reset     |  D4              |
    | DVDD            | Digital VDD          |  +5V             |
    | DGND            | Digital Gnd          |  Gnd             |
    | AN0-AN9         | Analog Input         |  Analog Input    |
    | AINCOM          | Analog input common  |                  |
    | AVDD            | Analog VDD           |  -               |
    | AGND            | Analog Gnd           |  -               |
    -----------------------------------------------------------------
    */
    #include <SPI.h>
    #include <SoftwareSerial.h>
    #include <math.h>
    #include <ads1262.h>

    #define PGA 32
    #define VREF 2.50                 // Internal reference of 2.048V
    #define VFSR VREF/PGA
    #define FSR (((long int)1<<23)-1)

    ads1262 PC_ADS1262;                     // class

    float volt_V=0;
    float volt_mV=0;
    volatile int i;
    volatile char SPI_RX_Buff[10];
    volatile long ads1262_rx_Data[10];
    volatile static int SPI_RX_Buff_Count = 0;
    volatile char *SPI_RX_Buff_Ptr;
    volatile int Responsebyte = false;
    volatile signed long sads1262Count = 0;
    volatile signed long uads1262Count=0;
    double resolution;

    void setup()
    {
      // initalize the  data ready and chip select pins:
      pinMode(ADS1262_DRDY_PIN, INPUT);                  //data ready input line
      pinMode(ADS1262_CS_PIN, OUTPUT);                   //chip enable output line
      pinMode(ADS1262_START_PIN, OUTPUT);               // start
      pinMode(ADS1262_PWDN_PIN, OUTPUT);                // Power down output

      Serial.begin(9600);
      //initalize ADS1292 slave
      PC_ADS1262.ads1262_Init();                      // initialise ads1262
      Serial.println("ads1262 Initialised successfully....");

     }

    void loop()
    {
      volatile int i,data;

     if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data             ready(DRDY pin)
      {
        SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes  conversion register
        Responsebyte = true ;
      }

      if(Responsebyte == true)
      {
        for(i = 0; i <5; i++)
        {
          SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
        }
        Responsebyte = false;
      }

      if(SPI_RX_Buff_Count >= 5)
      {

        ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
        ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
        ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
        ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

         uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)|   ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
         sads1262Count = (signed long) (uads1262Count);      // get signed value
         PC_ADS1262.ads1262_Reg_Write(MODE2, 5<<4 | 2);  //Here is where I set the gain
         resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
        // Serial.print(resolution,15);
         volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
         volt_mV   =   volt_V*1000;                           // voltage in mV
         Serial.print("Readout voltage");
         Serial.print(" : ");
         Serial.print(volt_V,9);
         Serial.print(" V ,");

       }

      SPI_RX_Buff_Count = 0;

    }

    float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
    {
      return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
    }

  [1]: http://www.ti.com/lit/ds/symlink/ads1262.pdf

body:
Here are the important parts of the code I use to READ or WRITE to registers in the ADS1263 chip... I hope this helps you over this hurdle...

    // The ADS1263 2 byte commands.
    // Note the 3 msb are the command, the remaining bits are the starting register address.
    // Refer to table 37 on page 85 of the SBAS661B.PDF for details of the ADC command map.
    // Read XXXn nnnn register(s) starting at address XXXr rrrr. The first byte 001r rrrr and the second byte 000n nnnn.
    // Write XXXn nnnn register(s) starting at address XXXr rrrr. The first byte 010r rrrr and the seconf byte 000n nnnn.
    const byte WREG = 0x40; // 0b01000000 ADS1263 Command Write 40h + reg address.
    const byte RREG = 0x20; // 0b00100000 ADS1263 Command Read  20h + reg address.
    const byte MASK = 0x03; // 0b00000011 mask out the msb's and limit block size from 0 to 3 bytes.

    unsigned int ads1263_Read_Reg(byte thisRegister, byte bytesToRead)
    {
    byte inByte = 0;
    unsigned int result = 0;
    byte readStatus = 0;
    byte readCRC = 0;

    ... REDACTED
    // ADS1263 expects the register address in the lower 5 bits of the byte. So no shifting of the bits is necessary:
    // Now combine the address and the command into one byte bit masked to add the read register command.

    byte dataToSend = thisRegister | RREG;
    byte lengthToRead = byte bytesToRead & MASK; // Enforce a maximum of 3 bytes.

    ... REDACTED

    SPI.transfer(dataToSend);
    result = SPI.transfer(0x00);
    lengthToRead--;
    if (lengthToRad > 0)
        {
        result = result << 8;
        inByte = SPI.transfer(0x00);
        result = result | inByte;
        lengthToRead--;
        }

    ... REDACTED

    Serial.print("Register Data: ");
    Serial.println(result, BIN);

    ... REDACTED
    }

If you used an array for a read buffer you would not have to enforce a maximum of four bytes at a time reading as unsigned int can only hold four bytes...


message:
How can I fix stuttering motors that are connected to ESC's [Arduino Uno]?

Been making a few posts about my drone and i am getting closer and closer to my goal to make it work.

Right now I have a problem with stuttering with all four of my motors (sometimes the motors does not even start but they beep instead). This is the motor and esc I use: https://hobbyking.com/en_us/mt1806-brushless-combo-include-esc-5030cw-ccw.html

I put together a very quick schematic on how i have everything connected:
[![enter image description here][1]][1]

So motor connected to the ESC and the ESC grounds go to arduino Gnd, the signal pins from the ESC goes to different pwm pins and the rest of the esc goes to the power distribution where i also insert my 3s lipo battery. From my power distribution i connect two cables to my arduino uno gnd and vin pin.

When I use this very simple code:

    ESC9.write (100);
    ESC6.write (100);
    ESC5.write (100);
    ESC3.write (100);
    delay (2000);

    ESC9.write (0);
    ESC6.write (0);
    ESC5.write (0);
    ESC3.write (0);
    delay (2000);

The motors start like they should but they stutter (some motors move more than others) and as you can see in my code i tell them to stop after 2 seconds to see if i can control them and indeed they stop nicely.

This is a 3 second video on how it looks once I enter my lipo battery:

https://vid.me/XpWg

Is this a case of bad soldering somewhere perhaps or do I need to calibrate my ESC/motor? Codewise I am just using a simple Servo and then I just use the code I posted above. Do I need to add anything else maybe? Since all 4 motors are stuttering/buzzing it is most likely not a problem with the motor/esc i suppose!

My arduino uno is a chinese copy, could that have anything to do with it?

Also I made this post earlier with a little less information but more info about my soldering: https://arduino.stackexchange.com/questions/32647/all-four-of-my-esc-motors-stutters-when-i-run-it-on-my-arduino-how-can-this-be

Appreciate every help and tips!

  [1]: https://i.stack.imgur.com/tpb43.png

body:
It isn't clear from your diagram or the video what wire thicknesses you've used or precisely how currents are being routed, or how big your battery is.

Let BPG denote the ground terminal on the battery pack, and BP+ the battery's positive terminal.

There should be heavy wire from BPG to the ground pin of each ESC.  There should be a signal wire (that is, heavy or light, makes little difference as long as motor currents have their own heavy wires to follow) from BPG to an Arduino Gnd pin.

There should be heavy wire from BP+ to the positive voltage pin of each ESC.  There should be a signal wire from BP+ to Arduino Vin.

There should be signal wires from Arduino PWM outputs to ESC PWM inputs.  There should be heavy wires from ESCs to motors.

Also, in your code try changing 100 on up to 200 or 250 (or near whatever the ESC maximum setting is) to see if problem persists at higher levels of PWM drive.  Also if your battery pack is small, add some more packs of the same voltage in parallel, or try a heavier-duty pack.

*Edit 1:* Check whether each of the motors can work ok by itself.  That is, either comment out three at a time, or use if-statements that check button or jumper settings.  If all the motors work ok singly, try them in pairs or triples.  There are six different combinations of motor pairs, so rather than trying all six of those you might first try the four different sets of three motors at a time, and if that reveals a combination of three motors that fails, try the pair combinations among those three to see if there is some interaction between two motors.  If problems occur when testing with fewer than four motors, try swapping motors on to different ESCs, to find out if the problem is due to a motor, an ESC, or the battery.  (You can also swap motors on ESCs and test all four at once, but testing with fewer motors going should provide a more systematic problem solving method.)


body:
Beeping noise comes from the motors when the PWM of ESC does not have enough power to rotate the motor. Since you are hearing a noise, this is a good indication that PWM exists.

Now, if you lower your duty cycle, beeping noise should decrease and vice versa. This way, you can know that the arduino is capable of controlling your ESC PWM and duty cycle.

Since you can control duty cycle and you have a PWM and no motion, there are a couple problems that comes to mind.

- PWM of ESC can not follow BLDC rotation speed. So your ESC can't detect back emf of your motor. (From your diagram, I think its a sensorless ESC.) This could happen if ESC voltage sense pin does not work, or there is noise etc. But its unlikely that all ESC are broken.
- You say that sometimes it works and there is stuttering. Well, stuttering exists also if BLDC can't sense back emf correctly so it is issuing the wrong angle at the wrong time and this causes the motor to sometimes go back a bit which appears as stuttering.
- ESC supply voltage drops when motors are running, this causes ESC to shut down/ behave erratically. This happens when you have bad soldering or thin wires.

I would say that the third is the most probable cause.

As for back emf detection, measure motor back emf yourself using your arduino (if you don't have an osilloscope, of course). Send data to PC and see if there is good back emf when you turn the motors (turn them fast using another motor or your hands with a quick motion)


message:
Controlling servo with IR led and photodiode

I have found myself a really nice scheme of a buzzer that is controled by the IR led and photodiode by I want to upgrade it so it can be used for controlling a servo. What I have in mind is that when there is no object the servo whould stand still and when object comes by it will go to 90 degrees, wait for 5 sec and go back to 0 position. I just want to know is that possible for an Arduino starter and where should I look for help. Thanks.

body:
Yes that is possible.

Start by googling for the two halves of your project separately. Find a project, example or tutorial which controls a servo. Get it working. Understand it.  Then find one which deals with a sensor similar to the one you want to use, get it working, understand it.

Then you'll have everything you need to get your project up and running.


body:
The convenience of the Arduio development paradigm is that most common hardware projects have been abstracted by software libraries to simple software interfaces.  This is the case for controlling common servos motors.

If you find it sufficient, use the [Arduino servo library][1] to control servo motors.  There are only 6 method to understand and in most cases you only need 2 or 3 of them.  [This example][2] appears to satisfy your requirements for a sweeping servo.

  [1]: https://www.arduino.cc/en/Reference/Servo
  [2]: https://www.arduino.cc/en/Tutorial/Sweep


message:
RFID reader for unknown tag 125kHz

I have an unknown RFID tag and tried to read its value. I bought two readers, RDM6300 125KHZ and RC522 13.56MHz. Each of the readers connected to Arduino works well with the purchased corresponding tags, but not with this tag. According to my information, the tag should be 125kHz tag, but RDM6300 foes not read it. The tag is simply not detected. I am sure that the tag works, I use it to open the door.

So my question is: Is there any other RFID reader for Arduino, which is different than the two that I have, and could work?

Thank you.

![1]][1]

  [1]: https://i.stack.imgur.com/P9ZCZ.jpg

body:
It could be something else (in the RFID low freq ~ 125khz) like a HID card.
Also it could be an NFC (high freq 13.56Mhz) that its not compatible with the RC522.

Do you have access to a phone with NFC, to start ruling out what could it be?


message:
Does Atmega-2560 support image processing capability?

As the title says **can I perform image processing on Atmega-2560?**

Basically I have to capture real time images and detect green or red color.

I have not thought of the frame rate but it is not that fast or slow.

body:
No. Your question really is: Can an 8-bit processor, running at 16 MHz, with 8 KB of RAM, do image processing at an acceptable rate? Unless you are talking about 10 pixels by 10 pixels, at a frame rate of 1 frame per second, then I doubt it.

You may want to ask the "real" question. See [The X-Y Problem](http://xyproblem.info/). There are sensors around that detect colours. If you are making a maze-following robot that needs to stop if it gets near to a red wall, that is a much more achievable objective.


message:
LCD from Arduino Starter Kit not displaying text

I've been tinkering with my new Arduino a bit and I was adding an LCD from the starter kit, using information from the eleventh project in the project book, "Crystal Ball." When I connect the Arduino to my computer, the LCD lights up, but no text is displayed on the screen.

Here are some screenshots of my connections:

[![Breadboard Connections][1]][1]

[![Pin Connection Numbers][2]][2]

Finally, here's the code that I uploaded to the Arduino:

    #include <LiquidCrystal.h>

    // Create this display with the pins that I wired
    LiquidCrystal lcd(12, 11, 2, 3, 4, 5);

    void setup()
    {
        // This is a 16x2 display
        lcd.begin(16, 2);

        lcd.print("hello!");
    }

    void loop()
    {
    }

edit: Additionally, I tried adding a potentiometer to control the display, but to no avail. Below is the wiring for this (back pin goes to the third to last pin for the LCD).

[![Potentiometer Powering][3]][3]

[![Potentiometer Connection to LCD][4]][4]

  [1]: https://i.stack.imgur.com/OgWeO.jpg
  [2]: https://i.stack.imgur.com/sRovu.jpg
  [3]: https://i.stack.imgur.com/wGe5D.jpg
  [4]: https://i.stack.imgur.com/RGYL0.jpg

body:
Looking at your first picture it looks like you are wired on 12 and 13 not to 11 and 12 like your sketch specifies.

Double check your wiring against this : https://www.arduino.cc/en/Tutorial/HelloWorld

Also take your multi-meter out and buzz your connections.


body:
In the end, it turned out being a combination of what [Andre's Answer][1] suggested, as well as the "brightness" of the LCD. My potentiometer seems to have kind of a "stick" to it, meaning that to get the LCD to move to the value necessary, I had to crank the thing harder than normal, then it started displaying my text.

  [1]: https://arduino.stackexchange.com/a/32708/29433


message:
Powering Arduino with reverse car lights?

I'd like to build a reverse car sensor using Arduino

When we select reverse gear, the reverse lights powers, so we can take electricity from them.

My question is can i power my Arduino directly from the reverse lights wires, or should i use regulators or anything else?

body:
Use a switching regulator such as the LM2596. You can get a ready board from eBay for about US$1

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/0xzjG.jpg


body:
It depends very much on the car and your Arduino. There are two factors to consider:

1. Leeching power off lights can have an adverse effect on the car's ability to sense a blown bulb.
2. Many Arduinos have a 2 second delay while the bootloader executes (some even have 8 seconds).

If your car doesn't sense blown bulbs (most modern ones now do, even cheap ones) and you can work without a bootloader (programming directly with a USBasp for example) to avoid the power-on delay, then it may be possible, yes.

As has been mentioned by others, using a switching regulator is the best method for powering the board as it avoids excess power loss through heat (which can especially be a problem in confined spaces). I would recommend not using one of the cheap eBay modules, but instead using a proper "cigarette lighter" to USB adaptor (available from all good gas stations priced $5) which is designed to work with automotive voltages. A car's 12V power has transients in excess of 50V sometimes (back EMF from the spark generation) and the electronics have to be able to cope with that - those cheap eBay modules aren't designed for that and could die taking your Arduino with it.


body: This is just to top off the other answers. If you have a fairly modern car that runs on LED lights, you can easily use that voltage. ***MOST*** LEDs run from around 3-6V soyou might want to measure the voltage. If everything is good, then you can connect the positive of the LED to the 5V of your Arduino and GND to GND.


message:
Can't communicate with SIM800 module

I am using Arduino Uno R3 and a SIM800L (voltage regulator built in). My initial setup included a 10kΩ resistor soldered between the lower end of the RX and GND pins on the SIM800L, and a 4.6kΩ resistor soldered on the jumper connecting SIM800L's RX and Arduino's declared TX (pin 7). SIM800L has its own power supply (5v-2A). This is a setup I have used previously on two different SIM800L modules, and everything worked fine without any (visible) problems.

Baud rate is set to 9600 in Arduino IDE, PC port (via Device manager), and the module, through the sketch.

After loading the sketch (first one) shown on [this site][1], the SIM800L connects to the GSM network (I can tell by the delay between blinks), but the module does not respond to AT commands send via serial monitor.

**The sketch**

    #include <SoftwareSerial.h>

    //SIM800 TX is connected to Arduino D8
    #define SIM800_TX_PIN 8

    //SIM800 RX is connected to Arduino D7
    #define SIM800_RX_PIN 7

    //Create software serial object to communicate with SIM800
    SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

    void setup() {
      //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
      Serial.begin(9600);
      while(!Serial);

      //Being serial communication witj Arduino and SIM800
      serialSIM800.begin(9600);
      delay(1000);
    }

    void loop() {
      //Read SIM800 output (if available) and print it in Arduino IDE Serial Monitor
      if(serialSIM800.available()){
        Serial.write(serialSIM800.read());
      }
      //Read Arduino IDE Serial Monitor inputs (if available) and send them to SIM800
      if(Serial.available()){
        serialSIM800.write(Serial.read());
      }
    }

**Things tried**

Thinking that the resistors might be causing this, I removed all of them, and made a clean connection with Arduino. And the problem persisted.

I tried resetting the module, by passing the ATW command into a sketch:

    serialSIM800.write("ATW\r\n");
and that also gave no results. Further testing with:

    if(!serialSIM800.available()) {
        Serial.println("Not working");
    }
indicated where the problem might be.

I have also tried changing the baud rate to 48000, 57600, and 115200, but that did not solve my problem.

**The question**

Am I right in assuming that a reset to factory settings could solve my problem? If so, how can I reset the module, **without** the AT commands? If resetting would do me no good, what else could I try?

  [1]: http://www.ayomaonline.com/programming/quickstart-sim800-sim800l-with-arduino/

body:
This is widely happen problem - serial communication with SIM800L stopped working.
You *can* do reset, but in my case it didn't help: on powered SIM800L module shortcut "RST" pin with the ground for half of second - unit should reset and restart. I think it's defective architecture/firmware, but unfortunately SIMCOM dropped support for this model, so best advise is to avoid SIMCOM until they study how to make quality products.


message:
Does Arduino Tian/LininoOS support Python 3?

I'm using an Arduino Yun running OpenWRT and it only runs Python 2.7.

I need to find a microcontroller+processor+WiFi board that supports Python 3. Does the Arduino Tian work for this, or are there any others?

body:
Yes, run the following

    opkg update
    opkg install python3-base_3.4.3-2_ar71xx.ipk


message:
Linking one circuit to two Arduinos

I don't actually have to achieve this, it's more of an attempt to see what the best way to do this is. I'm sure the answer also differs depending on what circuitry you're trying to connect.

In this case, I plan on an Arduino (probably a Pro Mini or similar) that will control some RGB LEDs (via the WS2811 chip). If I wanted to add a second Arduino that would drive the LEDs if the first one failed (obviously very unlikely), I was wondering how I would do it. The WS2811 chip takes 5V, GND and data in.

My best attempt at a solution is using 3 relays which are SPDT. Connect the LEDs to the main Arduino via the normally open, which is controlled by that particular Arduino, and connect the LEDs to the backup Arduino via the normally closed, which is held open by the main Arduino. In the event of a failure, the main Arduino would lose connection to the LEDs while the backup would make a connection.

This probably isn't a very safe way of doing it (especially if the relay failed for example). Is there a way to do this?

The two Arduinos will be powered from two separate laptops.

body:
You can try something like this:

Tie both arduino 5V to WS2811 chip VCC.

Tie both arduino GND to WS2811 chip GND.

Tie both arduino DATA LINE to WS2811 chip DATA LINE.

Tie an analog input pin from the backup arduino to chip DATA LINE.

Tie an analog input pin from the main arduino to chip DATA LINE.

Issue RS232 or some form of communications between the main and backup arduino.

Program the main arduino to control the data line. Program the second arduino to:

- Sleep, if DATA LINE PWM is present. (Optional: Ask main arduino if operational)
- If DATA LINE PWM is absent (you'll see this from analog input), ask main arduino if he is okay or if this is a fault
- If no answer is received and PWM is absent, assume main arduino dead, start own PWM on DATA LINE. Also, send message to main arduino that the backup is currently online and he should not intervene.
- If main arduino comes alive, he first checks if backup is operational (Also it's good to read if PWM exists). If message is received that backup is operational, send message to backup to shut off and take DATA LINE for self.
- If no message is received and no PWM is present in DATA LINE, assume backup dead, take DATA LINE to self.

Further notes:

- If you decide to use communications, make sure to use a handshake algorithm to prevent accidental interventions.

- You can do this project without the communications between chips but it will depend on your project and will require some clever coding.

- Make sure you create some clever time gaps on those messaging and reading stuff.

- I would advise you to both use analog readings and communications because it is a sort of double check on seeing who is active at the moment. Communications will ease your code development and analog read is required in case of com line failure.

Good luck!

P.S. Don't just use relays like that. It will make debugging and code writing very difficult.


body:
You first need to make a communication between both Arduinos and then you can control RGB led from any Arduino.

For the connection between both the Arduinos, you can make a serial port interface for doing this, you just need `softwareserial.h` library. Then you just need to connect the RGB LED to one Arduino. Then when you send a command from another Arduino to that one, the Arduino (Connected to RGB LED) can operate the LED according to the command.


message:
Arduino Disconnects after router password changes

I am working with arduino Uno R3 connected with EPS8266(http://www.amazon.in/ESP8266-Serial-Wireless-Transceiver-Module/dp/B00O34AGSU?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=858e5035-7713-403a-942e-487a0fe24800). After router password is changed, it should be re programmed with new password. Is there any another way not to do so repeatedly. I managed 2 SSID for router which one have always unique password. But I think this is not a solution. Is there any technique or idea that says only for particular mac address, the SSID will be opened.

body:
Routers have multiple "passwords".  I assume you are talking about your wireless encryption key (i.e. WPA/WPA2 key).  When the encryption key is changed, you are correct: you have to re-program the ESP8266 with the new key, because it can't learn this information on its own.  If this key were broadcast, then your network would not be secure as everyone would be informed of the encryption key.

Why is the key changing?  Is there really a need to change the encryption key often?

MAC addresses can be spoofed, so permitting a specific MAC address to "always connect" is not secure.


message:
How can I read delay of a note that I am playing

I am playing note tone with CapacitiveSensor and an output of tone
like this

    void loop() {
        time_before = millis();

        long total1 =  cs_2_3.capacitiveSensor(30);
        long total2 =  cs_2_4.capacitiveSensor(30);

        if((total1>200)||(total2>200)) {

            if(total1>200) {

                tone(12,261);
                time_after = millis();
                Serial.print("Time: ");
                Serial.println(time_after-time_before);
            }
            if(total2>200) {
                 tone(12,294);
                 time_after = millis();
                 Serial.print("Time: ");
                 Serial.println(time_after-time_before);
            }
        }
    }

How can I read how many seconds I play this note par example

body:
Try this:

    void loop(){
        long total1 =  cs_2_3.capacitiveSensor(30);
        long total2 =  cs_2_4.capacitiveSensor(30);

        if((total1>200)||(total2>200)){

            if(total1>200){
                time_before = millis();
                tone(12,261);
                time_after = millis();

                Serial.print("Time: ");
                Serial.println(time_after-time_before);
            }

            if(total2>200){
                time_before = millis();
                tone(12,294);
                time_after = millis();

                Serial.print("Time: ");
                Serial.println(time_after-time_before);
            }
        }
    }

Use code indentation if you can. Also, that first `OR` (`||`) is unnecessary. I think you need to re-write this, or is this what you wanted?


body:
Your code currently will only measure the code execution time and **not** the duration of the note(s) being played.

You need to follow [uint128_t's suggestion](https://arduino.stackexchange.com/questions/32715/how-can-i-read-delay-of-a-note-that-i-am-playing#comment64941_32715) and rewrite the code to detect the "button release", at which point you measure the time with `millis()`, **and** call `noTone()`. Only then will you be able to measure the note's duration.

I believe that the source of confusion is that you seem to think that `tone()` acts like `delay()` and waits for the note to finish - it **does not**. `tone()` merely starts the note and then the next instruction is executed, without waiting for the note to end.

So, using `millis()` straight after calling `tone()` will actually only measure the time it takes to execute the `tone()` statement (and a few `if` statements - depending on whether you use your original code, or [Maximus's code](https://arduino.stackexchange.com/questions/32715/how-can-i-read-delay-of-a-note-that-i-am-playing#answer-32718)).


message:
Why do we need to amplify the signal of an electret?

I do understand from my reading that I should amplify the signal from an electret to be able to read it with an Arduino. I'd love to know the science behind that, why should we amplify the signal to be able to get a correct reading ?

body:
Arduino (or any chip that uses ADC for that matter) has a resolution. For example, arduino analog read divides 5V to 1024 levels. A.k.a 0V -> 0, 5V->1024. That gives you 4.8mV per level.

Now assume that you want to read the voltage fluctuation of a very low voltage power supply that fluctuates from 0 mV to ~8mV. What does the arduino read? You'll see either 0 or 1. So basically, you just can't successfully read that low voltage with your current setup.

Now, if you use an analog OPAMP and amplify that signal to 5V, (0mV->0V, 8mV->5V) then you can use all 1024 levels available to you, provided by arduino.

That's why you need to amplify the signal.


message:
Interrupts on the Arduino NG

I am a newbie to using arduino.

I am using an arduino NG  (using an atmega8). One of the pins is a button that triggers an interrupt.

The problem I am trying to solve is that I want an arduino NG to store the timestamp (we are using mills as a timer -no need to consider the 50 day rollover error here) when the interrupt pin is pressed.

The timer of the interrupts in milliseconds is stored in an array and there are up to 100 such interrupt button presses.

After searching around I didnt find any information for using interrupts with atmega8 on arduino NG (though there is information of how to use interrupts on atmega168 with arduino NG ).

So my question is: Is this problem solvable with an atmega8 arduino NG? Does the atmega8 arduino NG have interrupts? Just need one interrupt. And what would be the code to read an interrupt on atmega8 version of arduino NG?

body:
ATmega8-family chips have 19 interrupt vectors, vs 26 in ATmega48/88/168/328-family chips.  (See Table 16.1, Interrupt Vectors in ATmega8A, in chapter 16 of [ATmega8 documentation](http://www.atmel.com/images/atmel-8159-8-bit-avr-microcontroller-atmega8a_datasheet.pdf); and see Table 12.1, Interrupt Vectors in ATmega48A and ATmega48PA; Table 12.2, Interrupt Vectors in ATmega88A and ATmega88PA; and Table 12-4, Reset and Interrupt Vectors in ATmega168A and ATmega168PA, in chapter 12 of the ATmega48/88/168/328-family datasheet.)

Both families have INT0 and INT1 External Interrupt Request pins, so if either of those is the pin your application depends on, it should work ok on an ATmega8 system.

I don't see any mention of pin-change-interrupts in [ATmega8 documentation](http://www.atmel.com/images/atmel-8159-8-bit-avr-microcontroller-atmega8a_datasheet.pdf) so an application depending on PCI's probably wouldn't work.


body:
> Does the atmega8 arduino NG have interrupts?-

Page 1 of the datasheet:

[![Atmega8 datasheet][1]][1]

Yes, it has interrupts.

---

> just need one interrupt.

Page 46 of [the datasheet](http://www.atmel.com/Images/Atmel-2486-8-bit-AVR-microcontroller-ATmega8_L_datasheet.pdf):

[![Atmega8 interrupts][2]][2]

It looks like you have 19 of them.

---

>  regarding interrupts atmega8 is different168 there-so that may imply the the same code wont work -and I couldnt find any examples when searching

Try using the Arduino libraries. If that doesn't work post your code.

  [1]: https://i.stack.imgur.com/8nccF.png
  [2]: https://i.stack.imgur.com/iWKyy.png


message:
Arduino Uno + USB Host Shield + Motor Shield

We have an obstacle avoiding robot, and we decided to upgrade it by controlling it with a PS3 controller, so I am asking if above the Arduino UNO we can attach the USB host and above the Host attach the motor shield where the motors are connected to?

body: You need to check the I/O used by each shield to make sure there is no conflicts.


message:
how to prevent IR signal to go through 3d printed plastic?

I'm working on two arduino (one a dock, the other one on a robot) communicating through a IR to let the latter know about its location.

I 3D printed a piece which goal was to channel the 3 IR led lights, to prevent them from overlapsing (exactly in the same manner as the [Kobuki][1].

For a reason I don't know, the IR signals seem to go through  the 3D printed piece which doesn't seem to let visible light through.

I known that there is no 100% absorbant materials, and I know "black for visible lights" doesn't necessarily mean "black for IR lights".

I think my problem is more related to my lack of experience in the field. My question is : why do I get signals from a IR led channeled toward a location I am not in ?

Patently, it means my light channels are not channeling light.

Therefore, better : How can I make a better (and cheap) channel for IR light ?

The piece I 3D printed is grey (silvery like I guess)

edit : to prevent incomprehension, i would like to clarify "channel". What I mean is to block all light "not going" in the right direction, whatever happens to that light. I apologize if it is not the word I should have used.

  [1]: http://wiki.ros.org/kobuki/Tutorials/Testing Automatic Docking

body:
You can not use [common modulation remote control receivers][1] as they contain an [ACG feature][2] which will likely "turn up the volume" until it detects even a weak reflected signal.  Instead consider if [this reflective sensor][3], which does not contain an AGC feature, is appropriate for your design.

Alternatively you might explore the response time of the AGC feature to see if you can defeat its intended purpose.  That is to say, rapidly switch between IR transmitters in order to keep the AGC level at low gain.  Essentially blinding it from weak reflected signals.

You might also transmit continuously on all IR sources and determine if the AGC will put the weak signals below the noise floor.

  [1]: http://www.vishay.com/docs/82491/tsop382.pdf
  [2]: https://en.wikipedia.org/wiki/Automatic_gain_control
  [3]: http://www.vishay.com/docs/82458/tssp40.pdf


body:
The best and cheapest way would be to use BLACK colored printing material as it would absorb the IR waves and would not let them pass!
I did a similar thing when I was building an IR-based Robot so using a black reflector and painting the chassis black increased the efficiency!

Black for visible light is the same for IR too as light is just a small spectrum of electromagnetic radiation, just as IR.


body: I realize this is old but I have had a similar challenge making an code wheel for an optical encoder.  PLA material did not block the infrared.  however, all of the codewheels that I have made with black PETG material have worked.  Obviously you would want to fill in the shape as much as possible and assure that you do not have gaps between the layers.  Personally I have not had to make any tweaks with the Prusa MK3 printer, black PETG material and the common 0.2 layer height.


message:
Sweeping servo 90 degrees

#include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

    void loop() {
      for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
    }

I have found this code that makes servo go 180 and back, but when I switch 180 degrees with 90, which is what I need, my servo doesn't do that (I tried the code in Arduino simulator).

Do I have to change something elese in the code (like delay time) so it whould go 90 degrees up and then 90 down?

Here is the link of circuit:

https://circuits.io/circuits/3597808-servo-90-degrees

body:
No you **don't have to change any time delay** in order to get it rotating by 90 degrees, **delay would just change the speed** of rotation of the servo. The simulator you are using is at fault here as the sketch with **180 changed to 90** works flawlessly.

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
                    // a maximum of eight servo objects can be created

    int pos = 0;    // variable to store the servo position

    void setup()
    {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

    void loop()
    {
      for(pos = 0; pos < 90; pos += 1)  // goes from 0 degrees to 180 degrees
      {                                  // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for(pos = 90; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
    }

MAKE SURE THAT YOU CHANGE **BOTH OF THE 180'S TO 90**.


body:
I just created a simulation on Wokwi Arduino simulator based on your code and it works perfectly fine.
Here is the **permanent** [link][1]
[![enter image description here][2]][2]

  [1]: https://wokwi.com/arduino/projects/278918656574882312
  [2]: https://i.stack.imgur.com/7nyM0.gif


body:
This line of code will properly set up the PWM timers to output the correct signal to move the servo to the value set in 'pos'
```
myservo.write(pos);
```
It has nothing do with speed. The servo will try to reach 'pos' as fast as possible.

The delay(15) in your code is the delay time between each "myservo.write(pos);"

The for loop works like this:
```
myservo.write(0); // Go to 0 degrees
delay(15); // Wait 15ms
myservo.write(1); // Go to 1 degrees
delay(15); // Wait 15ms
myservo.write(2); // Go to 2 degrees
delay(15); // Wait 15ms
myservo.write(3); // Go to 3 degrees
delay(15); // Wait 15ms
```
etc...

The time in seconds it takes to make a rotation is (range_in_degrees x 15)/1000

e.g. 180deg x 15ms/1000 = 2.7 seconds
90deg x 15ms/1000 = 1.35 seconds

Increasing the 15ms delay will make the servo rotate slower.

Also, make sure that you change the 180 degrees to 90 in BOTH for loops. If you change the value in one, the servo will slowly sweep from 0 to 90, then jump to 180 and slowly swing back to 0 and repeat. (or vice versa, depending on which one you forgot to change)


message:
How is the bootloader activated when device is running?

For the sake of specificity I am referencing my question to Arduino. It applies to all AVRs with hardware USB and a bootloader though.

The bootloader is capable of receiving new program data over the USB interface, and, after programming, releases the interface. It can then for instance be used for the emulation of a serial port, or even register as a HID.

I know what a bootloader is and how it reads program data from the PC and how it writes it to the devices flash memory.

I am asking how the bootloader is triggered again if the user wants to upload a new program. The PC needs to reset the AVR in order to fire up the bootloader. How is this reset instruction implemented in Arduinos with built-in USB hardware (e.g. the [Arduino Micro](https://www.arduino.cc/en/Main/ArduinoBoardMicro))? Is it solved by performing a software reset after the DTR line goes low just as in e.g. the Arduino Nano, except that the DTR line only exists in software?

**EDIT**: If that is the case, the solution is unique to Arduinos. I was thinking that there would be some standard way of doing it common to all AVRs.

body:
On microcontrollers with bootloader (not just AVRs), the bootloader is a separate executable in flash, and it's typically the program that runs on system startup.  The application will have a special trigger, such as a button sequence, getting a specific byte sequence over I2C, or really anything that will tell the bootloader to enter into its "update" mode.  From there, the bootloader will have some communication (I2C, USB, WiFi, serial, etc) to download and the flash the new application image.

[This link has more information about the Arduino bootloader][1]

> On the PC side, to trigger a reset on the RESET pin, the PC (avrdude.exe or GNU/Linux equivalent) opens the serial port to Arduino when your press upload and the code is ready to upload. This causes the Data Transmit Ready (DTR) line of the USB/TTL chip to go LOW. The Arduino board has a capacitor charging circuit that uses this LOW (charging the capacitor) signal to momentarily pull down the RESET line of the ATMEGA328P chip before returning it to HIGH (capacitor charging completes). So Arduino resets each time its serial port is opened.
>
> Upon reset, Arduino enters the bootloader.
>
> The bootloader looks at the source that caused the reset. There are several sources that can cause a reset. If the reset was caused by the RESET pin, then it waits for one second for the PC to send in commands. When it receives valid commands, it will start accepting new Arduino code in HEX format and erase the existing code to load new one. If it doesn’t receive valid commands, it times out after one second and triggers a Watch Dog Timer (WDT) reset.

For Arduinos with built-in USB, [such as the Micro][2], the Arduino library (firmware) triggers the system reset.  There's a little chunk of code that looks for the virtual COM port to open at 1200 baud and then close.  When that happens, the code triggers a system reset (by writing a register, typically) which launches the bootloader.

> Rather than requiring a physical press of the reset button before an upload, the Micro board is designed in a way that allows it to be reset by software running on a connected computer. The reset is triggered when the Micro's virtual (CDC) serial / COM port is opened at 1200 baud and then closed. When this happens, the processor will reset, breaking the USB connection to the computer (meaning that the virtual serial / COM port will disappear). After the processor resets, the bootloader starts, remaining active for about 8 seconds. The bootloader can also be initiated by pressing the reset button on the Micro. Note that when the board first powers up, it will jump straight to the user sketch, if present, rather than initiating the bootloader.
>
> Because of the way the Micro handles reset it's best to let the Arduino Software (IDE) try to initiate the reset before uploading, especially if you are in the habit of pressing the reset button before uploading on other boards. If the software can't reset the board, you can always start the bootloader by pressing the reset button on the board.

Personal story: I wrote an I2C bootloader for the PIC32.  The only communication with the device was through the I2C bus.  The main application had a special 3 byte trigger that would set a non-initialized variable in RAM, and then trigger a system reset.  The bootloader, which runs on system startup, would check that variable and if it was set, would wait for commands over I2C to download and flash the new application image.  That variable in RAM had to be specially marked as non-initialized, otherwise the C startup code would clear it and the bootloader would never update.

The bootloader also calculated a CRC32 over the application image to validate it before attempting to boot.  If the calculated CRC32 didn't match the stored CRC32 (which was part of the application image), then the bootloader would enter its firmware update mode.  This was a guard against trying to run a corrupted firmware image, which could happen if power was pulled during the update process.

  [1]: https://liudr.wordpress.com/2016/02/26/how-arduino-bootloader-works/
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardMicro


message:
How to get current time and date in arduino without external source?

I'm working on a project using Arduino Uno and SD card shield.
I'd like to store a variable at a specific time everyday in the SD card. How can I get the current time in Arduino ?
Any help would be appreciable.

NOTE : Arduino is NOT connected to PC.

body:
An accurate enough way is to use the `millis()` function. It  will return the value in milliseconds since the start of the Arduino. If you start the Arduino at a specific time, you will be able to calculate the exact date and time.

---

Why not an external module?? An RTC such as the DS3231 in merely 5$ and it includes a temperature sensor for you!


body:
> without external source

You can't. The Arduino Uno has no real-time clock. A real-time clock is only something like $1 from eBay. For example the DS1307 or DS3231. I found 5 x boards pre-assembled with the clock chip, including battery holder, crystal, chip, and circuit board for $US 4.20 on eBay. Batteries not supplied.

Hook that up to the I2C pins (A4 and A5), set the time once using a suitable sketch, and then you are ready to roll.

---

If you just want to do something every 24 hours (not necessarily at 9:36 a.m.) then you can just use `millis` to find when the appropriate number of milliseconds has elapsed. The result from `millis` will wrap every 49 days roughly but [you don't have to worry about that](http://www.gammon.com.au/forum/?id=12127).

Note that this won't let you log the date and time, but you can log something (eg. the temperature) every day, you would just have to know when you started logging.


body:
One possibility to consider is to use a **24-hour plug-in timer** that controls the power to the Uno.

I.e. something that looks like this:

[![enter image description here][1]][1]

The circuit would be: AC outlet -> Timer -> USB charger -> Arduino

You could set the timer to turn off the power to the Uno at say 11:30 PM and turn on again on midnight.

Under such setup, `millis()` will be the time since the last Uno start, which will usually be the time since the previous midnight.

When debugging, you could set the time-at-Uno-start to other than midnight.

The caveats are:

 - Your situation allows for daily 30-minute (or whatever the timer increments are) downtime
 - Can tolerate timer shifts due to power outages

  [1]: https://i.stack.imgur.com/a4xdM.png


message:
Adding external power supply to any arduino connected component

I have an Arduino Pro Mini 3.3v and the voltage is too small for my buzzer to ring loudly. I want to add a 9v battery to power the buzzer.

This is my current circuit:
Arduino (pin 9) => Buzzer +ve
Arduino Gnd => Buzzer -ve

I want to power the buzzer using an external 9v battery but I have no idea how to implement it in the circuit. All I know is that the ground should be common.

What next?

body:
Use a MOSFET. They are like little electronic switches. They will work fine with the 9V that you want to use.

[Tutorial][1].

  [1]: https://www.youtube.com/watch?v=o4_NeqlJgOs


body:
You can use an NPN transistor for this purpose.

All you have to do is connect it this way![enter image description here][1]

Obviously use a buzzer instead of the motor and pin 9 instead of 4 :D

Arduino (pin 9)==>1k-10k Resistance==>Transistor base

Buzzer +ve ==> + 9V

Buzzer -ve ==> Transistor collector

Transistor Emitter ==> battery -ve ==> Arduino GND.

So now whenever you set the pin 9 to HIGH the transistor would allow current to pass through it from collector to emitter and your buzzer would work just as you wanted.

  [1]: https://i.stack.imgur.com/kL334.jpg
  [2]: http://www.me.umn.edu/courses/me2011/arduino/technotes/motorswitchled/arduino-motor.jpg


message:
Use Raspberry and Arduino IDE to programm ESP8266

I currently use Arduino IDE to generate binaries for ESP8266. Afterwards I copy the binaries with SFTP to my Raspberry Pi and flash the binaries using esptool.py.

These are lots of steps I need to do manually. Is it possible to automate this and use the Raspberry Pi as a programmer known to the Arduino IDE?

The goal is, that the "Upload" button in Arduino IDE does the full job.

body:
Have you tried installing Python for Windows?

http://docs.python-guide.org/en/latest/starting/install/win/

In theory it should work and you should be able to run esptool.py on a Windows command line like you do on your Pi (provided that your usb to serial in recongnized by Windows).

If esptool.py fails to run under Python for Windows I would first suggest to open a ticket with the esptool maintainer and then try under a cygwin environement (https://www.cygwin.com).


body:
I was able to find a solution based on this post: http://www.linuxquestions.org/questions/linux-networking-3/serial-over-lan-from-linux-to-windows-825334/#post4062960

Following steps are necessary.

 - Install `com0com` and `com2tcp` on the Windows machine and `socat` on the Raspberry.
 - Then add a virtual COM-pair (`COM0 <-> COM25`) on the Windows machine with the help of `com0com`.
 - Execute following command on the Raspberry. `socat file:/dev/ttyAMA0,raw,echo=0,b115200 tcp-l:3016,fork&` (adjust the device `/dev/ttyAMA0`, baudrate `b115200` and port `3016` according your needs)
 - Start `com2tcp` on the Windows PC with following command. `com2tcp --baud 115200 --ignore-dsr \\.\COM25 192.168.0.1 3016`
 - Now you can use `COM0` in Arduino IDE to flash the ESP8266 attached to `/dev/ttyAMA0` on the Raspberry


message:
Looking for learning resources to teach the "principles" rather than "follow this" projects

I just got the Arduino starter kit as my background is software developer (C++, python, etc) and I'm interested to get into the electronics side, and I love LED effects and home automation of all kinds.
As such I'm quite comfortable with the type of C programming required (loops etc) but need to learn the principles of electronics.

Can you suggest any resources (websites, tutorials, books - I'm willing to pay for books if they are useful) whose focus is teaching the principles as well as doing specific projects?

The kit came with the "Arduino Projects Book" but I don't really like it as it's focused on "do this, do that, put the circuit together according to this diagram" rather than explaining the principles first. For example I did the "Spaceship Interface" (light up different LEDs in different patterns based on whether a button is pushed or not) and it introduces things like "You'll also need to add a 10k ohm resistor from ground to the switch pin that connects to the Arduino [...] it connects the pin to ground when the switch is open so it reads LOW when there is no voltage coming in through the switch". I understand that in principle I think, but why is it 10kohm, why do we have to connect it using a resistor when the switch is open, etc. (I see that we have to have a complete circuit and I'm assuming it is because the 10kohm is a "default" branch of most resistance with nothing else connected?)

I'm asking about general principles rather than the specific case of why do we have a 10kohm resistor in this case, but this is a pretty good example early in the book.

body:
I see people are voting to close this as too broad. Well, it is broad, but I'll try to give you some pointers. I used to wonder this stuff too, like "why use 10k and not 20k or 5k?". A good starting point is to watch some of Dave Jones' [EEVblog videos](https://www.youtube.com/channel/UC2DjFE7Xf11URZqWBigcVOQ).

For example [Designing a Li-Ion Battery Gauge with the LM3914 - EEVblog #204](https://www.youtube.com/watch?v=iIKGvHjDQHs) - this is already 5 years old. He has done a lot of them. This particular one describes using the LM3914 chip to make a battery gauge, and in the middle he works through the resistor values using Ohm's Law.

Another entertaining and informative blog is [Afrotechmods](https://www.youtube.com/user/Afrotechmods). He also goes into detail but in a humorous way.

Also try [M J Lorton's blog](https://www.youtube.com/user/mjlorton).

My only problem with videos is, if you are trying to reproduce some of their stuff you end up having to rewatch a (perhaps lengthy) video and pause it from time to time to copy stuff off the screen.

For this reason I made some posts of my own on the [Electronics part of my own forum](http://www.gammon.com.au/electronics). (Some of the more popular ones are also here in Stack Exchange as reference questions, for example <https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino>).

You could also look at the [Adafruit](https://learn.adafruit.com/) and [Sparkfun](https://learn.sparkfun.com/tutorials) tutorials (amongst many others).


body:
Welcome to the Arduino world!

First I'd like to try to answer your question: (*This explanation does not apply to his situation as explained in the comments, but, I guess, it's a fun and useful read so I'll leave it here*)

> "You'll also need to add a 10k ohm resistor from ground to the switch pin that connects to the Arduino [...] it connects the pin to ground when the switch is open so it reads LOW when there is no voltage coming in through the switch". I understand that in principle I think, but why is it 10kohm, why do we have to connect it using a resistor when the switch is open, etc. (I see that we have to have a complete circuit and I'm assuming it is because the 10kohm is a "default" branch of most resistance with nothing else connected?)

I haven't seen your circuit but I think I know the deal here. The author is basically telling you to create a *pull-down* circuit. What this does is, what it says. It pulls down the voltage on arduino pin to GND. Now, why would you want to do that? I think because in your project, the author was reading analog values from that pin. He wants the pin pulled down because otherwise when the switch is open, the pin would be *floating* i.e. not connected to anything. Floating pin means that you will get random analog readings from that pin. Basically, if you don't connect that pin to any source/sink, it will act as an antenna. You will get noise. (You can actually use this to create random numbers for your arduino!)

Now, about that 10kOhm resistor: Its depends on two things. First, if you put a low value resistor, then you will draw lots of current from the supply to the ground when the switch is closed. You normally don't want that, why spend energy more than you have to? So, you pick any big resistor that you can possibly pick. But how big can you really put there? This depends on the analog read pin's current consumption. Whenever you do an ADC (analog to digital conversion) a.k.a analog read, your pin sinks/supplies tiny amounts of current and samples it to determine voltage. Atmel datasheet says that:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/X26Lh.jpg

As you can see, the good guys in Atmel already did some tests and determined that with the current Atmega328p (Arduino-UNO chip) chip, a source of 10kOhm internal resistance is sampled the best. (When you open the switch, the 10kOhm resistor is basically a 0V source with 10kOhm internal resistance)So basically, I guess, that's why the author used 10kOhm. Could you have used 20kOhm instead? Of course...

Now about the electronics book thing. The best practice with electronics is to both read and do. So, whatever book you pick, make sure it has examples and explanations that you can try. Don't buy a highly theoretical book with lots of math and physics. Don't use a simple do-this do-that book either. I can't provide you a single good book, because that's not how I prefer to learn. But I might have some good suggestions for you if you prefer to study like this as well:

- Learn the basics or R,L,C. Study filters, energy, their differential equations etc. Any book, website will do.
- Use software and simulate theoretical/explanatory circuits. LTSpice is best. For bigger projects, something like MATLAB is better.

If you do that, you'll gain some insights on how things actually work.

- Move on to transistors: BJT, MOSFET etc. What are they and how they behave?
- Combine transistors and R,L,C to create some digital-analog circuits. How do you make a RAM cell? Can you make an arithmatic logic unit?

At this point, you should be comfortable with most elements of electronics.

- Since you started with arduino, study RISC/CISC architechture. What actually is a microcontroller?
- Since you know software, try using assembly code to turn on and off some leds. This is where you meet software and hardware at the lowest possibly level you can.
- Try to make your own microcontroller using FPGA! (I've done this -it was a simple and not-so-useful CPU but nevertheless it provided insight. You can invent your own assembly language!!)

At this point you should be able to understand most basic arduino projects.

- Read atmega datasheets.
- Read Transistor, motor driver IC etc. any driver datasheet and search the terms on google. What do they mean?

After that you can do this:

- Pick a project, and do it from scratch. Without, copying any circuits from the internet. Can you place atmega chip to work stand alone, away from arduino board? Can you use that and make for example a BLDC driver?
- Pick a project and ask stackexchange. (Well, obviously). There are some really brilliant people here that are willing to help. Personally, I feel I'm learning better if I try to answer other peoples questions and ask questions.

I guess the downside/upside is you never stop learning. Electronics combined with software is a huge area of expertise.

So I wish you Good luck!


message:
Why doesn't the Ethernet W5100 shield work on Gigabit switch?

I have an Arduino Uno with an Ethernet Shield based on the Wiznet W5100 chipset : [![Ethernet Shield][1]][1]

It worked like a charm until I had to move it to another location and plugged it to a Gigabit switch. I had no link, the plug LEDs were off, or just on for a fraction of a second then off again.

I tried several switches, router and Internet boxes (french Freebox), and I ended up with the conclusion that it doesn't work when plugged onto a Gigabit switch. On every 10/100 switches, it works.

BUT

I also have a W5100 small module not designed like the shield :
[![W5100 module][2]][2]

This one is working on Gigabit switches !!!

I did see another post here : [WizNet W5100 not connecting to modern switches and routers][3], where someone told the lower bits of the first MAC Address byte should be 00. So I changed the MAC address to 08:af:01:00:00:03 with no more luck, the shield still doesn't get connectivity.

I googled for this but didn't find any resources. I'm surprised this hasn't come over, knowing that so much ethernet shields are out on the market!

I tried a second shield (like the first picture), same issue : no connectivity on Gigabit switches.

I know other old NICs or laptops that don't support Gigabit are working correctly with Gigabit switches that should "pull down" the port to 100 instead of 1000.

Does anyone have an answer about why it doesn't work and how we can have an Arduino work when connected to a Gigabit switch? (other shields?)

  [1]: https://i.stack.imgur.com/hACY0.jpg
  [2]: https://i.stack.imgur.com/WGJn5.jpg
  [3]: https://arduino.stackexchange.com/questions/28654/wiznet-w5100-not-connecting-to-modern-switches-and-routers

body:
The fix for this is to solder a 120 Ohm resistor between pins 1-2 and 3-6 of the RJ45 socket (where pin 1 is closest to the left side of the socket when looking at the top of the board. (Credit to keithsw1111 for the fix)

See https://forum.arduino.cc/index.php?topic=372779.0 for full details.

I know this was asked a long time ago however this post comes up quite high on a google search of the issue so its good to have reference to the fix.


message:
Arduino-RS232 converter baud rate problem

i have built a TTL/RS232 converter to send strings via RS232 using an Arduino nano, following the tutorial:[Arduino-RS232][1]. My problem concerns the transmission baud rate, because in the tutorial it is suggested a short script which manually generates the code which will become the RS232 signal. In this script some constant delays are used, i.e. "bit9600Delay 100 " and so on. These delays are set for a baud rate of 9600, but i need to double it to have a baud of 19200. Is it enough to divide by two those constant values or should i use a different method? Thank you very much

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoSoftwareRS232

body:
It is never good to base code on delays instead of intervals.  This is especially true for faster intervals where the execution of the code its self consume a significant portion of the interval.  Also note, some protocols only occasionally resynchronize.  RS232 resynchronizes after each byte (about 8 bits of data).  So any accumulated delay errors may impact the integrity of the bits furthest from the resynchronization event.

Instead of delays use the Arduino's built in hardware to send and receive RS232 communications.  The hardware is designed to work independently of code execution and will out perform software implementations especially for the faster baud rates.