text:
How would i capture and split serial data?
How would i capture the following serial data, and split it into parts?
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>
the parts i need from this is
Alarm - This is a state. i.e Alarm, Idle, Paused, Working
MPos: - This is a series of positions X,Y,Z
WPos: - This is a series of positions X,Y,Z
What i want to do is capture the string from serial (See above for formatting)
Then display the information on the LCD.
i.e.
X: 0.000  Y:0.000
Z: 0.000  Idle
I've managed to figure out how to do all the LCD display stuff, and send commands to the serial, but it appears there are so many variations on how to split the data up, that i't really confusing to me, as well, almost all of the examples i find use loop to do this, but i would like to have this done in a function, that way i can display this info only when needed, not constantly, as i'll be useing the LCD for a menu system.

An actual example of what the string looks like would help - your description is very very vague and of no use to us whatsoever.

Wierd.. i did include an example.. not sure where it went.
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>
That is the string i need to capture and split up

Ah, it probably thought it was HTML and pruned it out.

Are all the parts always there and always in the same order?

Yes, all parts are always there, and always in the same order, however, they are not always the same.
I.e.
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>
<[1],MPos:[2],[3],[4],WPos:[5],[6],[7]>

This could be any of the following: Idle, Run, Hold, Door, Home, Alarm, Check
This is Machine Position X
This is Machine Position Y
This is Machine Position Z
This is Work Position X
This is Work Position Y
This is Work Position Z

This string is actually fairly easy to split up, because everything is separated by commas nice and regularly.
Assuming you have the string in a char array (aka a C string) and not a String object (I and most other programmers abhor the String class) you can use the function strtok() to split the string up into parts.
So you have the string:
char string[] = "<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>";

The function strtok() takes, on its first call, the string you want to split and the delimiter that you want to split on.  It returns a pointer to the chunk:
char *alarm = strtok(string, ",");

alarm now contains <Alarm and strtok() moves its internal pointer to point at the next character, so it sees the string as MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>
With the next and subsequent calls to strtok() you don't give it the string, or it will reset its internal pointer.  You just pass it NULL and it gives you the next block:
char *mposX = strtok(NULL, ",");
char *mposY = strtok(NULL, ",");
char *mposZ = strtok(NULL, ",");
char *wposX = strtok(NULL, ",");
char *wposY = strtok(NULL, ",");
char *wposZ = strtok(NULL, ">");

Note that I changed the delimiter on the last one to > so it chops off that extra character that we don't want (and there is no , after the last part).
So now you have 7 variables that point to chunks of the string, which has internally been chopped up and modified into individual substrings:
*alarm = "<Alarm";
*mposX = "MPos:0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "WPos:0.000";
*wposY = "0.000";
*wposZ = "0.000";

So now we can clean up the three entries that have extra stuff in them, and that is a simple as adding an offset value to the pointers we have:
alarm += 1;
mposX += 5;
wposX += 5;

Our list of pointers now looks like this:
*alarm = "Alarm";
*mposX = "0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "0.000";
*wposY = "0.000";
*wposZ = "0.000";

The position variables can now be passed through strtod() to convert them to float values:
float mx = strtod(mposX, NULL);
float my = strtod(mposY, NULL);
float mz = strtod(mposZ, NULL);
float wx = strtod(wposX, NULL);
float wy = strtod(wposY, NULL);
float wz = strtod(wposZ, NULL);

You can do different things depending on the content of the *alarm string by using strcmp():
if (strcmp(alarm, "Busy") == 0) {
    // Something to do when Busy
}

etc.
Or you can just use it to print the content to the LCD.


text:
Remote Wireless Tripwire
I've had an idea for an Arduino project, but I'm not sure where to start. My idea is this: have an Arduino Nano connected to an HC-SR04 ultrasonic sensor, as well as an nRF24L01+ radio. This will be the tripwire module, which will send an alert to a second Arduino (connected to another nRF24L01+ of course) whenever something passes by.
This wouldn't be a stationary unit, it would need to be able to be placed and sense in a variety of locations so the distance would need to be set on power up.
Another issue I'm running into is getting the nRF24L01+ units to work for this purpose. I want to know that the units are wirelessly connected, so having a packet sent every second or so lets the receiving unit know that they're connected, and an additional packet for the tripwire trigger sets off an indicator led.
Is this even possible?

You might find a pir sensor cheaper on $$ and power consumption if battery powered.

Welcome to Arduino StackExchange! This sounds like multiple questions to me. The only real question there: "Is this even possible?" would have the answer: Yes. If possible, reword it to fit more into the question-and-answer format that StackExchange uses.

This sounds very doable. The first point, tuning the distance threshold at startup, could be done with a bank of DIP switches or a potentiometer on an analog pin to set the value. You might include some startup code continuously pings the transducer and displays the result on an LED, until you press a button to tell it "use this".
The second, is a very typical communication technique - sending "hello" packets periodically to confirm that communication is up. In your case, the same packet could carry a hit/no-hit bit within it.

It would be easier and faster just to send triggered/not triggered status every second.

Just have it trigger, whenever the distance changes by more than x amount. That way there is no need to initialize, and it would also update if the surroundings change (e.g. someone places a trashcan in the path of the sensor) and doesn't just dumbly report a trigger all the time (instead of only when someone passes in front of the trashcan in the example).

source: Stack Exchange

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

sort: votes


text:
Cannot upload sketch to Atmega328p TQFP soldered on PCB
After creating a working prototype with DIP ATMega328 chip/ Arduino UNO I recently got PCBs assembled with SMD components and ATMega328P TQFP soldered onto them, but now I'm having a hard time trying to upload the Arduino program.
This is the schematic of the PCB with ATMega328P TQFP with ISP headers for programming:

I'm using USBasp programmer with upgraded firmware to upload the code. The chip gets detected and also I can upload sketches to it but the problem is the code runs slow, which I found out is due to the default 8MHz internal clock.(the blink program makes LED blink every 16 seconds instead of 1 second,i.e. with delay(1000))
Now to switch to the external 16MHz clock which I want to use I found out here that I have to change the fuse values from the default

lfuse: 0x62   hfuse: 0xD9   efuse: 0x3F

to

lfuse: 0xFF   hfuse: 0xDE   efuse: 0x05

I tried it two times and both the times it screwed up the ATMega328P chip
C:\Users\p>avrdude -p m328p -c usbasp -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efu
se:w:0x05:m

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified
avrdude: reading input file "0xDE"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.03s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xDE:
avrdude: load data hfuse data from input file 0xDE:
avrdude: input file 0xDE contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0x05"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.03s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: input file 0x05 contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified

avrdude: safemode: Fuses OK

avrdude done.  Thank you.

C:\Users\p>avrdude -p m328p -c usbasp

avrdude: error: programm enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Both of the PCBs are not responding to the USBasp programmer and now I have only got one PCB left. I desperately want to get the final one working.
This is my first time using the SMD ATMega328P chips and any help would be appreciated.

You should connect AVcc to a supply voltage. According to the datasheet AVcc has a minimum requirement of Vcc - 0.5 V. Also put a 0.1 µF decoupling capacitor between AVcc and Gnd.

It looks like the capacitors on your crystal are considerably bigger than they should be.
You are switching the clock to the external crystal, and because you have such massive capacitors on it it's failing to oscillate.  Without that oscillation the chip can't run, and so it can't respond to the programming.
The crystal capacitors should be roughly 2x the "load capacitance" of the crystal you are using.

CX1 = CX2 = 2(CL - CSTRAY)

Is there a value for capacitance you can suggest?

Use the formula I stated and insert the load capacitance of your crystal.  You can most likely ignore the stray capacitance as it should be tiny. Without knowing what crystal you have I can't suggest a value.  It will be in the low 10s of picofarads though.

Got it, thanks,will let you know if it works

The arduino board uses 22pF.

@Gerben Which one? Most I have seen use ceramic oscillators.  Or are you on about the USB interface chip (32U4 or whatever it is on your version)?

I just looked at the schematic of the UNO SMD. They used 22pF on the ATMega8u2's crystal. But I don't know anything about crystals.

22pF is quite common since 11pF crystals are quite common.

Majenko is quite right, the value of 0.1 µF is far too high. I assume you have spare Arduinos lying around. You can force a clock signal onto XTAL1 by using a signal from my Bootloader Programmer. That would at least let you change the fuses. However your longer term solution is to replace the capacitors. 18 pF to 22 pF would be reasonable values to try.

Thanks everyone for the tips, I will change the caps and let you know the result!

As expected it worked with 22pF caps! Thank you every one

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


text:
Handling serial streams biggers than the available ram
I need to parse text coming into my MC (Leonardo) over the hardware serial port. The data comes in burst, and the parsing routine manage the data flow with easy when it is less than the serial buffer.
I will like to be able to receive around 512Kb of serial data, save it somewhere (not in the arduino memory of course) and the execute the parsing routine on it. I think saving the stream to an external EEPROM and then retrieving it slowly so my parsing code can actually fallows will do the trick. I can control the speed of the serial stream from 300 bauds (not optimal) up to 112000 bauds.
Is the approach correct? Can I write to the EEPROM faster than a 9600 bauds serial stream without collapsing the arduino?

SD card would probably be a more sensible alternative.

