text:
Formatting of IP address via printf(...) family similar to Serial Object
I am trying to use an sprintf with an IP address and I am not sure why Serial.print() is able to convert an IP address to a reasonable humanly readable representation.
I mean, presumably it uses an overloaded function that detects what type the parameter is. I want to somehow leverage that functionality with printf or sprintf.
What I know:
IPAddress ip = WiFi.localIP();
Serial.println(ip);

works great and outputs "192.168.4.1".
char *buf = malloc(128);
sprintf(buf,"%s",String(ip).c_str());

generates buf as "17082560" which isn't wrong, but it's not the usual format for an IP address.
I could write a function to output it the way I want, but I figured there must be some relatively simple way to utilize the functionality that Serial.print() provides but somehow channel it to an sprintf() call. Or any other simple way to provide a formatted IP output would be appreciated.

Whereas KIIV's answer solves your problem, it does not address some very
interesting parts of your original question:

I am not sure why Serial.print() is able to convert IPAddress to a
reasonable human readable representation

This works thanks to a couple of abstract classes in the Arduino library
called Print and Printable. A Print object is anything that can
output text, like a serial port, a network connection or an LCD. A
Printable object is anything that can be converted to a text
representation and sent through a Print object.
From Print.h:
class Print
{
    // ...
    virtual size_t write(uint8_t) = 0;
    // ...
    size_t print(const String &);
    size_t print(const char[]);
    size_t print(unsigned int, int = DEC);
    size_t print(const Printable&);
    // ...
    size_t println(const String &s);
    // ...
};

In other words, in order to create a Print, you only have to implement
write(uint8_t), which should output a single character. Then you get
all the print() and println() methods.
From Printable.h:
class Printable
{
  public:
    virtual size_t printTo(Print& p) const = 0;
};

This means you can make any object Printable by implementing
printTo(Print&).
From IPAddress.h:
class IPAddress : public Printable {
    // ...
};

This means IPAddress objects are Printable: they know how to print
themselves into any Print. You can find the implementation of
IPAddress::printTo(Print&) at the end of
IPAddress.cpp.
Thus, to answer your question, Serial.print() does not really know how
to create a textual representation of the IPAddress, but IPAddress knows
how to send itself through Serial, or any other Print object.

I want to somehow leverage that functionality [...] there must be some
relatively simple way to utilize the functionality that Serial.print()
provides but somehow channel it to an sprintf() call.

The functionality is not provided by Serial.print(): it's the fact
that the IPAddress is Printable. In order to leverage that, you have to
create a Print object. You cannot use sprintf() for that, but you can
create a Print object which behaves like sprintf() and writes into a C
string:
// Write into a C string (a char array), a la sprintf().
// Warning: there is no check for buffer overflow.
class StringPrinter : public Print
{
public:
    StringPrinter(char *buffer) : buf(buffer), pos(0) {}
    virtual size_t write(uint8_t c)
    {
        buf[pos++] = c;  // add the character to the string
        buf[pos] = 0;    // null perminator
        return 1;        // one character written
    }
private:
    char *buf;
    size_t pos;
};

which could be used like this:
char buf[16];
StringPrinter(buf).print(ip);

For the sake of simplicity, I would generally prefer the straight
sprintf() solution. However, if you are short on flash, the code above
is likely to be smaller, as sprintf() is large and you are very likely
to be already using Print in your program.

Awesome information about the abstract classes. This is kind of what I was dying to know.

In short: hex(17082560) = 0x0104A8C0 where: 0x01 = 1, 0x04 = 4, 0xA8 = 168 and 0xC0 = 192. See the pattern? It's printed as a single uint32_t.
Of course endianness is reversed as platform is little endian but IP Adresses are in network byte order (big endian)
And because you didn't understand this answer, there is also whole code:
uint32_t ip = (uint32_t) WiFi.localIP();
sprintf(buf, "%u.%u.%u.%u", ip & 0xFF, (ip>>8) & 0xFF, (ip>>16) & 0xFF, (ip>>24) & 0xFF);

Maybe even better:
IPAddress ip = WiFi.localIP();
sprintf(buf, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);

yes, as I said, "which isn't wrong, but its not the usual format for an IP address". this doesn't answer my question. Thanks, though.

@Octopus: I hoped you'll figure this out by yourself. Anyway code added (untested)

right on. now i'm having one of those "why didn't i think of that" moments. perfect!

There is also a one-line solution just as you wish. Instead of String(ip) use ip.toString().
IPAddress ip = WiFi.localIP();
char *buf = malloc(128);
sprintf(buf, "%s", ip.toString().c_str());

Background: The function Serial.println(ip); calls Print::print(const Printable& x), which in turn calls IPAddress::printTo(Print& p).
size_t Print::print(const Printable& x) {
    return x.printTo(*this);
}

Alternatively, String IPAddress::toString() creates the desired string and reserves just the needed amount of memory (code from ESP8266 2.7.4)
String IPAddress::toString() const
{
    StreamString sstr;
#if LWIP_IPV6
    if (isV6())
        sstr.reserve(40); // 8 shorts x 4 chars each + 7 colons + nullterm
    else
#endif
        sstr.reserve(16); // 4 bytes with 3 chars max + 3 dots + nullterm, or '(IP unset)'
    printTo(sstr);
    return sstr;
}

"%u.%u.%u.%u", ip & 0xFF

instead of, should be
... "%u.%u.%u.%u", (ip>>0) & 0xFF,...


text:
Calling I2C functions inside an ISR
I have an Adafruit 2.8" cap touch display, which has an interrupt pin (IRQ). I tried to use this with my Arduino Nano, but encountered a problem:
When trying to get the touched point from the display during a display triggered interrupt, it would not work because the touch screen is connected via I2C and according to this post, it is not possible to call I2C functions inside an ISR on an Arduino. Therefore the IRQ pin does not make much sense to me, as I would have to poll if the screen is touched inside the main loop.
My question now is: is this a problem specific for the AtMega 328p? I am thinking about getting an ESP32 based board. Would it be possible to get the I2C data inside an ISR on this chip? Or is it just not possible at all?

Use the ISR to set a boolean value. Have the main program read this value, to see if it needs to fetch an update from the display.

@Gerben Though it is possible, I don't see much sense in doing this. I could as well just poll touch.istouched() via I2C directly, so I don't need the IRQ pin at all.

Using the IRQ is a a bit faster, as touch.istouched() requires I2C communication.

@Gerben as I wrote in the comment to ratchet's answer, what's the point of setting a boolean value in the ISR vs reading the pin in the loop? the only advantage is if the pin can stay high for a very short time, but this is not the case. So instead of calling an ISR to set a bool and then poll the bool in the loop, poll the pin in the loop.

@frarugi87 if that's the case, than, with this device, using interrupts doesn't have any benefits.

Here is an analogy for you to help you understand why using the IRQ is a good idea.
Imagine you are at a conference. There's hundreds of you in the audience, and you are in a question and answer session with the person on the stage. Maybe their presentation has just come to the end and they're fielding questions from the audience.
Lots of people have questions, and any member of the audience can raise their hand at any time to ask a question.
Now there's three ways of the presenter handling it.
The first way is your way of using an interrupt and responding to the interrupt within the interrupt handler itself.  This is like the presenter stopping what he is saying mid sentence to answer the new question. That's just nasty, and both confusing for the presenter and the audience.
The second way is for the presenter to continue until the current question has finished being answered, then pick someone at random from the sea of hands. While the question is being answered people are getting antsy waving their hands around to get noticed, and there's no guarantee that it will be first come first served. People may then not be paying attention to what is a good answer to an important question because they are fixated on theirs.  That's just the same as you polling the interrupt line, or polling the screen directly. If the interrupt line isn't active at the time you poll it you'll miss it.
The third, and best way, is if the presenter sees a hand go up while he's answering a question, and acknowledges that person with an "Ok, I'll come to you next.". Everyone else knows that waving their hand around is pointless, so don't bother - and the next question can be asked immediately after the current question has been answered. Everyone is happy.  That's the proper way of handling a system like this - when the interrupt triggers you remember "Ok, I'll come to that interrupt signal in a moment when I'm ready". Then in your loop, when you have the time, you act on the interrupt that you remembered earlier. You get to respond at your speed to a signal that you may otherwise have missed.
So to sum up: using an interrupt to remember that something is pending and then act on that remembered state is how you should use interrupts to manage communication.

Great answer! I love to use analogies myself and think I got it now :)

Well, in the third way there is no guarantee that first come is first served. Moreover it implies that when the presenter is mid sentence he stops, looks at the person with the raised hand, tells "yes, I noticed you, I'll answer you next" and then resumes from mid sentence. In my opinion your third way is applicable only n two cases. First is when "timid people" raise their hand for a brief moment and then lower it. If you are not fast enough to catch it then you may miss it. The second is if there is a very urgent task, and the person needs to be answered in a very quick time. In all the[...]

[...] other cases, IMHO, it is useless to stop the main operations to just notice that something happened; you can check it later. So, to sum up, interrupts are good if 1) the event is so short you may miss it between polls or 2) the event is so important it requires immediate reply. In this case, a human interaction lasts for at least some hundreds of ms, and requires a reply in almost the same time, which is eternity compared to the microcontroller speed. If you cannot guarantee one check every, let's say, 50ms you have problems in responsiveness that you have to solve regardless of ISRs

