message:
How to connect Arduino device to Linux?

I wrote Arduino sketch and it works. It waits for a command and answers text on response.

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

Simultaneously, I can't get any response with command line tools.

For example, I have the following code to get temperature:

    #!/bin/bash
    tty=/dev/ttyUSB0
    exec 4<$tty 5>$tty
    stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
    #stty -F $tty 9600 -echo
    #printf "temp\n" >&5
    echo temp >&5
    read reply <&4
    echo "$reply"
    #tail -n 1 - <&4

It returns empty or hang under different circumstances.

Also, if I run built-in `Serial Monitor`, I can see responses on command lines like:

    echo temp > /dev/ttyUSB0

But I see nothing with commands like `tail -f /dev/ttyUSB0`

What I am doing wrong?

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

body:
Add the flag `-hupcl` to your `stty` command.  That will disable the assertion of DTR which is resetting the board.

     hupcl (-hupcl)
                 Stop asserting modem control (do not stop asserting modem
                 control) on last close.

The first time it is run there will be a reset, since setting that flag entails opening the port, which causes a reset.  So you need to add a delay long enough to get past the bootloader - minimum 2 seconds, best make it 3.

You can do that with the `sleep` command: `sleep 3`

Note that you now won't be able to upload a new sketch since you have disabled the auto-reset feature that allows you to enter the bootloader, so before uploading a new sketch you need to turn the reset back on with

    stty -F $tty hupcl

If you don't disable the reset then every operation in your script that opens and then closes the serial port will trigger a reset of the board.  So in summary try this:

    #!/bin/bash
    tty=/dev/ttyUSB0
    stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts -hupcl
    sleep 3
    echo temp >$tty
    read reply <$tty
    echo "$reply"
    stty -F $tty hupcl


sender: user

message:
Concatenate string constants

Please take a look at following example (I have Java background):

    const char* BT_ADDRESS = "abcd,ef,ghijkl";

    void bar(const char* string) {
      ...
    }

    void foo() {
       bar("AT+BIND=" + BT_ADDRESS);
       bar("AT+LINK=" + BT_ADDRESS);
    }

How to achieve this with "Arduino-C++" so BT_ADDRESS only has to be entered at one location?

sender: assistant

body:
There is, as you may expect with C, many different ways of doing this.

The simplest is probably to use, instead of a const variable, a preprocessor macro.

In C you can concatenate string literals like this:

    print("AT+BIND=" "abcd,ef,ghijkl");

Note the lack of anything but spaces between the strings - they are concatenated together. You can even do it on separate lines - it's a technique that is great for incredibly long strings.

Now you can, of course, replace one of those with a preprocessor macro:

    #define BT_ADDRESS "abcd,ef,ghijkl"
    print("AT+BIND=" BT_ADDRESS);
    print("AT+LINK=" BT_ADDRESS);

The preprocessing replaces BT_ADDRESS with the string literal "abcd,ef,ghijkl" and all is well.

Other options, depending on what `print` does, is to expand it to take two `const char *` parameters and deal with them both separately.  For instance, you might have:

    void print(const char *command, const char *data) {
        Serial.print(command);
        Serial.println(data);
    }

    print("AT+BIND=", BT_ADDRESS);

If you don't know how many parameters you may want to pass you could use *variadic* arguments:

    #include <stdarg.h>

    void print(int count, ...) {
        va_list args;
        va_start args, count);

        for (int i = 0; i < count; i++) {
            const char *arg = va_arg(args, const char *);
            Serial.print(arg);
        }
        va_end(args);
    }

    print(2, "AT+BIND=", BT_ADDRESS);

Yet another option is to pre-format the data into a single string using the various string operators.  For example:

    int len = strlen("AT+BIND=") + strlen(BT_ADDRESS);
    char temp[len + 1]; // Be sure to keep space for the terminating NULL.
    strcpy(temp, "AT+BIND=");
    strcat(BT_ADDRESS);
    print(temp);

I could go on all night with different options...  The first one using the preprocessor is probably easiest though.


message:
Doesn't Arduino reports DSR (Data Set Ready) correctly?

I was told, that when computer opens port, it sends DTR (Data Terminal Ready) signal to Arduino, which initiates Arduino reboot.

This looks like part of DTR / DSR flow control. According to this, in response to DTR, Arduino should no only reboot, but also raise DSR (Data Set Ready) signal when it is ready to receive data

And computer should wait for it.

Does it happen so?

body:
No, this doesn't happen.

DTR is used purely for resetting the board.  Personally I would have chosen the RTS signal instead, but the wise guys at Arduino decided on DTR.

The Arduino has no knowledge of the DTR signal, it only knows that it has been rebooted.  Whether that reboot came from DTR, or from the reset button, or wherever, it has no knowledge.

So the DTR is being (in my opinion ab-) used to perform the resetting in order to make uploading a sketch easier and that is all.


body:
No, it does not, and can not for the simple reason that there is no DSR line connected to the processor.

Generally host software / serial driver configuration ignores DSR.

On the boards with an 8u2/16u2 the custom firmware therein can report whatever virtual state of the signal it is programmed to. On those with hardware USB-serial they will report however the pin is hard wired, or whatever value it is pulled to or floating at.

None of these (possibly excepting a Leonardo type board or an ARM one with native USB) reflect anything about the state of the target processor, so software hoping to talk to an Arduino should ignore the DSR signal.


message:
How to apply a programme to all values in a list simultaneously

I'm attempting to turn on a set of LED's one at a time and then switch them all off at the same time, I am stuck however on turning them off at the same time.

That is my code:

    int ledpins[] = {2,3,4,5,6,7,8,9}; //creates a list of the pins in use

    void setup() {
      for (int i = 0; i < 8; i++){
     pinMode(ledpins[i], OUTPUT);  // iterates over the list led pins from the 0 pin to the pins before the eigth
      }
    }

    void loop() {
      for (int i = 0; i < 8; i++){
     digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
      }

      delay(100); //when all on will wait 100 ms
      digitalWrite(ledpins[0,7], LOW); //turns off all the leds at once
      delay(100);
    }

The annotations are for my own understanding.
I just need help turning all the LED's off at once which I dont know the command for.

body:
You have already done it twice, why are you struggling the third time?

    for (int i = 0; i < 8; i++){
      digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
    }

> // turns all the pins of one at a time

Except that it is happening so fast you can't see then doing it individually. So just do the same but set them to LOW:

    for (int i = 0; i < 8; i++){
      digitalWrite(ledpins[i], LOW); // turns all the pins off one at a time
    }

Now you might want to add a delay into the loop that turns them on so you can see them turn on individually instead of all at once:

    for (int i = 0; i < 8; i++){
      digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
      delay(50);
    }


body:
There is another approach that is to use direct port manipulation. It is a lot faster than using `digitalWrite` in the sense that it requires less clock cycles to execute and allows you to change one port at a time (the UNO has 3 ports called D, B and C). You can find an introduction to port manipulation on this page: <https://www.arduino.cc/en/Reference/PortManipulation>

Here is an example that toggles the LED you chose:

 void setup()
 {
  DDRD |= B11111100; // Pin 2 to 7 as outputs
  DDRB |= B00000011; // Pin 8 to 9 as outputs
 }

 void loop()
 {
  // Pin 2 to 7 HIGH
  PORTD |= ( 1<<2 ) | ( 1<<3 ) | ( 1<<4 ) | ( 1<<5 ) | ( 1<<6 ) | ( 1<<7 );
  // Pin 8 to 9 HIGH
  PORTB |= ( 1<<0 ) | ( 1<<1 );

  _delay_ms( 500 );

  // Pin 2 to 7 LOW
  PORTD &= ~( 1<<2 ) & ~( 1<<3 ) & ~( 1<<4 ) & ~( 1<<5 ) & ~( 1<<6 ) & ~( 1<<7 );
  // Pin 8 to 9 LOW
  PORTB &= ~( 1<<0 ) & ~( 1<<1 );

  _delay_ms( 500 );
 }


message:
Powering multiple servos on external battery

I am working on a project with my school's 3D Printing Club where we are making a humanoid robot and I am attempting to wire the arm at the moment, and program the hands to translate text to sign language. The portion of the arm I am currently working with uses six TowerPro 5010 servos, one for each finger, and another for the wrist, and I am controlling it with an Arduino Uno. I have a 9v wall plug that I am powering the Arduino with, and a 4xAA battery pack (wired in series for 6v, last measured at 5.7) that I would like to use for the servos.

Initially, I wired the servo ground pins to the Arduino GND output, and the servo power pins to the battery pack's 6v output, I connected the ground on the battery to the ground on the Arduino, and I attached the servo motors to their IO pins. This approach worked perfectly for two servos, barely for three, and not at all for four. Even with most of the motors staying still (I was only moving one at a time with three and four servos, but I can move two simultaneously no problem with nothing else connected). Not sure how to describe the load on them quantitatively, but they are pulling on fishing line that has a good deal of resistance, but nothing excessive, or near their limits.

I have been googling around for hours, and I found some tutorials where a similar battery was powering eight servos at a time, and so I am unsure why mine was cutting out so soon.

I tried to reduce the load of the servos, but nothing I tried worked. At one point I tried wiring the servos on a shift register to only power the ones I needed, but then I realized this was a dumb idea because my shift register would never be able to output enough current to power even one servo. I have some 5v voltage regulators, but I don't think they will help since the servo takes from 4v to 6v, and I looked through all my transistors, but they are all designed for very small currents. I have a relay which should be able to switch that voltage that voltage easily, but only one of them. If possible I would like to try and do this without purchasing any additional components such as motor controllers or specialized batteries, but I understand that if I need to I need to.

If anyone has any advice on how to proceed I would greatly appreciate it. Thanks.

body:
If you dont mind to use a bit of space for a dedicated board that controls your servo and power them, I would suggest to use http://www.adafruit.com/product/815 which is very good.

Your issue might become a power draining where the batteries cant keep up to give enough amper to use 3 or 4 servos at the same time.

I am not sure what kind of batteries you are using, probably not rechargeable ones but I would suggest to get an ampermeter to get the real draining on your circuit.

After that you will understand a bit better what is going on and why this issue is happening on your configuration.

I cant find the power consummation of this servo so I Cant give much more information.


message:
What type of sensor could I use to determine the mass of a small object (under 1 kg)?

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

My robot needs to be under 6 lbs and have a footprint of 35 x 35 cm. Thanks!

body:
Just a little brainstorming:

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

  [1]: https://en.wikipedia.org/wiki/Hooke's_law


body:
A load beam cell would be good.  Put it as one leg of your robot, and calibrate it with the arm in a particular location dangling over the cell.   You'd need the beam load cell, and an instrumentation op amp, or HX711 (https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide) to do the interfacing.

