text:
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;
      }
    }
  }
}

How are you currently controlling them? With buttons or through USB with a PC? Or just hardcoded movements? What type of servo's do you use? The servo's I usually use have just 1 speed and don't give any feedback. With moving slow you would mean delaying between small steps of rotation?

I assume you are using a library for this. All the libraries already do this for you. As you need to continuously send position data (once every 20ms) to the servo.

Thanks for the replies. I have made an edit to the OP with the relevant code added. I'm controlling the servos from a PC using Tinker's sliders. I think I'm just having a conceptual block here. Would I be right in saying that the above code controls the servos in a serial fashion (eg the centre() function in the Python code the servo's are looped through)?

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.

In my opinion your code already does what you want to do. It's just that you can't move the sliders "in parallel" cause you, as human, are too slow.  If you want to be able to make sinchronized movements, you can put a button on the UI which sends the sliders positions to the arduino instead of sending them when the sliders position change. This way you can set the coordinated moves. As for the speed, you'll have to slow down the movements making small increments instead of setting the final value to the servo. If you need it I can write some pieces of code for this

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.

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


text:
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

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.

Wow, thank you so much! this is gold, I really like the temp diff and the resolution ideas.

Multiply the temperature by 100, not 10 !

Oops, typo there.

source: Stack Exchange

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

sort: votes


text:
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?

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.

Awesome, thanks for the reply.  I'll setup the wiring just like the product image, with 1k or slightly higher resistors to be safe.  What do you mean that Pin 8 should be different?  Is there a specific value is should be or what is the significance of that pin?  Sounds like you have used one of these before - do you recommend an Arduino library?

pin 8 is for the colon and it has two leds attached in parallel. Since you are multiplexing the digits, that means the leds are on only 1/4th of the time. So to match the brightness you'd supply the colon leds half the current. So I'd just double the resistor value for pin 8 (unless you're not going to use the colon at all). I just looked at the datasheet. No idea what libraries are good, but I think all will work just fine on your display.

Thanks - that makes sense about pin 8.  I was able to get everything working with a library I found (minus the colon for now).  I used 8, 1k2 resistors on each segment pin which should give me around 20 mA per pin and the brightness is still very good.  One final question, does it matter if the resistors are on the eight segment pins or the four digit pins?  I think the current would still be the same right?  I have limited space so I would prefer to use 4 resistors over 8.

No, that will not work. Having the resistor in the digit means the all the leds in digit share one resistor. So the more segments are on, the more leds have to share the current, the more dim they are. So a 1 will be much brighter than an 8.

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


text:
using seek() in Arduino to go to the end of a variable-sized file
Anyone know how to use the seek() function of Arduino SD Library 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

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());


text:
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:

Get the computer to recognize that a gateway is plugged into a USB port
Prompt the user to enter the new ssid and network password
Write to the ssid and password fields
Compile the code and save it (equivalent compile/upload in the IDE)
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?

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.

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.


text:
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?

This is why IR communications uses actual protocols instead of just presence of the signal.

Can you explain? I use a library to read IR signals from a remote control of a portable dvd player

You'll need to find out what encoding the remote uses, that will be trial and error.  You might be better of buying a cheep one that you know the encoding for off eBay or aliexpess.

Yes mine use the NEC protocol that seems generic because I have another that use the same protocol. I've kinda found my solution so I'll edit my first entry. Thanks

Remote controls use a carrier wave to make it easier to distinguish IR noise from IR signals. What kind of IR-sensor are you using?

I salvaged one from a fan and got another from the Microsoft Xbox control kit. To tell you the truth this often happened before with the other one.

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.

Yes that seems to be correct. Thanks for the link and fast answer.
My bad but I did not know where to point that first issue. With the help received I can propose an answer myself now. So I'll post some code for reference

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.

That's a good idea!! Thanks
This can be reproduced depending on intensity of light, velocity of action(no slow dim), type of artificial light and distance between. We are talking about a physical phenomena here. I'll edit my question to propose an explanation.


text:
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

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.

hmm really? i should reconsider then. @Passerby, i need to control 4 relays, 1 I2C RTC DS1307, sync RTC time from NTP server, and a web server which allows scheduling setup (e.g: turn on/off different relay at particular time of day). Do you think ESP8266 able to handle all these?

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. 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!


text:
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?