No analogy is ever perfect, that's why it's an analogy, not a similie. And in general most interrupt signals from peripherals come in 2 types: active until acknowledged, or a brief pulse. The former can be polled, the latter really requires an interrupt handler to catch it and latch it.

exactly .. :D +1

I started writing this as a comment, but the more I wrote the more I needed space to complete my thoughts, so here it is as answer.
In my opinion, reacting to a user interaction should NOT be put in ISR; consequently the best thing to do is to avoid the interrupt and poll that wire.
IMHO interrupts need to be used in very few cases, and only when the reactivity to a trigger is needed within (tenths of) microseconds. Whenever the latency can become greater than one millisecond it is much better to avoid the interrupt and all its problems, which are (not limited to)

the need for the microcontroller to save the context
interrupting other "tasks", which can be time critical (see for instance the timing in a software serial)
interrupts can happen any time (maybe in the middle of a write to a int variable)
variables shared between an interrupt and "normal" program cannot be optimized (should always be declared volatile)
ISRs must be as short as possible
usually you can't have multiple interrupts (you become blind to other interrupts, or they get delayed until your ISR is completed)

Point 1 delays your actions uselessly.
Point 2 will be a problem when trying to debug some strange problem in your communication or acquisition or software PWM or anything based on precise timing.
Point 4 implies that shared variables will always be read from memory rather than saved in register (and this will slow down your code)
Point 5 and 6 state that you cannot use long communication routines (serial, I2C, SPI, anything) inside the ISR.
These are common to all microcontrollers generally speaking, so my advice is don't use the interrupt, at least not in this case, since reacting to a user interaction is slow (even 50-100ms will not be noticeable). Poll the wire, then when you detect it ask the controller the position.

The better way to do it would be to set a volatile flag in the ISR and handle that in the main loop.
This relies on you making sure the main loop never blocks so the flag can be check often.
volatile bool isr_happened;

void isr(){
    isr_happened = true;
}

void loop(){
    if(isr_happened){
        //do i2c

        isr_happened = false;
    }

}

But then what's the point on having the ISR? Better to poll the pin periodically rather than polling the variable and have the ISR to block the normal code. This can be useful only when the pin can change very quickly, but a user interaction runs for at least 100ms, and moreover knowing that it was pressed but being unable to know where is useless, so I'd avoid the ISR as per my answer

The ISR can react to the change in the signal's level much more reliably than polling, since it is always checking, whereas polling checks periodically. Checking the state of a single pin, or a boolean variable, is far more efficient than repeatedly transferring chunks of I2C data. Use the ISR as a latch to store when the IRQ pin has changed, and use that latched value at a time that suits you, not the display, to read the coordinates.

source: Stack Exchange

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

sort: votes


text:
How to connect Arduino 5v pin with multiple things?
I am trying to connect a Bluetooth module and a gas sensor to Arduino.

Bluetooth module: HM-10
Gas sensor: MQ-2

I read the guides for the HM-10 and MQ-2 and they both need to use the Arduino's 5v pin. I did a lot of searching but I could not find a proper example.
I would like you to give me a link to an example that uses the 5v pin for multiple modules. It would be nice if the circuit configuration was included.

I read the guides for the HM-10 and MQ-2 and they both need to use the Arduino's 5v pin. I did a lot of searching but I could not find a proper example. do you envision it being much more complicated than wiring them, separately and individually, to the 5v pin? that's how it is normally done gazillion of times every day.

If you are trying to connect multiple things, you should first consider if it is appropriate to have their power passing through the Arduino at all.  Often it's better to give them their own routes to the power supply, and only share a common ground with the Arduino.  Additionally, the HM10 requires something like 3.3v NOT 5v.

5V is just 5V. It's not a signal, it's just a voltage level. If you need to connect multiple things to it then just connect multiple things to it. If that means connecting wires together then so be it.
Yes, you can use breadboards for it, but that's pretty wasteful if all you want to do is connect a few 5V wires together. It's simpler just to strip the ends and twist them together. Maybe add some tape to insulate them so you don't get accidental short circuits.

The simplest way is to just use a breadboard to connect your devices to your Arduino:

I can't read Chinese, so I can't check the specifications of these particular devices, but you need to be aware of the power limitations on your Arduino.
The maximum total current you can draw when the device is powered via external power supply is 1A for the Arduino Uno, 800mA for the Due and 500mA for the Nano. Check the specs for your board on the Arduino site.
Arduino-compatible devices may vary - check the specs for the device you're usiing.

Note: If you're not powering your board via USB, the total 5V current limit coming out of the Arduino is limited by the voltage regulator on your particular board, and/or your input power supply (whichever provides less power).

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


text:
How to read data from Arduino with Raspberry Pi via I2C?
I have connected a Raspberry Pi 2 model B to an Arduino Uno via Bi-Directional Level shifter, from this BLOG:
Raspberry pi    GND    ----------   GND     Arduino
                3.3v   ----------   5v
                SCL    ----------   A5
                SDA    ----------   A4

I hope my I2C connection is correct.
And my Arduino is connected to an 8-Channel relay board.
Now I have written code in which I can control the relay board with the Raspberry Pi. For example, if I Press '1', relay 1 goes high.
Now I want to send data back from the Arduino to the Raspberry Pi in order to cross-check if relay 1 is high or not. If relay 1 is high then it should send some data back to the Raspberry Pi.
My Raspberry Pi code is:
import smbus
import time
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

def writeNumber(value):
    bus.write_byte(address, value)
    # bus.write_byte_data(address, 0, value)
    return -1

def readNumber():
    number = bus.read_byte(address)
    # number = bus.read_byte_data(address, 1)
    return number

while True:
    var = input("")
    if not var:
        continue
    writeNumber(var)
    number = readNumber()

My Arduino code:
#include <Wire.h>

#define SLAVE_ADDRESS 0x04
#define RELAY1 9

int number = 0;
int state = 0;

void setup() {
    pinMode(RELAY1, OUTPUT);
    Serial.begin(9600); // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);
    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);
    Serial.println("Ready!");
}

void loop() {
    delay(100);
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
       number = Wire.read();
       Serial.print("data received: ");
       Serial.println(number);
        if (number == 1) {
            if (state == 0){
                digitalWrite(RELAY1, HIGH); // set the LED on
                state = 1;
            } else {
                digitalWrite(RELAY1, LOW); // set the LED off
                state = 0;
            }
        }
    }
}

// callback for sending data
void sendData(){
    Wire.write(number);
}

Now if I type 1, and due to some loose connection relay 1 doesn't go high, I want the Arduino to take data from the relay board and send it to the Raspberry Pi every time.
It will be great if someone can explain also that how it works.
Hope I was able to explain the problem. I have done lots of research but was not able to find some answer.
I am a beginner in Python so please help me.
Thanks in advance.

Character '1' is not number 1. Try "number == '1'.

That is not the question, The question is how to pass the value from digital pin of Arduino to rapsberry pi.

See my answer here about connecting I2C between a 3.3V device and a 5V device.

You might want to graduate to the pigpio library for the Pi side of this.
Here is where you can find examples of how it works.
here is a fun one that is like Wireshark - will show you the I2C traffic:
https://github.com/joan2937/pigpio/tree/master/EXAMPLES/C/I2C_SNIFFER
Here is the FAQ about I2C

Character '1' is not number 1. Try "number == '1'. – Mikael Patel Mar 9 '16 at 11:34


text:
Pause between switching motor direction
I'm new both to this forum and to Arduino. My robot is comprised of Arduino Uno with Arduino Motor Shield, 12V DC gear motor, and two limit switches. The robot supposed to move endlessly on rails between the two walls back-and-forth. I have it all wired up and am able to switch the directions of the motor's rotation by pushing the limit switches. However, I also want to have a pause between switching of directions:
... Robot moving forward ...
If front limit switch is pushed
Stop motor
Pause 2 seconds
Run motor CCW
... Robot moving backwards ...
If rear limit switch is pushed
Stop motor
Pause 2 seconds
Run motor CW
... Robot moving forward ...
Simple delay(2000) doesn't work as the limit switch remains pushed against the wall. I've been trying out millis() approach but the fact that limit switch remains pushed (HIGH) I can never produce a difference in time needed to trigger an action. I learned about State Machine but not sure if and how this could help my case?
Can anyone please help me in implementing a two second pause between the switching of the motor's direction?
Below is the code that momentarily switches the motor's direction when robot reaches the wall and limit switch is pushed.
int switchFront_State = 0;
int switchRear_State = 0;

const int ledYellow = 6;
const int ledGreen = 5;

const int switchFront = 4;
const int switchRear = 2;

const int motorDirection = 12;
const int motorBreak = 9;
const int motorPWM = 3;

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

  pinMode(switchFront, INPUT_PULLUP); // Front switch
  pinMode(switchRear, INPUT_PULLUP); // Rear switch

  pinMode(ledYellow, OUTPUT);
  pinMode(ledGreen, OUTPUT);

  // Setup Channel A
  pinMode(motorDirection, OUTPUT); // Motor direction pin
  pinMode(motorBreak, OUTPUT); // Motor break pin
  pinMode(motorPWM, OUTPUT); // Motor PWM pin
}

