message:
Printing arduino pin numbers to MySQL

I mistakenly posted this on stack overflow first.  The community was kind enough to point me to this forum.  I apologize for the double-post.

I've been working on an Arduino Uno r3 + WiFi Shield project for a few months now building up the complexity as I go. I've hit a wall. I started this project with exactly zero experience writing code of any kind and exactly zero experience working with boards. If you have any doubts as to whether or not I'll understand your response, please dumb it down!

I've made a simple arduino + wifi shield setup that can report a button push to a MySql database. All of the .php stuff on the backend works and the database is managed with phpmyadmin. I'm trying to add a second button but can't seem to make it work and need some help.

I have settled on a four-field database table as the output:

* 1st column: the key. A sequential, unique identifier for each entry
* 2nd column: the pin number that the sensor is connected to
* 3rd column: the sensor value
* 4th column: the date and time

Notice that I'm not using a dedicated column for each sensor. By using the sensor pin input, I want to simply print the sensor pin number in a column. This (a) saves space in the table and (b) allows the Arduino to use as many sensors as it has pins.

The idea is that each button press (even if two are pressed simultaneously) will get it's own line, sensor pin source, value, and timestamp. No values will be sent unless a button is pressed.

I haven't the foggiest idea of how to implement this! Help!

---

**My question:**

How can I ask the sketch to retrieve the pin from which a signal originates and write it to the db as a number in the second column? The 13th line of code is what will write the pin number (I think). The "senseval=" needs to be a variable that reports the source pin.

I don't know how to set this up and google has led to nothing but dead ends. I'd like this thread to answer the questions I'm sure a few more people have/will have!

---

My sketch is included below and the insert_php_doc below that. I'm using the Silinas/Benoit "Arduino /Post" example from github:

<!-- language-all: lang-C++ -->

    #include <SPI.h>
    #include <WiFi.h>

    char ssid[] = "linksys";
    int status = WL_IDLE_STATUS;
    WiFiClient client;
    IPAddress server(xxx,xxx,xxx,xxx);

    int inPin_0 = A0; // choose the input pin (sensor #1)
    int inPin_1 = A1; // choose the input pin (sensor #2) //ADDED FOR SECOND BUTTON//
    int sensorSense_0 = 0; //variable
    int sensorSense_1 = 0; //variable //ADDED FOR SECOND BUTTON//
    String SensorVal = "senseval=";// "yourdata="
    String senseval;//yourdata //MUST KEEP sensval for PHP

    void setup() {
      Serial.begin(9600);
      pinMode(inPin_0,INPUT);
      pinMode(inPin_1,INPUT);  //ADDED FOR SECOND BUTTON//
      connectWifi();
    }

    void loop() {
      sensorSense_0=analogRead(inPin_0);
      if (sensorSense_0 == LOW){
        postData();
        delay(5000);
      }
      sensorSense_1=analogRead(inPin_1); //ADDED FOR SECOND BUTTON//
      if (sensorSense_1 == LOW){ //ADDED FOR SECOND BUTTON//
        postData(); //ADDED FOR SECOND BUTTON//
        delay(5000); //ADDED FOR SECOND BUTTON//
      }

    void connectWifi() {
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid);

        delay(7000);
      }
    }
    }
    void postData() {
      senseval=SensorVal+String(inPin_0);
      senseval=SensorVal+String(inPin_1); //ADDED FOR SECOND BUTTON//

      if (client.connect(server, 80)) {
        Serial.println("connecting...");

        client.println("POST /insert_mysql_doc.php? HTTP/1.1");
        client.println("Host: www.<domain>.com");
        client.println("User-Agent: Arduino/1.0");
        client.println("Connection: close");
        client.println("Content-Type: application/x-www-form-urlencoded;");
        client.print("Content-Length: ");
        client.println(senseval.length());//yourdata
        client.println();
        client.println(senseval);//yourdata
        client.stop();
      }
      else {
        Serial.println("Connection failed");
        Serial.println("Disconnecting.");
        client.stop();
        connectWifi();
        printWifiStatus();
      }
    }

---

<!-- language-all: lang-php -->

The insert PHP from https://github.com/ericbenwa/POST-Arduino-Data-Wireless:

    <?php

    foreach ($_REQUEST as $key => $value)
    {
        if ($key == "senseval") {
            $senseval = $value;
        }
    }

    // EDIT: Your mysql database account information
    $username = "test_user";
    $password = "test_password";
    $database = "test_db_name_here";
    $tablename = "test_table_name_here";
    $localhost = "localhost";

    // Check Connection to Database
    if (mysql_connect($localhost, $username, $password))
      {
        @mysql_select_db($database) or die ("Unable to select database");

        // Next two lines will write into your table 'test_table_name_here' with 'yourdata' value from the arduino and will timestamp that data using 'now()'
        $query = "INSERT INTO $tablename VALUES ($senseval,now())";
        $result = mysql_query($query);
      } else {
        echo('Unable to connect to database.');
      }

    ?>

body:
First of all, your statement: "*I've made a simple arduino + wifi shield setup that can report a button push to a MySql database.*" is incorrect (or, at best, misleading) as the code you're running in Arduino is **not** talking with MySQL at all, but simply calling a remote PHP script via an HTTP/POST request.

So now your problem can be split in two parts:

 1. checking if your arduino (via its own wifi shield) is correctly talking with remote HTTP server (invoking proper PHP script with related parameters);

 2. checking if your PHP script is correctly dealing with MySQL.

As for 1), my first suggestion is to check web-server log files. Unfortunately you didn't tell us which web server (Apache? IIS? Other) are you running, as well as which operating system are you relying on (Linux? Windows? Other?). With Apache running on linux, tipically log files are stored in `/var/log/apache` or `/var/log/httpd` folders. There are plenty of other troubleshooting approaches but... please, let's start checking log files, ensuring that PHP script is invoked;

As for 2), your PHP script is lacking basic error-handling: should the `insert` (launched by the `mysql_query` function call) fail, you'll never know. I **strongly** suggest you to add proper error-handling code.
Based on [official documentation][1] it's as easy as checking the result value of the `mysql_query` call: "*...For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error....*" so what you have to do to improve your code (...and being notified about errors raised by MySQL via PHP) is to use something like following code:

    $result = mysql_query($query);
    if (!$result) {
       die('Invalid query: ' . mysql_error());
    }

Having said all the above, let me add a couple of other notes.

 - in your OP, you wrote: "*I'm trying to add a second button but can't seem to make it work*". So it seems that previously you were testing with only one button and, in such a case, everything worked. Is it right? If yes, please, can you tell us what you changed to add proper handling of second button?

 - in your code I see following lines:

.

    [...]
    senseval=SensorVal+String(inPin_0);
    senseval=SensorVal+String(inPin_1);
    [...]

Please note that they are probably wrong, as the second line will override the assignment of the first one. So, with such lines, you'll surely/always loose the value related to `inPin_0` (in other words: the first line, is useless).

 - giving a look to the server-side PHP script, I noted that it has been built to handle only **one** parameter (`sensval` passed to PHP via GET/POST parameter; with PHP storing it in the `$sensval` variable). So... to change the behaviour so to handle two different values... it's not trivial (in other words: such a change require a minimun understanding of web-programming and... getting deep to analyze such requirement is out of scope --I think-- of this answer).

  [1]: http://php.net/manual/en/function.mysql-query.php


sender: user

sender: assistant

body:
    int inPin_0 = A0; // choose the input pin (sensor #1)
    int inPin_1 = A1; // choose the input pin (sensor #2) //ADDED FOR SECOND BUTTON/

    ...

      senseval=SensorVal+String(inPin_0);
      senseval=SensorVal+String(inPin_1); //ADDED FOR SECOND BUTTON//

The above is wrong because you are sending the **pin numbers** and not the values read from those pins. You previously read them here:

      sensorSense_0=analogRead(inPin_0);
      ...
      sensorSense_1=analogRead(inPin_1); //ADDED FOR SECOND BUTTON//

It is `sensorSense_0` and `sensorSense_1` that you should be sending.

Also, as Damiano Verzulli pointed out, your second assignment to `senseval` clobbers the first. You want something more like:

      senseval  = SensorVal + String(analogRead(inPin_0)) + ", ";
      senseval += SensorVal + String(analogRead(inPin_1));

Even that may not be perfect, I didn't read your PHP side.

---

Looking at the PHP side now:

    $query = "INSERT INTO $tablename VALUES ($senseval,now())";

That isn't going to work too well for two values. I don't know your database schema, but that won't handle two values very well. A bit of tweaking and it might, or you could do two `INSERT` statements.


message:
Arduino connecting relay has no power output

I'm a newbie trying to control something through a relay. I've tried two relays with two different setups.

# Setup 1
External 12V dc input to the relay (SRD-12VDC-SL-C) and signal pin from arduino to the IN pin, GND of ext. power supply to the GND of the Arduino, NO and COM to the load object (i.e. an LED).

# Setup 2
Similar to setup 1, but using SRD-05VDC-SL-C, 5V from Arduino (Vin from Arduino also tested).

# Test program
Modified version of the 'blink' example.

# Symptom
1. The load object has been verified to be working before the testing.
2. Both setup can be verify the input is working, the power led and switch led of the two relay module are lighted as expected, and I can hear the click sound while switching.
3. No output can be obtained, both from the load object and using a multimeter.

# Update
[![relay setup][1]][1]
<br>
Sorry, I'm supposed to upload a Fritzing schematic, but I can't find a proper relay as I'm using.

1. The DC+ (red) of the relay is connected to the external ATX 12V.
2. The DC- (black) of the relay is connected to the external ATX ground.
3. The IN (blue) of the relay is connected to the Arduino pin 8.
4. The external ATX ground (white) is connected to the Arduino ground.
5. The NO (red) of the relay is connected to the load object Vcc.
6. The COM (black) of the relay is connected to the load object ground.

# Sketch

A simple modified version of Blink example is used for testing.

    const int relaySignalPin = 8;

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

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(relaySignalPin, HIGH);
      delay(1000);
      digitalWrite(relaySignalPin, LOW);
      delay(1000);
    }