See What happens when code is uploaded using the bootloader? - the flashing is by design.

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

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

To show that the bootloader is functioning satisfactorily to the hobbyist. Boot loader helps to upload new sketch on the chip.


text:
Servo problem when use gps with softwareserial
When I use together servo motor and gps module with softwareserial , I found problem .Servo turing without signal.When I remove gps receive pin ,servo normally work. I use arduino mega 2560, ublox NEO6M and micro servo SG90 .Help me please!

Why are you using SoftwareSerial on a board that has lots of UARTs? Ditch it - all your problems will be solved.

What do you mean?

I mean why do you need to use SoftwareSerial? It is not good when doing anything else that relies on interrupts since it blocks the whole system when it's receiving a byte.  Just use the real hardware UARTs - that's what they're there for.


text:
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?

Buy a multimeter.  It's the single most essential tool for anyone doing anything with electronics. You cannot exist without one. Go out and buy one immediately. It doesn't have to be an expensive one - as long as it can test voltages and has a diode test (or continuity test 'beep' function) it will suffice.

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.


text:
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.

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%2BHhdNL.SY300.jpg like this.
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
Is it possible to power my arduino pro mini 5v with 3.3v supply and use it directly with beaglebone

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.

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.

Thx for answer, but I need UART communication

@solderingiron  Why? What's so special about using the UART pins that you can't achieve just as easily through the USB CDC/ACM UART emulation?


text:
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!

If you choose to use an Uno you probably need to reprogram the ATMega16u2 on the board, that does the usb-to-serial. I think it would be easier to have a arduino in which the main chip support USB, like the Leonardo or Micro. But I haven't done anything with USB myself.

If you modify the firmware of the USB interface chip, implement software USB, or use a native-USB board like the Arduino Leonardo,  it would be fairly trivial to run a time-out timer on USB traffic and thus see if the normally periodic polling of this slave ceases.

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.

This is a great idea.  So glad I asked; I can't believe it didn't even cross my mind.

No, that's really not going to work well.  The USB signalling is outside the bandwidth of the arduino ADC.  You need to look for transitions, not levels.


text:
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!

I don't see why it shouldn't work; what happens instead?

The seven segment display stays off, nothing lights up; but i am sure i have it connected right, because the first code works. But the compiler doesn't give any errors....

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.


text:
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?

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. (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. 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.


text:
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!

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

You'll need to look up for your particular model of servo what it is rated for.
From this random datasheet 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.


text:
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?
#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
}

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:

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.
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).

I don't think that library uses a timer interrupt. See sevseg.refreshDisplay(). Communication between the arduino and one-wire device will only take a few milliseconds. Not enough to be noticeable. The big problem is that the Arduino wait a while between requesting a measurement, and retrieving the measured value.

@Gerben Oops - that line was scrolled off the bottom of the code area - I completely missed that.


text:
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.
#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
  }
}

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.


text:
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?

Not the easiest solution, but I've modified the bootloader on a Trinket, to have it wait only if the board was reset, and not on regulator power on. Something similar can be done for the Mega. That way you can still use serial to program the board, unlike Majenko's solution.

@Gerben: +1 - this is worth making into an answer.

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.

I am using a Mega 2560, so I guess I need to use another Arduino for programming the Mega via the ICSP connector. Is that right?

Yes, that's right.  There's plenty of tutorials on the web of how to wire it up. It's just the same as how you install the bootloader on a blank chip, but instead you're installing your sketch. It can be done direct from the IDE if you select the right programmer and programming operation.

I used an AVRISP Mk2 programmer.
I selected AVRISP V2 in 'Arduino IDE 1.6.5, with Tools > Select Prorammer
When I select Sketch > Upload using Programmer, I get the following error...

"Error while uploading: missing 'program.tool' configuration parameter"
I'm using Ubuntu 14.04 with Arduino IDE 1.6.5

AVRISP is not using an Arduino as a programmer - there should be a separate entry for that.

OK. So I connected an Arduino Uno

I loaded Arduino ISP program from Examples
Selected Tool > Programmer > ArduinoISP
Then Sketch > Upload Using Programmer
And I get this error: "avrdude: Error: Could not find USBtiny device (0x2341/0x49)"

Yes, I've checked and rechecked - I have indeed selected ArduinoISP and not USBtiny.