void runMotorBackward(){ // Motor moving backward
  digitalWrite(motorDirection, LOW);
  digitalWrite(motorBreak, LOW);
  digitalWrite(motorPWM, 128);
}

void motorStop(){ // Stop motor
  digitalWrite(motorBreak, HIGH);
  digitalWrite(motorPWM, 0);
}

void runMotorForward(){ // Motor moving forward
  digitalWrite(motorDirection, HIGH);
  digitalWrite(motorBreak, LOW);
  digitalWrite(motorPWM, 128);
}

void loop(){
  switchFront_State = digitalRead (switchFront);
  switchRear_State = digitalRead (switchRear);

  if (switchFront_State == HIGH){ // If front switch is pressed
    digitalWrite(ledYellow, HIGH); // Yellow LED
    motorStop();
    runMotorBackward();
    } else {
    digitalWrite(ledYellow, LOW);
  }

  if (switchRear_State == HIGH){ // If rear switch is pressed
    digitalWrite(ledGreen, HIGH); // Green LED
    motorStop();
    runMotorForward();
  } else {
    digitalWrite(ledGreen, LOW);
  }
}

Have you considered using a full state machine rather than just sensing the states of the switches?

I don't get why delay(2000) does work?

Gerben, delay(2000) works but it requires limit switch to be in LOW position in order for motor to run again. Originally, I tried placing delay(2000) between motorStop() and runMotorForward() / runMotorBackward() which worked but not in the useful way for me. In other words, the delay would be fired if the limit switch is pushed (HIGH) but the motor wouldn't start running again till the limit switch is released again (LOW).

Ignacio Vazquez-Abrams, I'm not sure what do you mean by "full state machine?" As I suggested, I'm new to Arduino and programming in general.

I think the problem is because there is no delay time after your motor switch its direction, so the robot is stay on position where the switch is pressed. I don't know if this gonna work, but perhaps you can add delay after the direction changed.
But based on your code, I can't find a condition to run if no switch is pressed. For alternative, you can try this
int direction_state = 1; //state where robot moves forward

void loop(){

  /*notes that here I assume while robot moving forward,
   *the rear switch is impossible to pressed, so does while
   *robot moving backward, the front switch is impossible to
   *pressed.
   */

  while ((digitalRead (switchRear)==LOW) && (digitalRead (switchFront)==LOW))
  //no switch pressed, loop will break if any switch pressed
    {
      if (direction_state == 1) runMotorForward(); else
                                runMotorBackward();
    }

  //indicator which switch is pressed and start of 2s motor stops
  if (direction_state==1) digitalWrite(ledYellow,HIGH);
  else digitalWrite(ledGreen,HIGH);

  motorStop(); //stop the motor
  delay(2000);

  //indicator 2s motor stops finished
  if (direction_state==1) digitalWrite(ledYellow,LOW); //indicator front switch is pressed
  else digitalWrite(ledGreen,LOW);

  direction_state = -direction_state //toggle the state
  if (direction_state == 1) runMotorForward(); else
                            runMotorBackward();

  delay(2000);

}

Feel free to ask if it's not works

Well, your suggestion above is exactly what doesn't work, adding i.e. delay(2000); after runMotorForward() / runMotorBackward() is not firing at all. Originally, I tried placing delay(2000) between motorStop() and runMotorForward() / runMotorBackward() which worked but not in the useful way for me. In other words, the delay would be fired if the limit switch is pushed (HIGH) but the motor wouldn't start running again till the limit switch is released again (LOW). As I described above, this is not an option as robot will get stuck first time it reaches a wall. The 2nd code doesn't have pause?

dpw, if you look at my code you'll realize that pressing on either limit switch (by hand) will set the robot in motion. I power the robot, it's not moving, then i press say the front limit switch and robot immediately starts to move backwards, hits the rear wall, changes the direction, runs towards the front wall, hits the front wall, changes the direction... endlessly, or as long as it is powered. All I want is that the robot pauses for two seconds when it hits the wall instead of just "bouncing" off of it.

Hi Dragan, I've edited the answers. Perhaps you can try it

Hi dpw, thank you sooooo very much for the corrected code. I uploaded it and it works EXACTLY the way I want!!! BTW, would it be possible to make switchRear to only switch motor to run forward and similarly that switchFront only switches motor to run backward. As of now, the directions could be confused if a "wrong" switch is pressed by accident.

Sure it can, you can modify the "while" condition. Happy I can help, and good luck to your project

Hello friends, something went wrong with my robot after I changed the motor. All of a sudden, the above code dhimaspw provided stopped working correctly!? On power up, the robot starts to run fwd for 2sec, stops for 2sec, starts to run rew for 2sec, etc??? It used to run till it receives a signal from one of the two limit switches. The circuit is untouched, except the new motor, which I find so confusing.

It would be better if you post another question, and put details about your motor there.