# Question
I have no idea on why there's no voltage can be obtain between NO and COM while the switch is on, what's wrong with my setup?

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

body:
It sounds, from your textual description (*please* post a schematic or at least a photo of your setup) that you aren't providing power to the relay.

A relay doesn't have a *power output*.  It never *provides* power - it is merely a magnetically operated switch.  It is used to switch an external source of power on and off.

Treat the NO and COM pins as either side of a normal button or switch and wire it accordingly - that is (for example) connect COM to the positive of your power supply, NO to one side of your load, and the other side of your load to the negative of your power supply.

You can share the same power supply as you are feeding to the logic / drive side of the relays.


body:
So basically there are two wires connected to the same positive 12v source, one connected to VCC on the input side of the relay board and the other connected to the output side common terminal.
And there are three connections from the same negative 12v source, one connected to the ground of the relay board, one connected to the ground of the arduino, and the other connected to the ground of the load.
Then, of course, the connection to the relay to one of the digital pins of the arduino.

Well I'm pleased to report it works!

Now to discover what the jumpered COM/GND connection on my relay board does or does not do. I will report back.


message:
Can a Ethernet USB Dongle be instead of ethernet shield for arduino?

Can a Ethernet USB Dongle be instead of Ethernet shield for arduino in order to cut costs?

body: No.  Arduino can't behave as USB host.


body:
Possibly with an Arduino Due in USB OTG mode if you want to spend months and months (or even years) delving into the USB specs, reverse engineering the driver for the USB dongle and writing the software to get it working.

"Possible" but certainly not worth it when you can use a simple Ethernet shield and have it all working within a day.

And definitely not possible on anything like an Uno, etc.

Also it's possible on an Arduino that runs a full operating system (Linux) like the Edison or (possibly) the Yun (OpenWRT side of the operations, not the Arduino side).


body:
No, not directly. As @Majenko pointed out its possible but most likely over your head. I am not a big fan of the ethernet shield as I like to use my Arduino for prototyping and then build the project with the components. There are a 2 easy alternatives which are inexpensive options for accessing a network or internet via the Arduino

 - ENC28J60 Ethernet LAN Network Module
 - Esp8266 Serial Wifi Wireless Transceiver

Both are inexpensive (between $5 and $7 USD). There are tons of tutorials on line to get you up and running


message:
Can we use serial communication in arduino only for RX pin

Can we use serial communication in arduino only for RX pin, so that I am free to use pin 1(TX) as digital I/O:

<!-- language: c -->

    Serial.write('a');
    pinMode(1,OUTPUT);
    digitalWrite(1,LOW);

body:
<!-- language-all: lang-C++ -->

HardwareSerial takes over the Tx and Rx pins. However you can use SoftwareSerial.

Arduino forum user whiteglint143 made an adaptation of SoftwareSerial that does read-only.

<http://gammon.com.au/Arduino/ReceiveOnlySoftwareSerial.zip>

See [Receive Only Software Serial  - Arduino Forum](http://forum.arduino.cc/index.php?topic=240741.0)

---

> You can regain control over the TX or RX pins by unsetting the TXENn or RXENn bit in the UCSRnB register.

Like this?

    const byte LED = 1;

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      UCSR0B &= ~bit (TXEN0);  // disable transmit
      Serial.println ("Testing");
      pinMode (LED, OUTPUT);
      }  // end of setup

    void loop ()
      {
      digitalWrite (LED, HIGH);
      delay (500);
      digitalWrite (LED, LOW);
      delay (500);
      }  // end of loop

Gerben's suggestion works, in a sense. The pin flashes, but rather disconcertingly, the Tx LED on the board also flashes, out of sync with pin 1. Clearly the signal is making its way to the ATmega16U2 chip, which then flashes the indicator LED. This may not be desirable if you have something connected to the serial port, as it may be interpreted as low-speed serial communications.


message:
How to rsync my node.js project to my intel edison board, through ssh?

I would love to get rid of Intel's heavy XDK software, and be able to quickly push the updates of my node.js code into my Intel Edison (arduino compatible) board.

I tried this: `rsync -avz ./ root@192.168.100.177:/node_app_slot/`

But `rsync` is not installed on the board.

How would you do this?

body: rsync works by talking to the rsync executable running on the remote target; without said executable you will need to drop to either scp or a tar pipe.


body:
You have few options:

 1. use the Yocto sdk to compile rsync and then deploy it
 2. switch to [Debian][1] and then use the standard way to deploy rsync
 3. use scp, like the OP wrote, using the [answer][2] from Rick

If you are already looking for a more typical Unix way of doing things, option 2 might be the most efficient for you, in the long run.
I have not tried it, but AFAIK it should be possible to revert easily, since Edison uses dfu for system upgrades, so you should be able to go back to the stock SW, in case you do not like the Debian installation.

  [1]: https://learn.sparkfun.com/tutorials/loading-debian-ubilinux-on-the-edison
  [2]: https://unix.stackexchange.com/questions/105140/how-to-copy-only-new-files-using-scp-command


message:
Why did my program stop working when I eject the serial cable like it did an auto reset?

Arduino Uno based on 328p micro-controller board only works while I am inserting the serial cable between the board and the computer and I can control the speed of my two motors and every thing is work properly, but when I eject the serial cable it works badly and there is no control, is that some thing occurs like auto Reset?

There is always 5 volt feeding the Arduino, I get 5 volt regulated from the battery using "5v regulator", this regulated voltage is always connected to the Arduino board.

body:
Try increasing the voltage of the power supply. Maybe there might be a problem with the current. The Arduino has a 5V regulator on-board, try using a 9V battery. MAKE SURE THAT YOU CONNECT TO THE DC BARREL CONNECTOR.

Good luck!


message:
Communicating Via Serial1 on Arduino Mega

Apologies if this a relatively simple question, but I am rather new to Arduino's and cannot seem to find any concise information on the topic.
This is my XBee, mounted on a shield and placed onto a MEGA 2560. I want to leave Serial for USB debugging and use the Serial1 for XBee communication.
[![enter image description here][1]][1]

Just to confirm, the two XBee's do communicate if I use SoftwareSerial.   This is the code that works using SoftwareSerial:

    #include <SoftwareSerial.h>

    // XBee's DOUT (TX) is connected to pin 10 (Arduino's Software RX)
    // XBee's DIN (RX) is connected to pin 11 (Arduino's Software TX)
    SoftwareSerial serial1(10, 11); // RX, TX
    boolean nextLine = false;
    void setup()
    {
      Serial.begin(9600);
      serial1.begin(9600);
    }

    void loop()
    {
       while(serial1.available()){ // there is data being sent from the xBee
        char read = char(serial1.read());
        if(read == 'A'){
          //Where ~ is the EOT character
          serial1.write("55.134~");
        }
      }
    }
How do I communicate using Serial1?

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

body:
There is a good [example][1] on the Arduino site, but in short, you'd use the Serial1 (or -2 or -3) object the same way you use the Serial object:

    Serial1.begin(9600);
    if( Serial1.available() ){ ... }
etc.

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


body: If you take a look at the headers on the Mega, you'll notice that one of them has labels of "RX1" and "TX1" through "RX3" and "TX3". You'll also notice that the XBee shield *does not* connect to that header, therefore you *cannot* use `Serial1` through `Serial3` with the shield. Either switch to a breakout board that you can connect manually or stick to software serial.


message:
Using Piezzo Electric buzzer 10V with an Arduino Lilypad USB

I bought a 10 V Piezzo electric buzzer and I wonder how to connect it to an Arduino (in my case a Lilypad USB, but the question stands for any Arduino I guess...).
I hadn't realized this was a 10V buzzer, whereas the Arduino will support at most 5V.

I tried a simple layout such as below, with [the sample code from a sparksfun tutoral](https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-11-using-a-piezo-buzzer), but that's not working!

[![lilypad connected to buzzer][2]][2]

So, how can I do it? ... or should I use another buzzer ?

Thanks

  [2]: https://i.stack.imgur.com/PaTyG.png

body:
Your options:

 1. Try it anyway with 5V: the buzzer might still produce loud enough sounds for your needs.
 2. Use the line from the arduino to drive an "amplifying" stage (ex: 2N2222 in ON/OFF mode) - but this will also require a 10V source (like a step-up voltage converter)
 3. Get a piezo that is designed to operate at 5V


message:
10k ohm Potentiometer vs 10k ohm Resistor on LCD Display

I'm trying to use a LCD Display with my Arduino, but I don't have a potentiometer and all of the guides I find always require one, usually a 10k ohm potentiometer.

The point is that I'm not very good at this stuff, but I understand that the potentiometer is actually a resistor that can vary, am I correct? In that case, if I use a simple 10k resistor I would have the same result as if I was using that potentiometer at the higher resistance (10k).

Would it be correct to use the resistor instead of the potentiometer? Then I would have to plug the positive on one side of the resistor and both the negative and output to the LCD on the other side of the resistor?

body:
No, it would not be correct to use a single resistor to replace a potentiometer.

On an LCD the potentiometer is used to adjust the *bias level* of the LCD - that is the contrast.  You need to use it to set a voltage between Vcc and Vee, which you feed into Vo.  That is, a voltage somewhere between +5V and -5V.

You can't do that with one resistor.