text:
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 for Arduino and wired it according to picture.

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,

Are the relays 12V or 5V?

So the fan never goes on?

It should be 12V, on relay is written G5LA-14 12V DC. No, the fan never goes ON.

I am trying to post image of relay, could not find option. First time user.
Now I have to go for few hours.

Did you disconnect the jumper between JD-VCC and VCC?

Yes, i removed jumper. The same behavior. I understood that JD-VCC connects 5V power source from Arduino to coil, so no external power needed.

Yes, i removed jumper. Instead I connected 12V. The same behavior. I understood that JD-VCC connects 5V power source from Arduino to coil. I tried various things for hours and hours. And cannot get it. On the other hand I have dumb 5V relay that works fine when inserted.
The problem is that I will have more power lines; 3.3/5V exclusuvely for Arduino and sensors (TTL & CMOS levels) no high currents. 12V mostly for some actuators and 220V for pumps, lightning. Using optocoupled relays I can isolate them all. At 12V I will have 4 x 900W modified server power supplies to drive actuators.

This is location where I read about JD-VCC and in general terms how to do it:
http://electronics.stackexchange.com/questions/18908/not-sure-how-to-
wire-my-5vdc-to-120vac-arduino-relay-board

Do you confirm you hear a click? If so, please detach the wiresfrom the 3-screws-connector and check continuity with and without the relay engaged, in order to understand which is the common. Then put the voltmeter at the fan terminals, and check the voltage. Check also the 12V voltage (it may drop when you try to engage the relay)

And sorry for the necroposting, did not realize it was a 2-years-old post ;)

Lets troubleshoot this circuit:

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.
The picture on the website shows a jumper link between VCC and JD-VCC. Make sure this is removed.
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.
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.
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.
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.
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.

Add a comment if there is something I have forgotten...

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.

First of all the schematic is the one of the board, not one of his circuit, so it is just an error in the drawing, not on the circuit. Then if he did really short it the effect would be to blow (maybe) the transistor, not the optocoupler..

Looking at what I assume is the same module on the Sainsmart website it looks like the relays are 5V. That means the 12V you have pumped into them has made the Magic Smoke™ escape.
Throw them away, buy some new ones, and next time don't put in more than twice the voltage it needs.

I tried 5V using JD-VCC jumper, but did not work. Not sure whether I did hear clicks when releasing relay. Then I read somewhere that JD-VCC can be used to provide supply to relay and completely isolate coil form GPIO (maybe even here but in Raspy thread).   Which is exactly why I bought them, optocoupler. I checked relay module and it is OMRON G5LA-14 12 V. So, I connected it. I do not know how they can make 12V for coil from 5V i send from Arduino.   There is no credible user guide, so in a mean time I burned out brand new Mega 2560 for this. Such a pity.

Still, I am happy. I tried 12V, but I planned to manage 220V devices using these relays. When I saw that there is no plenty documentation I decided not to risk.

Ok, so if that module has 12V relays on it then it's not the same one I am looking at.  Is this the actual module? http://www.sainsmart.com/arduino/arduino-components/relays/omron-12v-2-channel-relay-opto-couple-for-arduino-uno-r3-raspberry-pi-arm.html If so then you have called it the wrong thing which caused confusion.

It is actualy this one.
http://www.sainsmart.com/arduino/arduino-components/omron-12v-2-channel-relay-opto-couple-for-arduino-uno-r3-raspberry-pi-arm.html

@politkom Ok, so I have helped you out and edited your question for you so it has the proper information in it.  You might want to look at the schematic - it is meaningless with that module since it doesn't tell us what the jumpers on that board are supposed to do. If you can't find the real schematic then I suggest you grab your digital multimeter and trace it through and draw the schematic yourself.

This is real schema downloaded from Sainsmart site. I just added external connections.

That schematic is the same one as used on the 5V modules, not the 12V modules. It is not correct for the 12V ones since it doesn't show the full circuit.


text:
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

You want a database but to avoid using a computer? I sense you will have problems with that.

Yes, for example can be used raspberry. And for Ardingly I know that can be done a HTML page host using ethernet shield, but I'm not sure if can be done a proper server.

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