You need to make your switch logic edge sensitive rather than state sensitive. (That's the digital electronics term for it.) That means that you need to react to the change from switch off to switch on, not to the switch being on. (Since you're using INPUT_PULLUP mode, a switch on = LOW.
So:
In your loop, don't use
switchFront_State = digitalRead (switchFront);

instead, use code like below to detect a switch press:
int newSwitchState = digitalRead (switchFront);
if (newSwitchState == LOW && newSwitchState  != switchFront_State) {
    switchFront_State = newSwitchState;
    //Code to handle the limit switch being pressed
} else if (newSwitchState == HIGH && newSwitchState  != switchFront_State) {
    switchFront_State = newSwitchState;
    //Code to handle switch changing to the off state
}

You'll probably also need to use millis() to add some debouncing to your switch. (Ignore switch changes unless 10-20 milliseconds has passed, to avoid the switch jittering on and off when it is initially pressed or released.)

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


text:
Deep Sleep Reset with Shock Sensor
I am trying to design a circuit that wakes my ESP8266 (Wemos D1 Mini) from deep sleep using a shock sensor. I can achieve this using the reset pin but I need
it to ignore further requests to reset to give it time to run the code in my sketch. Provided there is still motion it will just continue to reset meaning the code only gets run after the 'shock' stops. I have tried all kinds of things with capacitors and transistors to delay subsequent resets but with very limited success. Can someone please point me in the right direction or suggest an easier way to do this? Many thanks in advance.

What kind of "shock" sensor, and what kind of "shocks" are you subjecting it to?

I'm using a ky-002 sensor. Shocks will be from slight movement.

Use the fact that GPIO16 is LOW in deepsleep and high otherwise - i.e. if GPIO16 is high, you want to prevent your shocks from effecting the reset pin - a simple OR gate may be all you need

@Tinted, why do you commet for JamesB?

This is actually somewhat more tricky than you would at first thing.
First off, the "shock sensor" is merely a spring inside a tube.  This will create lots of triggers while it's being "shocked", which really is messy.
Secondly, you only want those shocks to make it through to the ESP when you are in deep sleep.
Thirdly, you don't want whatever you connect to adversely affect, or be affected by, other circuitry that is connected to the reset pin.
So you first really need to "condition" the output of your sensor so that it gives a clean pulse that can reset the ESP8266. Then you need to "gate" that signal so it can only get through while the board is asleep.
For conditioning the shock sensor signal I would be inclined to use a 55 timer in monostable mode.  You can find a good circuit and description here which looks like this:

Now to gate that signal (which is active high) you need a signal to gate it with.  Since all the GPIOs of the ESP8266 are "dead" while it's asleep you need it to be in a "default on" state and have the ESP8266 drive an "I am awake" signal to disable the output.  So you'd have a pullup resistor on a GPIO to make it default HIGH (to match the trigger pulse for simplicity) and then use pinMode() and digitalWrite() as the first things after waking up (and at the start of setup()) to indicate it's awake by driving it LOW.  Then you combine those two signals:

If the trigger is HIGH and
If the gate signal is HIGH
Then pull reset LOW
Otherwise don't affect reset

So you make a truth table:
Trig | Gate | Res
-----------------
  L  |  L   |  HiZ
  L  |  H   |  HiZ
  H  |  L   |  HiZ
  H  |  H   |  L

The tricky one here is the "HiZ" - This means "High Impedance" - or in effect "Don't affect the reset pin at all".
Apart from that the truth table is that for a NAND gate - if both inputs are HIGH then the output is LOW - otherwise the output is HIGH.  Except we want HiZ not HIGH.
To make that HiZ there's two things you can do:

Use a NAND gate that has an "Open Collector" (or "Open Drain") output, or
Use an AND gate and create your own "Open Collector" that inverts the output by adding a transistor.

For option 1 you can use the 74AC01 which is a "Quad 2 input NAND gate Open Collector".  For option 2 you can use the 74AC08 and any NPN transistor (or N-channel MOSFET with a suitable threshold).

simulate this circuit – Schematic created using CircuitLab

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


text:
Joining several PIR sensors
I wish to use some PIR (HC-SR501) sensors and give some response if at least one of them detects human movements.
For simplicity I wish to use only one input pin in an Arduino UNO. My idea is to connect all the output wires into a single Arduino digital input. Should it work?
I am in doubt because the following two reasons:

The sensors must be far away from each other (about 5 sensors partially covering an area of about 200 m^2). That implies that wires are long and I do not know if this can have some adverse effect.
I do not know if it is bad to supply the 3.5V of some sensor that is currently detecting movement to the output of the sensors that are not detecting anything.

Thanks in advance

Don’t know about the first question but your second concern can be solved by a simple diode one each line to make sure current only goes one way.

The BISS0001 that your unit uses provides an "active high" output. To connect multiple devices together you just need to "OR" the signals.
There's many ways of doing that.
The simplest method is the "wired OR" circuit, which just involves one pulldown resistor plus one diode per device:

simulate this circuit – Schematic created using CircuitLab
You could also use a multiple-input OR gate chip. You can get these in 2- (74HC32), 3- (74HC4075), 4- (74HC4072) input versions.

Thank you! Could you comment why a resistor is needed and how to calculate its resistance as a function of the number of PIR employed?

The resistor is simply a pull-down. When all the inputs are LOW the diodes are reverse / not-at-all biased. When one goes high they become forward biased by the current through the diode and the resistor to ground. The value is pretty meaningless. The BISS0001 can source up to 10mA, so it wants to be larger than 500Ω. The number of PIR modules is irrelevant. If you have very long wires you might want to reduce the pull-down a little.

Thank you! I just read about pull-down. In practical terms, the resistor is needed to avoid false positives due to noise. Right?

It is needed to form part of the circuit. It's what provides the LOW when none of the PIRs are providing a HIGH.


text:
Voltage divider and NodeMCU inputs
Some sensors give as output a voltage between 0 and 5V. The analog inputs of the NodeMCU require voltages between 0 and 3.3V. I plan to make a voltage divider with two resistors like in this link for compatibility.
To provide the desired voltage the quotient of the values of the resistances is fixed (approx. 1/2 for this case). However, the absolute values of the resistances are not.
Q: How to choose those absolute values? Which are the criteria and why?
I have a good background in electromagnetism but I know very few about electronic Engineering.
I think that low values must work, e.g. 1Ω and 2Ω (and surely greater values). But I am unsure of VERY high resistance values because I suspect that there should be some current intensity requirements.
Thank you.

As @Majenko commented, the A0 input has a fixed voltage divider (see NodeMCU Schematics) that connects the A0 input to a 220kOhm resistor, then to the ADC pin of the ESP8266, then to ground via a 100kOhm resistor.

This effectively fixes the resistor values that can be used to scale the input of the NodeMCU. For a 0-5.0V input range (with sufficiently low impedance) you need to scale the ADC pin from 0-1.0V by adding a ~180kOhm resistor between the 5V output and the A0 input of the NodeMCU, creating a 400kOhm-> ADC -> 100kOhm divider like this:

simulate this circuit – Schematic created using CircuitLab

what are the trade-off with this compared to adding a parallel resistor between A0 and GND?

I don't think there are any trade-offs to be honest. You need to divide your 0-5.0V sensor output by 5 to create a 0-1.0V signal on the ADC pin of the ESP8266 and this is about the simplest and most efficient way to achieve that. The resistor values are sufficiently high as to create very little load on your sensor output. The only drawback I can think of is in the case of very high frequency signals.

For digital inputs, do I need to add two resistances, right?

Digital inputs dont’t have an internal voltage divider on the NodeMCU board and accept 3.3V input. To scale from 5V to 3.3V you need a divider 3/5 divider. For example:        5V Input->2.2kOhm->NodeMCU input->3.3kOhm->GND

To better understand voltage divider, one can look at this online calculator https://ohmslawcalculator.com/voltage-divider-calculator to see the actual formula and try the calculator to compute the unknown wanted.
It is not well publish the existing voltage divider on the NodeMCU, of course you need to browse the schematic to figure it out.
It goes the same with existing pullup resistor for some GPIO.
@Majenko your explanation is excellent!

The low end of the values is limited by how much current your sensor can provide. If you use 1Ω and 2Ω resistors in series then your sensor will need to provide 1.67A to create 5V across the divider. I doubt that your sensor can do that. For most sensors, you would want to use resistors in the kilohm or tens of kilohm range.
The high end is limited by the input impedance of the analog input pin. If your resistor values are large compared to this input impedance then the input impedance of the analog pin will affect how the voltage divider works. If the analog input is multiplexed and the ADC has a sample-and-hold at the input, then very large resistances in the divider will not allow the sampling capacitor to charge fast enough. For most ADC inputs, you would want to use resistors in the tens or hundreds of kilohms.

Thank you! There is still something that I do not get about low values: If the sensor works giving an output up to 5V when it is connected to an Arduino, and the sensor cannot provide 1.67A, it implies that there is already an enough large resistor in the Arduino board (or NodeMCU). Doesn't it? In such case, there should not be a problem using small resistances in the divisor. In other words, if the sensor can work with the board without any additional resistance, how can it be that adding resistances forces the sensor to provide greater currents? Excuse if it is a silly question. Thanks.

the less resistance in the divider, the more wasted heat and constant current consumption there is to deal with. Sure a 1ohm pair scales 5v into 2.5v, but it also wastes 2.5W of power and makes enough heat to fry 10 common resistors. If the sensor cannot supply those amps, it will drop the voltage or fry the sensor.

@user1420303 The problem is that the resistance of the divider is in parallel with the input resistance of the microcontroller, not in series. Putting resistances in parallel results in an equivalent resistance that is less than either of the original resistances. Very large currents will flow through your divider.

For ATMega based Arduinos the effective resistance seen by the ADC should not be higher than 10kohm for the reason you describe. Since it is the Thevenin resistance that is seen a two to 1 divider using 20kohm resistors would give 10k effective. In general use something between 1k and 10k.


text:
can i use bluetooth from a speaker as a bluetooth module?
i have a Bluetooth speakers that i don't want,and i was wondering if i can use its Bluetooth as a Bluetooth module to use it with Arduino.
if so how what pins should i use. here is a pin diagram for the module.

it is a bluetooth module ... you could monitor the state of the rx and tx pins

i don't know which pins to use

there is a pad labeled RXD1 and a pad labeled TXD1... use those ... see if the voltage on them changes

where did you get the pictures?

i got them from a Chinese pdf when i was looking for information

what other information was in the pdf?

https://drive.google.com/file/d/10mo3RCH8rkPNug8zLBfqPJ4xnyeFZ0ff/view?usp=sharing                           https://drive.google.com/file/d/1c6PKiCihaJIQ_E5oNBttr-Y1TXne45p2/view?usp=sharing  but they are chinese

In principle you can use it with an Arduino, though that really depends on what you want to do with it. You didn't explain that.

That is a common bluetooth audio receiver that has been used with Arduino in the past (I recall seeing a question here recently about controlling the volume of one with an Arduino), but only for audio separate to the Arduino. What do you think you might want to use it for? It receives audio and outputs it through its speaker pins. The main chip may be programmable, but good luck getting information on that, or a toolchain to do it.

I thinks those modules are for audio (A2DP) only. Do you want to use it to create a UART (Serial) connection over bluetooth?

You say "i was wondering if i can use its Bluetooth as a Bluetooth module to use it with Arduino." What do you want to do with it, exactly? Edit your question to be more specific. Play music over Bluetooth? (answer probably = yes.) Serial Bluetooth communications? (answer probably = no)

sorry for the late reply but this is all i wanted :D "Serial Bluetooth communications? (answer probably = no)". big thanks to everyone tryed to help

Bluetooth actually uses many different protocols to support many different Bluetooth applications.  For 2 channel good fidelity music with high latency and a very low bandwidth return only suitable for short infrequent commands like PAUSE and PLAY, most use A2DP or Advanced Audio Distribution Profile.
As most Arduino platforms use very low powered processors, good fidelity sound manipulation is not possible or is very difficult.  This only leaves the very low bandwidth return channel only suitable for short infrequent commands.  If you can imagine a use case for this channel it may be possible to use a low powered Arduino to send these PAUSE, PLAY, STOP type commands.
That said, you may want to buy a new well supported (in the Arduino community) Bluetooth module which uses the HID (Human Interface Device) protocol so you can build a keyboard for example or which uses the SPP (Serial Port Profile) protocol so you can build something that sends arbitrary data.
Added later...
I see in the diagram that there may be an "microphone in pin".  If true this hints that the module also supports the Bluetooth HFP (Hands Free Profile) protocol.  This is a lower fidelity 2 directional low latency audio channel with a very low bandwidth return only suitable for short infrequent commands like ANSWER and HANGUP.  Instead of music this is used to make phone calls.  This might be of more interest to Arduino project builders as this might be made into an intercom.


text:
How do I convert a program made on Notepad to my Arduino on Proteus
I had the Arduino IDE but I accidentally deleted it. I have no internet connection, so I could not download it again. I do not currently possess the Arduino hardware itself but I do have Proteus and the Arduino library in it.
So I want to program my Arduino. Previously I would simply write the sketch and compile it and go to where I compiled it and simply add it on my Proteus Arduino and run it. Since I don't have the Arduino IDE, I tried using Notepad and tried to save it as a .hex file and run it on Proteus and there was an error created saying Error reading hex file.
So how can I program my Arduino on Proteus with the given materials (Notepad, Proteus)? Can it be done? Or is there any other way?

If you don't have an Internet connection how did you post this question?

Download the IDE on your phone, then create a WiFi hotspot on your phone. Connect your PC to your phone wirelessly, then transfer the IDE from your phone to your computer.

Besides displaying source code and letting you edit it, the IDE uses avr-gcc (and half a dozen other avr- utilities, like avr-objcopy, avr-ar, avr-nm) to compile and link the code and convert it to an elf or hex form, then uses avrdude to download it.  Using proteus, you can get by without  avrdude, but not without a suitable compiler and linker.
If you have a micro-SD slot on your phone, perhaps you can download the IDE to a card and then move the card to your computer to install the IDE.


text:
Gboard 800 (SIM900 + ATmega 328)
Greetings dear reader!
I have some trouble storing my IMEI code inside a variable. It always returns an error: "void value not ignored as it ought to be".
Since then I tried to write it to the serial line by just running the gsm.SimpleWriteln("AT+GSN"); AT command, but I am stuck at storing this displayed value inside a variable. Does anyone here know a way to store a serial value into a variable? I just want to send the IMEI code as an identifier to the cloud application...
Thanks in advance, your response is really appreciated.
The code:
#include "SIM900.h"
#include <SoftwareSerial.h>
//#include "inetGSM.h"
//#include "sms.h"
//#include "call.h"

//To change pins for Software Serial, use the two lines in GSM.cpp.

//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.

//Simple sketch to communicate with SIM900 through AT commands.

//InetGSM inet;
//CallGSM call;
//SMSGSM sms;

int numdata;
char inSerial[40];
int i=0;
boolean startUp = false;

void setup() {
  Serial.begin(9600);
  Serial.println("GSM Shield testing.");

  //Start configuration of shield with baudrate.
  //For http uses it is recommended to use 4800 or slower.
  if (gsm.begin(9600)) {
    Serial.println("\nstatus=READY");
    getIMEI();
  } else Serial.println("\nstatus=IDLE");
};

void loop() {
  //Read for new byte on serial hardware,
  //and write them on NewSoftSerial.
  serialhwread();
  //Read for new byte on NewSoftSerial.
  serialswread();
};

void serialhwread() {
  i=0;
  if (Serial.available() > 0) {
    while (Serial.available() > 0) {
      inSerial[i]=(Serial.read());
      delay(10);
      i++;
    }
    inSerial[i]='\0';
    if(!strcmp(inSerial,"/END")) {
      Serial.println("_");
      inSerial[0]=0x1a;
      inSerial[1]='\0';
      gsm.SimpleWriteln(inSerial);
    }
    //Send a saved AT command using serial port.
    if(!strcmp(inSerial,"TEST")) {
      Serial.println("SIGNAL QUALITY");
      gsm.SimpleWriteln("AT+CSQ");
    } else {
      Serial.println(inSerial);
      gsm.SimpleWriteln(inSerial);
    }
    inSerial[0]='\0';
  }
}

void serialswread() {
  gsm.SimpleRead();
}

void getIMEI() {
  long IMEI = gsm.SimpleWriteln("AT+GSN"); // IMEI code
  Serial.println(IMEI);
  return IMEI
}

Can you maybe share your code?

Ofcourse but it is not complete yet, because I dont have a clue on what to do next;P

gsm does not name a type, probably because you did not create an gsm object. Something like: CallGSM gsm; should be at the top of your sketch (not in comment).

The SimpleWriteln() function just sends an instruction. It doesn't return anything.  Once you have sent the instruction to retrieve the IMEI you then have to actually read the IMEI.
However, fortunately, there is a function that does it for you:
char imei[20];
gsm.getIMEI(imei);

The IMEI should now be in the C string imei. What you do with it then is up to you.

Many thanks man!, but i still get an error. Namely: " 'gsm' does not name a type :\ i looked through all the documentation and couldnt find in the GSM.h library any function that contains .getIMEI() any other advice on tackeling this problem? thanks apreciate the support;)

Well, you're using gsm.* throughout your program - but it looks like you didn't bother to define it (or it's defined by the library but you have the wrong library?)

Yeah I think it is a library related problem to, because if I read the GSM library I don't see any word that contains the GSM.GetIMEI(). But I need this GSM library... so I can't easily swap them out. Do you have any advice on this? On how to make them both compatible within the same file?
I'm really grateful that you help me with this, because I was really  losing hope with this project;)

I was looking at the library linked to by the product page. Are you trying to use a different one? The other commands you use are in the library I was looking at...

I'm using the one they specified, maybe I have an old version I will try to update it, and try to work with the one they currently have on there site;) I will come back on this topic thanks!


text:
Does AWG size affect signal from sensors?
Would using a thicker cable like 16 AWG affect the signal being received from an RFID or Ultrasonic sensor?
I understand AWG can make a significant impact on voltage when a thick cable is used over a long distance. In my head signal data is delicate so a nice thin wire will ensure little disturbance....
Looked around and couldn't find a clear answer so hopefully someone can help!

you asked the same question twice ... yes, wire size does affect the signal ... whether the actual data is affected depends on the type of data, analog or digital ...... nice thin wire will ensure little disturbance most of the signal will be absorbed by the wire

I don't think thickness matters. The problem is that a long wire acts like an antenna, picking up external "noise", that can influence your signal. This is mostly an issue for analog signals, or really fast digital signals.

I use 30AWG wire for Arduino signals. I never had any problems with those wires. And to be precise I use silicon wires which are extremely flexible - perfect.

A signal is just a varying voltage.  A wire is just a (very long) small resistor.  The device reading the signal is just a current sink.
That's three terms there: voltage, resistance, and current. Three terms you should know are related by Ohm's Law.
Also, some simple rules:

The thinner the wire the bigger the resistance
The longer the wire the bigger the resistance
The more load on the wire the greater the current

And of course, that all means:

The greater the resistance or the greater the current, the greater the voltage drop across the wire.

If the voltage drop gets too great then the device receiving the signal won't be able to work out what it is.
But then of course a wire is also an antenna picking up all sorts of noise. The longer the wire the more noise it will pick up. And the thinner the wire the greater the resistance and the greater the resultant voltage drop, meaning the lower the noise margin and immunity.
So no, a thinner wire isn't better than a thicker wire. The exact opposite is true.

There are also things like it has some self inductance and capacitance which acts against changes. And of course there is signal crosstalk caused by it. Also there should be matching impedance on both ends, so there are no signal reflections.

Yes, but none of that really has anything much to do with the thickness of the wire. I could have gone into signalling methods, voltage levels, NRZ, differential signals, shielding, etc... but all that is outside of the scope. Maybe if the question was asked on the EE.SE, but not here.

True. Maybe skin effect, but it'll be on higher frequencies than low speed serial or pulses from ultrasonic sensor.

I'd put the last line in bold to make it easy on skimmers.

Of course at high frequencies the problem gets a lot more complicated. As you say, most of that doesn't have much to do with wire thickness, but I would make that the major point of the answer: "As long as your wire is thick enough to limit the voltage drop so that you have good signal to noise, wire thickness is much less important than a whole range of other factors: Inductance, capacitance, RF shielding, etc etc."


text:
Problem burning bootloader on ATmega328P using internal clock
I'm trying to burn the arduino bootloader onto my ATmega328P so it uses the internal clock. I followed the tutorial in this page but I'm getting this error.
avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

I tried placing a cap from reset to ground but it doesn't wort either.
Any idea on what might be wrong with my procedure?
Thanks
[EDIT]

I followed the procedure described at the bottom of the page linked (Minimal Circuit (Eliminating the External Clock)).
I used the bootloader in "breadboard-1-6-x.zip"
I am using the Arduino IDE v1.8.1

It isn't clear from question+webpage what your procedure is, or what you want to do.  What  “internal clock” do you mean?  The built-in 8 MHz RC oscillator ?  If so, please edit question to say so.  Also edit question to include a schematic of how you have things hooked up.  Do you have a USBasp to program the  ATmega328P system, or what?

I followed precisely the instructions listed on the link I provided. And yes it is the internal 8MHz RC oscillator

You could edit the question and say what your programmer is, what fuse settings, which bootloader.  Or just let people guess.

I though providing a link of the tutorial which answers all of your questions was enough, but I'll edit it out.

The link describes several different procedures, and I think the details of what all was done aren't clear

Ok, i'll edit it.

Step 5 of the "Minimal Circuit (Eliminating the External Clock)" says, "Once you've done this, you can burn the bootloader and upload programs onto your ATmega328 as described above."  Which of the two methods shown did you use?  What  what what programmer are you using?

I'm using Arduino as ISP

Please run my chip detector sketch and report the results (copy/paste).

As noted in 6v6gt's answer, if the ATmega328 has been set to use a crystal, thereafter a crystal (or an external oscillator) are required for programming, until the fuses have been set to use the internal RC oscillator.  Here are a few thoughts, unfortunately somewhat scattered, on the matter.
If you have a parallel programmer (that delivers high voltage to the Reset pin and uses 8-bit parallel data signalling) you can use it to reset the fuses, since with that programming mode the clock is irrelevant.
Also, USBasp programmers interact with Avrdude to generate a programming clock of some specified frequency,   100kHz by default, 8kHz with the “Slow Clock” jumper installed.  Also see § “Set the clock in software” within USBasp ICSP programmer quickstart guide at freetronics.com.au.  Unlike the Avrdude man page, that reference says the default programming frequency is 375kHz and says “Avrdude’s -B option allows you to set the programming clock speed from software”, while the man page says -B specifies bit clock period (in microseconds) for the JTAG interface or the ISP clock of the JTAG ICE only.  Anyhow, a USBasp can reprogram fuses away from the crystal setting if a crystal or external oscillator is used, without depending on serial port data rates.  I don't know for certain whether it will work without a crystal or oscillator.
Note, rather than “sharing” a crystal via wires from one board to another – a practice that will broadcast lots of RF noise and might not get the signal across anyway – you could instead write a program on one Arduino to toggle a pin at high frequency, and use that output as an external oscillator to drive one of the crystal pins on another chip.  For example, the program below should generate a 2.67 MHz square wave on pin PB0 of an Uno or a Nano.
void setup() {
  cli();    // Avoid timer interrupts
  pinMode (8, OUTPUT); // PB0 is pin 8 on Uno / Nano
  while (1) PINB = 1;
}
void loop() {}

In the ATmega328 data sheet, see §14.3.1, Alternate Functions of Port B, and Table 14-3, which lists PB7 as XTAL2 (Chip Clock Oscillator pin 2), and PB6 as XTAL1 (Chip Clock Oscillator pin 1 or External clock input), indicating external oscillator attaches to the PB6 pin.

I would cli() before the while, otherwise the timer interrupt would make long glitches.

After that, how I have to connect it. The pin PB0 of the "clock generator" board to XTAL1 or XTAL2?

@jagjordi, see last paragraph of edit

I did what you said (configured the UNO to output the clock, connect pin 8 to XTAL1 (PB6) but I still get the same error. Device signature keeps changing every time I try to burn the bootloader. Any ideas?

If your ATMEGA328P has already been used with a crystal or already has a bootloader on it, then the fuses will be set to expect a crystal oscillator. In this case, you must initially have a crystal & the associated 2 capacitors connected. Once you have succeeded in burning the bootloader (this process also sets the fuses) you can dispense with the crystal.

can I connect the ATmega Cristal pins to the arduino board?

According to this, it should be possible to share a crystal (or resonator in the case of most newer Arduino boards) : https://forum.arduino.cc/index.php?topic=78584.0

I tryed connecting to the board oscillator. Now it gives me this error:

avrdude: Device signature = 0x00ffff
avrdude: Expected signature for ATmega328P is 1E 95 0F
Double check chip, or use -F to override this check.

Also the device signature keeps changing every time I try to burn the bootloader. Does this mean the ATmega is broken?

authors: ปรีชา ตุ้มโท


text:
esp8266-12e Nodemcu 1.0 board not starting uploaded data sketch from Arduino IDE
I've uploaded a sketch from the Arduino IDE to my (Amica) esp8266-12e board with the sketch data upload tool (ESP8266FS). This goes without any errors or problems. However, the code is never executed, it's like that the code isn't even on the board, it does nothing. I've tried flashing the firmware several times but this does not help. Depending on the installed firmware I get different messages on the serial monitor such as
NodeMCU 0.9.5 build 20150318  powered by Lua 5.1.4
lua: cannot open init.lua

or
Ai-Thinker Technology Co.,Ltd.
invalid

So installing different kinds of firmware is not the problem here. What did I do wrong which causes the board to 'ignore' the uploaded data sketch?

It appears that you have not uploaded the Arduino Core Software to your ESP8266 device because you are getting messages from the LUA interpreter which is overwritten when you install the Arduino Core Software.
The pre-requisites for using ESP8266FS to load sketches are here: ESP8266FS


text:
Is My Motor Shield Broken?
So I am trying to work on a mini battle bot project. However, it has been a while since I have worked with my Arduino electronics. So I am going through and learning how to do each thing before putting it all together. So far I have learned how to use the IR remote and got that working. I got my brushless motor with esc working with the Arduino. Now I am trying to get my dc motors working for the wheel component. I am just trying to get one motor running from the motor shield as proof of concept essentially. So here is the run down.
I have 8xAA batteries in  series with each AA running at 1.5 volts for a total of 12 volts. I have verified this with my multimeter. The dc motors need 9-18 volts to run, so 12 should have it running. However, I will probably step that up to 18 volts for maximum power and run 4 dc motors since I am guessing my project will be a little heavy, so I need as much power as possible. I have the 8xAA batteries connected correctly with positive to the positive and negative to negative on the motor shield. I have checked my soldering connection and the pins are not bent and it looks straight and good. I made sure I firmly pressed down to get it onto the Arduino. Motor is connected to m2 as per the code. I don't understand why this isn't working as it should work. I have tried using this form: Why is my Adafruit motor shield not spinning my motors?
And that did not solve it. I originally was using a 9 volt battery but that form told me to use more than 9 volts and to use AA batteries, so I did that. I also checked my connections and made sure soldering is good. Here is my code:
#include <AFMotor.h>

// DC motor on M2
AF_DCMotor motor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor party!");

  // turn on motor #2
  motor.setSpeed(200);
  motor.run(RELEASE);
}

int i;

// Test the DC motor
void loop() {
  motor.run(FORWARD);
}

I have connected my motor to the battery directly and motor runs just fine. I have checked the voltage of my battery and it is great, not below the 12 volts and not above 13 volts. I have opened up serial monitor and I do see 'motor party' so I know the code is running. I looked for errors down below and saw none. The port I have checked and it is correct. Motor shield is made by Adafruit. I do have the correct library installed, in fact I just installed it today so I have up to date library. The lights on the Arduino light up and the light indicating power on the motor shield also light up when my AA batteries are plugged in. When I plug it in, lights light up but motor doesn't run. Here are a few pictures.
https://i.sstatic.net/cSo3x.jpg
I am have a hard time figuring this out, so if anyone can help me, thanks in advance.

I would double check the wiring.  The motor controller is pretty tough.  Most likely you would know if you blew it up.  Is there a drive enable light on the motor shield?  Does it come on?  If not, try replacing with motor drive with an LED or measure the pin with a meter.

I have tripled checked the wiring, it is all good as you can see in the picture. About the drive enable light, I see a "power" led that does light up when the AA batteries are connected to it. Other than that, I do not see one. For measuring the pin, do you mean measure m2 on the shield? If so, I have tried that but my multimeter reads 0 when set to 20 volts DC. Partially why I think it is broken, but I never seen any smoke or anything to really tell me that I 'blew it up.'

I just added 2 more pictures to the end, via the site I gave. These show it plugged in as well as a close up while plugged in.

I haven't used this board but it does look pretty nice.  I found tech info on it here it uses a couple of 6612 dual h-bridges.  It looks like each motor uses a PWM (speed) signal and two directional control signals which look generated on board and controlled over SPI

This AF Documentation uses different commands.

So what you said actually made it work, so my problem was the wrong library and wrong code, the code I used was for the old library. I see that the code uses OOP programming now, so I am assuming I need to create a new object for each motor right? Anyways, I would like to give you the credit since even jDAQ said it was noted by you. So give an answer and I can give you the check mark.

Oh, I see with the documentation, it just said I can give it another name and initialize it with a different motor, so I don't need to create an entirely new object.

The commands you are using don't match the ones listed for this board.  Here is the AF Documentation for the Motor Shield Board V2.
Try
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *motor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor party!");

  // turn on motor #2
  AFMS.begin();
}

int i;

// Test the DC motor
void loop() {
  motor->run(FORWARD);
}

Note: In this library, getMotor() returns creates a pointer; so, you have to use "->" rather and "." to access the motor run() method.

As noted by markshancock, you are using an older version of the Adrafruit Motor Shield library meant for the version 1 of the board (you have the version 2.3), and according to their forum they are not compatible (they use different communication protocols) use the newer version of the library https://forums.adafruit.com/viewtopic.php?f=31&p=276888

So yes a new library and different code did the trick. It now works, however, I want to give the right person credit here which you said "as noted by markshancock" so I will give him the credit if he posts an answer, if not then I will give you the thumbs up and check mark. I do see that this new code uses OOP so I assume I have to create a new object for each motor?

Oh, I see with the documentation, it just said I can give it another name and initialize it with a different motor, so I don't need to create an entirely new object.

Thanks @BobG.
Glad to hear that was the issue.  I added an answer as you requested :)