You can, however, do it with two resistors.  Some experimentation will provide the right values to use.  Pick a pair of resistors which add up to around 10K (the exact value doesn't matter that much) and join them together end to end.  The two ends are the equivalent to the ends of the track of the potentiometer, and the join in the middle is the wiper.

To change the "value" of the potentiometer you then need to change the value of both resistors.  If you reduce one resistor you need to increase the other so that they still add up to around the same value.  What you are working with here is not the actual values of the resistors, but the ratio of the values of the two resistors.


body:
you can use the digital pin to do this instead of resistance or potentiometer. I used a delay 500 which gave me good readable display. a value of 100 was to bright

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

    void loop()
    {
     digitalWrite(13, HIGH);
      delayMicroseconds(500);
    /* 100 gives Approximately 10% duty cycle @ 1KHz with 500 i get a good value for screen text brightness*/
      digitalWrite(13, LOW);
      delayMicroseconds(1000 - 500);

    /* now you can add your LCD code to print what ever you like.*/
    }


message:
Hard-resetting an arduino

I need to hard reset (or seriously breathe life into) a stuck Arduino clone (Sunfounder UNO) which doesn't get recognized by Windows (error 43) after installing the wrong sketch. I am using the latest Arduino toolset and, before today, the setup was functional.

The problem is probably that I am writing to the serial in the `setup()` section like this:

<!-- language: c -->

    void setup() {
      pinMode(a0, OUTPUT);
      pinMode(a1, OUTPUT);
      pinMode(a2, OUTPUT);
      pinMode(b1, OUTPUT);
      pinMode(m0, OUTPUT);
      pinMode(m1, OUTPUT);
      pinMode(m2, OUTPUT);
      pinMode(OK, OUTPUT);
      pinMode(KO, OUTPUT);

      pinMode(carry, INPUT);
      pinMode(result, INPUT);
      delay(1000);

      Serial.begin(9600);
      Serial.write("Arduino Tester v. 0.1\n");
    }

Arduino seems to be running the code. The problem is that Windows doesn't recognize it and doesn't set up a COM port for it.

So: i'd like to nuke it and restart from scratch.

How is this done?

body:
The word "clone" immediately rings alarm bells.

Firstly, for a "normal" Arduino (like an Uno, etc) the sketch cannot influence whether Windows detects the board or not.  All that is handled by a completely separate chip.

A lot of the cheap clones these days are coming out of China with a really really cheap USB serial adapter chip.  These barely work at the best of times.  Looking at the pictures I have found of your clone (the manufacturer's site is considerably lacking in any information whatsoever) it doesn't look like it's one of those chips, but one never can tell.

If they have followed the reference designs for the Arduino then it will be an Atmel ATMega32U4 (IIRC) chip that deals with the interface to the computer.  That has firmware of its own on it, and if that has become corrupted (very unlikely) or damaged (possible) then it could cause it to not be recognised.  If that is the case the in the former instance (corrupted) you will need to replace the firmware on it. For that you will need either a hardware ICSP programmer or another Arduino.  In the latter instance you're stuffed, since you would need to replace the chip.

As I say that is unlikely.

Instead your problem is most likely actually with either Windows or the USB cable.  You may need to remove and reinstall the Arduino drivers, or try a difference USB cable.  Also try your "Arduino" on another computer.


message:
Smart Servo Shield: How to upload code to AtMega8

I recently bought a Smart Servo Shield controller from DFrobot to use with my new AX-12A Dynamixel servos. The shield is attached to an Arduino Uno. The shield itself works fine, but it does not support all of the functions that I need. The shield has an AtMega8 on board, and they also give you the slave code that it runs to look over. If I were to modify said slave code, is there a way for me to upload to the shield's controller? If so, how would I go about doing that?

Smart Servo Shield
http://www.dfrobot.com/index.php?route=product/product&product_id=958#.VfXqzxFVhBc

body:
Like the wiki says, remove the solder jumpers from the "UART SELECT" jumpers and connect to the "UART FOR Atmega8" connector in order to program it via serial. Don't forget to replace the solder jumpers after.

If you want to use ISP instead then make sure to remove the shield from the Arduino first since the shield connects all the ATmega8 ISP lines directly to the Arduino ISP lines.


message:
Ethernet to Cellular Modem Possible? | GSM + Ethernet + Arduino

Is it possible to combine an Arduino µC with a GSM shield and an ethernet shield such that a device connected via ethernet to the Arduino has internet access over the GSM network?

I have a system with an ethernet port to connect to the internet. It works fine if I plug it into my switch at home. However, I would like this system to have its own cellular internet connection.

This is what I have found so far:

 1. I'm basically trying to replicate the following:
https://nimbelink.com/e2clink-ethernet2cellular/#parts

 2. If the following reddit post:
https://www.reddit.com/r/arduino/comments/3azxs6/create_gsm_cellular_ethernet_modem_with_arduino/
 is any indication, I would think the answer is "no" but I am hoping to confirm from the expertise available here.

body:
No, it's not possible.

Chiefly because the normal Ethernet shield is not capable of routing.  The Arduino never talks to the ethernet - it talks to the chip on the shield and tells it how to handle the ethernet connection - everything else is then done by the ethernet chip and the results passed back to the Arduino.

Similarly with GSM - you make requests to it and it goes off and does the work.

To link the two together you would need raw access to the incoming ethernet packets, and you would then have to perform NAT (Network Address Translation) and maintain internal state tables for current streams and such, and pass reformatted packets on to a GSM modem that could accept raw data like that.

Way outside the scope of a lowly Arduino.

Maybe possible with one of the higher end Arduino-ish systems like the Edison, Galileo or Yun (just) since they run Linux and have a real Ethernet port and a proper USB port to communicate with a proper celular modem.


message:
Client.connect galileo gen2 not working

I'm having a problem with the intel galileo gen2 ethernet. I am trying to get a webpage, but I can only connect to the ethernet, not the webpage.
I get this in the Serial monitor:
[![Serial monitor output][1]][1]

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

My code:

    /*
      Web client

     This sketch connects to a website (http://www.google.com)
     using an Arduino Wiznet Ethernet shield.

     Circuit:
     * Ethernet shield attached to pins 10, 11, 12, 13

     created 18 Dec 2009
     by David A. Mellis
     modified 9 Apr 2012
     by Tom Igoe, based on work by Adrian McEwen

     */

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = { 0x98, 0x4f, 0xee, 0x01, 0x8d, 0xdf };
    // if you don't want to use DNS (and reduce your sketch size)
    // use the numeric IP instead of the name for the server:
    IPAddress server(216, 58, 217, 206); // numeric IP for Google (no DNS)
    //char server[] = "www.google.com";    // name address for Google (using DNS)

    // Set the static IP address to use if the DHCP fails to assign
    IPAddress ip(192, 168, 0, 177);
    IPAddress dns(192, 168, 1, 122);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        // wait for serial port to connect. Needed for Leonardo only
      }
      delay(5000);
      // start the Ethernet connection:

      Ethernet.begin(mac, ip, dns, gateway, subnet);
      Serial.println("connected to ethernet");
      // give the Ethernet shield a second to initialize:
      delay(1000);
      Serial.println("connecting...");

      // if you get a connection, report back via serial:
      int ch = client.connect(server, 80);
      if (ch) {
        Serial.println("connected");
        // Make a HTTP request:
        client.println("GET /search?q=arduino HTTP/1.1");
        client.println("Host: www.google.com");
        client.println("Connection: close");
        client.println();
      }
      else {
        // kf you didn't get a connection to the server:
        Serial.print("connection failed, error code ");
        Serial.println(ch);
      }
    }

    void loop()
    {
      // if there are incoming bytes available
      // from the server, read them and print them:
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }

      // if the server's disconnected, stop the client:
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();

        // do nothing forevermore:
        while (true);
      }
    }

Any help is greatly appreciated.

body: 6 months after figuring out the answer, I found this question again. I solved this question by adding `system("ifup eth0")` which completely solved the problem.


message:
Problem with Arduino code

Please help me with this code it's shows some error [but I can't be bothered to tell you what].

    #include <TimerOne.h>

    /**

     Analog Clock

     Paul Cox Dec 2010

    */

    #define    PI       3.141592653589793e-06;

    byte rows[8] = {9, 14, 8, 12, 1, 7, 2, 5};

    byte cols[8] = {13, 3, 4, 10, 6, 11, 15, 16};

    byte pins[16] = {5, 4, 3, 2, 14, 15, 16, 17, 13, 12, 11, 10, 9, 8, 7, 6};

    byte screen[8] = {0, 0, 0, 0, 0, 0, 0, 0};

    volatile byte screenRow = 0;

    volatile byte screenCol = 0;

    int iHour = 0;

    int iMin = 0;

    int iSec = 0;

    void setup()

    {

      Timer1.initialize(100);

      for (int i = 2; i <= 17; i++)

      {

         pinMode(i, OUTPUT);

      }

      Timer1.attachInterrupt(doubleBuffer);

      Serial.begin(9600);

      resetAnim();

    }

    void doubleBuffer()

    {

      digitalWrite(translatePin(rows[screenRow]), LOW);

      digitalWrite(translatePin(cols[screenCol]), HIGH);

      screenCol++;

      if (screenCol >= 8)

      {

         screenCol = 0;

         screenRow++;

         if (screenRow >= 8)

         {

           screenRow = 0;

         }

       }

       if((screen[screenRow] >> screenCol) & B1 == B1)

       {

         digitalWrite(translatePin(rows[screenRow]), HIGH);

         digitalWrite(translatePin(cols[screenCol]), LOW);

       }

       else

       {

         digitalWrite(translatePin(rows[screenRow]), LOW);

         digitalWrite(translatePin(cols[screenCol]), HIGH);

       }

    }

    byte translatePin(byte original)

    {

      return pins[original - 1];

    }

    void allOFF()

    {

      for (int i = 0; i < 8; i++)

      {

         screen[i] = 0;

      }

    }

    void on(byte row, byte column)

    {

      screen[column-1] |= (B1 << (row - 1));

    }

    void off(byte row, byte column)

    {

      screen[column-1] &= ~(B1 << (row - 1));

    }

    void resetAnim()

    {

      for (int i = 0; i < 8; i++)

      {

         screen[i] = B11111111;

         delay(25);

      }

      for (int i = 0; i < 8; i++)

      {

         screen[i] = B00000000;

         delay(25);

      }

    }

    void loop()

    {

      drawClock();

      iSec++;

      if (iSec == 60)

      {

        iSec = 1;

        iMin++;

        if (iMin == 60)

        {

           iMin = 0;

           iHour++;

           if (iHour == 12)

           {

              iHour = 0;

           }

        }

      }

      delay(10);

    }

    void drawClock()

    {

      allOFF();

      setHand(iHour,12,3);

      setHand(iMin,60,4);

      setHand(iSec,60,5);

    }

    // work out the pixel for a hand - val is out of a possible max val

    // radius is distance from the centre

    void setHand(int iVal, int iMax, int iRadius)

    {

      double  dAngle = (iVal * 2 * PI) / iMax;

      double  dPosX = 4.5 + (iRadius * cos(dAngle));

      double  dPosY = 4.5 + (iRadius * sin(dAngle));

      drawLine(5,5,constrain(round(dPosX),1,8),constrain(round(dPosY),1,8));

    }

    void drawLine(int x0, int y0, int x1, int y1)

    {

      int      iTemp;

      boolean  bSteep = abs(y1 - y0) > abs(x1 - x0);

      if (bSteep)

      {

         iTemp = x0; x0 = y0; y0 = iTemp;    // swap x0,y0

         iTemp = x1; x1 = y1; y1 = iTemp;    // swap x1,y1

      }

      if (x0 > x1)

      {

         iTemp = x0; x0 = x1; x1 = iTemp;    // swap x0,x1

         iTemp = y1; y1 = y0; y0 = iTemp;    // swap y0,y1

      }

      int deltax = x1 - x0;

      int deltay = abs(y1 - y0);

      int error = deltax / 2;

      int ystep = ((y0 < y1) ? 1 : -1);

      int y = y0;

      int x = x0;

      while(x <= x1)

      {
        if (bSteep)
        {
           on(y,x);
        }
        else
        {
           on(x,y);
        }
        error = error - deltay;
        if (error < 0)
        {
           y = y + ystep;
           error = error + deltax;
        }
        x++;
      }
    }