Phant is No Longer in Operation
Unfortunately Phant, our data-streaming service, is no longer in service and has been discontinued. The system has reached capacity and, like a less-adventurous Cassini, has plunged conclusively into a fiery and permanent retirement. There are several other maker-friendly, data-streaming services and/or IoT platforms available as alternatives. The three we recommend are Blynk, ThingSpeak, and Cayenne. You can read our blog post on the topic for an overview and helpful links for each platform.

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.


text:
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;
}

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.

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.

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.

Here's an example of using the CD4511 driver method: https://123d.circuits.io/circuits/912097
Here's an example of the serial-in to parallel-out (74HC595) method: https://123d.circuits.io/circuits/583641

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

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.

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

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.

You can easily test this in 123D Circuits, check this out:
https://123d.circuits.io/circuits/1019227-7-segment-circuit
Click start simulation and then click on the buttons to light up the corresponding segment.

I'm not convinced this addresses the question at all.

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


text:
Ping sensor with three or four pins?
I bought a Ping Ultrasonic Range Finder. 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.

The sticks (they are really called pins) have these little white marks next to them. They're called letters. You read them and they tell you what the pins do.

@Majenko It's so thin I don't think I will read something there.

I said next to not on.

@Majenko Right, you're right. What does it mean "echo", "vcc" and "Trig"?

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/

In what do I use the trigger pin?

@PichiWuana That link tells you.


text:
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.

There's a device you can buy off the shelf that can do all this already: it's called a mobile phone.  The kids most probably already have one.

An arduino is a bad choice for this project, as it will lock you into using a larger, more expensive "hacker friendly" form of the GPS and data uplink (GSM or whatever) functions than would be used by an existing all-in-one solution.

It sounds like he is supposed to make the project, not buy a phone off the shelf.

Apparently OP want the device to be small & mobile phone nowdays is 5/6 inch

Guys as Nick said I need to make the project for learning not buy a complete solution, I don't need to track my kids I just gave you an example

you just need this https://ru.aliexpress.com/item/33045644281.html this module has ESP32 Wireless Module GPRS Antenna SIM Card SIM800L GPS apart from this you need a sim card/wifi internet , some wires, and power source i guesss 3.3v then you are ready to go

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

GPS takes a potentially significant time to regain satellits depending on how long it is off and where satelllites are. Maintaining an emphemeris or even producing an active one would help minimise acquistion time.

Generally, GPS' store their ephemerides, and/or they can be downloaded from the GPS. You may wish to test this - get a lock, power everything down, then power everything up, and time how long it takes to get a positive location. Ephemerides are valid for an hour, and GPS' come in and go out of view. Nevertheless, you will still use less power waiting for the download than you would leaving it on. If you are only polling once an hour, it may be worth polling every 55 minutes instead.

Ephemerides don't take longer to expire if you keep using them, you just get a new download before the old one has gone - this takes the same time as it would to get one after it has expired.

Further research shows ephemerides are valid for 4-6 hours, and are updated every 2 hours. Same applies - If you get a lock every hour-and-one-second, and shut down in between, you should need to download ephemerides at the 6 hour 6 second mark; if you get a lock every 59:59 minutes, you will need to download new ephemerides at 6:59:53. This may vary due to different satelites being visible, and from receiver to receiver.

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.

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.


text:
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.

You need to send two bytes - a high byte and a low byte.
There are two things you need to know with SPI:

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

So you have:

Chip Select idles HIGH
You lower Chip Select
You send one byte
You send the other byte
You raise chip select

At the receiver you:

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

Can i use the arduino's functions  lowByte() highByte()?

You can, yes.  Or just do it manually with >> 8 and & 0xFF

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() {}


text:
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

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


text:
Help with button library, hold>2s doA else doB
I'm using JChristensen's Button Library 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 variable1 always gets set to 0.

No it was an example of what my code was.  I was hoping for someone to write something generic and I'd learn and adapt from it.  In any event, I have included the full code now.