Do you really need the all the data before you can parse it? Can't you parse it on-the-fly? Could you change the sender code so that it wait when the arduino is busy (send-ack pattern). EEPROM has a limited amount of write cycles, so it's not ideal. Serial RAM, like e.g. 23K256, would be more appropriate. (though I can't tell if the arduino can write fast enough, as you asked)

You can parse indefinitely large amounts of data with a state machine parser.
General description: State machines
As an example, I wrote recently an HTTP server which parses incoming HTTP data (eg. cookies, parameters, POST data, GET data) on-the-fly.
You need enough RAM for one item of data, naturally. But then you act upon it, and then discard it. In the case of the web server, you could conceivably process a complex form with thousands of actions on it (eg. turn on switch 5, pump 3, heater 22). It parses each action, and then you act on it, then you parse another action.

You can even consider the Arduino bootloader as an example of this. The Optiboot bootloader is 512 bytes on a Uno, but it can re-flash 32 KB of program memory. How? The programming data comes down in bursts (packets, if you like) and it processes each packet at a time, then discards it and reads the next one.

Hello @Nick! I keep seeing your name popping out in the Arduino forums and here in stackexhange always helping the comunity. Thank you!!!

@DomingoSL Nick's website is an excellent Arduino reference http://www.gammon.com.au/forum/index.php?bbtopic_id=123


text:
Including libraries from header files sometimes doesn't work
I, once again have difficulties including libraries from code files other than my .ino file.
I have several .cpp and .h files in my project to keep it sorted and clean.
However one of my header files starting like this:
#ifndef DPLANDEF
#define DPLANDEF
#include <Arduino.h>
#include <EEPROM.h>
#include "syssettings.h"

yields the following errors:

In file included from
  /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.cpp:2:0:
  /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.h:5:20:
  fatal error: EEPROM.h: No such file or directory  #include
                      ^ compilation terminated. Fehler beim Kompilieren.

EEPROM.h should be known to the IDE, because I can find it in the libraries menu, too. If it was a custom library, I might have botched something during installation, but this is a standard library. It should work out of the box. What's the problem here?

See Classes and objects: how many and which file types I actually need to use them? - that mentions the issue of putting your includes in the main .ino file.

@NickGammon Interesting roundup of the whole thing. bookmarked now.

The problem here is that it's a header file.  The IDE doesn't treat header files like it does INO files - it doesn't parse them for included libraries, etc.
In order for it to work you must also include EEPROM.h in your main INO file so that the IDE knows that you want to include it in the rest of your files.

Thanks a lot. In the past I fiddled cluelessly around until it finally somehow worked out. After adding all libs to my INO header file, all libraries are detected, but I have a new problem. The IDE somehow managed to circumvent the include guard definition of PinChangeInt.h (custom library, which I tested already successfully). Linker is now complaining about lots of double definitions. Sigh. I guess time to move to a "real" IDE!?

@Ariser Include guards only work within the same compilation unit.  If you include the file in separate cpp or ino files it will exist multiple times, and any variables or functions defined in there will be conflicting.  You should never have functions or variables in headers - put them (once) in cpp or ino files and put extern references to them in the header files.  The header files then act like a "sharing" point for the variables and functions in the other cpp and ino files.

Sigh. I guess time to move to a "real" IDE!? - you would have that problem anywhere. As Majenko said, .h files are for declarations. To define something it should be done once, in a .c or .cpp file. You won't get double definitions on the class declaration. Your PinChangeInt library should also have a PinChangeInt.cpp file which is compiled once.

@Majenko I'm familiar with separation of declaration and definition. But I didn't suspect that this library was broken. I should have been alerted by the fact, that it was i linker and not a compiler error. Looking closely, this library lacks a source file completely. What a mess, I'm going to rewrite it...

@NickGammon: More like passing to a real build process.
The Arduino builds stuff in a way that is meant to help newbies, but it's disconcerting, to say the least, to those who are used to more traditional Unix ways of building code. Make, to mention one.

@Ariser: you could have a look at this: http://www.instructables.com/id/How-to-get-started-with-Eclipse-and-AVR/?ALLSTEPS
I'm not too fond of Eclipse, but it beats to a pulp the Arduino IDE hands down any day. And if you have an AVR Dragon, you can also ditch the serial prints and debug like it's supposed to be done on embedded devices: http://www.larsen-b.com/Article/315.html

@IgorStoppa - yes it is intended for newbies, and you must surely admit that Make is not for the faint-hearted. The process is described in a reply I made. I note that Ariser now says that the library is a mess, which presumably lets the build process of the hook a bit. The IDE can't help it if people put all their functions into .h files.

@NickGammon: the build process is still a mess as it does (black) magic with headers and I consider it as an encouragement to people doing even more evil things with headers.


text:
run two motors in turns without using delay()

I googled solutions and tried, but I still cannot get it working.
I've tried BlinkwithoutDelay.
I feel it is very confusing to track timing of two motors (i.e., step, direction, speed) for the following routine loop:

step 1: run motorA_forward() for 10 seconds;
step 2: run motorAB_stop() for 1 seconds;
step 3: run motorB_backward() for 3 seconds
step 4: run motorAB_stop() for 1 seconds
step 5: run motorA_backward() for 10 seconds
step 6: run motorAB_stop() for 1 seconds

Please help me on this!! I really appreciate your time and comments.
Thank you.
The following is my working code.
// ----------LIBRARIES--------------

#include <Wire.h>
#include <LIDARLite.h>
LIDARLite myLidarLite;

// ----------CONSTANTS--------------

const int motorA_pin_1 = 8;           // the pin numbers for the motors
const int motorA_pin_2 = 11;
const int motorA_pin_speed = 9;
const int motorB_pin_1 = 12;
const int motorB_pin_2 = 13;
const int motorB_pin_speed = 10;

//------------VARIABLES--------------

byte motorA_state_1 = LOW;             // used to record whether the motots are on or off
byte motorA_state_2 = LOW;             // LOW = off
byte motorB_state_1 = LOW;
byte motorB_state_2 = LOW;

int currentMillis               = 0;     // stores the value of millis() in each iteration of loop()
int motorA_Forward_Interval     = 5000;  // will store last time the motor was moved
int motorA_Backward_Interval    = 5000; // will store last time the motor was moved
int motorA_Stop_Interval        = 2000;  // will store last time the motor was moved
int motorB_Stop_Interval        = 2000;  // will store last time the motor was moved
int motorAB_BreakTime_Interval  = 2000;

unsigned long motorA_Forward_Timer      = 0;     // will store last time motorA start was updated
unsigned long motorA_Backward_Timer     = 0;     // will store last time motorA start was updated
unsigned long motorB_Forward_Timer      = 0;     // will store last time motorA start was updated
unsigned long motorB_Backward_Timer     = 0;     // will store last time motorA start was updated
unsigned long BreakTime_timer   = 0;     // will store last time motorA/B break time was updated

//------------INITIALIZATION--------------

void setup()
{
  Serial.begin(115200);
  myLidarLite.begin();

  pinMode(motorA_pin_1,OUTPUT);         // set the motor pins as output:
  pinMode(motorA_pin_2,OUTPUT);
  pinMode(motorA_pin_speed,OUTPUT);
  pinMode(motorB_pin_1,OUTPUT);
  pinMode(motorB_pin_2,OUTPUT);
  pinMode(motorB_pin_speed,OUTPUT);

}

//------------LOOPING----------------------
// Notice that none of the action happens in loop() apart from reading millis()
// It just calls the functions that have the action code

void loop()
{
    Serial.println(myLidarLite.distance());

    unsigned long currentMillis = millis();

    motorA_forward();  // for 10 seconds
    motorAB_stop();    // for 1 seconds
    motorB_backward(); // for 3 seconds
    motorAB_stop();    // for 1 seconds
    motorA_backward(); // for 10 seconds
    motorAB_stop();    // for 1 seconds

}

//------------SUBROUTINE----------------------

void motorA_forward()
{
  if(currentMillis - motorA_Forward_Timer <= motorA_Forward_Interval)
  {
    motorA_state_1 = HIGH;   // Turn motor A on - backward
    motorA_state_2 = LOW;  //
    motorB_state_1 = LOW;   // Turn motor B off
    motorB_state_2 = LOW;   //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorA_Forward_Timer = currentMillis;
  }
}

void motorA_backward()
{
    if(currentMillis - motorA_Backward_Timer <= motorA_Backward_Interval)
  {
    motorA_state_1 = LOW;   // Turn motor A on - backward
    motorA_state_2 = HIGH;  //
    motorB_state_1 = LOW;   // Turn motor B off
    motorB_state_2 = LOW;   //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorA_Backward_Timer += currentMillis;
  }
}

void motorB_forward()
{
    motorA_state_1 = LOW;   // Turn motor A off
    motorA_state_2 = LOW;   //
    motorB_state_1 = HIGH;  // Turn motor B on - forward
    motorB_state_2 = LOW;   //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorB_Forward_Timer = currentMillis;
}

void motorB_backward()
{
    motorA_state_1 = LOW;   // Turn motor A off
    motorA_state_2 = LOW;   //
    motorB_state_1 = LOW;   // Turn motor B on - backward
    motorB_state_2 = HIGH;  //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorB_Backward_Timer = currentMillis;
}

void motorAB_stop()
{
    motorA_state_1 = LOW;   // Turn motor A off
    motorA_state_2 = LOW;   //
    motorB_state_1 = LOW;   // Turn motor B off
    motorB_state_2 = LOW;  //

    analogWrite(motorA_pin_speed,0);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,0);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    BreakTime_timer = currentMillis;
}

int currentMillis               = 0;     // stores the value of millis() in each iteration of loop()
...