body:
It's amazing the difference one character can make:

* You must NEVER terminate a #define with a `;` unless you absolutely know that you need one when it is expanded.

You have a macro defined:

    #define    PI       3.141592653589793e-06;

That macro is then used here:

    double  dAngle = (iVal * 2 * PI) / iMax;

Expand the macro PI and you get:

    double  dAngle = (iVal * 2 * 3.141592653589793e-06;) / iMax;

Which obviously is a syntax error - you have a rogue `;` in there where you really don't want one.

Oh, and one other thing - you shouldn't define PI - the Arudino core already defines it for you to a greater accuracy than you are:

    arduino/Arduino.h:#define PI 3.1415926535897932384626433832795

... though you seem to be working in microPi's whatever those are...


message:
Why are there 3 crystals on the Mega2560 schematic?

I am a software engineer who is new(er) to electronics, I only started a couple of months ago. I've built a bunch of custom circuits, then some arduino nodes that are around my apartment that communicate with a C# server. So I've at least got the breadboarding part down.

So now I am working on a controller board that connects to my home automation system and determines the color on the LED light strips I installed into my bookshelf. So I want to transfer from working with pre-built Arduinos to building my own full node, there are some things I think I'm missing.

I've noticed that there are duplicate parts on the schematic for the [Arduino Mega2560 schematic][1] (such as there being 2 voltage regulators - one is replacement if the other is not available). I couldn't find any such description however for why there are 3 crystals located on the board. I see 3 different circuits for crystals (all of which are 16MHz).

Specifically, I am referencing the following
[![Crystal 1][2]][2]

[![Crystal 2][3]][3]

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf
  [2]: https://i.stack.imgur.com/ylfe5.jpg
  [3]: https://i.stack.imgur.com/3vI1B.jpg

body:
One of the crystals is for the ATMega8U2 chip which is being used for USB-Serial conversion.

The other two crystals are both for the ATMega2560. Why two? Basically they only populate one of the two, but they have two different footprints. One is for a surface mount resonator, the other for a through-hole crystal.

Having two footprints gives the option during assembly to go for the cheapest package at the time. It also means that the hobbyist can replaces the low accuracy resonator with a high accuracy crystal if their project requires.

---

As a side note, if you look at Y1, you will notice it is not the symbol for a crystal, it is of a resonator.


message:
How do I start a function with serial input?

I want to create a LED Sunrise/Sundown alarm clock. Therefore, I will use a Raspberry Pi that is sending commands over serial to a Teensy 3.1. Like:

 - "30 Minute Sunrise starting with Color(255,140,0)"
 - "20 Minute Sundown with Color(255,140,0)"
 - "start something else with these 3 parameter.

But I don't even get the basic serial part working. E.g. I tried this:

    void setup() {
      Serial.begin(9600);
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    }

    void loop() {
      if (Serial.available() > 0) {
        if (Serial.read() == 'A'){
          int inte1 = Serial.parseInt();
          int inte2 = Serial.parseInt();
          int inte3 = Serial.parseInt();
          int inte4 = Serial.parseInt();
          int inte5 = Serial.parseInt();
          if (Serial.read() == '\n') {
            Serial.print(inte1);
            Serial.print(inte2);
            Serial.print(inte3);
            Serial.print(inte4);
            Serial.println(inte5);
          }
        }
      }
    }

I planned to do a `case` switch afterwards. `Inte1` should define sunrise/sundown, `Inte2` the minutes, 'Inte3-5' the rgb color.

However, when I enter "A 1 100 100 100" it is not printing anything at all.

What is the best way do get this working?

Thanks in advance!

body:
Okay, as Majenko and Nick Gammon have suggested. The `\n` had not arrived in the serial buffer. That way the if clause was not fulfilled and nothing was printed. This code has worked for me now:

    if (Serial.available() > 0) {
     if (Serial.read() == 'A'){
      char inte1 = Serial.read();
      int inte2 = Serial.parseInt();
      int inte3 = Serial.parseInt();
      int inte4 = Serial.parseInt();
      int inte5 = Serial.parseInt();
      Serial.print(inte1);
      Serial.print(inte2);
      Serial.print(inte3);
      Serial.print(inte4);
      Serial.println(inte5);
     }
    }
Although i read quite a bit now, serial input is still a mystery to me.


message:
Where to get the potentiometer that comes with Arduino kit

Does anyone know where I can get the potentiometer that comes with the Arduino kit? You can see them [here][1].

[They are sold out on their website][2].

  [1]: http://www.arduino.cc/documents/datasheets/Potentiometer.PDF
  [2]: https://store.arduino.cc/product/C000013

body:
It's just any old trimmer pot. It's nothing special. Why do you feel you need that specific one? Any pot (of the right value) will do.  What value is it? (That datasheet is a generic one for all values).

Visit your favourite electronics retailer (IRL or on line) and pick a pot that is a suitable value and jiffles your tipples.


message:
Looking for circuit diagram for evaluation of a pulsed signal

How can I evaluate a pulsed signal in Arduino? The signal comes from an car alarm system and is called (-) output 200 mA. Arduino and the car have the same GND. Can I attach the output through a resistor to PB0 (D8) or PD5 (D5)?
Alarm system is called Ampire. Probably the same as Viper. I just wanted to read these pulses, but I do not know exactly how I connect this output correctly with Arduino.
This is the description for this Output:

----------

 **HN1/9 BROWN/WHITE – 200mA (-) Horn honk output: This wire supplies a 200mA (-) output that can be used to honk the vehicle’s horn. It provides a pulsed output when the security system is armed/disarmed and in trigger sequence or in panic mode. In most vehicles with (-) horn circuits this wire can control the vehicle’s horn without adding a relay. If the vehicle has a (+) horn circuit, an optional relay must be used to interface with the vehicle’s horn circuit**.

----------

body:
I found a user manual at [AMPIRE Car Alarm System for High-Speed CAN-Bus](http://www.ampire.de/Security-Systems/Security-for-CAN-Bus-System/AUDI/AUDI-A3/from-model-year-2013/AMPIRE-Car-Alarm-System-for-High-Speed-CAN-Bus.htm?shop=ampire_en&SessionId=&a=article&ProdNr=CAN3903V&t=2899&c=16941&p=16941).

> **N1/9 BROWN/WHITE – 200mA (-) Horn honk output:**
>
This wire supplies a 200mA (-) output that can be
used to honk the vehicle’s horn. It provides a pulsed output when the security system is armed/disarmed
and in trigger sequence or in panic mode. In most vehicles with (-) horn circuits this wire can control the
vehicle’s horn without adding a relay. If the vehicle has a (+) horn circuit, an optional relay must be used
to interface with the vehicle’s horn circuit.

> **IMPORTANT!**
 Never use this wire to drive anything but a relay or a low-current input! This transistorized output can only supply (-) 200mA and connecting directly to a solenoid, motor or other high current device will cause the module to fall

Judging by that this output will sink up to 200 mA. You could conceivably set an Arduino pin to INPUT_PULLUP and let this output drive it low to indicate it is active.

Personally I think I would use an optocoupler, in case there were unexpected voltages on that pin. You would need a series resistor to limit current through the LED in the optocoupler, say 1 k would be about right if you were connecting it to the 12V car system.

    Vf = 1.2V (say)
    Voltage over resistor = 12 - 1.2 = 10.8 volts
    Current through LED = 10 mA
    Limiting resistor = 10.8 / 0.01 = 1080 ohms

Now the output of the optocoupler can sink your Arduino pin, which you have configured as input pullup.

Write a test sketch to see what you are getting through it, but a multimeter should probably tell you, if it just flashes it slowly.

---

Suggested schematic:

[![Schematic for optocoupler][1]][1]

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


message:
Making servo spin and able to detect angle

After researching other posts I can see how to make a servo spin continually and remove the ability to set to a specific angle.

What I'm trying to do is make a small project that has a spinning 'game wheel', each segment of the wheel has a prize on it (think almost wheel of fortune). The catch is when someone has landed on a prize once it cannot be landed on again so I want to manipulate the spin slightly so it doesn't stop on the same prize. Do do this I need to be able to get the spin AND know where the needle is pointing.

Is there a component that will allow both a full rotation AND the ability to control the location of the needle at the same time? I suspect servos can do one, or the either but not both.

body:
The way I'd do it is the following:

 * use an optical encoder with an [endstop][1], they come @ 1€ on ebay, bought 4 today :-) - this will tell you the angular speed and incremental position
 * use a photo transistor to detect a specific point on the wheel (make a small hole or paint a spot in a different colour) - this will give you
the absolute position of the wheel, to calibrate the previous step.