user1229925, I edited the question (selected code and pressed ctrl-k to code-format it; changed word 'Entering' to 'Setting' after the code; crossed out variable1, not knowing what it should be.  Does the "Clearing Scores" msg ever appear?

So it's supposed to work like this:  1) hold button down for 2 seconds to enter settings menu.  While in settings menu ill 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.  Does that help @jwpat7 ?

My earlier comment about the action of the code had numerous incorrect parts, so I deleted it.  See my answer below.

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.

I think 2 seconds is way too long; half a second might be a more reasonable transition from ordinary press to long press.

Wow.  This works great!  Thank you for the thoughtful explanation next to everything.  It unfortunately resets the score every time you exit settings, but other than that I'm much closer then before.  How do I ever repay you.

See edit about avoiding that  reset.  Feel free to accept answer (click some green button) and upvote.

That edit at the end didn't end up working.  Can I paypal you to help finish?

I'm too busy to accept more work at the moment.  I imagine the problem at the end was the two lines being before } } instead of after; see re-edit.

moving that made no change as did removing them completely.  I'll keep trying to figure something out.It's almost as if the return; isn't working.


text:
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.

And you're sure you've copied ALL the git files into your sketch folder?

Yes sir, I have.

In BikeTracker.ino, change the reference to PubNub.h to an absolute path.

@CharlieHanson I know you're right. I'm just overlooking something stupid I can't figure it out! lol. This morning tried out to #include <PubNub.h> instead of predefined set up #include "PubNub.h" (as the github repo says). I did also try running this PubNubJsonWiFi PubNub.h already included system directive. When I fixed the #include <../aJson/aJSON.h> library the main issue reappeared (error: 'PubNub' was not declared ...). I'll keep looking at this and post feedback when I have any information. Ty!

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


text:
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.

This is my code.
#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.

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.

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.

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....

Relay connection is correct. V+ of relay to 9v, GND of relay to GND and INP of relay to D8. As I mentioned in the question, it is working perfectly fine when the AC load is not connected.

I suppose it has something to do with the relay. I'm going to try with Solid state relay.

Noise more likely. Try optoisolating or decoupling (attach >100uF electrolytic capacitor to the power pins) the supply to the ESP.

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.

"I think you can get Relays with AC output and a DC Switching signal" - This is what I'm doing. By the way I got it working with using only ESP8266. I'm not sure whether I can post that answer here as I don't use adruino.

@SherinMathew, sorry mate I had to check. :)

If you can get the circuit working without the relay, and you can get it working without the Arduino can you get the Arduino driving the relay (no esp) ?

Yes, I was able to drive the relay using Arduino. I was using a PIR sensor to switch on the same tubelight using Arduino and relay. That was my first experiment. Then I decided to control the same using my phone. That is when ESP8266 came into picture.

I think you might be drawing too much current because the parts work but not the whole.  When you ran the esp8266 test were you powering the 3v from the Arduino? Could you power the relay from a separate psu and use a transistor to let the Arduino switch it?

Thanks for the suggestions @Matt. I tried all those options. Finally used ESP8266 alone as I only wanted to prove that I can control AC using my phone. I didn't bother too much to make it work with Arduino and ESP8266.


text:
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:
#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: How can program/arduino restarted by IDE?

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:

Insert a sleep(3); immediately after opening the port to give the bootloader a chance to time out and start running your sketch, or
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.

I understand that I am not waiting for send, but I am waiting for receive. Why port >> answer not waiting if bootloader sends nothing? Shouldn't port >> answer wait for space or newline?

It can only wait for something if you are sending something. You aren't sending anything because you aren't receiving anything, because what you send isn't getting through to your sketch.

How this is implemented? How >> can know that I didn't send anything? How it can distinguish silence from delay between request and response and initial silence? Suppose I implement your suggestion on "I Am Ready" how can I wait for "I Am Ready" if >> will just drop waiting when it wants?

P.S. Note that my questions are for understand what is happening

If the port is opened in non-blocking mode then it will never wait for anything, ever.  I don't use fstream so don't know how it opens the port - if it's non blocking then you cannot use >> to read from it.  You should be using low level IO for talking to a serial port, not file IO.  Use open(), read() and write(), with a good smattering of select() to see if there is actually anything to read from the port.


text:
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?

Why do you feel the need to modify it?

I bought a regular PIR (with 220V relay) and as I remember well motion detection board needs higher voltage than what ardruino can supply 3.3V and 5V.

So supply it with that higher voltage then.

I would rather avoid it but it looks like there is no other way.

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 to print it for you, and you might not even have to design the case because thingiverse has a few already...

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