void loop()
{
    Serial.println(myLidarLite.distance());
    unsigned long currentMillis = millis();

You have two currentMillis variables. The global one never changes. You change a different one inside loop.

Remove the data definition. eg.
void loop()
{
    Serial.println(myLidarLite.distance());
    currentMillis = millis();  // change the global variable

Also make the global one unsigned long:
unsigned long currentMillis               = 0;     // stores the value of millis() in each iteration of loop()

This is a classic example where Object Oriented Programming (OOP) can make your life so much easier.
The principle behind OOP is to define a Class which contains all the actions you want to perform on something - in this case a motor.  The Class contains all the instructions on how to do things like set the motor speed, the direction, start it, stop it, etc.
From that Class you then create Objects.  The beauty is there is only one Class which has the abstract concept of "Motor Control", but that Class is used to create one Object for each motor you want to control.
A Class, and hence the Objects derived from it, are all completely self contained, which makes it so much easier to manage.  All the variables associated with a single motor are wrapped up inside the Class and you don't need to worry about unique names for them all on a per-motor basis.
For example, you might define a class like this:
class Motor {
    private:
        int _speedPin;
        int _directionPin1;
        int _directionPin2;

    public:
        Motor(int sp, int dp1, int dp2) {
            _speedPin = sp;
            _directionPin1 = dp1;
            _directionPin2 = dp2;
        }
        void begin() {
            analogWrite(_speedPin, 0);
            pinMode(_directionPin1, OUTPUT);
            pinMode(_directionPin2, OUTPUT);
            digitalWrite(_directionPin1, LOW);
            digitalWrite(_directionPin2, LOW);
        }
        void forward() {
            digitalWrite(_directionPin1, HIGH);
            digitalWrite(_directionPin2, LOW);
        }
        void reverse() {
            digitalWrite(_directionPin1, LOW);
            digitalWrite(_directionPin2, HIGH);
        }
        void speed(int speed) {
            analogWrite(_speedPin, speed);
        }
        void stop() {
            analogWrite(_speedPin, 0);
            digitalWrite(_directionPin1, LOW);
            digitalWrite(_directionPin2, LOW);
        }
};

Everything you need to control a motor is in there.  Then you could use that to create two motor objects:
Motor leftMotor(3, 4, 5);
Motor rightMotor(6, 7, 8);

You provide the pins that control the motor to the constructor of the object - that is pin 3 is the speed pin of the first motor, and pins 4 and 5 are the direction control pins, etc.
You can now control the motors very simply.  Configure the pins by calling the begin function defined in the class above:
void setup() {
    leftMotor.begin();
    rightMotor.begin();
}

And now you can use similar decision making as normal to decide when to do what.  The main difference is that your motor control code now looks as simple as:
leftMotor.forward();
rightMotor.reverse();

or
leftMotor.stop();
rightMotor.forward();
rightMotor.speed(30);

You then end up with a program that is much cleaner and easier to follow.  And adding a third or forth motor is as simple as defining more Motor objects with their pins.
This video is a good introduction to what OOP is and how it differs from the "traditional" approach:

https://www.youtube.com/watch?v=MTfWr7o7Q4U


text:
How do I use 3 Hc-sr04 ultrasonic sensors to control 3 vibration dc motor?
This code we are using only one motor and one hc-sr04 ultrasonic sensor, the code is shown below:
#define trigPin 7
#define echoPin 6
#define motorPin 5

void setup()
{
  Serial.begin(9600);// to use the serial monitor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motorPin, OUTPUT);
}

void loop()
{
  int duration,distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2)/29.1;
  Serial.print(distance);//to print the distance on the serial monitor
  Serial.println("cm");

  // to make the motor vibrate depending on the distance
  // if the ultrasonic sensor is too far from the obstacle it will vibrate slowly
  // if the ultrasonic sensor is very close to the obstacle it will vibrate very fast

    if(distance <= 60 && distance >= 45)
    {
      // to make the motor vibrate
    digitalWrite(motorPin, HIGH); // making the motor on

    delay(200);
    digitalWrite(motorPin, LOW);// making the motor off
    delay(200);
    }

    else if(distance < 45 && distance >= 30)
    {
    digitalWrite(motorPin, HIGH);
    delay(100);
    digitalWrite(motorPin, LOW);
    delay(100);
   }
    else if(distance < 30){

    digitalWrite(motorPin, HIGH);
    delay(50);
    digitalWrite(motorPin, LOW);
    delay(50);
  }
  else
  {
    digitalWrite(motorPin, LOW);
  }
}

We want you to tell us your comment about the code.
And we want to add two more motors and two ultrasonic sensors, one of them in the left and the other in the right.
We want you to help us in the code, because we don't know how we can change it for two other motors.

Welcome to the Arduino StackExchange! We hope your stay will be fruitful. To help us view your code you should put it into "code blocks". I have edited your post and done it for you this time. Please read Editing Help to assist you in doing this. What is your question exactly? We want you to help us in the code isn't really a question.

do you have a sketch, maybe a Fritzing sketch, for your arduino setup?

There's a few things you need to consider when making multiple things happen at the same time.
Firstly is timing. You can't make two things happen concurrently with different timings if you have delay() in there, since nothing else can happen while delay() is executing.  So you have to get rid of all delay() calls and replace them with examining the difference between successive calls to millis().
For instance, imagine you're in the kitchen and you want to boil and egg and make a cup of tea at the same time.  You fill the kettle and turn it on.  You put a pan of water on the stove with an egg in it to boil.
Now you could sit and stare at the egg until it's boiled enough for you to eat, but what happens to the kettle while you're doing that?  It's boiled, turned itself off, and started to go cold.
So instead you put the egg in the pan and look at the clock.  Then you think "in 5 minutes I will take the egg out of the boiling water".  You might set an alarm for 5 minutes time if you have one, or you may keep glancing at the clock periodically to see if the 5 minutes have past yet.  Meanwhile the kettle has boiled and you've made your cup of tea.
Then the 5 minutes have passed.  You know that because you remembered what time you put the egg on to boil and you know what the time is now, so you can subtract one from the other to find that 5 minutes have passed.
Now let's make it a little more complex.  Imagine you want two eggs - one soft boiled and one hard boiled.  The hard boiled one may want 8 minutes, the soft boiled one 5 minutes.
So you put one egg on to boil and remember the time.  Roughly three minutes later you put the other egg in and also remember that time.
Once enough time has passed that the first egg has been in 8 minutes you take it out.
Once enough time has passed that the second egg has been in 5 minutes you take it out.
You have had to remember two start times which you then compare separately to decide what to do with each egg when.
To translate that to your program - you have to remember a start time for each action for your motors, along with the state of the motors - and when the right time has elapsed you change the state of the motor (motor on -> motor off - egg in pan -> egg on plate) and remember the time at which you changed the state so you can know when to change the state again.
That's exactly what the BlinkWithoutDelay example does to make an LED change state (on -> off -> on) at certain times by remembering when it last changed state so you know when to change the state next.

Thanks a lot for replying .. the idea of our project is making a hat for blind person, inside the hat we have 3 hc.sr04 ultrasonic sensor and 3 motor  located in : front  , right and left , the motor should vibrate slowly when the obstacle is far and vise versa ... can you help us in code itself ? even if we can communicate to you by your email..

I have rolled the two basic functions (ping and blink) into simple libraries that should get you going.  It should be a very simple matter to put them together. I haven't tested the Pinger library yet since I can't find my ultrasound board off hand, but it's very simple and should work. https://github.com/MajenkoLibraries/Blink https://github.com/MajenkoLibraries/Pinger

Thanks a lot .. plz give me ur email as soon as possible .. I want to ask u about the code :(

If you have a problem with one of the libraries please raise it as an issue on Github. If you have a problem with understanding certain aspects of Arduino programming please ask a fresh question on this site detailing what you have tried and what you are having problems with.  I don't hand my email address out willy-nilly.


text:
Varying motor speed with the L293D
Im using a potentiometer to control the speed of two generic 6-8V DC motors. The potentiometer input is scaled from 0-1023 to 0-255, I then use the analogWrite() function to write this value to the enable pins on my L293D motor controller.
Im sure this should control the speed but it doesn't, I have the code printing the value it sends to the enable pins and this is correct, but no speed increase, the motors either move at one speed or don't move at all. My enable pins are 12 and 13 on my Arduino Uno, previously 5 and 6 but I moved them to see if that was the problem.
Is there a problem with the PWM frequency maybe? I don't understand why it won't go faster and slower after days of troubleshooting.. The inputs are all set correctly, allowing both motors to move in the forward direction..
int Speed = analogRead(speedChange);
int SpeedMap = map(Speed,0,1023,0,255);
analogWrite(enable1, SpeedMap);
analogWrite(enable2, SpeedMap);

Its a long shot but does anyone know enough about PWM control on DC motors to think of any things I may be missing while trying to do this? Ill provide any info ASAP, thanks

Pins 12 and 13 on the Uno aren't PWM capable.

Thanks! You put me on the right track.. I plugged them back into 6 and 7 and I had a new set of problems.. Then I switched enable 2 into pin 5 instead of 7 and it works! Not sure why pin 7 is a bit dodgy unless that dose have pwm either

The pins that have PWM available are marked with a ~ symbol.  On the Uno that is pins 3, 5, 6, 9, 10 and 11.

@Majenko, you should put that as an answer

Although I am still figuring things out, but i hope the following things help:
http://www.solar4rschools.org/sites/default/files/robotic-sunflower-lesson4-handout4.pdf
The problem, as far as I think is that the enable pins are the ones which are supposed to help you control the speed. Please connect them to the PWM ports on your Arduino/any other device you may be using for your project.
Or, you can simply write a code which keeps on disabling and enabling the enable pins to get the desired speed (that's what PWM is supposed to do but you can try it this way, at least).

I guess you're not using the designated PWM pins provided on the Arduino Board, anyhow I suggest you read this instructible: http://www.instructables.com/id/Arduino-DC-motor-speed-and-direction-L293D/step2/L293D-Pin-Layout/ ,Perhaps this can help you in making proper connections and also help you with the code :)


text:
How can i read serial data into a string until a certain character is recieved?
This is not a duplicate of my other question. This question deals with reading specific data within a serial stream. The other question deals with reading and adding data into a manageable data string.
What I'm trying to do is send a command to serial, get the response, and put it into a string, and then break that string up into usable parts of data.
The problem I'm having, is there is a delay between the time the serial command is sent, and the response. meaning the serial data isn't being captured before the function moves onto the next line. Using delay() doesn't appear to work, as i believe it halts everything for that delay period.
What I'm hoping to do, is read the data from serial and if the character '<' is received, place it, and everything after it into the buffer until the character ">" is received.  After the last character is received, and placed into the buffer, continue on with the script.
Unless of coarse someone has a better idea on how to approach this.
i would also like to note that this is just a part of a larger project. If you need to see the entire project, please let me know and i will provide a link where you can download it.
The string i'm expecting as a response would be similar to this:
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>

Here is the code i have so far:
float mx;
float my;
float mz;
float wx;
float wy;
float wz;
String dAlarm;
char buffer;
void gPos() {
  Serial1.print("?\n");
  buffer = Serial1.read();
  char string[80];
  string[buffer];
  char *alarm = strtok(string, ",");
  char *mposX = strtok(NULL, ",");
  char *mposY = strtok(NULL, ",");
  char *mposZ = strtok(NULL, ",");
  char *wposX = strtok(NULL, ",");
  char *wposY = strtok(NULL, ",");
  char *wposZ = strtok(NULL, ">");
  alarm += 1;
  mposX += 5;
  wposX += 5;
  mx = strtod(mposX, NULL);
  my = strtod(mposY, NULL);
  mz = strtod(mposZ, NULL);
  wx = strtod(wposX, NULL);
  wy = strtod(wposY, NULL);
  wz = strtod(wposZ, NULL);

  if (strcmp(alarm, "Idle") == 0) {
    dAlarm = "Idle";
  } else if (strcmp(alarm, "Run") == 0) {
    // Something to do when Busy
    dAlarm = "Run";
  } else if (strcmp(alarm, "Hold") == 0) {
    // Something to do when Busy
    dAlarm = "Hold";
  } else if (strcmp(alarm, "Door") == 0) {
    // Something to do when Busy
    dAlarm = "Door";
  } else if (strcmp(alarm, "Home") == 0) {
    // Something to do when Busy
    dAlarm = "Home";
  } else if (strcmp(alarm, "Alarm") == 0) {
    // Something to do when Busy
    dAlarm = "ALARM!";
  } else if (strcmp(alarm, "Check") == 0) {
    // Something to do when Busy
    dAlarm = "Check";
  }
  dispPos();
}

void dispPos() {
  int state = 0;
  int x = analogRead (0);
  if (x < 800) {
    state = 1;
  }
  if (state == 1) {
    dPos = false;
  }

  if (dPos == true) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("X");
    lcd.print(mx);
    lcd.setCursor(8, 0);
    lcd.print("Y");
    lcd.print(my);
    lcd.setCursor(0, 1);
    lcd.print("Z");
    lcd.print(mz);
    lcd.setCursor(8, 1);
    //lcd.print(" ");
    lcd.print(dAlarm);
    delay(3000);
  } else {
    mainMenu();
  }
}

possible duplicate of How would i capture and split serial data?

Sorry nick gammon, not a duplicate of that question. That question dealt with capturing and splitting the data. This deals with doing it for specific data only. The difference between the two is one asks how to capture and split, this one delves deeper and captures based upon certain criteria.

You have lost me as to the difference between "capturing and splitting the data" and "for specific data". You are quoting the same data: <Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>. It's all very well do "delve deeper" but this is splitting the basic problem across two separate questions. One with, and one without, "certain criteria" I gather.

I guess i could go ahead and delete the question, but i have a feeling it would just be asked again, simply because it deals with a specific problem within a general subject. As far as i know, we aren't supposed to expand upon the initial question with another one. As i said, the first one deals promarily with general serial data collection, and processing. Where this question deals with a specific string within the serial stream. Just because i used the same example, doesn't mean the question is a duplicate, it offers other readers information not available in the first question's answer..

What you need to do here is implement a small finite state machine.
Basically you need to look at each character as it comes in and make a decision what to do with it depending on what state you're in at the moment.
Basically the operational decisions you need to make are:

Is the character a < and am I currently not reading a string?

Yes, start reading the string.

Is the character a > and am I currently reading a string?

Yes, finish reading the string and process it

Is it any other character and I am currently reading the string?

Yes, add it to the buffer.

So you can see there some common questions:

What is the character?
What am I doing at the moment?

So you need to have a simple state variable that remembers if you're reading the string or not, and something to say where in the buffer you are so you know where in the buffer to add any incoming characters.
boolean readingString = false;

A simple true/false will suffice to depict if we're reading the string or not.  Start off not reading the string.
char buffer[80] = "";

A buffer to store the text - maximum of 80 characters (including the NULL terminating character)
int charPointer = 0;

Something to know where in the buffer are currently.
Now to read the characters:
First get the next character from the serial port:
loop() {
    if (Serial.available()) {
        int incoming = Serial.read();

Now decide what to do with it.  We have a number of possible situations, some of which can be combined into single options.  For instance, if we get a "<" while reading a string it's an error condition - but do we really care?  It could be that we lost the end of the last string and have just started a fresh one - so we can just treat it as the start of a string regardless of what state we're in.  Let's use a switch for this since it's nice and tidy:
        switch (incoming) {
            case '<':
                readingString = true; // Start reading string
                charPointer = 0; // Set the buffer pointer to the start
                buffer[0] = 0; // Make the string empty
                break;

            case '>':
                if (readingString) {
                    processBufferData(); // Do something with the buffer
                }
                readingString = false; // Finish reading
                break;

            default: // Anything that's not > or <
                // If we are reading the string and the buffer isn't full
                if (readingString && charPointer < 78) {
                    // Add the character to the buffer and increment the pointer
                    buffer[charPointer++] = incoming;
                    buffer[charPointer] = 0; // Don't forget to terminate the string
                }
        }
    }
}

So the reception of a < starts the string reading, the reception of a > stops it and triggers the processing of the string, and anything else (while we are reading the string) gets added to the buffer.

for some reason i'm not getting the result i expect.
I think because elsewhere in the script i already have serial available, and perhaps it's interfering, or something else more drastic is happening.
If you're willing to take a look. Perhaps you can spot, and explain what i've done wrong and where so others can learn from my mistakes.
Also.. Please don't laugh too hard at me, it's only my second or third week using the arduino IDE
I've uploaded my project to Here

You must only consume the serial bytes in one place, otherwise who knows what'll happen.

hrm.. well.. that kind of shoots my entire project down then.
What i'm trying doing is sending data to an arduino Uno with GRBL, through an arduino mega with an LCDKeypad shield.
That way i can display the POS on the LCD, have a menu system for common GRBL stuff. As well as use the PC (and at a later date SD) to send g-code to the uno.
So the flow would be PC-> Mega+Keypad -> UNO | Uno -> Mega -> LCD+PC
So far everything is working OK, but i've had to avoid using if(serial.available) as it's always available so it can send data from PC to UNO, and from UNO to PC.

Just move the reading routine out of the timer and into the serialcomms routine, and print the characters in there instead.

I Thought about that, and was working on it as you responded.
I left the command in the timer that requests the status string from GRBL (the string we are processing)
That way it can continue to update without interference.
And i moved the reading of the string to the serial comms. Going to test it now :)

@ArcAiN6 You need to remove it from the timer.  The routine only consumes one character with each call, so it can run directly within loop() without any blocking.  If you have it in the timer it will only take one character every time the timer fires - it will take forever to read one string in.

I think you misunderstood what i left in the timer loop.
I moved everything out of the timer into serial coms, except for the command that tells grbl to display position..
This is the only thing left in the timer.
Serial1.print("?\n");
The reason i did that is because everytime GRBL replies with position, it causes the stepper motors to stop moving for a fraction of a second. This may not seem like a big deal, but if this happens every few miliseconds as the loop gets back to the serial function we've created, it would cripple the stepper motors, and possible cause grbl to poop the bed.

@ArcAiN6 Ok, that's cool.

With that problem solved thanks to your insights, I'm off to search out information on how to compare those floats we created, that way i can update the display in real time as the positions change :)

Floats can be tricky to compare since they are only approximations.  It could be better to do them as integers - multiply the value by (say) 1000 and store them as integers then divide them by 1000 to display them.

nod I was looking that over, and was contemplating on convert them to integer, then round them off, then compare the rounded integer of the stale data, against the rounded integer of the new data.


text:
Arduino IDE not handling library code correctly?
The author of the PinChangeInt library and the EnableInterrupt library states at github:

When the PinChangeInt was in a .h and .cpp file, the Arduino IDE tried
  to compile it twice. I have a technique that you can use- #define
  LIBCALL_ENABLEINTERRUPT - that if you put it ahead of your #include in
  all files but the sketch, then you should be able to use the library
  without conflicts. If you know how to make it work in another way-
  remember, this is a library and will not compile in the same directory
  as the sketch and any other .h/.cpp/.ino files- then I'm all ears.

I came there, because both libraries failed to build with linker errors due to double definitions. So far so good. I split the PinChangeInt library in .h and .cpp myself and it compiled flawlessly. I did not try to split the other library yet because it looks like much work to me.
So now my question(s): Is GreyGnome right with his statement, that library code gets compiled twice when split in code and headers? And if so, what are the consequences? Memory waste? Runtime errors? What about the many other (working) libraries exhibiting separate code and header files?

I have no clue what he's on about. CPP files only get compiled once. Otherwise the whole Arduino system would fail miserably since most other libraries are split into CPP/H.

My guess is that he didn't split the files properly and ended up with duplicate references.

Ahem, so if I have some time again, I'll try to split this library too.

As I mentioned in your somewhat related thread the IDE does things in a reasonably understandable way:  Classes and objects: how many and which file types I actually need to use them?.

@NickGammon: I read that already. But how does this help me with that library? Do I have other means than rewriting it?

I just took a look at the library. He puts function definitions in the .h file. That will only work if it is included once in your project. All the definitions (the actual functions, not the prototypes) need to be moved into a .cpp file. Ditto for variables. It's not that much work to split it into two files.

I'm just hesitating to do it, cause I have to redo it each time when I want to incorporate an official update of this library. I tend to wait until the author is done with fixing all bugs and extenisons.

Header files are parsed by the preprocessor and the compiler wherever they are included.
There's nothing weird about that.
One can avoid multiple inclusions by using header guards.
That's pretty standard too.
I have not looked at the library, but, for example,  a typical error is to not declare variables as extern in the header and instead leave the real declaration in the header, which will lead to multiple instances, possibly clashing at link time.
Variables that are part of the library API should be declared as extern in the header and the real declaration should be done only in the .C/.CPP file.
Interrupts are an even more special case: the AVR gcc relies on very specific names to identify interrupt handlers and each of them can be present at most once.
So there are even more chances for having linker problems, if not declared correctly.

The problem is, that both libraries lack .c/.cpp files entirely. Hence the real declaration is in the header and it is not possiple to declare it extern. The compiler takes the header guards correctly. But the linker throws the double declaration errors afterwards.

Indeed, what should be done is to split the library into .h and .cpp, so that it can work in a sane way.
FWIW, though, using PCINT is trivial, if done without the library, assuming that you only care about one specific platform (say ATMega328p). The library bends backwards several times to cope with the different layout of AVR ports across various ATMega chips. But if all you care about is one chip, you can write much simpler code.

On my Interrupts I show how you can use pin-change interrupts in about 4 lines of code. My personal view is that if you are targeting a particular processor it is easier to just write those four lines. By the looks of it you have already spent a number of days to "save the effort" of writing those few lines. The problem is, that both libraries lack .c/.cpp files entirely. - so? Split the file into two files. ... it is not possiple to declare it extern - anything is possible.

To be fair, the library does more than what is accomplished by those 4 lines. Replicating the same functionality would take a similar amount of code. But it could be done without abusing the header.

To elaborate on your comment ~
An easy way to prevent multiple definitions from re-inclusion of the same header file is to ensure it's only defining things once.
e.g. my_header.h
#ifndef __MY_HEADER_H__
#define __MY_HEADER_H__

// some header code.

#endif //#ifndef __MY_HEADER_H__

When the header is first compiled, the definition of __MY_HEADER_H__ gets created by the compiler due to the 2nd line of the file.  On subsequent compiles, which are caused by including the same header in more files, the 1st line '#ifndef' conditional skips everything down to the '#endif'.
When you write (or split) C / C++ code, it's common to wrap the class and function definitions (which go in the .h header file) in these compilation control blocks, and then the .c/.cpp file only gets the function bodies.
e.g.: my_rgb.h ~
#ifndef __MY_RGB_H__
#define __MY_RGB_H__

#include <stdint.h>

uint32_t packRGB(uint8_t r, uint8_t g, uint8_t b);

class RGB
{
public:
    RGB(uint8_t r, uint8_t g, uint8_t b);

    void toGreyscale();

private:
    uint8_t red;
    uint8_t green;
    uint8_t blue;
};

#endif //#ifndef __MY_RGB_H__

and my_rgb.cpp
#include "my_rgb.h"

// Note: this would typically be a member function
// but is separate to show a standalone function definition.
uint32_t packRGB(uint8_t r, uint8_t g, uint8_t b)
{
    uint32_t packed;

    packed = (r << 24) | (r << 16) | b;

    return packed;
}

RGB:RGB(uint8_t r, uint8_t g, uint8_t b)
{
    red = r;
    green = g;
    blue = b;
}

void RGB::toGreyscale()
{
    uint8_t grey = 0.2126 * (float)r + 0.7152 * (float)g + 0.0722 * (float)b;
    r = g = b = grey;
}

Including the header file multiple times will give "redefinition" errors at compile time.  Including the same function multiple times will give double definitions at link time.
If you stick to this method of laying out .h and .c/.cpp files you will never have a problem with multiple definitions on your own files.  (Unless you re-define a library function by accident, etc.)
Of course it's ok (and quite common) to define short little functions in the header/.h file too. (The compiler typically generates these as inline code though.)  I'm not trying to explain the complete workings of headers & .C files, just presenting you a method which will always prevent multiple definition problems.


text:
Which sensor is best for obstacle detecting with retroreflector?
Distance is about 3m. IR or visible light - does not matter.
It is possible that object/obstacle can be shiny, so for correct detection necessary large amount of reflected light.
Maybe for this task better to use specific retroreflector?
UPDATE:
there will be two sensors with distance about 3-4 cm between.
Object must cross 1st sensor's reflector but do not cross the 2nd one.
The scheme of this sensor should be this:

But the use will be this:

If you use a laser and mirror, you probably only need a simple photo-transistor  (of approximately the same wavelength as the laser). Shiny object have to be precisely aligned to reflect as much light as a mirror does, so it's hard to not be detected.

@Gerben OK, I will update the task. I don't believe that sonar is capable for desired distance and accuracy.

@Gerben There is possibility that the light of the surrounding will affect on result.

Lasers are nice for this, they are bundled quite well. You could use a sonar/ping/ultrasonic sensor for this. But they might interfere with eachother if they're too close. And yes, lasers don't do very well on shiny objects if set up like this.

I think the question is worded to get a specific answer; I do not know if this is the answer you want. I'll give you that answer first:
I'd say an infrared LED, and an infrared detector.
Strobe the LED, then measure the difference between when it's (known to be) on, and when it's (known to be) off, to compensate for ambient light.
However, if I was doing this, I'd consider an ultrasound sensor - no retroreflector needed; instead you get the distance to the (obstacle or reflector).

Reflector does not require any power and can work at quite large distance. I have updated the scheme - it is not possible to use ultrasound sensor

I think you're better off with a set-up like this.
A shiny object might bounce the laser as if it were a mirror.
But we wan't to know if the laser was interrupted.
So. If we place the sensor on the other side, we can accurately say if the light reaches the sensor. Thus if there is an object between (shiny or not).
But what if another light-source shines into my sensor? It'll think that there is no object.
We can encapsulate the sensor, so that only light from the direction of the laser can shine into it. And we can filter out other light "colors".
Also the strength of the laser should be bigger as any other ambien light (not too strong also). You could even choose to make the laser pulse a specific pattern and let the sensor check if it's right.

What is the length of sensor "vision" and how narrow is the sonar? Distance between two sensors should be about 5-6 cm (maximum -10).

@XuMuK what you man by length of sensor "vision" the sensor can see the light source, as long as the light source is bright/strong enough. It's hard to pre-calculate this, just get one of which you think is strong enough to make a difference (against ambient light).

@XuMuK regarding the "narrowness" of a sonar, it'll be different for each part, you should check the datasheet of the specific part. Or choose one which fits your needs.


text:
Error AT%13% With GSM/GPRS Shield
I've been trying to control a relay with a GSM shield for an Arduino project. I haven't had any success with either the Software Serial or the GSM library. I've declared the GSM variable in debug mode and it gives me the error AT%13%.
Using Software Serial, it hangs at SIM900.read().
The SIM card connects to the network, I can see that on the board - the LED flashes every 3 seconds and gives me signals for incoming calls and SMSs.
I can't tell if the error is with the SIM card, the connections to the Arduino board, the power supply (12V) or something completely different. Here are the two code examples I'm using with the different libraries.
Anyone else getting this error? What is the best way to make it go away?
Thanks in advance for any help!
SoftwareSerial.h
#include <SoftwareSerial.h>
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900(7, 8);

int Relay1 = A2;
int Relay2 = A3;

void setup()
{
  Serial.begin(19200);
  //Set up relay control pins
  pinMode(Relay1, OUTPUT);
  digitalWrite(Relay1, HIGH);
  // wake up the GSM shield
  SIM900.begin(19200);
  delay(10000);  // give time to log on to network.
  SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  // output contents of new SMS upon receipt to the GSM shield's serial out
  delay(100);
  Serial.println("Ready...");
  }

void loop()
{

  //If a character comes in from the cellular module...
  if(SIM900.available() >0)
  {
    inchar=SIM900.read();
    Serial.println(inchar);
    if (inchar=='#')
    {...}
    SIM900.println("AT+CMGD=1,20"); // delete all SMS
  }
}

GSM.h - in this case I haven't even gotten past the .begin() command. This code is from the example at http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS
#include <GSM.h>

// PIN Number for the SIM
#define PINNUMBER ""

// initialize the library instances
GSM gsmAccess(true);
GSM_SMS sms;
GSM3_NetworkStatus_t   gsmStatus;
// Array to hold the number a SMS is retreived from
char senderNumber[20];

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

  Serial.println("SMS Messages Receiver");
  char code = 'X';
  Serial.flush();
  gsmStatus = gsmAccess.begin(PINNUMBER,false,false);

  int retrycount = 60;
  while (gsmStatus != GSM_READY && retrycount-- > 0) {
    delay(1000);  // lower delay value could lead to unstable state
    theGSM3ShieldV1ModemCore.manageReceivedData();
    gsmStatus = gsmAccess.getStatus();
  }

  if (gsmStatus != GSM_READY) {
    Serial.println("\n[ERR]: GSM connection failed\n");
    Serial.flush();
    gsmAccess.shutdown();
    delay(250);
    digitalWrite(3,LOW);
  }

  Serial.println(" [DONE]");

  // connection state
  boolean notConnected = true;
  // Start GSM connection
  while (notConnected)
  {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
  {
      notConnected = false;
  }
    else
    {
      Serial.println("\nNot connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  Serial.println("Waiting for messages");
}

You seem to be using different baud rates in each example. Which is the correct one?

Do you get a AT%10% error if you change your \rs with \ns?

Sorry for the mix-up with the baud rates. They are actually irrelevant since both are correct, the codes are from two different examples.
Unfortunately I was not able to resolve this problem using GSM.h. I stuck with SoftwareSerial.h but have found a reliable, reproducible solution to the problem.
First, I now useSIM900.print("AT+CNMI=1,2,0,0,0\r"); to initialize my SMS mode, it seems to enable properly every time.
Second, after the read() from the SIM card I clear out the contents with SIM900.flush() which seems to prevent phantom messages from appearing.

Check your baud rates. They appear to be different. That will cause problems.

They are two different codes, not meant to run together. But true, the baud rates for the top and bottom don't match, but that does not solve the problem.

I used Mega 2560 connected to GSM shield as following:

GSM TX --- pin 10 on Mega
GSM RX --- pin 3 on Mega
GND to GND


text:
How to program a CLK signal and its inverse with Arduino/AVR
Is it possible to simultaneously output a clock signal and it's inverse using the timer register(s)?
I'm using the following code in arduino to output a 1MHz signal on OC1A:
//Use Timer/Counter1 to generate a 1MHz square wave on Arduino pin 9.
//J.Christensen 27Apr2012

void setup(void)
{
    DDRB = _BV(DDB1);                  //set OC1A/PB1 as output (Arduino pin D9, DIP pin 15)
    TCCR1A = _BV(COM1A0);              //toggle OC1A on compare match
    OCR1A = 7;                         //top value for counter
    TCCR1B = _BV(WGM12) | _BV(CS10);   //CTC mode, prescaler clock/1
}

void loop(void)
{
}

How about this?
void setup()
  {
  // Defining PB1 and PB2 as outputs by setting PORTB1 and PORTB2
  // Setting DDB1 and DDB2
  DDRB |= bit (DDB1) | bit (DDB2);

  // stop timer 1
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A = bit (COM1B0) | bit (COM1B1)  // Set OC1B on Compare Match, clear
                                        // OC1B at BOTTOM (inverting mode)
         | bit (COM1A1)                 // Clear OC1A on Compare Match, set
                                        // OC1A at BOTTOM (non-inverting mode)
         | bit (WGM11);                 // Fast PWM, top at ICR1
  TCCR1B = bit (WGM12)  | bit (WGM13)   //       ditto
         | bit (CS11);                  // Start timer, prescaler of 8

  // Initialize OCR1A = 300 (pulse_width = 150us), OCR1B, and ICR1
  ICR1 = 0xFFFF;
  OCR1B = 299;
  OCR1A = ICR1 - OCR1B;

  }  // end of setup

void loop()
  {
  }

Results on a Uno:

Output on Uno pins 9 and 10.
Change the prescalers and counters to your desired frequency.

The screenshot doesn't show one signal exactly the inverse of the other. The pattern is inverted. If you had a 50% duty cycle, it would be an exact inverse.

It looks good except they overlap (slightly) by 50ns. If I set them to 16 and 8, respectively, they don't overlap but they are slightly asymmetrical

OK, make OCR1A and OCR1B both 7:
  ICR1 = 15;
  OCR1B = 7;
  OCR1A = 7;

Why 7? And why 15?
The counts are zero-relative. So by counting to 15 on a 16 MHz processor we are actually getting 1/16th of the clock, namely 1 MHz. And half of that is 8 (which, zero-relative, is 7). So we are really doing:

Period: 16 ticks of the 16 MHz clock
Duty cycle: 8 ticks of the 16 MHz clock

Now, one cycle:

They change over at the same instant - pulse width exactly 500 ns.

And they change back at the same moment - pulse width also 500 ns.

Thanks! I was able to get a 1Mhz square wave by eliminating the prescaler and setting ICR1 = 15 and OCR1B = 7. It looks good except they overlap (slightly) by 50ns. If I set them to 16 and 8, respectively, they don't overlap but they are slightly asymmetrical.

See amended reply for how to fix this.

Various AVRs have the capability to output both the normal and inverted timer waveform from a single output compare register simultaneously on two pins. These devices include, but are not limited to, ATtinyX5/V, ATtiny26/L, ATtinyX61A, and ATmegaXXU4.
The ATmega328P does not have this capability, therefore the smallest primary source Arduino that does is the Leonardo (ATmega32U4) and comparable devices. The Adafruit Trinket and the Digispark (both ATtiny85-based) also offer this.

What about also setting COM1B0 and then setting the initial values of OC1A and OC1B to opposites by writing to PORTB?
Also, I presume you mean 1 MHz and not 1 mHz?

Another option is to do this in hardware - it's trivial to invert a signal.
For example, see the selected answer for https://electronics.stackexchange.com/questions/30238/how-to-invert-a-digital-signal - the second diagram - connect Vs to your clock, and Vo will be your inverted clock. For the two resistors, anything over 1k should be fine. Or use an inverter (which is the same thing, in one component, but is much less likely to be in your random-part box).
Note: There will be a very short delay going through this circuit - one place I saw suggested 1.5ns, but see the spec sheet of your transistor. A 1mhz clock "ticks" at 1,000ns (I guess, 500ns on, 500ns off), so this delay shouldn't be significant.

Thanks, I originally tried to use an op amp to invert the signal and was surprised by how slow it was – it took about 10µs to switch. This probably would have been a faster, better approach, but if I can do everything in software that would be ideal.

This is out of my field of expertise a bit, but op-amps have a slew rate, which I believe means the time to change states. For example the LM158 is quoted as having 0.3 V/µs which means therefore to go from 0 to 5 V would take 5 / 0.3 = 16.66 µs, which is fairly close to your observations. You can get faster op-amps.


text:
Linear acceleration from MPU 6050
When reading the MPU 6050 has accelerometer and gyro, I assumed it was linear acceleration, but now I second guess that.  From this video https://www.youtube.com/watch?v=qmd6CVrlHOM it seems like they are using acceleration and gyro to make one rotation direction.  I need to know what direction the mpu is moving, not just a rotational value.  Is there a way to extract this information?

Please tell us more. Do you want to measure the acceleration and deacceleration in a direction, or the motion with a constant speed in a direction ?

I am trying to find vertical velocity with mpu6050 but I failed. Did you find any benefical thing ? Thanks.

The MPU6050 has an accelerometer and a rate gyro (which tells you how fast it is rotating). The accelerometer will tell you which direction is down and in a motionless situation, that is all the information you have.
You'll probably want something like the MPU9150, it has a compass, which will give you the directional information you're asking for.

A compass will not tell you direction of movement, only direction of (apparent) orientation

When you're motionless you're ok, no movement information to report :-) The bigger problem, I think, is that at a steady speed you also have 0 acceleration, but you are moving. A compass will tell you your heading, but that may or may not be your direction of movement. I think you're talking about building an INS (inertial navigation system), you'll need to be able to determine a starting state and then track changes (accelerations) from there. You may want a GPS.

The MPU6050 has accelerometers in the x, y, and z axis. When placed on flat surface with no acceleration, you should get 0g (or whatever unit it uses, I cannot remember off the top of my head) in the x and Y directions, and 1g in the z axis. By continuously polling these values, you can find out the linear  acceleration of each axis at a given moment in time.
What you saw is probably because the chip also has three Gyroscopes, for measuring rotational acceleration and speed. The chip can do both.


text:
avr-g++ (or avr-gcc) and LiquidCrystal library
I'm trying to run a simple Hello World program from Arduino 1.6.5 from terminal. When I run it in Arduino IDE, it works good. When I'm trying to get it by avr-g++ I have hard way to figure out how to include all libraries - so far I got this script:
avr-g++ -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o main.o main.cpp
-I"../arduino-1.6.5-r5/libraries/LiquidCrystal/src/"
-I"../arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/"
avr-g++ -mmcu=atmega328p main.o -o main
avr-objcopy -O ihex -R .eeprom main main.hex
sudo avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM1 -b 115200 -U flash:w:main.hex

First line (with both -I flags) compiles, but after running second line, I get:
main.o: In function `main':
main.cpp:(.text.startup+0xa): undefined reference to `LiquidCrystal::begin(unsigned char, unsigned char, unsigned char)'
main.cpp:(.text.startup+0x16): undefined reference to `Print::print(char const*)'
main.o: In function `_GLOBAL__sub_I_lcd':
main.cpp:(.text.startup+0x3a): undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
collect2: error: ld returned 1 exit status

How can I also include some libraries? I need the exact bash script.

Have you tried duplicating every nitty little step the IDE goes through.

I don't know how, though.

possible duplicate of not using the IDE and understanding the compilation/linking/upload process

I made a Makefile to compile the Blink program a little while back. It wasn't trivial.
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

I basically did this by observing what the IDE does (as Ignacio Vazquez-Abrams suggested) and replicated it. Now to add libraries you have to add even more steps.

It doesn't work well for me, even if i change everything. Linux can't find malloc.c in files.

You must be able to find them, as Ignacio Vazquez-Abrams suggested. Turn on verbose compiling, do a compile, and see where the IDE finds them.

Ok, I found them. Thanks. I'll post tomorrow results.


text:
Issue with CD74HC4067 MUX on high values
I'm having a small issue with the CD74HC4067 multiplexer/demultiplexer: I am using it to receive data from an array of sensors (at the moment I have only 2, but in a near future they will grow). Specifically I have a light sensor and a sound sensor.
Mux output is connected to A0 since the readings I do are analog. The pins I use to switch the channels are A3 and A2 (when the other sensors will arrive also A1 will be dedicated to that).
My problem is that when switching between one channel and another, my readings highly fluctuate, but only when the reading value is > 500 or so, and I don't understand why. In a simple sketch I've tried adding some delay (40 msec) and the issue goes away. But in my project which is far more complex and uses also other analog channels I need a delay of ~1 second to get a correct reading, which is absolutely unacceptable since I need it to run in real-time(ish). I also tried using the digital pins to control the mux but to no avail. The only thing that seems to stabilize everything is connecting a capacitor between the MUX out and ground, and using a 20msec delay, but it only works for a bit.
I hope I've been clear enough and that someone can point me the right way!
EDIT:
Here is the schematic

(Error in the drawing: "temp" is actually a "light sensor" as in the bottom of the post...)
And my code:
#define MUX A0
#define S0 A2
#define S1 A3

void setup() {
  Serial.begin(9600);
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);

  selectMux(1);
}

void loop() {

  //selectMux(0);
  //Serial.println(analogRead(MUX));
  //selectMux(1);
  Serial.println(analogRead(MUX));

}

void selectMux(byte port) {
//  pinMode(MUX, mode);
  int r0 = bitRead(port, 0);
  int r1 = bitRead(port, 1);

  digitalWrite(S0, r0);
  digitalWrite(S1, r1);
  analogRead(MUX);
}

the analogRead(MUX) in the selectMux function was added because I read in a post that they suggested to do that in order to get a more accurate reading.
With this code only the results already fluctuate:
Output:
76
41
77
76
76
75
36
75
74
76
77
106
76
76
76
76

but it goes crazy when the input is higher, close to 5V:
Output:
948
780
340
948
948
635
437
949
948
499
551
949
950
396
684
950

If you enable the commented code that starts to switch the outputs it is even worse. As I said, adding delays helps, but in my final application I cannot afford to have 1s delays.
I also show that in the circuit there is a timer that uses other Analog pins, but in the code I didn't include that part. If you need I'll add that too.
Sound Sensor,
Light Sensor

It would be helpful to post your code, and a schematic, even if you just sketch it with pencil and scan it in. The code in particular I would be interested in. Please amend your post and include it. Reduce it to a  Minimal, Complete, and Verifiable example as far as possible. Thanks!

Ok, will do, thank you! At the moment I cannot post anything so I'll get back in a few hours! Cheers :)

@NickGammon added schematics and very basic code that runs with errors :)