text:
Can we use yx5300 to play audio from a file in Arduino?
I want to play a file that I have in my USB device through a yx5300 mp3 module.
I have a file in my USB device at path Music/hello.mp3. I want to play this file using the yx5300 module or some other module, if available.
I have already read this file using a shield. I want to pass the data to the yx5300.

No. That chip can only play files on an SD card that is directly attached to it.

So what else can I use..??

The Itead music player shield (https://www.itead.cc/wiki/ITEAD_Music_Player_Shield) may be of use. It can play direct from a USB memory stick.

This shield is unavailable ...Can you tell any other or where to buy....

No better than Google can.

https://github.com/Seeed-Studio/Music_Shield?files=1.  Can this library for music shield provided by seed used with any other music shield


text:
Receiving serial data in groups instead of individually
I have two different Vernier science probes connected to a Vernier shield that connects to an Arduino Uno. I have the Uno connected to an ESP8266 via the Tx.
Here is my Uno code:
String sensor1 ="Conductivity Probe ";
float interceptSensor1 = 0.0;
float slopeSensor1 = 960;
String sensor2 ="pH Probe ";
float interceptSensor2 = 13.720;
float slopeSensor2 = -3.838;
int timeBetweenReadings = 2000; // in ms

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

void loop() {
  float analogSensor1 = analogRead(A0);
  float voltageSensor1 = analogSensor1 / 1023 * 5.0;
  // convert from count to raw voltage
  float sensor1Reading= interceptSensor1 + voltageSensor1 * slopeSensor1;
  //converts voltage to sensor reading
  String sensor1Output = sensor1 + sensor1Reading;
  Serial.println(sensor1Output);
  delay(timeBetweenReadings);
  // delay in between reads for stability
  float analogSensor2 = analogRead(A1);
  float voltageSensor2 = analogSensor2 / 1023 * 5.0;
  // convert from count to raw voltage
  float sensor2Reading= interceptSensor2 + voltageSensor2 * slopeSensor2; //converts voltage to sensor reading
  String sensor2Output = sensor2 + sensor2Reading;
  Serial.println(sensor2Output);
  delay(timeBetweenReadings);
  // delay in between reads for stability
}

On the serial monitor every two seconds I get one line of output and it alternates back and forth between the sensors:
Conductivity Probe 807.04

pH Probe 4.12

Conductivity Probe 802.35

pH Probe 4.13

Conductivity Probe 802.35

pH Probe 4.12

Since I've only got a simple serial line to work with but I need to send multiple, different types of data to the ESP8266, my strategy is to send one line (ex. Conductivity Probe 807.04) and use logic on the ESP8226 to parse the string, isolate the float number (807.04), and  use Conductivity Probe to determine how that number gets further used (in my case, to publish to an MQTT feed called ElectroConductivity).
The Tx of the Uno + sensors is wired to the Rx of the ESP8266, and here's the ESP8266 code:
  while (Serial.available() == 0) {
  }
  sensorReading = Serial.readString();
  Serial.println(sensorReading);

The data comes in large groups instead of line by line:
pH Probe 4.12
Conductivity Probe 807.04
pH Probe 4.12
Conductivity Probe 807.04

I'm new to serial comms and Arduino in general. I'm guessing that there's an issue with how serial is read by the ESP8266.
EDIT
When I use sensorReading = Serial.readStringUntil('\n'); instead my output looks like this:
Conductivity PrpH Probe 4.12

Conductivity Probe 816.42

pH Probe 4.12

Conductivity Probe 825.8Conductivity Probe 821.11

Conductivity Probe 821.11

pH Probe pH Probe 4.12

ConductivitypH Probe 4.12

The question is why is he getting the data at the other end of the serial link in blocks rather than line by line.

readString() will keep reading until it times out. Instead try readStringUntil('\n') to read until you get a new line character.

Thanks! That seemed to have done it. BTW, it's \n, not /n. Was getting conductivity cut off when using the former, haha. So readString() will just read as much as it can before timeout? I never explicitly set a timeout for readString(), so I'm assuming that if it's not explicitly set then there's a default of like 4 seconds or something?

Bah, it didn't work. Please see updated post.

@user3135509 oops. Fixed the \ Vs / typo. That new behavior is weird, it's almost as if something isn't keeping up and the serial receive buffer is overflowing between loops. Do you have a lot of other code in the loop or is it just reading and printing for now? At this point I'd be tempted to read the incoming serial data byte by byte rather than using the readString functions, that way you gain a lot of flexibility and can ignore any timeout related issues.

On the Uno side, everything you see in the OP is what's in the loop. On the receiving side of the ESP8266, there are other things in the loop, such as setting up MQTT subscriptions and publications. So, uh, having other code running in the loop() function, code that's unrelated to serial, would cause the serial buffer to overflow?

@user3135509 it depends on how long the other stuff takes and how fast the serial data is coming in. It looks like you have 2 seconds between lines so that should be plenty of time, as a sanity check maybe comment the other stuff out and see if it starts working or not.


text:
Insert Variables In AT commandes
I'am trying to apply USSD operation with variable codes, for example this piece of code return my account balance:
             gsm.SimpleWriteln("AT+CUSD=1,\"*100#\"");

i want to change "*100#" to variable so gsm.SimpleWrite uses what the variable contains. I want to find how to make it work like this:
             gsm.SimpleWriteln("AT+CUSD=1,\"Variable\"");

EDIT: here is my code to give you a better view. it return balance in serial monitor.
#include "SIM900.h"

  void setup()
    {
   Serial.begin(9600);
    Serial.println("GSM Shield testing.");
       if (gsm.begin(9600))
            Serial.println("\nstatus=READY");
      else Serial.println("\nstatus=IDLE");

         gsm.SimpleWriteln("AT+CUSD=1,\"*100#\"");
      delay(10000);
             char msg[200];
             gsm.read(msg, 200);
            Serial.print("resp: ");
            Serial.println(msg);
 }
    void loop()
     {

    }

What kind of variable? And what library has the SimpleWriteln method?

im using SIM900.h. for example var1 = *100# and var2 = *122# i want to applied it like that.

gsm.SimpleWriteln is different from serial.print in many ways, including syntax.

I cannot find which "SIM900.h" library you are using - none of the ones I found have "SimpleWriteln" in them, so this is pure assumption about what functions and overloads may be available.
Just split your string into chunks, like you would with any serial device:
gsm.SimpleWrite("AT+CUSD=1,\"");
gsm.SimpleWrite(command);
gsm.SimpleWriteln("\"");

Where command is a suitable container for your data - say const char *.

check the post i added the code, and i tried what u said, it returns error. Sim900.h lib located at: Arduino\libraries\SIM908IDE100. i think its with th  default libs.

You must have installed that library. That means you must have downloaded it from somewhere. That means you must surely know where you downloaded it from. Unless you can tell us that we can't help you further.

I think I have found a copy online, though I can't be sure. It looks like the library hasn't been well written - it doesn't support the F() macro (which is kind of stupid really). I shall remove those from my code example.

any other suggestions to make a USSD operation?

Does my example not do what you want?

it returns Error. which means wrong syntax in AT manuel

Did you mistakenly use SimpleWriteln instead of SimpleWrite ?

it worked! thank you. i just define command as char* , like this.  char *command

authors: Дмитро Жигалкін


text:
Is there any chance of fixing it?
I am new to arduino and robotic stuffs and I thought it would be a good idea to test circuits on my breadboard using arduino's R3 5V pin as power supply. The accident happened when I short circuited the things on the breadboard and after a while arduino gave off a nasty smell. The only part overheated on arduino was the left side of the micro-controller. After that I cant upload nor run code on arduino.
After I explained you my situation, can you imagine a potential problem?(e.g I mean is it a voltage regultor problem, a micro-controller faillure, both of them, or something else?)
Can I fix it?
(#1 - I know arduino boards are cheap. I just want to know if I can do anything        with that.
#2 - No comments about  the accident accepted.)
Thank's in advance.
Regarding the image, my vendor claims the arduino to be an exact copy of "open-source" arduino R3

Comments are not for extended discussion; this conversation has been moved to chat.

Can I fix it?

If your power supply still works, there's a decent chance you can repair the board by replacing its microcontroller which is conveniently socketed.

Can I fix it?

it depends on your skills and the nature of the problem and how far you are willing to go to fix it.
I would first try to rule out a supply problem - very rarely a mcu will burn to the extent of giving off smells / overheat. So unplug the mcu and use a multimeter to measure its Vcc vs. GND pin voltage, test trace continuity, etc.
after that, plug in a new / known good chip and see if you could upload code to it.


text:
Power bank turns off spontaneously
I currently have a 50,000 mAH USB power bank powering my Arduino Uno and micro servomotor. Unfortunately, my power bank has an automatic shutoff and shuts off after 2 hrs of runtime (I need 16 hrs for my project). I can restart the power bank by hitting the on button and it will run just fine for another 1-2 hrs at which point it will shut off. In one instance, the power bank ran for the desired 16 hrs straight hours. I believe that my arduino/servo are very close to the current threshold of the bank which could explain some of the variability I am seeing in terms of turn-off time. Would hooking up a resistor in the circuit do the trick and if so where?
Not quite sure about the brand of power bank (just one I found off Ebay). I believe the arduino uno and servo consume about 60 mA for power.

This might be too vague to answer.  Perhaps  edit question to specify brand and model of  power bank and tell how much current is drawn on average by Uno and servo.

50,000 mAH for a USB power bank sounds extremely well specified. Some powerbanks shut off after detecting a period of low current consumption. There are tricks to periodically shunt a low value resistor across it, say with a timer, to create sufficient load to keep the powerbank 'alive'. A powerbank I have (much smaller than yours) requires a 47 Ohm resistor shunted across it every 2 seconds for 20 mS to suppress its auto shutoff.

I have a "50000mAh" power bank. By my estimation, and looking at what could actually physically fit in (I haven't torn it down yet), you can expect 8 18650 batteries at no more than 3600mAh each, totalling 28800mAh - probably less, since cheaper batteries used in cheap power banks have less capacity than the top of the range expensive ones.

once it shuts down automatically, how do you turn it back on? if it's by replugging, you can simulate that electronically with a relay or mosfet.

@LookAlterno Yes I know, I subscribe to the bear's channel already. Chinese stuff is fine if you know what to look out for and what pitfalls to expect. Rule 1: ignore the quoted specifications. Rule 2: Buy one and dismantle it to find out exactly what it is. Rule 3: tell others.

@LookAlterno Btw, the power bank to which I refer I actually find really good. It's about 6200mAh and works really nicely. I have had to reattach some of the USB sockets to the circuit board where I have broken them off, but apart from that it's really nice.

This is not a recommendation! This is just my own observation.
I found that this type of cheap power banks works great with low current applications like powering an Arduino UNO: https://www.aliexpress.com/item/32845722067.html

You have a couple of options, depending on how much you want to dive into electronics.

Find/buy a new powerbank that does not auto-shutoff
Find the current-sense resistor on the internal circuitry of your existing powerbank and change it out so that the device always thinks there is current flowing, or is more sensitive to your low-draw attachment. I was able to find a few websites describing this for specific powerbanks by searching.
Add a dummy load in parallel with your circuit, which wastes power, but does trick the powerbank into staying on.

It's also worth noting on the side, that you very likely do not have 50,000 mAh capacity in this powerbank, as others have noted. However, you ought to be able to get 16h of runtime with even a lower-rated powerbank if your claim of 60mA current draw is true.

Thank you jose! Yes, I am very skeptical about the "50,000 mAh" but suffice it to say I have never completely drained the power bank so it is likely in the five digit range.

Generally the mAh number they quote is the internal battery capacity. They have to step that up from 3.7 V (nominal) to 5V and will be using the cheapest possible supply to do that because they can without impacting the numbers on the spec. Which means you'll be looking at about 60-65% of the headline number in terms of mAh delivered to the USB output.

@Andrew: i would think a fixed-output boost converter would be more efficient than 60%; even adjustable ones (not optimized) are typically >80% worst-case. The fact that the case is not 35% as hot as the watts out says so too...

@dandavis I was assuming about 85% for the power supply. The rest is the inherent current capacity loss when converting voltages. 1000 mAh at 3.7 V = 740 mAh at 5 V assuming 100% efficiency.

@Andrew: true. you also can't get more than 80% or so out of the cell; buyer beware.

I can't see this helping.
It could only help if your power bank switched off its output when the current  drawn dropped too low - but unless your  circuit's current consumption drops after two hours, which you don't mention, that is unlikely to be the reason it's switching off.

Thanks Mark! I cannot say for certain whether or not my current consumption decreases with time. The powerbank sometimes will shut off 15 min after it has been turned. And in some lucky cases stays on for 16 hrs straight. I believe that whatever current threshold my powerbank has my servo/arduino are right at the tipping point.

Expanding @jose can u c first suggestion I did a little research and found that Voltaic Systems sells power banks with an option to disable auto-shutoff mode. There may be others. I found two of their power banks offered on Amazon. The blurb in the Amazon listing explicitly mentions using it with Arduino and Raspberry Pi.

As the company Voltaic has been mentioned I feel that it would be helpful if I warned you of that company. We are after all trying to offer solutions and if you follow the advice of the person who suggested Voltaic then I know from first hand experience that the thing turns itself off even when the auto shutdown mode is disabled. Though this may not be an end solution I know that by helping you to avoid useless information I can keep you on track and help you towards your solution. In detail : I'm a chauffeur and I bought a Voltaic for this specific reason and guess what? It switches off even when auto shutoff mode is disabled. I wanted my customers to be able to charge their devices as quick as poss and with as little complication as poss. I'm thinkin bout puttin a led fibre optic charging cable in so there is always a tiny power usage from the LED near the big USB jack. At least then also the cable wld be more 'look at me, look at me' I'm thinkin the problem comes either from an auto time out or from the completion of the charging of the power bank which is itself on a dribble charge from the car's electrics.

Look into the OmniCharge for that: https://www.omnicharge.co/ It won't let you down. You could even feed a SLA battery with this device if it's drained and can't start your car.

Could you please clarify a bit more how this would solve asker's problem?


text:
Issue regarding executing sketch code when not connected to USB
`I have an Arduino Uno A000066 Board R3 that has an Arduino A000079 Motor Shield Rev3 attached to it. Also I have connected two DC Servo Motors to the Motor Shield and wrote the following sequence:
 void setup()
    {
      //Setup Channel A
      pinMode(12, OUTPUT);     //Initiates Motor Channel A pin
      pinMode(9, OUTPUT);      //Initiates Brake Channel A pin

      //Setup Channel B
      pinMode(13, OUTPUT);     //Initiates Motor Channel A pin
      pinMode(8, OUTPUT);      //Initiates Brake Channel A pin
    }

    void loop()
    {
      //Phase 1 - going to the wall
      //Motor A forward - Max Speed
      digitalWrite(12, LOW);   //Establishes forward direction of Channel A
      digitalWrite(9, LOW);    //Disengage the Brake for Channel A
      analogWrite(3, 255);     //Spins the motor on Channel A at max speed

      //Motor B forward - Max Speed
      digitalWrite(13, HIGH);  //Establishes forward direction of Channel B
      digitalWrite(8, LOW);    //Disengage the Brake for Channel B
      analogWrite(11, 255);    //Spins the motor on Channel B at max speed

      delay(4000); // Adjust to correspond the distance

  //Phase 2 - getting back to initial point
  //Motor A backward - max speed
  digitalWrite(12, HIGH);  //Establishes backward direction of Channel A
  digitalWrite(9, LOW);    //Disengage the Brake for Channel A
  analogWrite(3, 255);     //Spins the motor on Channel A at max speed

  //Motor B backward - max speed
  digitalWrite(13, LOW);   //Establishes backward direction of Channel B
  digitalWrite(8, LOW);    //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at max speed

  delay(4000);

  //Phase 3 Stop for 7.5 seconds
  // Motor A stop
  digitalWrite(9, HIGH);   //Engage the Brake for Channel A
    //Motor B stop
  digitalWrite(8, HIGH);   //Engage the Brake for Channel B
  delay(7500);

  //Phase 4 Go to second point
  //Motor A forward - max speed
  digitalWrite(12, LOW);  //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);    //Spins the motor on Channel A at full speed

  //Motor B forward - max speed
  digitalWrite(13, HIGH);  //Establishes foward direction of Channel B
  digitalWrite(8, LOW);    //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at half speed

  delay(2000); // Adjust to correspond the distance

  //Phase 5 Final Stop
  //Motor A - stop
  digitalWrite(9, HIGH);   //Engage the brake for Channel A
  //Motor B - stop
  digitalWrite(8, HIGH);   //Engage the brake for Channel B

  delay(60000);        // 1 minute stop
}

While connected to USB, the device executes perfectly the sequence. As soon I run the sequence using the DC Source, the device does not respect any part of the coding. It started simply going forward while reversing the polarity randomly blocking the movement sometimes.
Looking forward to your suggestions.

What is your power source?

If that stuff in the question is code, mark it as such.  Click edit, and in the edit box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. To highlight text click-drag across it or use the arrow keys while holding the shift key.  ¶   While colorful, the phrase “the device does not respect any part of the coding” does not have a well-defined or specific meaning that imparts any information about what actually happened.  You could edit your question and tell what happens.

Is your "DC Source" a 9V battery, or what?  A stack of coin cells?  Some AAA batteries?  (Typically, none of those are good enough to keep the Arduino from resetting when the motors turn on.)


text:
Is the A6 module broken?
Hi recently I've could send some messages with the A6 GSM module, which uses AT commands. To switch on the board, you need to press the power button about 4 seconds or connecting the VCC pin to the PWR pin to avoid manual switching on. In this Andreas Spiess' video (minute 2:21), he recommends reset the device to give to the board a defined state. I had not done this until the device didn't work properly with some scripts. To reset it, he advises to reset the modoule. Its RST pin needs 0.70 mA and works at low level. In addition, the Arduino can not provide that current with a single pin so he uses a N-channel MOSFET (3055) to reset the board.
In my case I used a transistor (I don't know if it's NPN or PNP) and I connected the circuit like in his video. It worked! But it given strange results to the serial monitor  (yes, I set the baud rate correctly). After reset the board it switched on automatically because it was connected the PWR pin and VCC pin. The mistery occured when I unplugged the board (even its current) and then I reconnected it again. Since that moment it doesn't work, it doesn't switch on its LED to show you that the board is working. So, can anyone explain me why the 3055 it's neccesary to reset the board? Can it be done using Ohm's Law, a digital pin and a big resistance to give to the board the 70 mA?
Thanks!

try use program "at command tester" with ftdi for example, it works in my case but the the free license only works to 30 days.

Its RST pin needs 0.70 mA and works at low level. It is 0.70 mA or 70 mA as you mention later on?

I come across this problem too..based on what you said, i think it works like this:
The parameter you are looking for is power rating.. Arduino digital pin can only tolerate some amount of current, and im guessing it is less than 70mA..if you still do that, it is possible to damage that pin..since you want a LOW level for trigger, you can connect that RST manually to GND.. GND is also 0V just like the DIGITAL LOW, but it has no internal circuitry as of digital pin - meaning that you can sink a lot more current to GND..
If you want to be on the safe side, connect a limiting resistor(use ohm law for value), and also take note on the resistor power rating..