text:
Sending AT commands to a gprs shield using serial port
I have a GPRS shield connected to an arduino uno board, i want to use the shield to send sms and do phone calls, from a C# Wpf application, the arduino is connected to the application using the serial port,
In order to do that I've upload the following sketch to the arduino board:
#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);
unsigned char buffer[64]; // buffer array for data recieve over serial port
int count=0;     // counter for buffer array
void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);             // the Serial port of Arduino baud rate.
}

void loop()
{
  if (GPRS.available())              // if date is comming from softwareserial port ==> data is comming from gprs shield
  {
    while(GPRS.available())          // reading data into char array
    {
      buffer[count++]=GPRS.read();
      if(count == 64)break;
    }
    Serial.write(buffer,count);            // if no data transmission ends, write buffer to hardware serial port
    clearBufferArray();              // call clearBufferArray function to clear the storaged data from the array
    count = 0;                       // set counter of while loop to zero
  }
  if (Serial.available())            // if data is available on hardwareserial port ==> data is comming from PC or notebook
    GPRS.write(Serial.read());       // write it to the GPRS shield
}
void clearBufferArray()              // function to clear buffer array
{
  for (int i=0; i<count;i++)
    { buffer[i]=NULL;}
}

every thing works perfectly when sending AT commands to the shield using the Serial Monitor, for example to dial a call this is all what i need to do

this works perfectly, but when trying to do the same thing from c# application, nothing happened !
here how i send the AT command from the code :
private readonly SerialPort _serialPort;
public void Callphone(string number)
{
    _serialPort.Open();
    _serialPort.Write("ATD + +" + number +";");
    Thread.Sleep(100);
    _serialPort.Close();
}

PS: sending sms works fine from the serial port, using the same way :
 public void SendSms(string number, string message)
    {
        _serialPort.Open();
        _serialPort.Write("AT+CMGF=1\r");
        Thread.Sleep(SleepTimeStamp);
        _serialPort.Write("AT+CSCA=\"" + MessageCenterNumber + "\"\r");
        Thread.Sleep(SleepTimeStamp);
        _serialPort.Write("AT+CMGS=\"" + number + "\"\r");
        Thread.Sleep(SleepTimeStamp);
        _serialPort.Write(message + "\x1A");

        Thread.Sleep(SleepTimeStamp);
        _serialPort.Close();
    }

Am i missing something ?

I dont't know much about C# but I have some ideas. And as noone answered. Let's try! ;-) 1st) I saw that you append \r in the working example. But you did not in Callphone.  2nd) what is the content of your number string? Is is prepended with a +? Then you write ATD + ++<number> to the shield. 3rd) In the working example you send a lot of text compared to the Callphone. Perhaps you have to flush the buffer.

Let the arduino send your string to your terminal and verify that it's 100% right. Much like a loopback.
(Also, you don't really need an arduino inbetween?)

Thank you guys for your time, @Peter Paul Kiefer I've tried all you suggestions 1) adding the \r didn't solve the problem, 2)I've verified on debug mode no extra '+' is sent, I've even tried sending "ATD + +213698629552" directly without using  a param, 3) each time the buffer is flushed, and i am also triggering the call only (no sms send code is executed first ), Thanks again and do you have anything else i can try ?

@FuaZe He uses an arduino shield, so I think the arduino is nessecary ;-)! It's a good Idea to echo the sended command, to see if a part of the command would be removed. @SamTheDev When you send the ATD command directly without a parameter, did you forget the ; at the end in your code too or is it just a typo in you comment? Another idea: When you communicated with the shield using the arduino terminal,  you send a single AT command at first. Did you do that in your C# program too? I don't know If it is nessecary but it's the only difference I see.

Using an UART-USB cable/chip you can send commands directly to and from the GSM module. Though you will have to power it with an external supply (which you always should). Doing so will enable you to play around with the different AT commands and responses before you're programming it out (so that the arduino will send those).


text:
How can I send a number from a master and make the slave read it?
I am building a fan controller using an Arduino and a Raspberry Pi (the Pi is the master and the Arduino is the slave). The Raspberry Pi generates random numbers and I want the slave (Arduino) to be able to read the string of numbers and increase the current speed of a pwm fan by the amount read.
How I can read the bits sent over I2c as numbers to allow me to do what I want to do?

See I2C Anything.

If you are only going to send "random number" why not let the Arduino generate them instead and remove the Pi all together. https://www.arduino.cc/reference/en/language/functions/random-numbers/random/

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


text:
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?

//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();