I don't think you should leave s2 and s3 floating. Connect them to ground.

It worked! Thinking about it a floating pin does not mean nor 0 nor 1, so, yeah I was naive in leaving that detail out! Thanks a lot :)

@Gerben - maybe add that as an answer with some more info. Seems it worked.

I don't think you should leave s2 and s3 floating. A floating pin does not mean nor 0 nor 1.
Connect them both to ground.

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


text:
How can I make motor vibrate using arduino depending on the ultrasonic distance?
I want to make the vibration motor vibrate depending on the distance to an obstacle, for example if the distance is too short it should vibrate quickly and vice versa.
How can i make motor vibrate using arduino depending on the distance?
Can you explain for me how can I use the delay in the vibration code?
I found this code in the internet for vibration:
digitalWrite(y, HIGH);
delay(50);
digitalWrite(y, LOW);
delay(50);

I know that I can change the delay, but how can we do it depending on our purpose?
Please help me .. I don't know the use of the delay :(

You could just replace the "50" in the first delay with the ultrasonic distance variable, I'll explain a bit more below.
Let's assume your ultrasonic sensor outputs an analogue value between 0V and 5V. The output is connected to analog pin A0. Then you just set pinMode(A0, INPUT) and analogRead the value from the pin and store it in the variable X or whatever. Then you just use the variable X as a delay and it will do what you want. The higher the value gets the longer it will vibrate. Something like this:
[...]
val = analogRead(A0);
digitalWrite(5, HIGH);
delay(val);
digitalWrite(5, LOW);
[...]