Also good would be the cells from a bathroom scale as the four feet -- you could hook them up like https://electronics.stackexchange.com/a/199907/30711 or https://electronics.stackexchange.com/a/199470/30711

One thing cool about using the robot feet for measurement is that you could calibrate for more sensitive measurements while reaching far from the base, and rougher measurements closer.  You could also calculate how far you could reach without toppling over.


message:
NeoPixel Ring Usage Without Arduino

I am looking at purchasing a [NeoPixel Ring][1] for a project, but need it to work without an Arduino. Once the NeoPixel has been programmed by the Arduino, will it function when powered without the Arduino? I am not looking at changing colors or anything, I want to set the LEDs to solid red and not change.

I have found in the Adafruit website that it says "NeoPixels don’t just light up on their own; they require a microcontroller (such as Arduino) and some programming." But is this only to get them working initially, or do they require an microcontroller permanently?

  [1]: http://www.adafruit.com/products/1643

body:
No, the settings for the colors are stored in RAM on the individual devices so they need to be reprogrammed every time they are powered on.

On the other hand, it is possible to use a much smaller device such as a surface-mount ATtiny85 to program them, and light_ws2812 runs on said device just fine. And once they have been programmed it is possible to put the MCU in deep sleep so that it consumes almost no power.


body:
I recently completed a project using one of these LED rings. I knew these were normally used with an arduino for control, but at the time I was still testing things, so I decided to buy one and mess with it.

I soldered a standard 3-pin ARGB cable to the 5v, GRN, and Data In to the ring and connected it to one of the argb headers on my PC. The results were as follows:

1) The ring did light up and stayed illuminated with the PC.

2) The ARGB header was connected to a splitter which came from a ASUS motherboard header.

3) Armoury Crate (ASUS’s argb software) was already set up on my computer and this software was what was sending signal to the ring via a splitter.

4) There were SOME LEDs on the ring that behaved as expected based on the colors and pattern set up in Armoury Crate. However, some LEDs although we’re illuminated, we’re flashing various colors that didn’t match to how it was set up in Armoury Crate.

Take aways:
These NeoPixel rings DO work without an arduino in terms in terms of receiving voltage and lighting up. However, because of how these are programmed they may not behave as expected or intended if connected to a non-arduino controller.

For my application, the multi-color pattern ended up looking nice, so I decided to keep it as is.


message:
BH1750 Light sensor always giving output as 54612lx

urgently need some inputs,

Connection:

    VCC-5v
    GND-GND
    SCL-SCL(analog pin 5)
    SDA-SDA(analog pin 4)
    ADD-NC or GND

Code pasted below
used library from GIT : https://github.com/claws/BH1750

    #include <BH1750.h>
    #include <Wire.h>

    BH1750 lightMeter;

    void setup(){
        Serial.begin(9600);
        lightMeter.begin();
        Serial.println("Running...");
    }

    void loop() {
        uint16_t lux = lightMeter.readLightLevel();
        Serial.print("Light: ");
        Serial.print(lux);
        Serial.println(" lx");
        delay(1000);
    }

body:
There may be a regulator and logic shifter on the board you are using but according to the data sheet the device is a 3V device with 1.8V logic and I2C levels.  So this is the first thing you need to check.

Have you got 4.7K resistors pulling the SDA and SCL lines to Vcc?

Can you change your code to turn the device off and then take a reading?

There is nothing wrong with your code, your wiring looks OK, so that implies that there is something wrong with the device or the Arduino.  Change the device (and code) for another I2C device and see if that works fine.  If it does then it looks like there might be a problem with the BH1750.

Hope that helps.


body:
Looking at the `BH1750.cpp` and `BH1750.h` and I think i've noticed some errors:

 1. Change `#include "Wire.h"` to `#include <Wire.h>` in the header file, trivial perhaps but still...
 2. In the method `BH1750::readLightLevel` in the .cpp, comment out `Wire.beginTransmission(BH1750_I2CADDR);` and `Wire.endTransmission();`; they aren't needed for a Read and may be responsible for the wrong value you're getting.
 3. You can also try replacing `_delay_ms(10);` with `delay(10)`, just in case
 4. You may also try commenting out `level = level/1.2;` just to see if this division has any adverse effects.

Save the files after making the changes.


body: I had to connect my `SCL` and `SDA` pins to dedicated **20th and 21st** pins on `Arduino MEGA 2560`.


body: I bought some "GY-302" modules on ebay, it's a breakout board with the BH1750 sensor on it. I tried one of them and it didn't respond at all, like you I saw 54612 (which is just 65535/1.2). I tried another of these modules and it worked. So, on the one that didn't work, the sensor chip was not well aligned and centered, and the soldering looked ugly on one side, so I used my soldering iron to attempt to reflow and re-align/center it. If you attempt to do that too, clean your soldering tip and do not add any solder! Now the soldering looks even uglier (under microscope..), but the sensor is working well! I don't have any pro equipment, not even a small tip for my crappy soldering iron, so I guess I am lucky that it worked.


body: i didnt solder my light sensor and it had the same error, as it was just resting on the pins, try pushing it up so the sensor makes contacts with the male headers or just solder them :D


message:
Arduino with seven segment

Can anyone help me regarding the output of this program?

What is the function of `Num_Write`?

Here is the code below:

    int num_array[10][7] = { { 1,1,1,1,1,1,0 }, // 0
    { 0,1,1,0,0,0,0 }, // 1
    { 1,1,0,1,1,0,1 }, // 2
    { 1,1,1,1,0,0,1 }, // 3
    { 0,1,1,0,0,1,1 }, // 4
    { 1,0,1,1,0,1,1 }, // 5
    { 1,0,1,1,1,1,1 }, // 6
    { 1,1,1,0,0,0,0 }, // 7
    { 1,1,1,1,1,1,1 }, // 8
    { 1,1,1,0,0,1,1 }}; // 9

    void Num_Write(int);

    void setup() {
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
    }

    void loop() {
      for (int counter = 10; counter > 0; --counter) {
        delay(1000);
        Num_Write(counter-1);
      }
      delay(3000);
    }

    void Num_Write(int number) {
      int pin= 2;
      for (int j=0; j < 7; j++) {
        digitalWrite(pin, num_array[number][j]);
        pin++;
      }
    }

body:
Num_Write will map the output pins to display a number on the 7-segment display.

*Please note that the schematic below is not the best, nor the proper way to connect a 7 segment display. It's intended to show the connection for illustrating purposes, not for actual wiring. Each segment lead should have it's own resistor. Also, depending on if you have a Common Anode or Common Cathode 7 segment, wiring will differ.*

[![Image of a 7segment connected to a microcontroller][1]][1]

When the number 0 is being displayed (check in the num_array) all segments are lit, except for the last segment (segment G).

    void Num_Write(int number) {                 //Write a number to the 7-segment display.
      int pin= 2;                                //Take the starting (output) pin.
      for (int j=0; j < 7; j++) {                //Loop through all the segments of the given number.
        digitalWrite(pin, num_array[number][j]); //Write the output pin according to the pattern in the "num_array" for the given number.
        pin++;                                   //Go to the next pin.
      }
    }

So by looping through the pins, and looping through the array (while setting the pins) we can display a number on the 7 segment display.

Extra:
The output will be somewhat like this, but then reversed (9 to 0) and withouth the A, B, C, D, E and F.

[![seven segment counting up][2]][2]

  [1]: https://i.stack.imgur.com/ku5o8.jpg
  [2]: https://i.stack.imgur.com/Ivz0x.gif


message:
Parallel servo control?

I have an Arduino Nano & am success fully controlling 4 servos from it but it then occurred to me that I am controlling these in a serial manner, ie I set 1 position then the next then the next....

I would like the servos to act in a parallel manner i.e. that their motions can happen at the same time but at different speeds or different position.

Is this possible using just 1 controller (maybe some sort of polling/interrupt setup?) or will I need to run separate controllers for each set of servos & synchronize them?

EDIT: Added the PC side code & the Arduino side code

PC Python code:

    from Tkinter import *
    import serial

    usbport = 'COM5'
    ser = serial.Serial(usbport, 9600, timeout=1)

    def init():
        for servo in range(1, 5):
            print servo
            ser.write(chr(255))
            ser.write(chr(servo))
            ser.write(chr(90))

    class App:

        def __init__(self, master):

            frame = Frame(master)
            frame.pack()
            self.scale1 = Scale(master, from_=0, to=180, command=lambda ev: self.getAngle(1), bd=5, bigincrement=2, length=360, width=30, label='Servo 1')
            self.scale1.set(90)
            self.scale1.pack(side=LEFT)
            self.scale2 = Scale(master, from_=0, to=180, command=lambda ev: self.getAngle(2), bd=5, bigincrement=2, length=360, width=30, label='Servo 2')
            self.scale2.set(90)
            self.scale2.pack(side=LEFT)
            self.scale3 = Scale(master, from_=0, to=180, command=lambda ev: self.getAngle(3), bd=5, bigincrement=2, length=360, width=30, label='Servo 3')
            self.scale3.set(90)
            self.scale3.pack(side=LEFT)
            self.scale4 = Scale(master, from_=0, to=180, command=lambda ev: self.getAngle(4), bd=5, bigincrement=2, length=360, width=30, label='Servo 4')
            self.scale4.set(90)
            self.scale4.pack(side=LEFT)
            self.centre = Button(frame, text="Centre All", command=self.centre)
            self.centre.pack(side=TOP)

        def getAngle(self, slider):
            if slider==1:
                ang = self.scale1.get()
            if slider==2:
                ang = self.scale2.get()
            if slider==3:
                ang = self.scale3.get()
            if slider==4:
                ang = self.scale4.get()
            ser.write(chr(255))
            ser.write(chr(slider))
            ser.write(chr(ang))

        def centre(self):
            for servo in range(1, 5):
                ser.write(chr(255))
                ser.write(chr(servo))
                ser.write(chr(90))
            self.scale1.set(90)
            self.scale2.set(90)
            self.scale3.set(90)
            self.scale4.set(90)

    init()
    root = Tk()
    app = App(root)
    root.mainloop()