With this solution you do not even need a step motor, a DC motor will do it and probably has better characteristics, for the same cost.
So you could explore the DC option if it turns out that the stepper is not good enough.

  [1]: http://img.diytrade.com/smimg/1033354/32796591-447715-0/Optical_Endstop_for_3D_printer_use_together_with_RAMPS_1_4_controller/ed5e.jpg


body: As for Me the Best Way to To Use a Position Servo with the Feedback in it ( it comes with 6 wire ) then You put all Your Positions For the prizes in An Array and if Anytime You Land on An Index then You Should but it in an Array that Holds all the prizes angle visited Which you will use as a check Before Turning the Servo


message:
Potentiometer won't work

I'm trying to get the potentiometer seen at the top left of the photo to work, essentially as a dimmer. I've managed to upload the Arduino sketch, but it isn't working. Any help would be greatly appreciated!
NB: I have little-to-no electronics experience so my understanding of jargon is limited.

Thanks!

    /*
     SENSOR_LIGHTS: Potentiometer >> LED (Single Channel Script)

     This example dims light levels using an LED on pin 11
     and a potentiometer on A0.

     Created by Ryan Achten | SOMA | somavisions.com

     This example code is in the public domain.
     */

    int potentLevel;
    int ledLevel;

    //*************************CHECK*****************************

    int led = 11;           // the pin that the LED is attached to
    int inputPin = A0;      // the pin that the potentiometer is attached to

    //*************************CALIBRATE*************************

    const int numReadings = 1;  //change this to alter the number of values to be averaged
    int potentMin = 280;
    int potentMax = 700;        //maximum output from potentiometer
    int loopDelay = 100;       //delay time between loops. Too low may cause overclocking
    //                            while too high may cause delayed sensor response

    //***********************************************************

    int potentAve = 0;
    int readings[numReadings];
    int index = 0;
    int total = 0;

    // the setup routine runs once when you press reset:
    void setup()  {

      //*************************POTENT >> LED SETUP CODE*************************

      Serial.begin(9600);

      pinMode(led, OUTPUT);

      //***************************SMOOTH SETUP CODE*****************************
      // initialise all the readings to 0:
      for (int thisReading = 0; thisReading < numReadings; thisReading++)
        readings[thisReading] = 0;

    }

    //****************************SMOOTH LOOP CODE****************************

    void loop()  {

      total= total - readings[index];
      readings[index] = analogRead(inputPin);
      total= total + readings[index];
      index = index + 1;

      if (index >= numReadings)
        index = 0;

      potentAve = total / numReadings;
      Serial.print("Average Potentiometer Readings: ");
      Serial.println(potentAve);

      //*************************POTENT >> LED LOOP CODE*************************

      ledLevel = map(potentAve, potentMin, potentMax, 0, 255);
      Serial.print("LED Level: ");
      Serial.println(ledLevel, DEC);
      analogWrite(led, ledLevel);

      Serial.println();
      delay(loopDelay);

    }

[![Electronics Schematic][1]][1]

[![Photo of electronics][2]][2]

  [1]: https://i.stack.imgur.com/9idR0.jpg
  [2]: https://i.stack.imgur.com/Oq9U7.jpg

body:
Assuming the brown board in your drawing is stripboard, I have to as the question:

What is this?

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

If those five wires in that column are all ground, that link is basically short circuiting your MOSFET via the green wire next to it, thus rendering your whole circuit pointless.  The LEDs will just be on full brightness permanently since the current just flows from the input power, through the LED strip, through the red/white wire, through that little white link wire, then through the green/white and/or the brown/white wires to ground.

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


message:
Problem in SIM900 GPRS connection