Second option, if you only wish to turn it on if it is above or under a certain limit, would be using an if condition.
For example:
if(variable > 50){
  // if the variable named variable is over 50 this code is going to be executed
} else {
  // If the variable is below 50 this is executed
}

If you are unfamiliar with if conditions then I suggest reading this too.

I know that I can change the delay, but how can we do it depending on our purpose?

Are you asking how to use a variable? An example:
const int LED = 13;

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

void loop()
  {
  int amount = analogRead (A0);   // get a reading
  digitalWrite(LED, HIGH);
  delay(amount);
  digitalWrite(LED, LOW);
  delay(amount);
  }

That code reads some analog device, and adjusts the delay based on the figure it read.

I want to show you my thinking, and tell me please if it is right or wrong:
I build an relationship between the distance and the speed.
I know that (speed = distance/time) and if the obstacle is too close to the ultrasonic sensor the speed of the motor should be maximum, so I have decrease the time which is the delay, right?
I make the code according what i said above and it is shown below:
    if(distance <= 60 && distance >= 45)// the distance is too large
    {
    digitalWrite(motorPin, HIGH);

    delay(200);// I increase the delay to make the motor vibrate slowly

    digitalWrite(motorPin, LOW);

    delay(200);

    }

    else if(distance < 45 && distance >= 30)
    {
    digitalWrite(motorPin, HIGH);

    delay(100);

    digitalWrite(motorPin, LOW);

    delay(100);

   }
    else if(distance < 30){

    digitalWrite(motorPin, HIGH);

    delay(50);

    digitalWrite(motorPin, LOW);

    delay(50);

  }
  else
  {
    digitalWrite(motorPin, LOW);// If the distance is too large the motor will be off
  }