Arduino code

    *
     * ------------------------------
     *   MultipleSerialServoControl
     * ------------------------------
     *
     * Uses the Arduino Serial library
     *  (http://arduino.cc/en/Reference/Serial)
     * and the Arduino Servo library
     *  (http://arduino.cc/en/Reference/Servo)
     * to control multiple servos from a PC using a USB cable.
     *
     * Dependencies:
     *   Arduino 0017 or higher
     *     (http://www.arduino.cc/en/Main/Software)
     *   Python servo.py module
     *     (http://principialabs.com/arduino-python-4-axis-servo-control/)
     *
     * Created:  23 December 2009
     * Author:   Brian D. Wendt
     *   (http://principialabs.com/)
     * Version:  1.1
     * License:  GPLv3
     *   (http://www.fsf.org/licensing/)
     *
     */

    // Import the Arduino Servo library
    #include <Servo.h>

    // Create a Servo object for each servo
    Servo servo1;
    Servo servo2;
    Servo servo3;
    Servo servo4;

    // Common servo setup values
    int minPulse = 600;   // minimum servo position, us (microseconds)
    int maxPulse = 2400;  // maximum servo position, us

    // User input for servo and position
    int userInput[3];    // raw input from serial buffer, 3 bytes
    int startbyte;       // start byte, begin reading input
    int servo;           // which servo to pulse?
    int pos = 90;        // servo angle 0-180
    int i;               // iterator

    // LED on Pin 13 for digital on/off demo
    int ledPin = 13;
    int pinState = LOW;

    void setup()
    {
      // Attach each Servo object to a digital pin
      servo1.attach(3, minPulse, maxPulse);
      servo2.attach(4, minPulse, maxPulse);
      servo3.attach(5, minPulse, maxPulse);
      servo4.attach(9, minPulse, maxPulse);

      // LED on Pin 13 for digital on/off demo
      pinMode(ledPin, OUTPUT);

      // Open the serial connection, 9600 baud
      Serial.begin(9600);
    }

    void loop()
    {
      // Wait for serial input (min 3 bytes in buffer)
      if (Serial.available() > 2) {
        // Read the first byte
        startbyte = Serial.read();
        // If it's really the startbyte (255) ...
        if (startbyte == 255) {
          // ... then get the next two bytes
          for (i=0;i<2;i++) {
            userInput[i] = Serial.read();
          }
          // First byte = servo to move?
          servo = userInput[0];
          // Second byte = which position?
          pos = userInput[1];
          // Packet error checking and recovery
          if (pos == 255) { servo = 255; }

          // Assign new position to appropriate servo
          switch (servo) {
            case 1:
              servo1.write(pos);    // move servo1 to 'pos'
              break;
            case 2:
              servo2.write(pos);
              break;
            case 3:
              servo3.write(pos);
              break;
            case 4:
              servo4.write(pos);
              break;

            // LED on Pin 13 for digital on/off demo
            case 99:
              if (pos == 180) {
                if (pinState == LOW) { pinState = HIGH; }
                else { pinState = LOW; }
              }
              if (pos == 0) {
                pinState = LOW;
              }
              digitalWrite(ledPin, pinState);
              break;
          }
        }
      }
    }

body:
The python code is polling through the servos sequentially/serialy, but the arduino code looks parallel. The arduino will parse the string and pass the command to the servo code, passing control back to the loop() command before the servo reaches its assigned position. Maybe that is your question: "is servo.write(position) a blocking call?" If so, the answer is no, it is non-blocking, the motors will drive at the motors speed to the final positions independently. If you want coordinated movement through this scheme, you have to break the movements up and coordinate it on the python side without feedback.

For instance, if you want to go from position (90,90,90,90) to position (81,0,90,90) you will need to know it takes 900ms (for example) to complete the -90 move, and break it up into 10 segments of 100ms to coordinate the (-1,0,-10,0) steps.  Doing the coordination without feedback will be awkward, and might be better handled from your python/UI side.


body:
You can use an interpolation library and interpolate in-between as many servos as you like. The YouTube channel James Bruton does it on a lot of his robots so you can probably learn from his code. Also check out this GitHub repository:

https://github.com/luisllamasbinaburo/Arduino-Interpolation


message:
Most efficient way to store number in EEPROM?

I would like to store temperature readings in eeprom, the value from -55.00 to 125.99. What is the most space efficient way to store these numbers with two significant digits along with epoch timestamp?

Thanks

body:
My best off-the-top-of-my-head figure is 6 bytes.

4 bytes for the timestamp (assuming a 32-bit value).  Two byte for -32768 to +32767.

Multiply the temperature by 100 to make it into the integer range -5500 to +12599. That then fits comfortably inside a 16-bit signed integer.

*However*, there are other tricks you can use.

For instance, if you know the time of one reading you don't need to store the time of the next - only how much later it is.  One byte can then store up to 255 "whatevers" later than the previous entry - be that seconds, minutes, hours, whatever.

Similar with the temperature.  You can just store the difference from the previous reading as a single byte if you know that successive readings will never deviate by more than +/-1.27 degrees.

Also, you can check to see what the last saved temperature was, and only save a new temperature if it has changed from before.

Another thing is the resolution of your data.  You say 2 decimal points, but if the values are all multiples of 0.05 then what is the point of storing at 0.01 resolution?  Just store how many 0.05s there are (divide by 0.05) then multiply it out again afterwards to get the original temperature.  Most useful when coupled with a temperature difference to increase the storage range.

There's many tricks, you see, and which work best depend exactly on what you want to do with the data.


message:
4 Digit, 7 Segment Display Wiring (14 pin)

I purchased this 4 digit, 7 segment display from Adafruit:

Product: http://www.adafruit.com/products/865

Data Sheet: http://www.adafruit.com/datasheets/865datasheet.pdf

Everything I have searched for on the net either has 12 pins or 16 pins and most of those are only using 4 resistors.  This one has 14 pins.  I'm trying to wire it up to an Arduino but I'm not sure which pins should have resistors and which shouldn't.  If I wire it up like in the product picture with 1k resistors, I get 8.8.:8.8. and as I remove resistors from 5V, I can see the different sections that are lit/not lit.

Is that the correct way of doing it?  Can I now just wire those to the Arduino?

body:
It's just a 12 pin display, but with two extra pins for the colon.

Removing connections can help you better understand what it going on.

Resistor should be added to the anodes (pins 1,2,3,4,5,8,9,12,13) just like on the website. Pin 8 should be a different value, to match the brightness of the other (multiplexed) leds.

The other end of the resistor can be put into the Arduino. Depending on the resistor value you may need to add some transistor to drive the other pins (cathodes) on the display. Lower value resistors means a brighter display, but too much current for the Arduino to drive all 8 leds of a digit at the same time.

1k resistors, would mean about 3mA of current per segment. So if all segments are on in one digit, that would be 8*3, so 24mA. Which is approaching the maximum current an Arduino pin can source.


message:
using seek() in Arduino to go to the end of a variable-sized file

Anyone know how to use the [seek() function][1] of Arduino [SD Library][2] to position pointer at the end of a file?

If programming in Windows do something like:

    void fileInsert(char *file, void *data, size_t len) {

        FILE *filePtr;

        if ((filePtr = fopen(file, "rb+")) == NULL) {
            printf("Arquivo %s não pode ser aberto.", file);
            exit(EPERM);

        } else {

            fseek(filePtr, 0L, SEEK_END);
            fwrite(data, len, 1, filePtr);
            fclose(filePtr);
        }
    }

But the Arduino does not have the SEEK_END

  [1]: https://www.arduino.cc/en/Reference/FileSeek
  [2]: https://www.arduino.cc/en/Reference/SD

body:
You can only seek to an absolute position from the start of the file.  Fortunately there is the `size()` method that can tell you where the end is, though.

    file.seek(file.size());


message:
Modify SSID and Passwords in WiFi sktechs

This is a question about modifying sketches other than through the IDE.

I'm using an Arduino Uno r3 + Arduino WiFi Shield (not the 101).  Up to now I've been using the IDE to manually change the ssids and passwords to connect to wireless networks.  As a next step, I'd like to create something that will let update the ssid and password from a source other than an IDE, preferably a batch or bash file.  Over the air updates are out of the question (way too advanced) so it is safe to assume that all updates will be done via the USB cable.  Based on my limited knowledge of what I *think* needs to happen, I need to solve the following high-level problems:

 1. Get the computer to recognize that a gateway is plugged into a USB port
 2. Prompt the user to enter the new ssid and network password
 3. Write to the ssid and password fields
 4. Compile the code and save it (equivalent compile/upload in the IDE)
 5. Run the sketch to find and connect to the network

I'd like this to look like two blank fields and a "submit" button to the user.

My imaginary use case is that I'm installing a clone of my gateway/sensor network at a technically-illiterate grandparent's house.  I have no idea where to begin or even if such a thing is possible!

Assuming that it is possible, how can I make it easy for them to configure the gateway for use on their home network without resorting to the IDE?

body:
Yes, this is possible. However, you need to have some programming skills (Java, C, C++, anything really that can cope with serial comms) to write the computer-side program.

Forget 'automatic' running of a program without installing a service on the target computer to constantly monitor incoming serial comms. That said, there's nothing to stop you doing that but to me it's an unnecessary extra step. If the End User can handle connecting the Arduino to the computer without having a breakdown, then they can probably cope with launching the input program themselves.

Hence, write a program for the target computer that analyses COM ports for active connections. For each connection, listen for some kind of identification sequence. Perform a basic 'handshake' to verify that it's found the Arduino. Once it has, allow the User to enter the WiFi details, which are then passed on to the Arduino via serial. If you're feeling *slightly* adventurous (the necessary code is provided with the Arduino IDE as an Example, so it's no real challenge) you could have the Arduino scan for networks and offer the User a list to choose from.

On the Arduino, include within the sketch a method of opening serial comms with the target computer. This can be either:

 - **Within `loop()`**, at regular intervals, which becomes redundant after you've performed the setup correctly; or
 - **A one-time affair within `setup()`**. Each time the Arduino is powered on it attempts to establish comms with the computer, but times out after 30 seconds of 'silence', thus the User has to launch the program on the computer within a reasonable time.

Whichever approach you choose, the code in the sketch follows a similar essence - send a unique message to whatever is listening (if anything at all!) and wait for a specific response. If the computer is connected and the program is running, it should answer. Provided the answer received by the Arduino is expected (thus 'handshake' mentioned earlier), it should then wait for the SSID/pass to be entered by the User and sent by the computer. From there, connecting the Arduino to the network is a trivial process.


body:
You could also make use of the Arduino serialEvent() function. Behind the scenes, every time the loop() function returns, this function (if you define it) is automatically run by the Arduino if the Serial buffer contains data. So all you have to do is define the serialEvent() function and have it read from the serial port and compare what it gets against some pre-defined handshake value. If the read data is a valid handshake, the Arduino should respond with a unique value too and then await the SSID, password and other stuff you wish to set.
This means your can run your PC program anytime and simply have it send the handshake and wait for the Arduino's response before sending the wifi details. You can use serialEvent() like this:

        void serialEvent(){
            if (Serial.read() == 'Z'){ //if 'Z' is your handshake value
                Serial.write('X');   // if 'X' is the response expected by the PC
                getWifiDetails();   // the handler that gets the needed data
            }
            while (Serial.read() != -1);  // flush to get rid of any garbage
        }

The handshake value could be more than 1 byte to increase chances of uniqueness. This method assumes you aren't doing anything else with the serial port, since that could bring garbage to the forefront of Serial.read() calls and cause false triggering of serialEvent() and its IF condition. You could implement a timeout in your handler to handle such events though.


message:
Why does a light bulb activate an infrared sensor? Is there a way I can filter this out?

I've made 3 programs. One is written in python, c++ processing and bash.

Everything seems to be okay but then sometimes I get a signal from the arduino that activates the function to lower down the volume on the python code listening for serial data. This is sometimes random but it seems that I can reproduce the same behavior when I turn the light on. I can cause the same disruption if I wave my hands over it quickly.

How can I filter this? I know that IR is part of the electromagnetic spectrum in which the visible light takes part. The sensor is facing upward for a type of omnidirectional receptor. I've placed a TV IR blackish cover over it but with the same results. Do I need to use the function to hash decode the incoming signal? I suppose that it needs a simple circuit as any other sensor.

I want to discard the possibility of a random activation in my code.

Edit:

Taken into consideration the answers until now I can confirm that this is part of a physical phenomena due to the distance between my light and the device.

As for the solution to my volume problem It seems that I used "0" in the same statement as the ir code I remapped in the python code. It turned out to be part of the IRlib library of the arduino code that returns a "0" when it encounters an unknown signal. (due to protocol specification? - out of useful range? )

The thing is that I can change the if statement value for other than "0" but that won't stop it from returning "0" and that's a disadvantage. The solution that came to me is simply intercepting the signal and use continue to skip this.

Is there any alternative to this?

body:
Yes, a light bulb will put out some infrared light.

Decoding remote control signals isn't that hard - there is a tutorial at instructables - http://www.instructables.com/id/The-Easiest-Way-to-Use-Any-IR-Remote-with-Ardiuno/?ALLSTEPS

This also means you can tell the difference between different buttons.

P.S. - when posting in this forum, it helps to include your code and your wiring.


body:
What kind of light bulb is it?  Try using e.g. an LED instead of incandescent; you might get less IR signal.
Having a more complicated signal that is decoded by the receiver reduces your false positives.


message:
Possible configure ESP8266 as wifi shield for Arduino?

I know there's sketch to make ESP8266 becoming a simple web server. ESP8266 is cheap, small and consume less power compared to a Arduino Wifi shield.

Due to a more complex functionality requirement, I wish to place the web server code inside the Arduino itself (UNO, Nano or Pro Mini maybe). Is it possible to do this by configuring ESP8266 as a wifi bridge/shield to the Arduino? Or some mechanism methods which can route network traffics from ESP8266 to/from Arduino?

**Updated**
It connected to 4 relays & one I2C RTC DS1307.
It needs to sync RTC time with NTP server, and implement a web server which allows on-demand turn on/off each individual relay or by scheduling (e.g: turn on/off different relay at particular time of day). If RAM spaces allows, would like to implement a password access scheme for the web server as well

body: The ESP has 40 kb of ram and the average SPI flash rom used by ESP modules have 1 ~ 8 MB of code space. The average Arduino has much less of both. Uno R3 has the ATMega328, with 2kb of SRAM and 32kb of code space. Your trying to drive a truck with a mini cooper engine.


body:
I can't comment on Passerby's answer so here is an answer to that question in the comments: What ESP8266 are you using? The simple ESP-01, the one with just 8 pins, does not have four I/O ports. However if you have a more advanced ESP8266(for example the ESP12 on a breakout board) you do have 4 I/O pins and you could just threw out the Arduino entirely. The ESP8266 is better suited to serve as a webserver than your arduino. So as Passerby suggested try just using your ESP8266 alone instead of combined with your Arduino. Have a look at [this][1]. It is a tutorial on how to build a webserver controlling two LED's. All you would need to do is replace the LED's with the relays and add another two outputs. Note that you do need another powersupply for your ESP8266 than the Arduino. The arduino can only supply about 40mA, while the peek current of an ESP8266 can be around 250mA. Good Luck!

  [1]: http://randomnerdtutorials.com/esp8266-web-server/


message:
Why does the PIN 13 LED of Uno R3 blink every time I upload some code?

I was driving a relay from Arduino Uno R3 Pin 13. I observed that every time I upload some code the led on the board designating pin 13 would blink. I'm curious why this is so. I understand that the serial LED blinks cause there's a serial transmission but why an IO pin?

body: It's driven by the bootloader, which is performing the flashing (I suppose you are flashing through the USB port).


body:
See <https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader> - the flashing is by design.

[![Optiboot flashing pin 13][1]][1]

Probably the reason is to confirm that the bootloader has started.

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


message:
LED matrix appears dead

I recently purchased a 1.2 8x8 yellow matrix from Adafruit, along with a HT16K33 backpack for it. I joined the matrix and the backpack, connected everything to the arduino, followed the instructions on the site and got it to work. During animation certain rows would not light up and upon later examination I realized that I had to solder up the pins to the backpack because some pins would not completely make contact with the backpack. After soldering the matrix to the backpack, I fired up arduino and uploaded the matrix8x8 sketch that comes with the library to test the matrix and nothing happens.

I don't have a multimeter yet, but tried to check whether electricity is reaching the backpack which turns out to be true. (used a led and connected it to both + and -, and data and clock pins on the backpack.) in both cases the led lights up.

How can I check the health of the backpack and/or matrix?

body:
I hate to say it, but a multimeter would really come in handy for you.  Harbor Freight has some for under $10.

That said, without knowing anything specific about what you are using, you could try using the same LED you used to test power and put it in parallel with one of the LEDs on the matrix.  I'm guessing you don't have power at the LEDs though because it seems unlikely that all the LEDs would fail.  Check your solder work and make sure you have not shorted anything.  Also, you could have overheated a component when soldering causing it to fail.  Good luck.


message:
Connect arduino to beaglebone black

I want to exchange some date between arduino and beaglebone, as far as I know, most arduinos works with 5v levels, so I need to convert 5v into 3.3v beaglebone in order to communicate with it.
Unfortunatly I have no pro mini 3.3v now, only 5v arduinos.
So I need to convert levels.
I have several questions.

 1. I have UART TTL CP2102 converter, I am using it to programm my Arduino pro mini, can I use it directly with beagle bone without converter ? http://ecx.images-amazon.com/images/I/410n8+HhdNL._SY300_.jpg like this.

 2. I can buy this cable with pl2303 inside http://i01.i.aliimg.com/wsphoto/v0/32250361345/Free-postage-1pcs-PL2303-PL2303HX-USB-to-UART-TTL-Cable-module-4p-4-pin-RS232-Converter.jpg

 3. Is it possible to power my arduino pro mini 5v with 3.3v supply and use it directly with beaglebone

4. Can you provide simple level converter schematic to solder it quickly

All in all I need just to communicate with beaglebone via uart from pc with USB-UART converter or from arduino it doesn't matter, just to communicate and send some data.

Please suggest what is the best way to follow.

body:
The simplest way is just to plug the Arduino in to the BBB.

The BBB has USB.  The Arduino has USB.  Connect the two together and you have both power and data immediately available.

Depending on the Arduino and its version it will either be there as `/dev/ttyAMA0` or `/dev/ttyUSB0`

You can even use `avrdude` to upload new software to the Arduino direct from the BBB.


message:
Detect USB activity from a host

I am testing a WinCE device that loses all USB communication infrequently. I need to detect when the USB fails on this device. When it fails, the power is intact at the port, just no data at all on D+ and D- (I verified this with an oscilloscope). This host device is basically a black box to me so I can't do anything to it but check it's state.

My proposed solution:  Use an arduino of some type (preferably an UNO since I have one already) programmed to detect USB activity to let me know when USB is failing on the host device I am testing.

Is this possible? The arduino seems like a good solution for me because I assume it is a USB client, which I need in this scenario.  Any example or pointing me in the right direction would be of great help.  Thanks!

body: If all you are interested in is the voltages on the D+ and D- lines you could wire those direct into two ADC inputs on the Arduino and wire +5V and GND into the +5V and GND pin.  The Arduino can then sample the voltages and compare them to valid or invalid ranges.


message:
Why cannot I input arrays as digitalWrite arguments?

I am making my own "7 segment LED driver". I know there is a lot of examples on the internet, I just want to try my own. But I have a piece of code that does not work and I don't know why. Can somebody explain to me why it is not working?

When I put in this, it works:

    digitalWrite(pins[0], one[0]);
    digitalWrite(pins[1], one[1]);
    digitalWrite(pins[2], one[2]);
    digitalWrite(pins[3], one[3]);
    digitalWrite(pins[4], one[4]);
    digitalWrite(pins[5], one[5]);
    digitalWrite(pins[6], one[6]);

So of course I tried using for():

    for (byte i = 0; i >= 6; i++)
      {
        digitalWrite(pins[i], one[i]);
      }

And this does not work. But why? I think it should. Btw. *pins* is const byte array and *one* is const bool array.

Thanks in advance for any suggestions!

body:
You've written the `for` loop incorrectly.

    for (byte i = 0; i >= 6; i++)   <-- ERROR HERE
      {
        digitalWrite(pins[i], one[i]);
      }

That first line should be `for (byte i = 0; i <= 6; i++)`. `i` begins at zero, which is less than six, and the loop only runs while `i` is greater than 6.


message:
Is there a good XMPP (Jabber) library for Arduino?

I have a few sensors plugged in and getting some data from them. I want to use XMPP protocol to push the sensor data to my main server. Is there a good XMPP library available which I can use?

body:
A quick search pulls up https://github.com/adamvr/XMPPArduino which hasn't been touched since it was first created five years ago, and may or may not work. XMPP is a very heavy protocol that is very burdensome for a microcontroller to try and run. You could try and get the above library to work, or I would recommend one of the following alternatives:

 - Load an XMPP client onto the OpenWRT side of the Yun and send commands from the Yun to control it. (<strike>Although glancing through the list of packages, there does not appear to be a pre-existing one. So this might not be an option unless you are up for cross compiling one.</strike> Looks like there is at least one: BitlBee via https://github.com/arduino/openwrt-packages-yun)
 - Have the Arduino communicate using a lighter weight protocol (e.g. HTTP or MQTT) to another server or application that you write, which in turn sends your XMPP message using a readily available library.


message:
Power Supply for 30 Servos

I am now constructing something with 30 servos (each one will control an individual joint separately, so I guess I can't get away from this), how can I determine how much current do I need, I have a 5V 6A power supply, will that be working just fine? Many thanks in advance!

body:
Get one of the servo's working at full load & measure the current flowing through it, multiply that by 30.

That's a lot of servos :D


body:
You'll need to look up for your particular model of servo what it is rated for.

From this [random datasheet](http://www.rctoys.com/pdf/hitec-servos/HIT-HS55.pdf) I got values of about 5mA while idle and 150mA while running. Your 6A supply will be fine (if your servos don't draw significantly more than these) even if you run them all at once (which in practice, you might not).

Note that if you stall the servos they will draw more current, but it seems unlikely that you'd stall all of them at once.


message:
Execute Code While Refreshing a 7 Segment LED Display

I'm using the following library to drive a 4 digit, 7 segment LED display:

http://playground.arduino.cc/Main/SevenSegmentLibrary

The display is showing the temperature which it gets from a DS18B20 temperature sensor.  Since the LED display constantly needs to be refreshed, when the code runs to get the current temperature, the display temporarily turns off because the LEDs are not being refreshed.  The code I am using is below. Is there anyway to prevent the LED display from turning off while the temperature request code runs?

<!-- language: c -->

    #include <SevSeg.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>

    SevSeg sevseg;

    unsigned long timer; // the timer
    unsigned long INTERVAL = 30000; // the repeat interval (30 seconds)

    #define ONE_WIRE_BUS 2
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    void setup() {
      byte numDigits = 4;
      byte digitPins[] = {A2, A3, A4, A5};
      byte segmentPins[] = {8, 10, 6, 4, 3, 9, 7, 5};

      sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
      sevseg.setBrightness(90);

      // Get the initial temperature and show it on the LED display
      sensors.begin();
      sensors.requestTemperatures();
      sevseg.setNumber(sensors.getTempCByIndex(0), 1);
      timer = millis(); // start timer
    }

    void loop() {
      if ((millis()-timer) > INTERVAL) {
     // Reset the timer and get/display the current temperature
        timer += INTERVAL;
        sensors.requestTemperatures();
        sevseg.setNumber(sensors.getTempCByIndex(0), 1);
      }

      sevseg.refreshDisplay(); // Must run repeatedly to refresh the LED display
    }

body:
The problem here is that the display is driven using a timer interrupt.  The temperature sensor, being a one-wire device, has to have very careful timing to communicate with it.  As a result it disables interrupt so it has exclusive use of the CPU and can properly predict its timing while it's communicating.  And so the display can't refresh at the same time.

So what can you do?  Well, nothing really.  You can't have perfect timing for the temperature sensor while at the same time interrupting it for displaying the value.

So there's really two main options:

1. Change the temperature sensor.  Use an SPI or I2C temperature sensor that has a real hardware interface to communicate with it so you don't have to use big-banging.

2. Change the display.  A non-multiplexed display or a display with its own built in driver (most often with some serial protocol like I2C or UART) would mean you don't have to use interrupts to update the display.

Basically you have two technologies that won't sit together well on the same chip.

----

Update:

I missed the `sevseg.refreshDisplay()` function call since the website had scrolled it off the bottom of the code block.  Bah!

Ok, so it's not using an interrupt.  That could be a good thing, or it may be meaningless.  It takes time to do the temperature reading, and it's that getting in the way of the refreshing.

There's a chance you may be able to push the update "into the background" by attaching it to a timer interrupt, but if the OneWire communication does disable interrupts then the problem will still persist (I don't have OneWire to hand to look at the code right now).


message:
cannot read from softwareserial

I am able to use AT command from the Serial monitor however when I run the following code nothing is sent or received from the ESP8266. Can someone advise what could be the problem.

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

    #include <SoftwareSerial.h>;

    SoftwareSerial esp8266(0,1); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                 // and the RX line from the esp to the Arduino's pin 3
    void setup()
    {
      Serial.begin(9600);
      esp8266.begin(9600); // your esp's baud rate might be different
    }

    void loop()
    {
     if(esp8266.available()) // check if the esp is sending a message
      {
        while(esp8266.available())
        {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          Serial.write(c);
        }
      }

      if(Serial.available())
      {
        // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
        // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
        // but we want to send everything at the same time.
        delay(1000);

        String command="";

        while(Serial.available()) // read the command character by character
        {
            // read one character
         command+=(char)Serial.read();
        }
        esp8266.println(command); // send the read character to the esp8266
      }
    }

body:
    SoftwareSerial esp8266(0,1)

You can't use pins 0 and 1 for software serial since they are the hardware serial `Serial` than you use for communication with the PC.

Pick two other pins to use.


message:
Arduino Mega 2560 bootloader delay

I need to make my program run immediately on a reset or power up. However, the bootloader delays program startup by around 2.5 seconds. How can I get over this? Is there a way to turn off the bootloader wait period?

body:
Yes.  You remove the bootloader completely and program the Arduino using a hardware programmer.

If you could "turn off" the wait period you would never be able to get into the bootloader to program the board, so the bootloader would be completely useless.  So either way you would then need a hardware programmer to do anything constructive with the board.

A hardware programmer could be another Arduino, or a real hardware programming adapter.


message:
Sainsmart Omron 12V optocoupled 2 channel relay problem

I know that there are plenty of questions related to relays, but I have to ask. I am trying to sort out the issue and spend hours reading but cannot make progress.

I have [SainSmart 2-Channel 12V Relay Module](http://www.sainsmart.com/arduino/arduino-components/omron-12v-2-channel-relay-opto-couple-for-arduino-uno-r3-raspberry-pi-arm.html) for Arduino and wired it according to picture.

[![SainSmart 2-channel relay][1]][1]

Arduino UNO R3 board is powered from 12V plug external power supply. I take that 12V to power JD-VCC on relay (from VIN). Arduino 5V is used to power optocoupler circuitry.

I want to use to power 12/24/220V devices (on picture I wired 6V battery for troubleshooting).

So, when I set PIN7 to LOW i would expect that fan spins up. LED on relay goes RED, so I expect it is sign that relay is activated. However, fan does not power on.
When I bring PIN7 to HIGH, I hear click; LED goes OFF. I assume it deactivated relay. All the time I have 6V on voltmeter.

What I am doing wrong?
I really tried to find answer around, but either I do not see or it is not so obvious.

Thank you,

 [![WIRING][2]][2]

  [1]: https://i.stack.imgur.com/xzwDc.jpg
  [2]: https://i.stack.imgur.com/XUBE7.png

body:
<s>Looking at what I assume is [the same module on the Sainsmart website](http://www.sainsmart.com/arduino-compatibles-1/relay/sainsmart-2-channel-5v-relay-module-for-arduino-raspberry-pi.html) it looks like the relays are 5V. That means the 12V you have pumped into them has made the [Magic Smoke™](https://en.wikipedia.org/wiki/Magic_smoke) escape.

Throw them away, buy some new ones, and next time don't put in more than twice the voltage it needs.</s>


body: Remove the wire from the collector of your transistor and 12VDC, it should work fine.  It is possible you blown the opto coupler and transistor.


body:
Lets troubleshoot this circuit:

 1. The circuit diagram you put in your question shows a wire creating a short across the relay coil. Check this, as this will definitely stop your fan from spinning. However, I assume this is an error in the diagram.
 2. The picture on the website shows a jumper link between VCC and JD-VCC. Make sure this is removed.
 3. Check that the fan works when you power it directly from the 6V battery. The fan may work only at a higher voltage or run off of AC voltage. Also, the battery could be flat - measure its voltage when it is under a small load.
 4. Drive the input circuitry directly off of 5V. That is connect `VCC` to 5V and then directly connect `IN1` to GND. Open circuit the `IN1` input to turn it off. Check that this direct driving opens and closes the relay contacts.
 5. Check the 12V supply. Does the voltage drop significantly when the relay pulls in or out? Does it have enough current? `"Each [relay] needs 15-20mA Driver Current"` Measure it using your DMM in ammeter mode.
 6. Check your wiring is correct. It sounds simple, but you will be surprised by how many times the wiring is the cause of the problem.
 7. Measure the resistance of the relay contacts in both the open and closed states. Arcing or poor manufacturing can be causes for the contacts to not function as intended.


message:
Where can I storage a local database?

I want to create a website where the users can have their own database. An example:
- An user will receive some data from HTTP POST and I want to storage all the information into a local database to access to it. For example, the URL that the user has visited in the last month.

I know that the best option will be to create a database in my server and put each user in it, but it will be very long database and the information between users is not shared, therefore it will be more secure using a local database, but I don´t know if that can be done.

My project is about ESP8266 and uploading data to a server, so this can be done using a microcontroller instead the computer. I have seen the raspberry to use it as a server and storage there the database, but it is so expensive. Can be done using another board as Arduino, Texas Instruments, etc...

The main aim is to create a main hub to storage all the values received from the ESP8266 and then share over internet, but I don´t know how to build a hub where I can store a database inside and a HTML website to show the values. Any ideas? I would like to avoid a computer to do it.

I think in something for less than 10 GBP, because I bought and Arduino and Ethernet shield for 5 GBP both, fake version, but useful for my project

body:
You can use the Sparkfun data project:

https://data.sparkfun.com/

they build an open source tool called `phant` (https://github.com/sparkfun/phant) that you use to host on your own or use their free version online


body:
As I understand the question, you want a 'mini' database for your ESP8266, without the need to connect to the internet.

One way I can think of is that you could use your ESP8266 flash memory to store the database. Use SPIFFS with, say, 1 MBytes flash size, leaving 3 MBytes for your actual program (assuming the ESP8266 has 4 MB flash memory). More than 20 thousand record files for 50 bytes each.

But you'll need to write your own create, read, update, delete (CRUD) function to handle the files.

If someone has already written such functions, that would be useful to share here.


message:
LEDs: difference between common anode and common cathode?

What is the difference in using a common anode and common cathode of the 7 Segment in interfacing with the Arduino? How can you change the code if we need to add another 7 Segment display?

How can you change the code to have a counter in backwards (from 0 to 9)?

    const int ANODE = 2;

    const int LED1 = 3;
    const int LED2 = 4;   // pin for led 2
    const int LED3 = 5;   // pin for led 3
    const int LED4 = 6;   // pin for led 4

    // now bottom row

    const int LED5 = 7;
    const int LED6 = 8;
    const int LED7 = 9;
    const int LED8 = 10;

    int DELAY = 0;

    void setup() {
      pinMode(ANODE, OUTPUT);  // common anode is obviously an output

      pinMode(LED1, OUTPUT);   // led are output for low will be on
      pinMode(LED2, OUTPUT);   // led 2 is output
      pinMode(LED3, OUTPUT);   // led 3 is output
      pinMode(LED4, OUTPUT);   // led 4 is output
      pinMode(LED5, OUTPUT);   // led 5 is output
      pinMode(LED6, OUTPUT);   // led 6 is output
      pinMode(LED7, OUTPUT);   // led 7 is output
      pinMode(LED8, OUTPUT);   // led 8 is output
    }

    void loop(){

      if (DELAY == 300){
        delay(100000);
      }

      digitalWrite(ANODE, HIGH);

      digitalWrite(LED1, HIGH);
      digitalWrite(LED2, HIGH);
      digitalWrite(LED3, HIGH);
      digitalWrite(LED4, HIGH);
      digitalWrite(LED5, HIGH);
      digitalWrite(LED6, HIGH);
      digitalWrite(LED7, HIGH);
      digitalWrite(LED8, HIGH);

    delay(1000);

      digitalWrite(LED1, LOW);
      delay(500);
      digitalWrite(LED1, HIGH);
      digitalWrite(LED2, LOW);
      delay(500);
      digitalWrite(LED2, HIGH);
      digitalWrite(LED3, LOW);
      delay(500);
      digitalWrite(LED3, HIGH);
      digitalWrite(LED4, LOW);
      delay(500);
      digitalWrite(LED4, HIGH);
      digitalWrite(LED5, LOW);
      delay(500);
      digitalWrite(LED5, HIGH);
      digitalWrite(LED6, LOW);
      delay(500);
      digitalWrite(LED6, HIGH);
      digitalWrite(LED7, LOW);
      delay(500);
      digitalWrite(LED7, HIGH);
      digitalWrite(LED8, LOW);
      delay(500);
      digitalWrite(LED8, HIGH);

      delay(100);

      DELAY = DELAY + 150;
    }

body: Basically you just need to change the HIGH's by LOW's and the LOW's by HIGH's.


body:
A 7-segment is a packaged set of 8 LEDs (7 number-segments & 1 decimal point). Common anode means that the anode (positive) side of all of the LEDs are electrically connected at one pin, and each LED cathode has its own pin. So turning on any particular segment will involve running a current from this common anode (positive) pin to the particular cathode (negative) pin for the desired segment.

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

Common cathode means that the cathodes of all of the LEDs are common and connected to a single pin. The anode for each LED has its own pin. So driving one of these means running a current from the particular anode (positive) pin for the desired segment to the common cathode pin.

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

The way that you are diving the 7-segment involves using a separate pin to drive each segment, so you use 8 pins of the Arduino to drive the display. You will run out of digital pins if you try to add a second 7-segment. There are a couple of ways to address this. One is to add a 7-segment driver, like the CD4511. This limits you to being able to display only numerical digits, but uses only 4 pins of the Arduino per 7-segment.

Another, more versatile way is to add a serial-in to parallel out chip (74HC595, for example) to drive the 7-segment. This requires only two pins from the Arduino (data & clock), and they can be chained to have multiple 7-segments driven from those same 2 pins.

  [1]: https://i.stack.imgur.com/3Mu4Y.gif
  [2]: https://i.stack.imgur.com/0HLZa.gif


body:
Spent an hour trying to work it out, seems I have common anode leds.
So you have to connect the anode to the 5V (on arduino),
The voltages are then reversed, so use 255-v instead of v.

I think common cathode will be easier to understand and program for.


body:
To add to the existing answers:

> For the arduino with [its] symmetrical ability to source and sink exactly the same amount of current then there is no preferred way.

- [Grumpy_Mike on Arudino forums](https://forum.arduino.cc/index.php?topic=22413.msg169035#msg169035)

That being said, if you are using a driver circuit like the MAX7219 (which makes interfacing many digits much simpler and requires far fewer pins), use the one specified by the datasheet. For example, [the MAX7219 is designed to drive common-cathode LED displays.](https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf)


message:
Ping sensor with three or four pins?

I bought a [Ping Ultrasonic Range Finder][1]. It has four pins that you connect to the Arduino. I see in Internet that they have three pins. What does represent each pin and where to connect it to? I have an Arduino Uno Starter Kit.

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

body:
You have 4 *pins*.

* Vcc: +5V supply voltage (it stands for Collector Voltage)
* GND: Ground.
* Trig: Causes an ultrasound pulse to be generated (it stands for *Trigger*)
* Echo: Tells you when an echo has been received.

You can see how to wire and use it here: http://www.instructables.com/id/Easy-ultrasonic-4-pin-sensor-monitoring-hc-sr04/


message:
What components I need for a small GPS tracker

I am new to Arduino and want to create a graduation project for my university.
I am thinking to create a GPS tracker that can be attached to a cloth to track kids, for example.
So the requirements for this project is as follows:
- The device should be small
- It should upload its location to a web server constantly.
- the device should work with battery for at least 8 hours

Now what components are needed for this project?
What concern me a lot is that how can I find battery last this much time, if I need bigger battery, it may hinder the device from being attached easily.

body:
You need four things:

* A GPS receiver
* A GSM modem
* An Arduino
* A Battery

Using off the shelf products you would probably end up with something about the size of a cigarette packet at best - probably bigger.

To make it small enough to be unobtrusive would take a lot of work.  You would need to design your own circuitry combining everything that is contained in the three circuits above into the smallest design you can, and since most existing solutions use pre-built modules (*cans*) that are relatively large you would first have to discover how they work and replicate them as one single tiny module.

And then there is the battery.  GPS receivers are very sensitive devices. They have quite powerful preamplifiers to detect the incredibly faint signals of the satellites.  Consequently they use quite a bit of power.  Similarly GSM modems are quite power hungry, especially when they are far from a cell tower.

Put those together and you have quite large power requirements - so the battery will consequently be relatively large.  Many times the size of the circuit you designed above.

So if you're trying to make something that James Bond might stick on the back of someone's jumper without them noticing you're very much out of luck I'm afraid.

That is why most tracking of people is done using a larger device that most people have sat in their pocket already: a mobile phone.  You can already get software for most phones that will allow you to track your children.


body:
In addition to @Majenko's post, you will save considerable power by turning the GPS & GSM off when not needed - for example, you might decide that once per minute, or once per 5 minutes is enough (maybe send it a text to trigger "continuous mode"?). Once the Arduino has switched off the other devices, it can go into "sleep" mode for a while. Check out Nick Gammon's excellent treatise on power saving modes at http://www.gammon.com.au/power

You can save both power and size by replacing an entire Arduino with an ATTiny - prototype on an Arduino first, then once it's working, move to an AtTiny - they have fewer pins, less memory, and are cheaper & smaller.

I doubt you could get the size smaller than a small cellphone, which can be had for very little - $35ish plus shipping, from http://www.aliexpress.com/item/Cheap-original-Mobile-phone-LG-Optimus-One-P500-WIFI-GPS-JAVA-Android-OS-Unlocked-Mobile-Phone/32274282341.html?spm=2114.01020208.3.1.zgFwLV&ws_ab_test=searchweb201556_1,searchweb201527_3_71_72_73_74_75,searchweb201560_9


body:
You have two options. Option 1. Buy a ready made pet tracking device from online market e.g (https://www.aliexpress.com/item/Pets-Smart-Mini-GPS-Tracker-Anti-Lost-Waterproof-Bluetooth-Tracer-For-Pet-Dog-Cat-Keys-Wallet/32887784462.html?spm=2114.search0104.3.1.26793604pFMLma&ws_ab_test=searchweb0_0,searchweb201602_3_10065_10068_319_10059_10884_317_10887_10696_321_322_10084_453_10083_454_10103_10618_10307_537_536,searchweb201603_52,ppcSwitch_0&algo_expid=09c58262-a0e7-4205-8fba-cd8265c15b3e-0&algo_pvid=09c58262-a0e7-4205-8fba-cd8265c15b3e). Then you can download the app and start tracking movement.

Option 2: The other alternative is to build one from scratch by purchasing all the necessary components. This is option is most appropriate for students. You can check this page for more https://electronicsforu.com/electronics-projects/hardware-diy/gsm-gps-based-vehicle-tracking-system. However, you may not be able to achieve the small size as you wanted but you should have something close to it if you carefully select your components.


message:
Send numbers bigger than 256 by SPI

How can i send numbers like 300 or 1024 ?

I'm using the recommendation of the atmel's manual.

    void SpiTransmitir(unsigned char data)
    {
       SPDR = data;
       while(!(SPSR & (1<<SPIF)));//{Serial.println("While");}
    }
I imagined that one bit shift could be the solution, but it still fails.

body:
You need to send two bytes - a high byte and a low byte.

There are two things you need to know with SPI:

1. You must wait for one byte to finish transmitting before you send the next
2. The whole transaction needs to be wrapped with a digital *chip select* signal.

So you have:

1. Chip Select idles HIGH
2. You lower Chip Select
3. You send one byte
4. You send the other byte
5. You raise chip select

At the receiver you:

1. Wait for chip select to go low
2. Receive one byte
3. Receive a second byte
4. Chip Select rises
5. You combine the two bytes together into one integer.


body:
Try to join the numbers as follows:

    #define NUMERO 342

    void setup() {
      Serial.begin(9600);
      Serial.println(NUMERO, BIN); // Mostra valor do número em binário

      uint8_t MSB = 0, LSB = 0; // Dois números de 8 bits

      uint16_t junta = 0; // Valor junto em 16 bits

      MSB = NUMERO >> 4;
      LSB = NUMERO << 4;

      junta = (MSB << 4) | (LSB >> 4) ;

      Serial.println(junta, BIN);
    }

    void loop() {}


message:
pySerial and serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)

I'm having some trouble getting my arduino uno to communicate with a simple python script through pyserial.

Lets start with my arduino sketch:

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

    byte i = 0;
    void loop() {
      Serial.println(i);
      i = i + 1;
    }

Really dead simple. It just spews the numbers from 0 to 255 over and over again. It works fine in the arduino serial monitor and gets me the expected result.

The python script comes from:

http://playground.arduino.cc/Interfacing/Python

    import serial
    ser = serial.Serial('/dev/ttyUSB0', 9600)
    while True:
        print ser.readline()

However running this script gets me:

    $ python test.py
    Traceback (most recent call last):
      File "test.py", line 4, in <module>
        print ser.readline()
      File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 460, in read
        raise SerialException('device reports readiness to read but returned no data (device disconnected?)')
    serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)

I am using ubuntu 14.04 and python-serial_2.6-1build1_all.deb

body:
This may be a kernel bug. See here: https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/1501240

The workaround it seems is to use kernel `3.13.0-63-generic`.

You can change the kernel for a one-time boot by holding shift while starting up. To make the change persistent, you need to edit `/etc/default/grub`: https://askubuntu.com/questions/262965/grub-timeout-set-to-0-cant-access-grub-menu-anymore?rq=1


message:
Help with button library, hold>2s doA else doB

I'm using [JChristensen's Button Library][1] to debounce my buttons and provide extra functionality.  I'm trying to use his press & hold function to do something if the button is pressed and held for greater than 2 seconds.  If it is just pressed momentarily it should do something else.  His example use switch cases, and I couldn't get it to work.  Here is my example that currently doesn't work.

        #include <Button.h>
        #include <SPI.h>
        #include <printf.h>

        // Keypress state setup
        byte clearPin = 16; // Clear pin

        #define PULLUP true
        #define INVERT true // Since the pullup resistor will keep the pin high  unless the
        #define DEBOUNCE_MS 20 // A debounce time of 20 milliseconds usually works well for tactile button switches.
        #define LONG_PRESS 2000 // We define a "long press" to be 2000 milliseconds.
        unsigned long ms; // The current time from millis()
        Button clearBtn(clearPin, PULLUP, INVERT, DEBOUNCE_MS); // Declare the button
        int score=1;

    void setup ()
    {
      pinMode(16, INPUT_PULLUP); // Pin for clear button
      Serial.begin(9600); // Radio Setup
    }

    void loop()
    {
     clearScore(); // sets both home and away scores to 0 or enters settings menu
    }

    void clearScore()
    {
      ms = millis(); //record the current time
      clearBtn.read(); // Read the button

      if (clearBtn.pressedFor(2000)) {
        // Enter settings menu
         Serial.println("Settings Menu");
         while (clearBtn.read()!=1) {

         } // End While
       return; // Hopefully not proceed down to the next if
      }
      if (clearBtn.wasReleased() && !clearBtn.pressedFor(2000)) {
     score=0;
        Serial.println("Clearing Scores");
        delay(50);
      }

    }

Can anyone help please?  My serial output repeats "Settings Menu" over and over.  Once I let go of the button <s>variable1</s> always gets set to 0.

  [1]: https://github.com/JChristensen/Button "JChristensen's Button Library"

body:
The `loop()` and `clearScore()` code that you have is like the following.

    void loop() {
      clearScore(); // sets both home and away scores to 0 or enters settings menu
    }
    void clearScore() {
      ms = millis(); //record the current time
      clearBtn.read(); // Read the button
      if (clearBtn.pressedFor(2000)) {
        // Enter settings menu
        Serial.println("Settings Menu");
        while (clearBtn.read()!=1) {
          // do stuff
        } // End While
        return; // Don't proceed to next if
      }
      if (clearBtn.wasReleased() && !clearBtn.pressedFor(2000)) {
        score=0;
        Serial.println("Clearing Scores");
        delay(50);
      }
    }

When you reset the Arduino and then hold down the clearBtn, `clearScore()` will be called repeatedly. `clearBtn.pressedFor(2000)` will not be satisfied during the first two seconds of holding the button down, and `clearBtn.wasReleased()` will not be satisfied either, so `clearScore()` will do nothing during the first two seconds.

After the first two seconds, "Settings Menu" will be sent repeatedly:  `clearBtn.pressedFor(2000)` is true, so the first `if` succeeds each time `clearScore()` runs, and it will run repeatedly because it is called from `loop()`.  The `while` test, `clearBtn.read()!=1` [which in more-idiomatic C would be written as `!clearBtn.read()`] fails until the clearBtn is released, so the `while` loop does nothing.  Also, `clearBtn.wasReleased()` will be false, so the other `if` does nothing.

When the button finally is released, `clearBtn.pressedFor(2000)` goes false, so the first `if` fails and the second executes one time.

Here is some code that should act more like what you want, as expressed in your comment,
>It's supposed to work like this: 1) hold button down for 2 seconds to enter settings menu. While in settings menu I'll code other stuff. Stay in settings menu until the clear button is pressed momentarily again. Once you press clear button again from being in the settings menu, the score should NOT be reset, and it should just return to the main loop. 2) if the clear button was not pressed for more than 2 seconds, just clear the score.

    void clearScore() {
      ms = millis(); //record the current time

      while (clearBtn.read()) {
        if (clearBtn.pressedFor(2000)) {
          Serial.println("Settings Menu"); // Announce Settings menu
          while (clearBtn.read()) {}       // Await button release
          while (!clearBtn.read()) {       // Await button press
         // do  Settings menu stuff here
            // (possibly wait for clearBtn release, to
            // avoid immediately clearing score again)
          }
        }
        return;
      }

      if (clearBtn.wasReleased()) { // See if released, after short press
        score=0;
        Serial.println("Clearing Scores");
        delay(50);
      }
    }

*Edit edit:* To avoid  resetting the score at every settings exit, in the above code replace

            // (possibly wait for clearBtn release, to
            // avoid immediately clearing score again)
          }
        }

with

          }
        }
        while (clearBtn.read()) {} // wait for the settings-exit clearBtn release
        clearBtn.read(); // Do another read to avoid clearing score on next clearScore()

That is, right before the `return`, wait for clearBtn release, and read it again to be sure later reads won't register a release.  The latter `read` might not be needed, because `clearScore()` does a `read` when it tests the first `while` condition; you could experiment.


message:
Arduino: Error: 'PubNub' was not declared in this scope

I'm new to Arduino. When Arduino verifies this sketch https://github.com/MediaTek-Labs/Real-Time-Bicycle-Tracking-Map-using-PubNub throws the following:

    Build options changed, rebuilding all
    BikeTracker.ino: In function 'void setup()':
    BikeTracker.ino:45:5: error: 'PubNub' was not declared in this scope
    BikeTracker.ino: In function 'void loop()':
    BikeTracker.ino:91:14: error: 'PubNub' was not declared in this scope

I've read most answers are pointing out to www.arduino.cc/en/Guide/Libraries some people say it's common Arduino linking issue (easy to fix) after tried out multiple approaches with no dice.

I've also followed PubNub customer support advice (with list of steps below) but no avail:

> OCT 12, 2015  |  10:23AM PDT  PubNub replied: Eduardo,
>
> I got this from our hardware/IoT/embedded engineer:
>
> You are probably not including all the libraries, or has the wrong
> path for them.
>
> * When you download the source at
> MediaTek-Labs/Real-Time-Bicycle-Tracking-Map-using-PubNub on GitHub:
>  * Click .ino file and a pop up will ask if you need a new folder for the
> sketch – click Yes.
>  * Then copy the rest of the files from the source to
> this new folder.
>  * Compile it and see if you get any library path errors
> that you need to provide. Let me know if you require further
> assistance.

BTW this is my PubNub.h https://gist.github.com/egomez99/fb1d738ec39913629e9a

Hope someone can shed some lights.

body: It turns out my Arduino IDE could not find PubNub.* files until I manually added them as a Library.


message:
ESP8266 stops responding when isolated relay is connected to AC tubelight

I'm completely new to Arduino and do not have an electronics background.
I'm really keen to do a POC on home automation. As a start, I decided to switch on a tube light using ESP8266, Arduino Uno R3 and isolated relay. I have read that this can be done without arduino also.

I'm able to switch on and switch off the relay without any problem. But when the relay is connected to the tube light, the ESP8266 stops responding. I couldn't find what was causing the issue.

I also read that the ESP2866 should be powered properly to function correctly. I'm following the wiring schema 5 mentioned in the link http://yaab-arduino.blogspot.in/2015/03/esp8266-wiring-schemas.html.

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

This is my code.

<!-- language: c -->

    #include <SoftwareSerial.h>

    #define DEBUG true
    int relay = 8;
    SoftwareSerial esp8266(2, 3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
    // This means that you need to connect the TX line from the esp to the Arduino's pin 2
    // and the RX line from the esp to the Arduino's pin 3
    void setup()
    {
      Serial.begin(9600);
      esp8266.begin(115200); // your esp's baud rate might be different
      pinMode(relay, OUTPUT);
      digitalWrite(relay, LOW);

      sendData("AT+RST\r\n", 2000, DEBUG); // reset module
      sendData("AT+CWMODE=3\r\n", 1000, DEBUG); // configure as access point
      sendData("AT+CWJAP=\"xxxx\",\"xxx\"\r\n", 5000, DEBUG); // configure as access point

      sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
      sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // turn on server on port 80
      sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
      sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
    }

    void loop()
    {
      if (esp8266.available()) // check if the esp is sending a message
      {

        if (esp8266.find("+IPD,"))
        {
          delay(1000);

          int connectionId = esp8266.read() - 48; // subtract 48 because the read() function returns
          // the ASCII decimal value and 0 (the first decimal number) starts at 48

          if (esp8266.find("=="))
          {
            Serial.print("State : ");
            char c = esp8266.read();
            Serial.print(c);
            if (c == '1') {
              digitalWrite(relay, HIGH);
            }
            else {
              digitalWrite(relay, LOW);
            }
          }
          String webpage = "A";

          String cipSend = "AT+CIPSEND=";
          cipSend += connectionId;
          cipSend += ",";
          cipSend += webpage.length();
          cipSend += "\r\n";

          sendData(cipSend, 1000, DEBUG);
          sendData(webpage, 1000, DEBUG);

          String closeCommand = "AT+CIPCLOSE=";
          closeCommand += connectionId; // append connection id
          closeCommand += "\r\n";

          sendData(closeCommand, 3000, DEBUG);
        }
      }
    }

    String sendData(String command, const int timeout, boolean debug)
    {
      String response = "";

      esp8266.print(command); // send the read character to the esp8266

      long int time = millis();

      while ( (time + timeout) > millis())
      {
        while (esp8266.available())
        {

          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          response += c;
        }
      }

      if (debug)
      {
        Serial.print(response);
      }

      return response;
    }

The above code works perfectly until I connect the tube light to the relay.
The power supply used in 9v 1A wall adapter.

The relay used is http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&redirect=true&ref_=oh_aui_detailpage_o03_s00.

The v+ of the relay is connected directly to the wall adapters voltage and ground to ground of wall adapter. The input of the relay is connected to Arduino digital pin 8.

I'm really struggling hard to proceed here. Any help or hint would be much appreciated.

Thanks in advance.

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

body: I suspect that you've connected the relay wrong. I think that the LNP of the relay is supposed to be connected to D8 and the v+ to 5/3.3V and GND to GND....


body:
If you are doing what you have said you are doing then I think the answer is so obvious no one will ever see it.

You say you have a 9V 1A power supply.  Since you are powering the Arduino from this it is DC.  Is that correct?

You are connecting an "AC Tube light" to the relay (which supports 1A 12V DC).
If you are connecting an AC device to a DC supply then things probably do go wrong.

To test everything is working properly can you switch the AC light for a DC light?

I think you can get Relays with AC output and a DC Switching signal, but that will need a bit of research.

Hope that helps, if not comment and I'll try again.


body:
Finally I got this working using only ESP8266 and minor tweaks. I'll post the circuit here just in case if somebody is trying to do the same thing.

Please note that this was done as a POC and I'm not from an electronics background.

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

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

Kindly note the blue wire from the GPIO 01 to resistor and an LED. I had to do this because when the circuit is powered on a HIGH signal is sent from the GPIO and the relay is turned on. I think it is the default behaviour of ESP8266. To suppress this initial flow, I did this (There may be a better way to do this according to electronics experts).

Diode used is 1N4001 Diode

Decoupling capacitor is - 10nf/100V (0.01uf/100V) Box Capacitor - Polyester

Relay used is http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&redirect=true&ref_=oh_aui_detailpage_o05_s00

Transistor is bc547.

Before connecting the devices, I flashed nodemcu firmware to ESP8266 so that I can write code in Lua script. Refer any of these to flash the firmware -  https://www.youtube.com/watch?v=Gh_pgqjfeQc
https://www.youtube.com/watch?v=pp6O96B1-Jk

I used LuaLoader to transfer the following code to the ESP8266.
http://randomnerdtutorials.com/esp8266-web-server/

I'm posting my init.lua below.

**init.lua**

    wifi.setmode(wifi.STATION)
    wifi.sta.config("<ssid>","<password>")

    cfg =
      {
        ip="192.168.1.101",
        netmask="255.255.255.0",
        gateway="192.1681.1"
      }
      wifi.sta.setip(cfg)

    print(wifi.sta.getip())
    led1 = 3
    led2 = 4
    gpio.mode(led1, gpio.OUTPUT)
    gpio.mode(led2, gpio.OUTPUT)
     gpio.write(led1, gpio.LOW)
     gpio.write(led1, gpio.LOW)
    srv=net.createServer(net.TCP)
    srv:listen(80,function(conn)
        conn:on("receive", function(client,request)
    print("receive")
            local buf = "";
            local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
            if(method == nil)then
                _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
            end
            local _GET = {}
            if (vars ~= nil)then
                for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
                    _GET[k] = v
                end
            end
            buf = buf.."<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
 Control Panel
";
            buf = buf.."
Tubelight <button>ON</button> <button>OFF</button>
";
            local _on,_off = "",""

    print(wifi.sta.getip())
            if(_GET.pin == "ON1")then

                  gpio.write(led1, gpio.HIGH);

            elseif(_GET.pin == "OFF1")then
                  gpio.write(led1, gpio.LOW);
            elseif(_GET.pin == "ON2")then
                  gpio.write(led2, gpio.HIGH);
            elseif(_GET.pin == "OFF2")then
                  gpio.write(led2, gpio.LOW);
            end

            client:send("HTTP/1.1 200 OK\r\n");
            client:send("Content-type: text/html\r\n");
            client:send("Connection: close\r\n\r\n");
            client:send(buf);
            client:close();
            collectgarbage();
        end)
    end)

If everything is running, connect your phone or computer to the same wifi using "`<ssid>`","`<password>`" and access the IP 192.168.1.101 to see a webpage with one buttons "ON" and "OFF". Click on it an check whether it is working.


message:
How to wait Arduino ready with ANY method?

Recently I knew, that Arduino restarts any time somebody accesses it's serial port. I was trying to use this feature so that for each request Arduino restarts and give answer on request. Unfortunately, I found this is impossible with shell script, because shell script can't keep port open all time I send requests and wait responses: Arduino restarts on each port touch.

So, I wrote simple C++ program:

<!-- language: lang-cpp -->

    #include <iostream>
    #include <fstream>

    using namespace std;

    void help() {
     cout << "bmp180dims usage:" << endl <<
       "bmp180dims port command" << endl;
    }

    int main(int argc, char* argv[]) {

     if( argc != 3 ) {
      help();
      return 0;
     }

     fstream port;
     string answer;

     port.open(argv[1], std::fstream::in | std::fstream::out);

     port << argv[2] << endl;

     port >> answer;

     cout << answer << endl;

     port.close();

     return 0;

    }

Since this program has explicit `open` and `close` statements, I was thinking, this program will wait for Arduino answer, because of stream reading functions. But I failed again: this program returns nothing as if it is not waiting.

Why?

Apparently, the only way to communicate with Arduino, is to have daemon program, which always listen it's port. Is this really so?

Arduino-side code is here: https://arduino.stackexchange.com/questions/16769/how-can-program-arduino-restarted-by-ide

body:
Again, you're *not waiting for the bootloader to complete* before sending your text:

    port.open(argv[1], std::fstream::in | std::fstream::out);
    // Board resets and enters bootloader

    port << argv[2] << endl;
    // You send argv[2] to the bootloader

    port >> answer;
    // The bootloader doesn't understand what you sent so doesn't reply with anything

You *must* wait for the bootloader to complete *before* sending ANYTHING to the Arduino.

The two ways you can do that are:

1. Insert a `sleep(3);` immediately after opening the port to give the bootloader a chance to time out and start running your sketch, or
2. Provide an initial "I Am Ready" message from your sketch that your C++ program waits for *before* sending the text you want to send to elicit an answer.


message:
Where do I get motion detector for ardruino that can actually be installed in ceiling?

This might be a bit of off topic but I have nowhere else to go. :-) I have programmed motion detection with ardruino and would like to integrate it with my home automation system.

Would like to install the PIR in the ceiling of the entrance.

The problem is that all low voltage PIRs for ardruino are sold without any case (just a board).

Does it mean I have to buy a regular PIR (with relay integrated) and modify it?

body:
This might not be quite the answer you were looking for, but...

3D print your case.

I expect you haven't got a 3D printer but you can find someone on [3D hubs][1] to print it for you, and you might not even have to design the case because [thingiverse has a few already][2]...

  [1]: http://www.3dhubs.com/
  [2]: http://www.thingiverse.com/search?q=pir sensor&sa=


body:
Try looking at Alarm PID units, they typically will operate on 12VDC and have a relay output contact and a tamper contact.  They are not that expensive and come with a case.

Gil


message:
Processing printing sensor readings and raising NaN exception at the same time

I am using pressure sensor with Arduino Uno within Processing.
Given these variables:

    Serial myPort;              //the serial port
    float sensorValue = 0;      //the value form the sensor

Arduino is printing float numbers on Processing console, according to the snippet below.

    (...)

    void serialEvent (Serial myPort){
    //get the ASCII string
    String inString = myPort.readStringUntil('\n');

    if (inString != null){
    //trim off any whitespace:
    inString = trim(inString);
    //convert to an int and map to the screen height
    sensorValue = float(inString);
    println(sensorValue);
    sensorValue = map(sensorValue, 0, 1023, 0, height);
    //println(sensorValue);

However, I am getting a `NaN` exception:

`sensorValue = map(NaN, 0, 1023, 0, height);`

how is this possible? printing numbers that aren't numbers?

body:
//convert to an int and map to the screen height
sensorValue = float(inString);

You can't convert a String to a Float just like that by casting.  You have to interpret the characters within the String.  Oh, and a float isn't an integer.

All you're doing there is trying to cast the address of the String object to a float, which it really doesn't like, hence you get NaN.

Try:

    int sensorValue;
    sensorValue = inString.toInt();


message:
Lego Technic Servo Motor - 9V PWM

I want to control Lego Technic Servo Motor 88004.

The way it works is - Lego has a 4 cable connector. Two of them supply power (+9V & GND) and the other are optionally +9V and they are called C1 and C2.

Servo turns right or left max 90 deg when you supply PWM to either C1 ("left") or C2 ("right"). (or the other way round, but it doesn't really matter)

That basically means that what I need is a 9V PWM and be able to supply it to either C1 or C2. What is more the frequency has to be 1150 Hz.

Now the question is how do I achieve this goal?

I'm already using the L298N motor controller and happen to have one engine slot free.

1) If I can supply PWM from Arduino to "LNA" input in L298N - will it also cause the output to be PWM?
Because L298N has a transistor I have a feeling that the output is also going to be PWM unless there's something else there i.e. capacitor

Even if it's not does that matter at all - meaning is it going to still work?

2) How do I produce PWM with 1150 Hz from Arduino? My Arduino is 16MHz so I suppose that it should be possible to switch output with order of magnitude smaller frequency.

If what I'm trying to do makes no sense please try to point me to the right direction.

body:
 1. Yes, the output will be a pwm. You can see it from the [schematics][1].
 2. you have few options, with different precision and complexity:
    1. Configure one of the PWM HW blocks
    2. Do it by sw in a loop
    3. Use a timer to trigger a sw function - but it might be simpler to just configure the PWM HW block.
    4. Use some existing library that will implement one of the methods I listed

I would recommend Option 1: it's not so difficult, you will learn something of the AVR internals and it will be the solution with the least overhead. You can have a look at [this][2] tutorial. There are also many others floating around.

  [1]: http://www.st.com/web/en/resource/technical/document/datasheet/CD00000240.pdf
  [2]: https://sites.google.com/site/qeewiki/books/avr-guide/pwm-on-the-atmega328


message:
Need to power Arduino Mega 2560 with 3.3V

I found an LCD for my Arduino Mega 2560 that's parallel (I like that, I don't like SPI), but it works at 3.3V and isn't 5V tolerant. That's why I'd need to use level shifters, but that would use too much space and I'd like to power the microcontroller with 3.3V. But that would cause problems because the USART communication is set to be on 5V and that can't be changed.

Is there a way to power my Arduino at 3.3V? Is there an alternative Arduino for that?

Also, if there is, I'd need to have a 16MHz crystal on it. I know it's overclocking, but Gamebuino works at 16MHz on 3.3V and I would like to do the same.

body:
What about a 3.3v Arduino Pro Mini, you'll need to solder headers but that's not too onerous. See here [Arduino pro Mini][1] or even cheaper from eBay

  [1]: https://www.sparkfun.com/products/11114


body:
Have you considered maybe using the ["Sparkfun Mega Pro 3.3V"][1] plus a ["SparkFun FTDI Basic Breakout - 3.3V"][2] ?

It uses the same ATmega2560 processor and has the same I/O arrangement as the Arduino Mega 2560, but it runs off 3.3 V.
It doesn't have the 16 MHz crystal you wanted, but if you really insist on overclocking, perhaps you could replace its 8MHz resonator with a 16 MHz crystal?

[![Sparkfun Mega Pro with resonator circled][3]][3]

  [1]: https://www.sparkfun.com/products/10744
  [2]: https://www.sparkfun.com/products/9873
  [3]: https://i.stack.imgur.com/2J8Ov.jpg