I make simple code to read web page by [ITEAD Gboard][1]. Here is my code:

      Serial.write("\nStarting..........\n");
      mySerial.print("AT+CSQ");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----1-----\n");

      mySerial.println("AT+CGATT=1");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----2-----\n");

      mySerial.println("AT+CGATT?");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----3-----\n");

      mySerial.print("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----4-----\n");

      mySerial.print("AT+SAPBR=3,1,\"APN\",\"internet\"");
      delay(2000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----5-----\n");

      mySerial.print("AT+SAPBR=1,1");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----6-----\n");

      mySerial.print("AT+HTTPINIT");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----7-----\n");

      mySerial.print("AT+HTTPPARA=\"URL\",\"xx.xx.xx.xx/my/web/site\"");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----8-----\n");

      mySerial.print("AT+HTTPDATA=100,1000");
      delay(10000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\n-----9-----\n");

      mySerial.println("AT+HTTPREAD");
      delay(1000);

      while(mySerial.available()!=0)
        Serial.write(mySerial.read());

      Serial.write("\nend.\n");

Which i get the following output:

    Starting..........
    AT+CSQ
    -----1-----
    AT+CGATT=1

    ERROR

    -----2-----
    AT+CGATT?

    +CGATT: 1

    OK

    -----3-----
    AT+SAPBR=3,1,"CONTYPE","GPRS"
    -----4-----
    AT+SAPBR=3,1,"APN","internet"
    -----5-----
    AT+SAPBR=1,1
    -----6-----
    AT+HTTPINIT
    -----7-----
    AT+HTTPPARA="URL","xx.xx.xx.xx/my/web/site"
    -----8-----
    AT+HTTPDATA=100,1000
    -----9-----
    AT+HTTPREAD

    ERROR

    end.

AT+HTTPREAD return error. What wrong with me?

**Note**

xx.xx.xx.xx/my/web/site is my web page. The error is still there for all web page.

  [1]: http://imall.itead.cc/gboard.html

body:
The problem (I believe) is that half way through your program you switched from using `println()` to using `print()`, thus the commands from that point on aren't being executed until right at the end where you switch back to `println()`, so the whole of the text you send from point 3 onwards is being run as one single command - which of course is in the wrong format:

> AT+SAPBR=3,1,"CONTYPE","GPRS"AT+SAPBR=3,1,"APN","internet"AT+SAPBR=1,1AT+HTTPINITAT+HTTPPARA="URL","xx.xx.xx.xx/my/web/site"AT+HTTPDATA=100,1000AT+HTTPREAD


message:
Arduino code (on board) runs really slow

Stumbled upon this weirdest behavior, from time to time, my Arduino (UNO) runs gode really slow.

Searching this issue didn't clarify anything, most people have problems with IDE itself. My issue is related to actual board.

Heres a sample of my flow:

 - I compile & upload my sketch, all good
 - first initiation of program on the board seems to be "fast"
 - when I start to "animate" the neopixels it goes 3-4 times slower than it should
 - I'll touch the board, and animation goes fast again.

[Here's a clip of that, at the end you'll see the "slowness"][1]

* Test environment:
[![enter image description here][3]][3]

* Live environment:
[![enter image description here][4]][4]

The Touching part, is almost like if I "add" static electricity from my finger to the board, it wakes up and behaves normally.

For you who are curious about (non related) what animation I'm doing on neopixels, I'm turning on 15 pixels from 0 to 54. Like a "slide effect".
(I'm not using delay, only a delay(30) in the loop, rest of the delays are based on `millis()`)

Is there any general info / explanation that would explain this behavior, like in electronics, arduino boards specifically ?

EDIT: I should also add, when printing logs into serial monitor, that slowness also affects the  outputs... they appear as "slow" as the pixels flow. When all works normally, I see pixels change and logs 50 times per second (roughly), but in this slow motion, I see pixels change and logs around 20 times per second.  Taking out the `Serial` entirely from the code doesn't seem to have effect.

Code:

    #include <Adafruit_NeoPixel.h>
    #include <avr/power.h>
    #define LEFT_BLINK_IN 2
    #define RIGHT_BLINK_IN 3
    #define PIN           6
    #define NUMPIXELS     54
    Adafruit_NeoPixel     leftLight = Adafruit_NeoPixel(NUMPIXELS, 6, NEO_GRB + NEO_KHZ800);
    Adafruit_NeoPixel     rightLight = Adafruit_NeoPixel(NUMPIXELS, 10, NEO_GRB + NEO_KHZ800);
    int leftBlinkCount   = 0;
    int rightBlinkCount  = 0;
    int PIXELTOSHOW      = 20;
    bool OEM_RIGHT_ON    = false;
    bool OEM_LEFT_ON     = false;
    int R_PIXEL          = -1;
    int L_PIXEL          = -1;
    int G_PIXEL          = -1;
    int D_PIXEL          = -1;
    char LAST_COMMAND;
    bool DRL_ON         = false;
    int DRL_STARTPIXEL  = 35;
    uint32_t COLOR_YEL = rightLight.Color(240, 120, 0);
    uint32_t COLOR_RED = rightLight.Color(255, 0, 0);
    uint32_t COLOR_BLU = rightLight.Color(0, 0, 255);
    uint32_t COLOR_NON = rightLight.Color(0, 0, 0);
    uint32_t COLOR_WHI = rightLight.Color(255, 255, 255);

    unsigned long rightPrevMillis = 0;
    unsigned long leftPrevMillis = 0;
    unsigned long generalPrevMillis = 0;
    const long PIXEL_SWITCH_INTERVAL = 5;

    int DRL_RESETER_LEFT = 0;
    int DRL_RESETER_RIGHT = 0;

    void welcome()
    {
      int totalPixels = (NUMPIXELS + PIXELTOSHOW);
      while (G_PIXEL < totalPixels) {
        unsigned long leftCurrentMillis = millis();
        if (leftCurrentMillis - leftPrevMillis >= 12) {
          leftLight.setPixelColor(totalPixels - G_PIXEL, COLOR_WHI);
          rightLight.setPixelColor(totalPixels - G_PIXEL, COLOR_WHI);
          if (G_PIXEL >= 10) {
            leftLight.setPixelColor(totalPixels - G_PIXEL + PIXELTOSHOW , COLOR_NON);
            rightLight.setPixelColor(totalPixels - G_PIXEL + PIXELTOSHOW , COLOR_NON);
          }
          leftLight.show();
          rightLight.show();
          G_PIXEL++;
          leftPrevMillis = leftCurrentMillis;
        }
      }
      G_PIXEL = 0;
      while (G_PIXEL < totalPixels) {
        unsigned long leftCurrentMillis = millis();
        if (leftCurrentMillis - leftPrevMillis >= 12) {
          leftLight.setPixelColor(G_PIXEL, COLOR_WHI);
          rightLight.setPixelColor(G_PIXEL, COLOR_WHI);
          if (G_PIXEL >= 10) {
            leftLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
            rightLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
          }
          leftLight.show();
          rightLight.show();
          G_PIXEL++;
          leftPrevMillis = leftCurrentMillis;
        }
      }
    }

    void blinkRight()
    {

      //slidePixels(rightBlinkCount, R_PIXEL, rightLight);
      if (rightBlinkCount > 0 && R_PIXEL > -1)
      {
          //Serial.println("RIGHT "+String(rightBlinkCount));
        LAST_COMMAND = ' ';
        unsigned long rightCurrentMillis = millis();
        if (rightCurrentMillis - rightPrevMillis >= PIXEL_SWITCH_INTERVAL) {
          rightLight.setPixelColor(R_PIXEL, COLOR_YEL);
          if (R_PIXEL >= PIXELTOSHOW)
          {
            rightLight.setPixelColor(R_PIXEL - PIXELTOSHOW, COLOR_NON);
            if (G_PIXEL > -1 && DRL_ON == false) {
              leftLight.setPixelColor(R_PIXEL - PIXELTOSHOW, COLOR_NON);
            }
          }
          leftLight.show();
          rightLight.show();
          R_PIXEL++;
          rightPrevMillis = rightCurrentMillis;
        }
        if ( R_PIXEL >= (NUMPIXELS + PIXELTOSHOW)) {
          rightBlinkCount--;
          if ( rightBlinkCount > -1 ) {
            R_PIXEL = DRL_RESETER_RIGHT = 0;
          } else {
            L_PIXEL = G_PIXEL = -1;
          }
          if(DRL_ON){
            D_PIXEL=DRL_STARTPIXEL;
          }
        }
      }

      }

      void blinkLeft() {
      //  slidePixels(leftBlinkCount, L_PIXEL, leftLight);

        if (leftBlinkCount > 0 && L_PIXEL > -1)
      {
              //Serial.println("left  "+String(rightBlinkCount));
        LAST_COMMAND = ' ';
        unsigned long leftCurrentMillis = millis();
        if (leftCurrentMillis - leftPrevMillis >= PIXEL_SWITCH_INTERVAL) {
          leftLight.setPixelColor(L_PIXEL, COLOR_YEL);
          if (L_PIXEL >= PIXELTOSHOW)
          {
            Serial.print(" "+String(L_PIXEL));
            leftLight.setPixelColor(L_PIXEL - PIXELTOSHOW, COLOR_NON);
            if (G_PIXEL > -1 && DRL_ON == false) {
              rightLight.setPixelColor(L_PIXEL - PIXELTOSHOW, COLOR_NON);

            }
          }
          rightLight.show();
          leftLight.show();
          L_PIXEL++;
          leftPrevMillis = leftCurrentMillis;
        }
        if ( L_PIXEL >= (NUMPIXELS + PIXELTOSHOW) ) {
          leftBlinkCount--;
          Serial.println("Count "+leftBlinkCount);
          if ( leftBlinkCount > -1 ) {
            L_PIXEL = DRL_RESETER_LEFT = 0;
          } else {
            L_PIXEL = G_PIXEL = -1;
          }
          if(DRL_ON){
            D_PIXEL=DRL_STARTPIXEL;
          }
        }
      }

    }

    /*void slidePixels(int &blinkCount, int &blinkPixel, Adafruit_NeoPixel &sideLight){
      if (blinkCount > 0 && blinkPixel > -1)
      {
        LAST_COMMAND = ' ';
        unsigned long leftCurrentMillis = millis();
        if (leftCurrentMillis - leftPrevMillis >= PIXEL_SWITCH_INTERVAL) {
          sideLight.setPixelColor(blinkPixel, COLOR_YEL);
          if (blinkPixel >= PIXELTOSHOW)
          {
            if(G_PIXEL>-1){
              rightLight.setPixelColor(blinkPixel - PIXELTOSHOW, COLOR_NON);
              leftLight.setPixelColor(blinkPixel - PIXELTOSHOW, COLOR_NON);
            }
          }
          rightLight.show();
          leftLight.show();
          blinkPixel++;
          leftPrevMillis = leftCurrentMillis;
        }
        if ( blinkPixel >= (NUMPIXELS + PIXELTOSHOW) ) {
          blinkCount--;
          if ( blinkCount > -1 ) {
            blinkPixel = 0;
          } else {
            blinkPixel = -1;
            if(DRL_ON){
              G_PIXEL = -1;
            }
          }
        }
      }
    }*/

    int switchRB = 0; // 0 = red, 1 = blue
    void slideBlueRed() {
      unsigned long currentMillis = millis();
      if (currentMillis - generalPrevMillis >= 100) {
        if (switchRB == 0) {
          leftLight.setPixelColor(G_PIXEL, COLOR_RED);
          rightLight.setPixelColor(G_PIXEL, COLOR_RED);
        } else {
          leftLight.setPixelColor(G_PIXEL, COLOR_BLU);
          rightLight.setPixelColor(G_PIXEL, COLOR_BLU);
        }
        if (G_PIXEL >= 10) {
          leftLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
          rightLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
        }
        leftLight.show();
        rightLight.show();
        G_PIXEL++;
        generalPrevMillis = currentMillis;
      }
    }

    void drlLight(){

      unsigned long currentMillis = millis();
      if (D_PIXEL < NUMPIXELS) {
        leftLight.setPixelColor(NUMPIXELS-DRL_RESETER_LEFT, DRL_ON == true ? COLOR_WHI : COLOR_NON);
        rightLight.setPixelColor(NUMPIXELS-DRL_RESETER_RIGHT, DRL_ON == true ? COLOR_WHI : COLOR_NON);
        rightLight.setBrightness(128);
        leftLight.setBrightness(128);
        rightLight.show();
        leftLight.show();
        D_PIXEL++;
       //x //Serial.println(String(DRL_RESETER_LEFT) + " "+ String(NUMPIXELS - DRL_STARTPIXEL));
        if(DRL_RESETER_LEFT+1 < (NUMPIXELS - DRL_STARTPIXEL)){
          DRL_RESETER_LEFT++;
        }
        if(DRL_RESETER_RIGHT+1 < (NUMPIXELS - DRL_STARTPIXEL)){
          DRL_RESETER_RIGHT++;
        }
        generalPrevMillis = currentMillis;
      }

    }

    void setup() {
      Serial.begin(115200);
      leftLight.begin();
      rightLight.begin();
      pinMode(LEFT_BLINK_IN, INPUT);
      pinMode(RIGHT_BLINK_IN, INPUT);
      delay(50);
      welcome();
    }

    void loop() {

      if (digitalRead(LEFT_BLINK_IN) == HIGH) {
        if ( OEM_LEFT_ON == false ) {
          OEM_LEFT_ON = true;
          leftBlinkCount++;
          //Serial.println("LEFT "+String(leftBlinkCount));
          if (leftBlinkCount == 1) {
            L_PIXEL = 0;
          }
        }
      } else {
        OEM_LEFT_ON = false;
      }

      if (digitalRead(RIGHT_BLINK_IN) == HIGH) {
        if ( OEM_RIGHT_ON == false ) {
          OEM_RIGHT_ON = true;
          rightBlinkCount++;

          if (rightBlinkCount == 1) {
            R_PIXEL = 0;
          }
        }
      } else {
        OEM_RIGHT_ON = false;
      }

      if(DRL_ON && leftBlinkCount < 1 && rightBlinkCount < 1){
        drlLight();
      }

      blinkRight();
      blinkLeft();
      if(rightBlinkCount < 1 || leftBlinkCount < 1){
        delay(30);
        switch (LAST_COMMAND) {
          case 'q':
          case '?': {
            for ( int gp = 0; gp < NUMPIXELS + PIXELTOSHOW; gp++) {
              leftLight.setPixelColor(gp, COLOR_NON);
              rightLight.setPixelColor(gp, COLOR_NON);
            }
            leftLight.show();
            rightLight.show();
            G_PIXEL = -1;
            break;
          }
          case 's': {
            slideBlueRed();
            //Serial.println("bluuu");
            if (G_PIXEL >= NUMPIXELS ) {
              G_PIXEL = -1;
              switchRB = switchRB == 0 ? 1 : 0;
            }
            break;
          }
          case 'w': {
            welcome();
            if (G_PIXEL >= NUMPIXELS + PIXELTOSHOW) {
              G_PIXEL = -1;
            }
            break;
          }
          case 'd': {
            if(DRL_ON==false){
              D_PIXEL = DRL_STARTPIXEL;
              DRL_ON = true;
              LAST_COMMAND = '-';
            }else{
              D_PIXEL = 0;
              DRL_ON = false;
            }
            break;
          }
        }
        if (Serial.available()) {
          LAST_COMMAND = '-';
          while (Serial.available()) {
            char command = Serial.read();
            G_PIXEL=-1;
            LAST_COMMAND = command;
          }
        }
      }
    }

  [1]: https://www.youtube.com/watch?v=B-7562YRjLU
  [3]: https://i.stack.imgur.com/9HW7S.png
  [4]: https://i.stack.imgur.com/bAezE.png

body:
This kind of behavior is almost always caused by floating digital input pins. "floating" means not connected to either power or ground, so their voltage is free to float. These input puts have very high impedance (typically less than 1uA of leakage current), so bringing a charged object near them is more enough to change their state.

Probably the easiest way to nail down (and sometimes fix) this problem is to enable the pull-up resistors on the digital inputs.

In you program, this could be as easy changing the mode on the digital input pins from `INPUT` to `INPUT-PULLUP`...

    void setup() {
      Serial.begin(115200);
      leftLight.begin();
      rightLight.begin();
      pinMode(LEFT_BLINK_IN, INPUT_PULLUP );
      pinMode(RIGHT_BLINK_IN, INPUT_PULLUP );
      delay(50);
      welcome();
    }

This will almost certainly eliminate the intermittent behavior you are seeing.

What you end up with might not be what you want (you might want the pin to dault to 0 when not connected), in which case you can add an external pull-down resistor or change the software to work with default pull-up.


body:
Now, 3 years later, I found the actual source of your problem. I had a similar problem so I'm posting here for others to find this solution.

The problem is that the NeoPixel library disables ALL interrupts during the time it spends sending the pixel data. The millis() function is dependent on interrupts. It works by incrementing a counter once every millisecond, based on a interrupt, called from a hardware timer. If you disable all interrupts then the counter will not be incremented for the duration.

The NeoPixel library needs to disable them because NeoPixels need very accurate timing of the signals, and you'd suffer from visible intermittent glitches if not.

The millis() counter drops about 30 microseconds per a RGB pixel, or 40 microseconds for a RGBW pixel. You have 54 RGB pixels in your led strip. 54*0,030 = 1,62 ms. Which means that there's 1,62 milliseconds between each of your millis() updates. I.e. it updates too slow.

Your unstable button must've simply caused nonstop neopixel updates, due to some logic in your code.

There's no easy fix for this, but a few specialized alternative or companion libraries exist that use very device-specific peripherals to work around it. For example, you could use one of the hardware timers to measure the time spent sending NeoPixel data, and then manually go in and update the millis() counter accordingly when done. This requires hacking the NeoPixel library and reading the datasheets for your specific Arduino processor.


message:
Buttons and LED

I am creating a program that turns on and off an led. When two buttons are considered "high". But there is a twist, The first button needs to stay "high" until the second button is pressed and the led turns on. Here is my code so far.

    // Boolean logic for Button Switch
    boolean currentState = LOW;    //stroage for current button state
    boolean lastState = LOW;      //storage for last button state
    boolean ifcondState = LOW;    //storage for the current state of the ifturn  (off/on)

    // set pin numbers:
    const int buttonPinA = 3;     // the number of the pushbutton pin
    const int buttonPin1 = 4;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin
    const int ifcond =  12;      // the number of the ifcond pin
    const int ifturn =  11;      // the number of the ifturn pin

    // variables will change:
    int buttonStateA = 0;         // variable for reading the pushbutton status
    int buttonState1 = 0;         // variable for reading the pushbutton status
    int buttonStateIf = 0;         // variable for reading the If Condition status

    void setup() {
    //initialize Serial connection
    Serial.begin(9600);
    // initialize the LED pin as an output:
    pinMode(ledPin, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(buttonPinA, INPUT);
    // initialize the pushbutton pin as an input:
    pinMode(buttonPin1, INPUT);
    // If Condictional Pin
    pinMode(ifcond, OUTPUT);
    // If Turnon Pin
    pinMode(ifturn, INPUT);

    }

    void loop() {
      // read the state of the pushbutton values:
      currentState = digitalRead(buttonPinA);
      buttonState1 = digitalRead(buttonPin1);
      buttonStateIf = digitalRead(ifturn);

      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (currentState == HIGH && lastState == LOW){    //  if button has just been pressed
        Serial.println("pressed");
        //delay(1);

        //toggle the state of the ifcond
        if (ifcondState == HIGH){
          digitalWrite(ifcond, LOW);
          ifcondState = LOW;
        }
        else {
          digitalWrite(ifcond, HIGH);
          ifcondState = HIGH;
        }
      }
      lastState = currentState;

      if (ifturn == HIGH && buttonState1 == HIGH) {
        digitalWrite(ledPin, HIGH);
      }
      else ();
      digitalWrite(ledPin, LOW);
    }

I have Pin 12 (ifcond) And pin 11(ifturn) Jumped together. Pin 12 acts like a button to pin 11, When it goes high pin 11 reads the change.

The code works like this, When ButtonpinA goes high  pin 12 goes high and stays high until the next button push. This is the part that doesn't work Pin 11 should read if pin 12 if high or not. If it reads high and Button1 is also high it should turn on ledpin which it does not.

I am sorry for any confusion Thanks

body:
    if (ifturn == HIGH && buttonState1 == HIGH) {
      digitalWrite(ledPin, HIGH);
    }
    else ();
    digitalWrite(ledPin, LOW);

I think you have made a small mistake here.

What you are saying there is "If both these inputs are high then turn on the LED - otherwise don't do anything", and immediately after that "Turn off the LED".

So the LED is turned on when they are both high, and immediately turned off again, so fast you never see the LED lighting up at all.

I think what you meant to have was:

    if (ifturn == HIGH && buttonState1 == HIGH) {
      digitalWrite(ledPin, HIGH);
    } else {
      digitalWrite(ledPin, LOW);
    }

That way it will turn the LED on if both are HIGH, otherwise it will turn the LED off *only if the test for both being high fails*.


message:
Would Arduino Nano be good for Bluetooth + Sound

So I've been browsing around for a whole looking for a good microcontroller that's super small. So far the smallest one I found was an Arduino Nano. But before I go buying it, there are some questions I have about it.

1. Is Bluetooth compatible with it and if so where would I get the Bluetooth code?
2. Is there anything smaller than it that's Bluetooth compatible?
3. Would an Arduino Nano (Or the device in the question above) be able to play sounds?

body:
There are [Bluetooth boards][1] and chips that you can connect to a Nano.

You can play sounds with a Nano. Crudely with PWM and a direct connection, for finely with an external digital-to-analog converter.

But if super-smallness is what you are after, there may be better options.

The [Blue Bean][2] is a complete  BLE microcontroller on a single board that is smaller than a Nano+board.

If you want even smaller, you could get something like the new Cypress EZ-BLE module...

[![enter image description here][3]][3]
http://www.cypress.com/products/ez-ble-module-bluetooth-smart

It is a complete programmable BLE system on a tiny module. It is hard to imagine anything smaller than that!

  [1]: https://www.adafruit.com/products/1588
  [2]: http://www.makershed.com/products/lightblue-bean-bluetooth-4-0
  [3]: https://i.stack.imgur.com/mlfYc.jpg


message:
Transistors to switch monitor inputs

I am using the following setup on my Arduino UNO to measure cpu fan RPMs:

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

The code is set to bring the trigger pin for each transistor high when it is checking that fan's RPM and FreqMeasure.h is then used to check the frequency of the signal on pin 8 which is then translated to RPM and sent to the LCD display.

I am experiencing reading issues and suspect that the signal is remaining on the measuring bus during the subsequent reads, however before revamping my code I simply wonder:

Is my circuit logic sturdy? I am just getting my feet back under me with microprocessors and have always found transistors to be a tricky subject, thanks in advance for your help!

If you'd like to see more info all can be found on [GitHub.](https://github.com/msashlee/fanMon/)

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

body:
I have [simulated your circuit](http://www.falstad.com/circuit/circuitjs.html?cct=$+1+0.000005+10.20027730826997+50+5+43
R+240+160+208+160+0+2+721+6+6+0+0.5
g+288+176+288+208+0
f+240+160+288+160+0+1.5
R+432+80+432+48+0+0+40+5+0+0+0.5
r+432+80+432+144+0+10000
t+336+96+336+144+0+1+-4.999999997500001+-0.0000049995+100
w+288+144+320+144+0
w+352+144+432+144+0
w+432+144+496+144+0
r+336+96+160+96+0+10000
r+336+240+160+240+0+10000
L+160+240+128+240+0+0+false+5+0
w+352+288+432+288+0
w+288+288+320+288+0
t+336+240+336+288+0+1+-4.999999997500001+-0.0000049995+100
f+240+304+288+304+0+1.5
g+288+320+288+352+0
R+240+304+208+304+0+2+382+6+6+0+0.5
w+432+144+432+288+0
L+160+96+128+96+0+0+false+5+0
p+496+240+496+144+0
g+496+240+496+256+0
o+20+64+0+558+5+0.00009765625+0+-1
) and it seems sound enough to me.

It is a little confusing having the transistors there though.  I would prefer to convert the three open drain outputs to logic level outputs (each having its own pullup resistor) then use a digital 3:1 MUX (or discrete logic gates) to select the signal to sample.


message:
How to connect this motor driver board to Arduino to drive bidirectional motor?

I am familiar with using PWM on Arduino and have done so with simple 3-pin interfaces: e.g. PWM, DIR (direction) and GND pins. Choose a direction with DIR, set speed with PWM in software (0 - 255), simple stuff.

But this board I'm buying seems different:

http://www.ebay.com/itm/DC-43A-Double-BTS7960B-Stepper-Motor-Driver-H-Bridge-PWM-for-Arduino-Smart-Car-/141485439094

There seems to be 6 control pins:

`R_IS, R_EN, RPWM, L_IS, L_EN, LPWM`

But from what I understand this board would only be used for controlling one motor bidirectionally, so why is there a distinction between left and right?

So how would I go about using this motor driver board in a similar way to my `PWM, DIR, GND` boards that I've used before to control the motor direction and speed?

Thanks!

body:
I guess you have used DC Motor for your earlier cases? Or Step Motor with a logic on the stepper controllers?

Here you have two H Bridges which drives one Step Motor. So as I understand it, you have two PWM Inputs, one for each output channel to the coil windings of the stepper motor. Like an encoder signal you can set the direction with setting one pwm before the other. So the step motor is controlled via unipolar stepping.

For further help you need to say which motor you want to use with this card. But first I would look at the different stepping modes (unipolar and the two bipolar and maybe microstepping).

Greets


message:
USB mini type B port on Arduino Uno

I bought today an Arduino Uno R3, and I'm looking forward to make it an HID device. I have seen many projects using a serial USB type B port. As I want to build a little gamepad, I would like to use the smaller USB mini type B port to achieve similar results. Looking it up did not seem to bring significant results.

Am I missing anything? Do I have to use a serial port similar to the one used by Arduino or can I reproduce the project using the aforementioned port?

body:
It sounds like you are going to be attempting software "bit-banged" USB.  That, while possible, is severely frowned upon, especially when you have the resources to do it properly at your fingertips.

In answer to your question, yes, you can use a USB mini B connector.  It is no different to a USB B connector except it is much smaller and contains one extra pin - USBID - which you can completely ignore (it's only used on USB On-The-Go devices).

USB is quite a heavy protocol to do in pure software - it won't leave much "room" for you to do much else.  Better would be to re-program the ATMega16U2 chip that is used for the current USB interface.  You will need some form of hardware programmer for it - you can use another Arduino Uno, and once done you won't be able to directly program the ATMega328P chip through the USB, so you would need some other method for connecting that (external USB serial adapter cable, or another Arduino), but the ATMega16U2 chip is specifically designed to work with the USB.  Offloading the USB portion of your project onto that chip and using the serial interface that is already wired up to communicate commands and instructions to/from the ATMega328P would be a much more powerful (and reliable) system.  There's plenty of tutorials and links around to show you how to reprogram that chip.


body:
As an alternative to Majenko's suggestion you can implement Virtual USB as described at [Virtual USB Keyboard](http://www.practicalarduino.com/projects/virtual-usb-keyboard). You just need:

* 3 resistors
* 2 zener diodes
* a bit of wire
* a suitable USB socket

The advantage is you haven't modified your Uno's USB chip (the ATMega16U2) so you can continue to upload sketches in the normal way.

The disadvantage is that the software USB may be more flaky than a hardware-implemented one.

Personally I don't like reprogramming my ATMega16U2 because I may as well have used one of the chips with a ATmega32U4 chip on it in the first place (like the Micro) which is designed for easy reprogramming.


message:
Comparators for digital input mode

I've asked another question in electronics about what to use to compare 2 input voltages, the answer was to use comparators.

Digging around a bit, turns out most of the comparators outputs are pull-up, which makes it quite difficult to translate (probably due lack of general electronics knowledge, self-learned) and I'm not able to distinguish from maker's PDFs which comparators have pull-up or pull-down outputs.
I've figured PD comparators illustrate in PDF a resistor right after the output... but many illustrations I've seen doesn't clarify PD / PU, or I'm just missig that.

But my question is, are there any PD comparators (well known) where it's output can be connected to the digital pins or arduino (while those are defined as INPUT mode)?

I appreciate any guidance on this topic.

Just a side note, I want to switch on a led, when ever external source is at 12V and turn that same led off when it's below 11.5V...

body:
You can't put 12 volts into a Uno input pin in any case.

You could run it into a [voltage divider](https://en.wikipedia.org/wiki/Voltage_divider) and divide it down to somewhere on the range 0 to 5 V, and then do an analogRead to see exactly (or almost exactly) what the resulting voltage is.

I don't really see where comparators come into it in this particular case. I mean, you could use a comparator to turn the LED on, but then where does the Arduino come into it?

---

> I've actually tried with voltage divider, I went pretty high on my resistors, taking the 12V source and hooked in 4x1M resistors but the 12V never came down significantly.

You need a voltage divider like this:

[![Voltage divider][1]][1]

Those values give you 4 V on the Arduino pin if there is 12 V on the input.

Vout = (R2 / (R1 + R2) ) * Vin

So:

    (1000 / 3000) * 12V = 4V

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


body:
Many comparators come with open collector output. OC output means, it can pull down a potential, but cannot generate a voltage higher than ground.

If you have a high impedance input like your Arduino has, and you connect a OC output to it, nothing will happen unless you add a pullup resistor providing a positive voltage. Otherwise there won't be a closed electric circuit where any measurable voltages can be generatet.

Lucky you: Arduino input pins can generate a positive voltage by providing an internal pullup resistor. Read the documentation on input pins and pin direction to make use of this. This way you can connect an open collector output to your input pin without additional components.

But beware: This doesn't work with a comparator with a pullup output (I guess these are rather rare). In this case you have to provide an additional pulldown resistor to ground.

Caveat: You can use a comparator with totem pole or tristate output without pullup or down as long as its output swing does not exceed maximum allowable voltages of the input pin. I.e. you cannot connect a comparator supplied with 15 V and a totem pole output to the input of an arduino, because the high level will exceed 5 volts (I assume an Arduino Uno).

Now. How to learn from a datasheet, if the output is pulldown, pullup, totempole or tristate?
If a device features a pulldown stage, you will find a value for something called "Output Sink Current" in the section "electrical characteristics". For a pulldown stage this will likely be named "Output source current". A tristate output will be denominated somewhere in the datasheet for sure, because this is an extra feature.

Have a look at lm339!


message:
SIM900 AT command HTTP GET request not show the web page

I build a simple HTTP GET request by SIM900. Here is it:

    -----1-----
    AT+CSQ

    +CSQ: 25,0

    OK

    -----2-----
    AT+CGATT?

    +CGATT: 1

    OK

    -----3-----
    AT+SAPBR=3,1,"CONTYPE","GPRS"

    OK

    -----4-----
    AT+SAPBR=3,1,"APN","indosatgprs"

    OK

    -----5-----
    AT+SAPBR=1,1

    OK

    -----6-----
    AT+HTTPINIT

    ERROR

    -----6.1-----
    AT+HTTPPARA="CID",1

    OK

    -----7-----
    AT+HTTPPARA="URL","http://www.minimalsites.com"

    OK

    -----8-----
    AT+HTTPACTION=0

    OK

    -----9-----
    AT+HTTPREAD

    OK

    -----10-----
    AT+HTTPTERM

    ERROR

    +HTTPACTION:0,200,1240

    -----10.0-----
    AT+SAPBR=0,1

    OK

The step 9 AT+HTTPREAD I supposed to see some html from http://www.minimalsites.com. But i dont see anything, What wrong with me?

body: Check Your Connection Try Pinging the IP of Your Arduino and INstead of Using the AT commands use this library its easier and Nice https://github.com/amcewen/HttpClient


body:
From what I can see in your results, it seems `AT+HTTPINIT` returned an error. This means the HTTP service wasn't even successfully activated. So there's no way the commands you issued later would have been successful. From the AT command manual, AT+HTTPINIT is necessary before you can do any HTTP-related stuff.
You need to run the command `AT+CGATT=1` to attach GPRS, even if your query shows its value is already 1.
It could also be that your APN requires authentication, using a username and password. So once you find out the username and password authorized by 'indosatgprs' (customer care?), you can use them in the following commands.

        AT+SAPBR=3,1,"USER","Enter the username here"
        AT+SAPBR=3,1,"PWD","Enter password"

Both commands should return OK if successful. To view all the parameters you have set, you can use `AT+SAPBR=4,1`. If all the parameters are satisfactory, and you have sufficient airtime in the SIM, then you can attempt `AT+HTTPINIT`. Only if this command returns OK, should you proceed to run `AT+HTTPPARA`-related commands.


body:
You have to wait after `AT+HTTPACTION=0` for a while until you see something like `+HTTPACTION:0,200,1240`

Then continue to `AT+HTTPREAD`, you will see the result.

Finally, terminate HTTP.


body:
after days fighting with asynchronous and limit serial buffer size (64Bytes). I found this one.

this link help me out, it uses the standard library SoftwareSerial and my big txt file 1100 bytes or my html file (5814bytes)  are  download again & again with no issue!!

https://www.youtube.com/watch?v=cpgQOmQwUL8&t=1263s
http://www.iforce2d.net/sketches/gsm_HTTPGet.zip
nb: I change it to AltSoftSerial, no problem neither.
Thanks iforce2d

ps: you can also use the "ModuleSerial-master" library, but I need to save the space for other code (which already uses 74% of 2KB RAM) so I stick to AltSoftSerial which already found in my sketch


message:
How I can print several numbers via Serial with very few lines of code?

Could someone help me how to output the numbers from 1 to 10 via Serial, without having to write out each command by hand?

Below is my sketch - I need it concise instead of a long sketch:

    #include <Streaming.h
    //setup
    void setup() {
     Serial. begin(9600);//The faster the better
    }//Close the sertup

    //main loop
    void loop() {

      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(1) << endl;
      delay(1000);
      Serial<< _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(2) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(3) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(4) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(5) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(6) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(7) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(8) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(9) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(10) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(11) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(12) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(13) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(14) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(15) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(16) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(17) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(18) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(19) << endl;
      delay(1000);
      Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
      Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
      Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(20) << endl;
       delay(1000);
      while(1){}//freeze the main loop

    }

body:
*[This replaces my earlier answer, and addresses information added to the question.]*

You apparently want a sketch that outputs 1, 2, 3 ... 100 to serial output, where each number string is embedded within a control sequence.

Here are two ways.  The first program outputs the sequence once, using ordinary Arduino `Serial.write()`, `Serial.print()` and `Serial.println()` statements:

Program 1.  Output 1, 2, 3 ... 100 once

    void setup() {
      Serial.begin(9600);
      for (int j=1; j<=100; ++j) {
        Serial.write(27); // Send escape character
        Serial.print("[2J"); // Send erase-screen command
        Serial.print("\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t");
        Serial.println(j); // Send j in decimal format
        delay(1000);
      }
    }
    void loop() {}

The other program will output the sequence repeatedly.  It uses the `Streaming.h` library, but in a  rational manner; for example, instead of quoting every character separately like the program in the photo, it quotes character sequences in strings.  Note, Esc [2J is an [ANSI escape code sequence](https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes) that erases the screen it is directed to, if the screen device is ANSI compliant.

Program 2.  Output 1, 2, 3 ... 100 repeatedly

    #include <Streaming.h> // or "Streaming.h" if appropriate
    byte j=0;
    void setup() {
      Serial.begin(9600);
    }
    void loop() {
      ++j;
      // Send Esc [2J which will erase screen
      Serial << _BYTE(27) << "[2J";
      Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << j;
      if (j >= 100) j=0;
      delay(1000);
    }


body:
<!-- language-all: lang-C++ -->

Ah, a challenge!

> I have to write from 1 to 100, and I don't want to repeat it all 100 times

Your question did not make that clear. Anyway:

    int main () {
      Serial.begin (9600);
      for (int i = 1; i <= 100; i++)
        Serial.println (i);
      while (true);
      }

You can probably make it shorter at the expense of readability.

    int main(){Serial.begin(9600);for(int i=1;i<=100;i++)Serial.println(i);while(1);}