The code is okay, but one of the comments are wrong. Using a longer delay makes the motor spin longer, delay after turning the motor off increases the time between that and the next reading so keep that in mind.

Thanks a lot for replying, but u didn't tell me if my thinking is right or not according to the equation that i wrote above.. Also, which comment is wrong ?
Can u explain the idea for me more, cuz i got confuse little bit ... :(
Also.. can u give me ur email that will make the communication easier ??
plz reply as soon as u can ...

The first comment and the logic is wrong. You can not change the speed of a motor with a delay, you can change the duration of it being on or off. See my answer below for more details.


text:
Protocol options for data exchange between Arduino and ESP8266
I have a device built with an Arduino uno:

Arduino software installed on an Arduino uno
can be controlled via serial commands
can be controlled via physical buttons and sensors
on any button/sensor state change it writes the current state to serial
if no message has been sent within 5 seconds, it sends a no-change serial message

What is needed:

Use an ESP8266 to provide a bridge between current Arduino software and MQTT / web
I can program the ESP8266 as a web server, MQTT client, etc with the Arduino IDE or Lua (but I prefer the Arduino IDE since I can reuse parts of the code to generate / interpret communication).
the ESP8266 will handle everything that is required for wifi / web / MQTT; without the MQTT module the Arduino part will work stand-alone, only the remote control will be missing.
I would like to make minimal changes to the Arduino code (or none, if possible). Any changes would involve extensive re-testing, which I try to avoid.
the ESP8266 can be missing in some installs.

What options I found:

Serial

ESP8266 can read the serial output and be a bridge between web/MQTT and serial, will store the current state in memory to be sent when requested to avoid polling the device every time.
One of the benefits is no code changes / testing required for the Arduino part.

I2C

Make the Arduino the I2C master and the ESP8266 the slave (or the other way around) and implement bi-directional communication. Got the idea by reading this thread.

Some other information about the serial commands:
A data packet (command or state description) consists of 1 to 20 characters, with a possible peak of 20 packets in 5 seconds, and an average of one packet every 3 seconds. If needed, I can make this send 5 unsigned integers instead of alphanumeric characters.
If more than the I2C / serial pins are needed I can upgrade to an Arduino Mega (so the number of free pins is not an issue).
Are there any other options for this? (protocols, pre-made libraries for serial communication, etc). I'm trying not to reinvent the wheel..
Thank you for your time!

Firmata (https://github.com/firmata/protocol/blob/master/protocol.md) is one such existing communication protocol. However it's not clear what you want - you have already defined and built the serial protocol and you say you would rather not change that code... If that's the case just code your ESP to grab the serial data, parse it and send it to the web/MQTT server.

Most I2C tutorials made each Arduino a slave and master, but this approach is better, because each Arduino is either a master or a slave (not both) and no switching is needed. That makes things easier.
I2C is better than serial, because you can add more Arduinos in the same bus.
I have implemented I2C between two Arduinos and it's not more complicated that reading/writing to the serial port (which you have already done). And I bet you can generalize your serial port code to work with both serial and I2C comms.
This is my example (just a proof of concept). The slave Arduino controls a some pins, a temp. sensor and a watchdog under orders from the master Arduino. If slave doesn't receive a beat in time, it reset the master Arduino.
Master code
#include <Wire.h>

#define CMD_SENSOR    1
#define CMD_PIN_ON    2
#define CMD_PIN_OFF   3
#define CMD_LUMEN     4
#define CMD_BEAT      5

const byte SLAVE_ADDRESS = 42;
const byte LED = 13;

char buffer[32];

void setup ()
{
  Serial.begin(9600);
  Serial.println("Master");

  Wire.begin ();

  pinMode (LED, OUTPUT);
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);

  Wire.beginTransmission (SLAVE_ADDRESS);
  Serial.println("Send LED on");
  Wire.write (CMD_PIN_ON);
  Wire.write (2);
  Wire.write (10);
  Wire.endTransmission();
  int x = Wire.requestFrom(SLAVE_ADDRESS, 1);
  Serial.print("status=");
  Serial.println(x);
}  // end of setup

void loop ()
{
  Serial.println(".");
  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (CMD_SENSOR);
  Wire.endTransmission();
  int x = Wire.requestFrom(SLAVE_ADDRESS, 1);
  Serial.print("Disponibles = ");
  Serial.println(x);
  int temp = (int) Wire.read();
  Serial.println(temp);

  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (CMD_LUMEN);
  Wire.endTransmission();
  Wire.requestFrom(SLAVE_ADDRESS, 2);
  int light = Wire.read() << 8 | Wire.read();
  Serial.print("Light=");
  Serial.println(light);

  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (CMD_BEAT);
  Wire.endTransmission();
  Wire.requestFrom(SLAVE_ADDRESS, 1);

  delay (5000);
}  // end of loop

Slave code
/*
   Esclavo I2C

   Recibe los siguientes comandos
   <- 1° byte -> <- 2° byte -> <- 3° byte ->
   CMD_SENSOR
   CMD_PIN_ON    n° de pin     duracion en segundos
   CMD_PIN_OFF   n° de pin
   CMD_LUMEN
   CMD_BEAT

   Cada comando recibe una respuesta, ya sea el valor pedido
   o un status.
*/
#include <max6675.h>
#include <Wire.h>

typedef struct {
  int pin;
  unsigned long off;
} PIN_PGMA;

/*
   Lista de pines que se pueden activar via CMD_PIN_ON.
*/
#define PIN_LUMEN   A0
#define PIN_LED      2
#define PIN_RESET    3
PIN_PGMA pgma[] = {
  {PIN_LED, 0},
  {PIN_RESET, 0}
};
const int pgmaSize = sizeof(pgma) / sizeof(PIN_PGMA);

#define CMD_SENSOR    1
#define CMD_PIN_ON    2
#define CMD_PIN_OFF   3
#define CMD_LUMEN     4
#define CMD_BEAT      5

#define ST_OK         0
#define ST_BAD_PIN    1
#define ST_TIME_0     2
#define ST_BAD_LEN    3

#define MY_ADDRESS  42

//  Maximo tiempo de espera entre comandos CMD_BEAT. Pasado
//  ese tiempo, se activa el PIN_RESET.
//  En milisegundos.
#define BEAT_INTERVAL 10000
unsigned long lastBeat;
//  Largo del reset en milisegundos.
#define RESET_LENGTH  250
byte cmd = 0;
byte status = 0;

int thermoDO = 11;
int thermoCS = 12;
int thermoCLK = 13;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

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

  pinMode(PIN_LUMEN, INPUT);
  analogRead(PIN_LUMEN);

  for (int i = 0; i < pgmaSize; i++) {
    pinMode(pgma[i].pin, OUTPUT);
    digitalWrite(pgma[i].pin, LOW);
  }
  lastBeat = millis();

  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveCommand);
  Wire.onRequest (sendAnswer);
}

void loop()
{
  unsigned long now = millis();

  //  Baja la linea de RESET si no ha recibido un beat ultimamente.
  unsigned long diff = now - lastBeat;
  if (diff > BEAT_INTERVAL) {
    resetPin();
  }

  //  Recorre la lista de pines y apaga aquellos cuyo tiempo termino.
  for (int i = 0; i < pgmaSize; i++) {
    if (pgma[i].off > 0 && pgma[i].off <= now) {
      Serial.print("off pin="); Serial.println(pgma[i].pin);
      pgma[i].off = 0;
      digitalWrite(pgma[i].pin, LOW);
    }
  }
}

// called by interrupt service routine when outgoing data is requested
void sendAnswer() {
  byte temp;
  int  lightReading;

  switch (cmd) {
    case CMD_SENSOR:
      temp = thermocouple.readCelsius();
      Wire.write(temp);
      break;
    case CMD_LUMEN:
      lightReading  = analogRead(PIN_LUMEN);
      Wire.write(lightReading >> 8);
      Wire.write(lightReading % 0xFF);
      break;
    case CMD_PIN_ON:
    case CMD_PIN_OFF:
    case CMD_BEAT:
      Wire.write(status);
      status = ST_OK;
      break;
  }
  cmd = 0;
}

// called by interrupt service routine when incoming data arrives
void receiveCommand (int howMany) {
  cmd = Wire.read ();
  status = ST_OK;
  switch (cmd) {
    case CMD_PIN_ON:
      cmdPinOn();;
      break;
    case CMD_PIN_OFF:
      cmdPinOff();
      break;
    case CMD_BEAT:
      lastBeat = millis();
      break;
  }
}  // end of receiveEvent

void cmdPinOff() {
  if (Wire.available() != 1) {
    status = ST_BAD_LEN;
  } else {
    int pin = Wire.read();
    int i = searchPin(pin);
    if (i < 0) {
      status = ST_BAD_PIN;
    }
    else {
      pgma[i].off = 0;
      digitalWrite(pin, LOW);
    }
  }
}

int searchPin(int pin) {
  int i = pgmaSize - 1;
  while (i >= 0 && pgma[i].pin != pin) {
    i--;
  }
  return i;
}

/*
 * Programa el encendido y duracion del RESET.
 */
void resetPin() {
  if (digitalRead(PIN_RESET) == LOW) {
    unsigned long now = millis();

    int i = searchPin(PIN_RESET);

    pgma[i].off = now + RESET_LENGTH;
    lastBeat = now;
    digitalWrite(PIN_RESET, HIGH);
  }
}

void cmdPinOn() {
  if (Wire.available() != 2) {
    status = ST_BAD_LEN;
  } else {
    int pin = Wire.read();
    int len = Wire.read();

    int i = searchPin(pin);
    Serial.print("pin="); Serial.print(pin); Serial.print(",index="); Serial.println(i);
    if (i < 0) {
      status = ST_BAD_PIN;
      Serial.println("bad pin");
    } else {
      if (len == 0) {
        status = ST_TIME_0;
        Serial.println("ban len");
      }
      else {
        pgma[i].off = millis() + len * 1000;
        digitalWrite(pin, HIGH);
        Serial.println("ok");
      }
    }
  }
}

correction: an Arduino may be master OR slave.  A NodeMCU ESP8266 can only be master.

Using I2C (which i recommend over serial), you may not use a NodeMCU ESP8266 as a slave.  It can only function as master.  An Arduino, on the other hand, may be either.  Therefore, the Arduino will always be passive and the NodeMCU will be the master.
What you can do, is implement a semaphore (as described by Majenko here), where the Arduino signals that it has something to "say" to the master, causing the master to request from the Arduino.  It could, under these circumstances, be labeled an "obliging master" (neologism).
NEVER print to serial from inside requestEvent or receiveEvent.

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


text:
Multiway Relay Dimmer
I am looking for something like a multiway "relay dimmer".
Which lets me dim a light using an Arduino and a manual dimmer.

(The manual dimmer should work without any computer!)

The big black 'dimmer' symbol - are you intending to build this too? If so, what load is it driving - AC? DC? Mains (230V/110V)?

@CharlieHanson yes. It's a 230V

Then first look at how AC dimmers work. Using a triac as the dimming device (the simplest form) requires the controller (Arduino, rotary potentiometer, cycle-of-the-moon detector, etc.) to send a pulse at a specific time to the triac to make it conduct. Typically the power for each controller is drawn from the AC itself, so you'll have to consider this for your 'manual' controller, assuming the Arduino is powered via USB.

You could use a rotary encoder for that purpose!
Basically the rotary encoder is a knob that, for every "tick" you give it, it returns a different value to your Arduino. With a bit of programming you can sense the direction of the turn, if it is positive then you lighten up the LED, and vice versa.
I used that to control a RGB led, it works very well! here some more information on the rotary encoder and the code needed to use it.

But then the manual device would have to be connected to the Arduino and wouldn't work without it.. Right?

Yes, I was thinking that Arduino itself can act as your dimmer. Maybe I got your question wrong though, so you need the whole system to be able to work without an Arduino?

Correct - the Arduino is just a needed feature.. That's why I called it "multiway"

I don't quite understand this. You may or may not have the Arduino there? Why not? Will someone open up the wall plate and remove it? Is the general idea that you turn a knob if you want to manually change the lighting, but under Arduino control (eg. at night) the Arduino will dim the lights on its own?

I know this is somewhat redundant, but maybe you could create the dimmer with a smaller version of arduino (like a mini or so), that would be the "dimmer" of your block diagram. This would work on its own or connected to another Arduino using I2C or maybe something easier like TX/RX ports.

@NickGammon : correct. I chose this way in order to be save in case of an Arduino failure.

Yes ... but it shouldn't fail. I mean it might, but I've had light dimmers fail before, and they didn't have Arduinos in them.

I add another answer because I think I found something. After a few days searching on various sites that sell arduino stuff I found this http://www.dx.com/p/8-channel-5v-relay-module-extension-board-for-arduino-avr-arm-51-140703 that might be what you're looking for. One of the customers in the review states it can be used even without Arduino.
I know it's a relay, not a dimmer, but maybe you could add something to your circuit...


text:
Is Roboteq motor driver compatible with Arduino?
I'm planning use Roboteq motor driver for 24V brushed DC motor but I can't be sure that it's true or wrong. You know, Roboteq controller is too expensive and I don't want to spend money in vain. Have you any experience this controller? Are they compatible with Arduino?
http://www.roboteq.com/index.php/roboteq-products-and-services/brushed-dc-motor-controllers/mdc2230-detail  Roboteq Controller Link
I also think, Pololu RoboClaw driver. https://www.pololu.com/product/1499 I don't know is it enough for wheelchair. Because, I already have used Pololu VNH5019 and it is not enough. (synchronicity and noise problems etc.)
If you have any ideas, I will be glad. Thank you.

and i dont know this group suitable for this subject. If i wrong, correct me please.

This site is suitable for questions like this.

It is not directly supported. But the device description lists RS232 port that can be interfaced with an Arduino using a TTL to RS232 converter. The description also mentions "several Analog, Pulse and Digital I/Os which can be remapped as command or feedback inputs, limit switches, or many other functions" so it is totally possible to control the controller with an Arduino, but depending on the method you choose it may require some effort.


text:
Basic communication between Cotek and Arduino UNO
I am trying to get a reading from my Cotek through my Arduino and have it display on an LCD screen. When I run the code, though, nothing shows up. I am EXTREMELY new to using pretty much all this equipment so honestly, I have little to no idea what I'm doing. I am not sure if it is a wiring issue, an issue with the code or both. Any and all help is appreciated.
This is how the cotek is wired to the Arduino. The middle red wire (in the middle of the two resistors) is connected to AUX from the cotek. The two outer red wires are connected to the SDA and SCL of the cotek and their corresponding blue wires are connected to the SDA and SCL of the Arduino (the two resistors are 2KOhm pull-up resistors). The blue wire on the bottom is connected to the GRND of the cotek which is also connected to GRND of the Arduino.

This is my code using the I2C protocol:

#include <LiquidCrystal.h>
#include <Wire.h>

int analogPin = 5;
char address= 0;
int numBytes = 2;
char val = 0;
int debug = 5;
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {
  // put your main code here, to run repeatedly:
  Wire.requestFrom(address, numBytes);
  while(Wire.available())
  {
    val = Wire.read();
    Serial.print(val);
    lcd.setCursor(0,0);
    lcd.print(val);
  }
  //perform function to change val from hexadecimal to decimal number here
  delay(500);

I am pretty sure the LCD is wired correctly to the Arduino as I was able to communicate to it previously without using the Cotek. In any case, it doesn't matter as 'val' doesn't even appear on the serial monitor.
Again, any help would be appreciated. Thanks!

What's a Cotek?

Surely the Cotek does not use address 0? char address= 0; See my I2C page for a small scanner that will tell you the address of any I2C devices. This would also confirm that your wiring is OK.

Hi, thanks for the response. I tried running the code for the scanner and in my Serial monitor, all I got are random symbols that change each time I run it.