text:
Can SoftwareSerial be used in an ESP01
I am using ESP01 as a microcontroller that retrieves information from Firebase and sends them over serial to an Arduino Uno for other uses. I am not using NODEMcu since it has few analog pins and ESP01 is the only option available for me at this time.
Can the GPIO 0 and GPIO 2 pins available in the ESP01 be used as a serial communication pins when defined with SoftwareSerial library?
I want to keep the serial from the existing TX and RX for debugging and testing.

EspSoftwareSerial

Check your other post I answered it there. The ESP01 has 2 serial channels.

I am also interested in your reply.  Please give a reference to your other post.


text:
Hand position sensor
What is the simplest way to get an alarm sound when a human raise hands up.
Assuming he is wearing a sensor or whatever as a watch or ring.

tilt sensor .......

A tilt sensor, can be used as what you are trying to say, whenever someone (who wore it) raise his hand or move it, will trigger an alarm.
If you want to carry your alarm with you then...
You can use arduino nano or micro with a sensor and buzzer connected to it to just place it in gloves or watches etc.

source: Stack Exchange

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

sort: votes


text:
How do i improve this Code? (or how to pass a Char String into a Function to behave like a Variable)
Sorry i am a beginner and amateur when it comes to coding, can somebody help me to make the code inside the loop() less "monkey-like" by using a proper function?
I have tried a lot and at some point i am running out of ideas about how to even phrase the question on google.
My main problem when writing a function for this case is that i don't know how to pass a variable into a function which has to be written out as part of a Variable but also as part of Char Strings if that makes sense.
If you look at the code inside the loop() i actually only had to pass the number to the function, like "3" to change some Variables and Char Strings accordingly. I would be able to solve the issue with those Char Strings but i am completely clueless how to handle the Variable (rmd3, rmd4...).
"3" as in:
Variable:        rmd3,    Char String      "rmd3 = 1",   Variable Value:  rotary_mode = 3   and Char String:     "rotary_mode = 3"
This is a simplified version of my code but boils down to where i am stuck at. It refers to a rotary selector i am using which has 6 Positions (rmd1 - rmd6). However if i knew how to solve this issue i could use it in many other situations as well.

Bounce rmd3 = Bounce(45,10);    //rotary selector on pos.3
Bounce rmd4 = Bounce(44,10);    //rotary selector on pos.4
int rotary_mode = 0;            //Rotary Mode

void setup() {
  Serial.begin(11520);
  pinMode(45, INPUT_PULLUP);   //pin of pos.3
  pinMode(44, INPUT_PULLUP);   //pin of pos.4
  }

void loop() {
             rmd3.update();
             if (rmd3.fallingEdge()) {
                Serial.print("rmd3 = 1");
                rotary_mode = 3;
                Serial.print("rotary_mode = 3");
             }
             if (rmd3.risingEdge()) {
                Serial.print("rmd3 = 0");
                rotary_mode = 0;
                Serial.print("rotary_mode = 0");
             }

             rmd4.update();
             if (rmd4.fallingEdge()) {
                Serial.print("rmd4 = 1");
                rotary_mode = 4;
                Serial.print("rotary_mode = 4");
             }
             if (rmd4.risingEdge()) {
                Serial.print("rmd4 = 0");
                rotary_mode = 0;
                Serial.print("rotary_mode = 0");
             }
}´´´

Pseudocode:

´´´void loop() {
int rmd_int;            //Mode numbers as int from 1 to 6
char rmd_char = [2];    //Mode numbers as char from "1" to "6"

              rmd3.update();
              rmd_int = 3;
              rmd_char = "3";
              void selected_mode(rmd_int, rmd_char);
}

void selected_mode(int rmd_int, char rmd_char ){
             if (rmd[rmd_int].fallingEdge()) {
                Serial.print("rmd[rmd_char] = 1");
                rotary_mode = [rmd_int];
                Serial.print("rotary_mode = [rmd_char]");
             }
             if (rmd[rmd_int].risingEdge()) {
                Serial.print("rmd[rmd_char] = 0");
                rotary_mode = 0;
                Serial.print("rotary_mode = 0");
             }
}```

I really don't understand, what you are saying there. You are talking about providing a char string as function parameter, but I don't see such a function in your code. You don't show any function other than the standard loop() and setup() functions. And the description unfortunately is a mess. I understand, that it is difficult to explain, when you may have misconceptions or not understanding enough to find the correct words. Maybe you can show us directly with your code, what you are trying to do.

Do you want to pass a character array, as an argument, to a function?

It can sometimes help to write "pseudocode" to describe how you want your program to work. There's no syntax rules, and nothing you cannot do - just write your code as if everything you wanted to do could be done in any way you want to do it. Then we may be able to work out from that what it is you intend your code to do.

Whenever you start putting numbers on variable names and then want to use them, what you really want is an array.  With an array you can use those numbers to refer to different things.  What you want to do with a char array won’t work.   Aria me names only exist in the code as you write it.  They all become memory addresses once the code is compiled.  There is no concept of a variable name at runtime.

I added a Pseudocode so you could mabye get a picture what i mean. Left it out at first because i know its wrong and may cause confusion.

It's still unclear why you want to use the char though.  Is it just so you can print out the number 3 ?  If that's what you want the Serial.print(rmd_int); will do that for you. And if you want to printout the integer inside of a string you can use Serial.printf("here is an int : %i", rmd_int);

The question is somewhat confused, but I think I got what you mean. Your
code suffers from too much repetition. You only showed the handling of
two selectors, but you want to handle 6 of them. Repeating all the logic
6 times would make the code unwieldy and hard to maintain. So you
want to put the logic in a function and just call that function six
times.

I actually only had to pass the number to the function, like "3" to
change some Variables and Char Strings accordingly

You do not need to pass the number as a string: you can use
Serial.print() to format the number instead. And you do not need to
write a function either: you can just put a for loop inside the
loop() function:
const int rmd_count = 6;

Bounce rmd[rmd_count] = {
    Bounce(48, 10),  // rotary selector on pos. 0
    Bounce(47, 10),  // rotary selector on pos. 1
    Bounce(46, 10),  // rotary selector on pos. 2
    Bounce(45, 10),  // rotary selector on pos. 3
    Bounce(44, 10)   // rotary selector on pos. 4
    Bounce(43, 10)   // rotary selector on pos. 5
};

void loop() {
    for (int i = 0; i < rmd_count; i++) {
        rmd[i].update();
        if (rmd[i].fallingEdge()) {
            Serial.print("rmd[");
            Serial.print(i);
            Serial.println("] = 1");
            rotary_mode = i;
            Serial.print("rotary_mode = ");
            Serial.println(i);
        }
        if (rmd[i].risingEdge()) {
            Serial.print("rmd[");
            Serial.print(i);
            Serial.println("] = 0");
            rotary_mode = 0;
            Serial.println("rotary_mode = 0");
        }
    }
}

The key to using for loops is to structure your data in arrays,
instead of collections of variables named with numbers. Thus, instead of
rmd3 you would use rmd[3]. Note that array indices start at zero.
Obviously, you could put the body of the for loop inside a function,
but at this point that would not help much in simplifying the code.

Edit: As a clarification, and per Delta_G's suggestion, I'll try to
explain the difference between an array and a collection of variables.
Each variable you define is mapped by the compiler (technically, the
linker) to a memory area. You can think of the variable names as
convenient names assigned to those memory locations. If you write:
Bounce rmd0(48, 10), rmd1(47, 10), rmd2(46, 10), ...;

You get:
      ┌───────┐        ┌───────┐        ┌───────┐
rmd0: |       |  rmd1: |       |  rmd2: |       |  ...
      └───────┘        └───────┘        └───────┘

In the picture above, the boxes are the memory areas. They are large
enough to hold a Bounce object, i.e. their size is sizeof(Bounce).
Each one has a name. You have no control over where, within the memory,
those variables are allocated: it's the linker's call.
In contrast, when you declare an array, you get a single variable
which is mapped to a contiguous memory area large enough to hold the
whole array:
Bounce rmd[6] = { ... };

Gives:
     ┌───────┬───────┬───────┬───────┬───────┬───────┐
rmd: |       |       |       |       |       |       |
     └───────┴───────┴───────┴───────┴───────┴───────┘

The individual cells do not have a name, and you instead use indices to
access them. For instance, rmd[0] references the first cell. Please,
note that in this example there is no variable named rmd0: if you try
to use that identifier the compiler will complain it is not defined.
Again, an array is not a “collection of variables”: it is a single
variable.
The array cells do behave in some sense much like individual variables
(they are called lvalues), as you can use rmd[0] in the same way you
would have used rmd0 in the previous code. The point of using an array
is that the indices do not need to be literals: you can use a variable
instead (rmd[i], where i is a variable), which comes handy when you
want to loop over all the cells.

Edgar pointed out that I can write the variable rmd3 by int i = 3
and rmd[i].

I hope it is now clear that this is not the case. There is no variable
named rmd3 unless you create it explicitly. Declaring an array named
rmd does not create such a variable.

[Can I] "form" a variable by "characters"?

Your question is not very clear, but my guess is you are talking about
computed variable names. This is a programming technique where you
access a variable by computing its name at run time. For example, you
combine the strings "rmd" and "3" in order to build the name of the
variable "rmd3". Then you use this computed name to access the variable
that has this name.
Computed variable names are quite often supported by interpreted
languages. For example, in PHP this is called variable variables:
$foobar = 42;           // the variable we want to access
$start = "foo";         // one piece of the name
$end = "bar";           // the other piece
$name = $start . $end;  // build the name from its pieces
print $name . "\n";     // prints the variable name: "foobar"
print $$name . "\n";    // prints the variable's value: "42"

Computed variable names are not supported by C++, which is the
language you use to program an Arduino. And for a good reason: when the
compiler translates your program to machine code, the names of the
variables are lost, they do not make their way to the actual Arduino.
And this is a good thing, as you would not want those names to consume
memory on the microcontroller.
Note that the names are present in the .elf file, as they could be
useful for debugging. If you were programming for a PC, you program
could in principle look into the file and find those names. On Linux you
would do that with the dlopen() and dlsym()
functions, from the libdl library. The libdl technique is, however, very
far from the capabilities of your typical Arduino, orders of magnitude
more complex than a simple array, and perfectly useless for your use
case.

Brilliant, thanks! I did not know i can form the Variable rmd3 by rmd[i] and int i=3. Now i am wondering if this only works with numbers or if it would work as well by something like char i[] = "3".

I think this answer would be greatly improved by making sure it is apparent that you are using an array and not the list of variables that the OP had.  From the question in this comment it would seem that the OP is still confused about how that will work.

You're not "forming a variable" with rmd[i] and a 3.  He's gotten rid of your variables entirely and created an array.  With an array you can use an index to choose which member of the array you want to talk about, in this case member 3 which is the fourth member since counting always starts at 0.  Note the line that starts "Bounce rmd[rmd_count]" where the array is created.  Note that at no point to we create anything called rmd3.  We instead create an array simply called rmd (without any numbers) which contains several of those Bounce objects.

Yeah i got that, he is using an array but english is not my native tongue so i didn't knew how else to call it. So if variables are just adresses would it work with pointers somehow? All i care is the result... i got over 1800 lines of code for the same crap repeating over and over again but just with different variables. The only point of the code i posted at first as to make it "easy" otherwise i had to past 1800 lines of code.

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


text:
What is the best and most reliable way to detect if a book is pulled out of a book case?
What is the best and most reliable way to detect if a book is pulled out of a book case?
I have a book case which I want to mount sensors to so that I can detect when certain books are pulled out, I don't need to know how much, all I need is a boolean trigger if the book has been pulled out 2+ cm or so (works with lower too). I would preferably also want to know when they have been replaced but that is just a bonus.
The goal of the project is to move a servo which may or may not open a secret door when 3 books are pulled out in a certain order.
The sensors need to be able to work continuously 24/7 for years.
Here is a masterfully drawn picture to explain it even better.

So far I have been thinking of mechanical switches, Ultrasonic Sensor (HC-SR04), or possibly some sort of infrared light and sensor that can detect a change in intensity (where a lower intensity is book being pulled out).
The mechanical switch I could easily do, but I would prefer something that is less obvious, and less "clicky" when it's triggered. I don't want to give away that there is something special with a book if someone picks it up on accident.
Any ideas on how it can be done?
Would love tips for specific components as I'm not native to the arduino world and have a hard time finding exactly what I'm looking for.

IR proximity is probably the most discrete - the kind of thing that's built into your phone to detect if a case closes or opens.

Great idea for an Arduino project by the way :)

best way would be multiple cameras connected to a CV system ... seriously, best is meaningless .... specify some parameters, such as cost, speed, need for expandability, etc.

I'd suggest a Photo Reflective Sensor.

As Majenko stated in the comments, an easy and discrete way would be using IR proximity sensors behind each book. The IR light from them is invisible to the eye, they are easy to read with an Arduino and often the casing of the IR LED and IR sensor are black, so that you could easily hide them in a black backplate of your book case.
The IR sensor will output one pin state (HIGH or LOW depending on the sensor), when something (the book) is near it (on most sensor modules you can change to threshold to your liking), and the other, if nothing is near it (empty place in the book case)
Searching "ir proximity sensor" at amazon gives multiple good looking results for ready to use sensor boards.

Another - more hacky - way would be to build your own switches at the top of the book case. As a switch is nothing more than 2 electrical contacts with some mechanic suroundings, you could add a small piece of cardboard above each book, which falls down a bit, when the book is removed, but not enough, that it is easily spotted (a few millimeters should be enough). At the top of the case and on the cardboard piece you put some piece of tinfoil or aluminum tape. When the book is put in the box, the tinfoil pieces get pressed together by the book, thus make contact. Wire one piece to ground, the other to an Arduino pin.
I find the IR sensor solution better, but I wanted to include a solution, where you don't need to buy extra sensor modules.

If you want the book and shelf to look normal, then use tiny magnets in the books and either reed switches or hall magnetic sensors embedded in the bookshelf. You can even discriminate two books by minding the magnet's polarity.

Simple and reliable, this would be my solution.

The range of magnets isn't great, so the books have to always be precisely aligned. I'd advice against this.

I assume all these solutions need to know exactly what book is where (positioned).
A solution could be a long LED strip (or other light) above the books, and at the bottom a strip of photo resistors (LDR), placed at every 2 cm. Place this photo resistors far enough backwards to cover the end of the shortest book (unless you do never change the order of the books you can place them exactly at the width of the book minus a cm or so).

My original plan was to place thicker books that are easy to detect in certain spots and drill holes as needed for the sensors behind them.

In the solution with LDRs, it's better to have the LDR under the books, or place the LDR directly behind each book, but then the LDR should (almost) has to touch the book to prevent light getting on the LDR.

Why not use RFID tags and sensor. You can do an inventory any time you want. The RFID tags are inexpensive and the sensor is not that much and available for the Arduino. Nothing shows if you put the tag in the spine of the book.

a tag in the spine would be perpendicular to an under-shelf RFID sensor, which won't scan. Also, you only have about 2cm of range with a tag, so you would need 3 such sensors for three books, and a tag in the spine is probably out of the question due to limited range. Neat idea though, and if you can get them to scan, this is the only way to have different combos do different things...

Depends on the sensor and tag. Using a system in the 865 - 960 MHz – Ultra High Frequency (UHF) – A short, high-energy wavelength of about a one meter which translates to long read range. Passive UHF tags can be read from an average distance of about 5 - 6 meters, but larger UHF tags can achieve up to 30+ meters of read range in ideal conditions. If he goes to active tags the distance is much greater. If that is to far you can adjust the sensitivity down.


text:
Convert Hex to Decimal from signed 2's complement
I am reading data from a meter over dlms protocol and I am getting hex values from there. I want to convert that hex string to signed decimal value. For example - ff9d denotes a value of -99 [reference].
My hex to decimal code is:
unsigned int hexToDec(String hexString)
{
  unsigned int decValue = 0;
  int nextInt;

  for (int i = 0; i < hexString.length(); i++)
  {
    nextInt = int(hexString.charAt(i));
    if (nextInt >= 48 && nextInt <= 57) nextInt = map(nextInt, 48, 57, 0, 9);
    if (nextInt >= 65 && nextInt <= 70) nextInt = map(nextInt, 65, 70, 10, 15);
    if (nextInt >= 97 && nextInt <= 102) nextInt = map(nextInt, 97, 102, 10, 15);
    nextInt = constrain(nextInt, 0, 15);
    decValue = (decValue * 16) + nextInt;
  }
  return decValue;
}

Can anyone please help me how to do it in Arduino IDE?

Have you tried googling something like "C++ convert hex string to int"?

Yes, I have converted hex string to decimal. But can't figure out the signed part. I can share that code if you want?

Yes, please share the code. You can edit your question for including it.

I have edited my question @chrisl

You do not want to convert the number to decimal: you want to convert it to binary. An int is represented in binary. Decimal is used for representing integer literals in the source code, but the compiler converts them to binary and, at runtime, every number is in binary.

Any code snippet you have on how to do this in Arduino @EdgarBonet ?

For example – ff9d denotes a value of -99

The function you wrote returns an unsigned integer which, being
unsigned, cannot be negative. The simple fix is to declare it as
int hexToDec(String hexString)

That should be enough to get it working as expected. Note that the local
variable decValue still has to be unsigned, otherwise you would get a
signed overflow, which is undefined behavoir (i.e. “forbidden”) in
C++. Returning an unsigned number from a function that is supposed to
return a signed number is perfectly fine: you get an implicit conversion
which is guaranteed to do the right thing.
Now, if I may provide some more feedback about this function:

Use, if you can, plain C strings (char *) instead of String
objects, as the latter are not very friendly to your Arduino's memory.
Use fixed-length integers (uint16_t if your protocol dictates 16-bit
integers) instead of the generic int, otherwise your code will fail
if you move to a 32-bit platform, such as an ARM-powered Arduino.
Use character literals ('0' instead of 48) instead of hard-coding
ASCII code points, as that makes the code more readable.
Use a simple subtraction (nextInt - '0') instead of the quite
expensive map() function.

Here is my take at it. Note that it has a “classic C” accent you do not
need to replicate. You may prefer using indices to crawl the string.
int16_t hex2int(const char *hex)
{
    uint16_t value;  // unsigned to avoid signed overflow
    for (value = 0; *hex; hex++) {
        value <<= 4;
        if (*hex >= '0' && *hex <= '9')
            value |= *hex - '0';
        else if (*hex >= 'A' && *hex <= 'F')
            value |= *hex - 'A' + 10;
        else if (*hex >= 'a' && *hex <= 'f')
            value |= *hex - 'a' + 10;
        else
            break;  // stop at first non-hex digit
    }
    return value;
}

Example usage:
Serial.println(hex2int("ff9d"));  // prints "-99"

Edit: As revealed by the comments, the whole question is an XY
problem. You are asking help about your misguided solution rather
than your actual problem. The data you have is not hex: it's binary.
You have a 16-bit signed integer stored in a byte array, most
significant byte first. You figured out you can convert that to an
integer by converting it first to a string representation as
hexadecimal, then converting that representation back to a binary
number. Of course you can do that, but it's an overly complicated and
expensive way of doing something trivial.
The canonical way to recover an integer from a byte array is by
assembling the bytes together using bitwise logic and bit shifts. In
this case:
int16_t reactive_power = (uint16_t) data[dataSize - 5] << 8
                       | data[dataSize - 4];

How should I pass ff9d as string in the hex2int function?

@Prateek: See the example I added.

I am doing this:
String reacP = String(data[dataSize - 5], HEX) + String(data[dataSize - 4], HEX);
Serial.println(hexToInt(reacP)); but I am getting the error: cannot convert 'String' to 'const char' for argument '1' to 'int16_t hexToInt(const char)'**

@Prateek: Looks to me like you are converting binary data to hex string, only to convert it back to binary. Please edit your question showing how you get the data. Most importantly: what is the data type of data?

That datatype of data is unsigned char as in void ReactivePower(unsigned char data[], int dataSize).

I solved the issue by adding .c_str() in the hex value. Thanks a lot @edgarbonet once again!

@Prateek: This is a very bad solution. See the amended answer.

Ohh, is that the case. Let me then check your ammended answer. Just out of curiosity why is using .c_str() a bad idea ?

@Prateek: Converting to a string in the first place is a bad idea. Representing numbers as strings of ASCII digits is useful for human consumption, but useless in your situation. Your problem is the kind that can be trivially solved by moving a couple of bytes around. Instead, you are taking a very long, memory costly and CPU intensive diversion.

I realized the mistake @edgarbonet. Your method worked perfectly. Thanks mate!

Which mode of DLMS you are you using?

IEC 61107 or currently IEC 62056-21, was an international standard for a computer protocol to read utility meters. It is designed to operate over any media, including the Internet. A meter sends ASCII (in modes A..D) or HDLC (mode E) data to a nearby hand-held unit (HHU) using a serial port. IEC 62056

In your question you mentioned:

hex string

which means a string of hex characters using ASCII (modes A to D).
However, in the comments you mentioned:

void ReactivePower(unsigned char data[], int dataSize)
String reacP = String(data[dataSize - 5], HEX) + String(data[dataSize - 4], HEX);

which means an array of bytes obtained from a stream of bytes using HDLC (mode E).
ASCII (Modes A to D)
For ASCII (modes A to D), there is a simple transformation to get the digit value from the hex character.
              ASCII
 Hex   --------------------                            Digit
 char  Decimal  Hexadecimal    Op1    Low nibble  Op2  Base 10
-----  -------  -----------  -------  ----------  ---  -------
 '0'      48        30        & 0x0F       0              0
 '1'      49        31        & 0x0F       1              1
 '2'      50        32        & 0x0F       2              2
 '3'      51        33        & 0x0F       3              3
 '4'      52        34        & 0x0F       4              4
 '5'      53        35        & 0x0F       5              5
 '6'      54        36        & 0x0F       6              6
 '7'      55        37        & 0x0F       7              7
 '8'      56        38        & 0x0F       8              8
 '9'      57        39        & 0x0F       9              9
 'A'      65        41        & 0x0F       1       +9    10
 'B'      66        42        & 0x0F       2       +9    11
 'C'      67        43        & 0x0F       3       +9    12
 'D'      68        44        & 0x0F       4       +9    13
 'E'      69        45        & 0x0F       5       +9    14
 'F'      70        46        & 0x0F       6       +9    15
 'a'      97        61        & 0x0F       1       +9    10
 'b'      98        62        & 0x0F       2       +9    11
 'c'      99        63        & 0x0F       3       +9    12
 'd'     100        64        & 0x0F       4       +9    13
 'e'     101        65        & 0x0F       5       +9    14
 'f'     102        66        & 0x0F       6       +9    15

For characters '0' to '9', simply AND with 0x0F.
For characters 'A' to 'F' and 'a' to 'f', AND with 0x0F and add 9.

char ch = '1';
byte b = 0;
if (ch >= '0' && ch <= '9')
{
  b = ch & 0x0F;
}
else if ((ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))
{
  b = (ch & 0x0F) + 9;
}

It's also important to know whether the transformation was successful, e.g. the first character could be bad (either a null terminator or non hex character), so this needs to be tested for during the transformation. Also, there are four nibbles in an int16 so the transformation needs to quit when a maximum of four hex characters have been processed:
void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(115200);
}

void loop()
{
  char string[] = "A";
  //char string[] = "Waffle";
  //char string[] = "ff9d";
  int16_t the_int = 0;
  int count = AsciiToInt16(string, the_int);

  Serial.print(string);
  Serial.print(",  ");
  if (count)
  {
    Serial.print("Ok,  ");
    Serial.print(count);
    Serial.print(",  ");
    Serial.println(the_int);
  }
  else
  {
    Serial.println("Bad");
  }
}

int AsciiToInt16(const char* ch, int16_t& value)
{
  int count = 0;
  byte nibble = 0;

  // Stop after 4th nibble or null terminator.
  for(int i = 0; i < 4 && ch[i] != 0; i++)
  {
    if (AsciiToNibble(ch[i], nibble))
    {
      value <<= 4;
      value |= nibble;
      count++;
    }
    else
    {
      break;  // Stop after non hex digit.
    }
  }
  return count;
}

bool AsciiToNibble(const char ch, byte& b)
{
  if (ch >= '0' && ch <= '9')
  {
    b = ch & 0x0F;
    return true;
  }
  else if ((ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))
  {
    b = (ch & 0x0F) + 9;
    return true;
  }
  return false;
}

Output
A,  Ok,  1,  10
Waffle,  Bad
ff9d,  Ok,  4,  -99

HDLC (Mode E)
For HDLC (mode E), simply do:
void ReactivePower(byte data[], int dataSize)
{
  uint16_t reacP = (data[dataSize - 5] << 8) | data[dataSize - 4];
  Serial.println(dataSize);
  Serial.println(reacP);
}
. . .
  byte data[] = { 1, 3, 5, 2, 4, 8 };
  ReactivePower(data, sizeof(data));

Output
6
773


text:
status whether the switch is connected to arduino or not?
I made a small circuit in which a push-button is connected to Arduino via a pulldown resistor. So, whenever it is pressed it connects to 5V otherwise pulled down to the ground. this is working fine but I wanted to know is there any way to detect whether the push-button is connected to the circuit or not? In case if push-button disconnects from the circuit, how to detect it?

resistor across the switch ... use analog input

no ... it would produce a voltage level that is dependent on the state of the switch

another way would be to remove the pulldown resistor and connect the switch between two data pins

A push-button that is not being pushed is electrically equivalent to no push-button at all. Your Arduino will never be able to tell the difference.

Create a dpdt switch that uses two resistors to give different values for the two positions and use an analog pin.  Still you have the possibility that the floating input just accidentally reads the same as one of those values so it isn’t very reliable.

@Delta_G you could add a pull-up/pull-down on the Arduino pin, so it's never really floating.

No, not the switch I described.  If you put a pull-up or pull down you wouldn’t be able to tell the difference between not-pressed and disconnected.  The switch I’m describing would have two different analog readings for made or not made.  It would never read a simple high or low.  If you put a pull-up or pull down on the switch I described it wouldn’t work.  What I described requires the pin to float if disconnected so you can tell it’s been unplugged.

The simplest way, as @jsotola has said, is to put a resistor across the terminals of the SPST push-button and read the voltage using an ADC input of the MCU.
However, the resistor needs to be bonded to the push-button (or inside the push-button housing) to ensure that when, for example, a vandal rips the push-button out of your switchboard, the resistor is certain to go with it so that the MCU can tell the difference between HIGH, LOW, and MISSING as @EdgarBonet pointed out. You also need to consider the continuous current draw of the extra resistor for low power/battery devices. You could increase the resistor values, but that tends towards weak pullup/pulldown. If you increase the value of only the extra resistor, it shifts the output voltage closer to the rail voltage reducing the margin for error.

Figure 1 – SPST Push-Button AWOL Detector.
Perhaps a better, but more expensive way, is to use a SPDT push-button. This push-button requires no modification, but is more expensive than a SPDT push-button and requires an extra wire and resistor. This circuit draws less continuous current and has stronger pullup/pulldown.

Figure 2 – SPDT Push-Button AWOL Detector.


text:
GSM900A module is not connecting to the network
My GSM900A module is not connecting to the network. IT continuously blinks(1 sec). The power was given by the Arduino Uno board. Then I tried connecting an external battery(4.2V , 4200mAH). But it didn't work. What kind of a solution would be suitable for this issue?

maybe there is no network to connect to

Maybe you don't live in an area with the right frequency bands for the SIM900A to operate. Does your country even have a GSM network any more? Many don't now. It's old technology. You should be using an LTE modem nowadays.

gsm network is still available in our country.


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:
Esp32 heating slowly
I made a small little IoT device to control my light chains from my phone, I'm using a MOSFET to turn the power on or off, using an esp32 connected to the MOSFET, both esp32 and light chain is supplied from a standard 6v phone charger I just clipped the wires and used it,
I have a voltage regulator on the esp32 as seen on the image, when I run the system the esp32 slowly heats up to around 40-50 Celcius, and I can hear a small whinny sound from the chip, the esp32 is getting 3.3v as I should when I measure with a multimeter
what's wrong?
(btw it works with turning lights on and off, not sure if those was the resisters i used)

Is that a map of where the nearest starbucks is? If it's supposed to be a schematic it's completely meaningless and impossible to read.

lol, ye sorry I didn't really know any good side to make the schematic on, didn't think it was that important, just wanted to give a general idea of what the circuit was

The question editor also has the function to draw schematics in it. Just click at the "Schematics" button (the one with the little schematic diagram) in the question editor and then you can create a proper schematic, which will directly tie into your question.

There's a schematic editor available right from the editor with Ctrl-M.

Did you build the regulator circuit or is it a pre-built module?

What is connected to what? Are you running your light chain from the output of your voltage regulator? What is the output voltage of the regulator? How are you powering the ESP32? If the voltage regulator is putting out 5V and you're using that to power your light chain and as VIN to your ESP32,  the ESP's voltage regulator is still having to drop 5V down to 3.3. That shouldn't generate a lot of heat unless you are drawing significant current from the ESP's regulator.

My guess is that the phone charger is a bit crappy, and doesn't produce a very stable voltage. I'd try adding a large bulk capacitor between the 6V and GND, to try to lower the, so called, noise.

The esp module has no components on it that can produce sound continuously. Ceramic capacitors can do so when the get ac voltage, but in your case the only ac is the 3.3V line's ripple. Buck converters often make a sound (coil whine). Are you really sure the sound is coming from the esp? 40-50° is not uncommon for an esp when wifi is enabled

after further research I have found out the sound came from the phone charger, probably just the transformer in it, still a bit worried about the temperature since I have never experienced temperature going up because of wifi use


text:
AccelStepper help - it just won't move!
I should begin by saying I am not a programmer, do not really know much about programming, and am programming an Arduino Uno for the first time. I am using a Nema 23 motor (23HS22-2804S) with a microstep driver (ST-M5045). Within the following code is the description of what I need the program to do:
#include <AccelStepper.h>

/* Using a stepper motor,
 rotate a vibrational model using gears interconnected by springs
 in such a way as to induce torsional vibration, which should be visible by comparing
 movement of juxtaposed rotating gears with markers painted on. */

AccelStepper stepper(AccelStepper::FULL4WIRE, 2, 6, 4, 8);

int Microstepping = 8; /* Microstepping factor, as set on the ST-M5045 control board.
                          Multiplies the number of steps per revolution on the stepper motor.
                          Reference controller manual for adjustments to this number. */
int Steps = 200; /* Number of steps on your stepper motor.*/
int SPS;
int Amp;
int Freq;
// int SC;
int n = 2;
int i;
int totalSteps = Microstepping * Steps;

/* It should be noted that the Microstepping and Steps factors are not necessary, and adjusting the microstepping factor
 *  on the fly will not break the code. However, be aware that changing the microstepping factor by more than one interval
 *  at a time can cause the motor to not keep up with the sudden changes, i.e. losing torque or vibrating/stuttering. */

void setup() {               // THIS RUNS ONCE //

  // read potentiometers; raw inputs from 0 to 1023 //
  SPS = analogRead(0)*0.733; // MAX RPM ~28, max speed ~750 steps per sec (speeds above 1000 steps per second are unreliable,
                             // according to AccelStepper documentation)//
  Amp = analogRead(1)/20;     // MAX AMP ~51//
  Freq = analogRead(2)/170;   // MAX FREQ ~6 Hz//

  stepper.setMaxSpeed(SPS);
  stepper.setAcceleration(SPS/1.5);

  int nextStop = totalSteps/Freq;

  stepper.moveTo(nextStop);
  stepper.run();
}

void loop() {
  int nextStop = totalSteps/Freq;

// reaches here, doesn't execute if loop.
   if(stepper.distanceToGo()== 0){
     SPS = analogRead(0)*0.733;
     Amp = analogRead(1)/20;
     Freq = analogRead(2)/170;
     i = SPS - Amp;
     if(i <=0)
       i = 1;
     stepper.setSpeed(i);
     stepper.moveTo(nextStop*n);
     stepper.run();
    }
    n++;
}

When I use Serial.println() to check where the program is working and where it isn't, I see that it completes the setup loop without ever moving, and in slightly different versions of the same code, it has entered the if() statement and executed it (also without moving.)
An earlier version of the program runs and executes all statements, but only moves a maximum of about 20 steps per second, without the fluctuations in speed I call for, and doesn't respond in real time to any input from the speed potentiometer that puts the speed above 20.
Ideally, the program would run the demo at full speed, and freq times per second, it would slow down just enough to be noticeable as a torsional vibration.
I have tried running the program with and without the run() lines, and I have tried using runToNewPosition() in attempts to get the program to stop and properly execute the movement.
I made the setup loop as close as possible to the setup loop in bounce.pde, the example program in the AccelStepper documentation which moves the stepper motor between two points repeatedly, accelerating and decelerating before changing directions. The reason I did this is because I know that the setup loop in bounce.pde works, and so I would feel more confident that my setup loop is not the root problem.
Any help you can offer me is appreciated! Thanks for your time.

That driver appears to use a STEP / DIR interface. You'll need the DRIVER MotorInterfaceType, not FULL4WIRE.

towe, thank you for your response. As I began writing up this post, I began to realize that I am indeed using a driver between the Arduino and the stepper, which I had mistakenly taken to mean a special type of motor with only 2 wires, citing the AccelStepper documentation, which says "2 driver pins required." I'll try editing my program to use the DRIVER interface type.

Please read the documentation for the AccelStepper library.

Poll the motor and step it if a step is due, implementing
accelerations and decelerations to achieve the target position. You
must call this as frequently as possible, but at least once per
minimum step time interval, preferably in your main loop. Note that
each call to run() will make at most one step, and then only when a
step is due, based on the current speed and the time since the last
step.

source
You are only calling run once, after setting a new position.
Move stepper.run(); out of the if statement, the the end of the loop function.
      ...
      stepper.moveTo(nextStop*n);
    }
    stepper.run();
    n++;
}

Thank you for your answer. I have read the documentation a few times, and the description for the run() command means nothing to me because I have no clue what my step time interval is. Like I said, I don't know anything about these things.

run checks if the motor needs to make a (single) step, right now. If not, it just does nothing. You don't need to know when to call it. It will itself keep track of when a new step is needed. So you need to call it as often as possible. I know it isn't all that intuitive. I still find it a bit weird, but I understand why they did it.

Okay, thank you. I've run the program now with the edit you suggested, and it works. Doesn't achieve my end goal yet, but it's on its way.

@czar1249 If this solved your issue, please accept the answer.


text:
How to connect 10 coin vibration motors to UNO?
I am new to arduino and anything related to electricals and electronics. I need info on how to connect 10 vibration motors to arduino uno without damaging the board. Do I need an external circuit to regulate and control power supply or can I directly plug in all 10 motors to the board directly?

Lookup how to connect a motor to an Arduino (resistor, transistor and flyback-diode). These vibration motors sound small enough that you might be able to connect them directly to the Arduino, but you'd have to provide us with something like a part-nr, so we can check the current rating of the motors.

Specifications: Outer diameter: 10 MM; Thickness: 3 MM
Rated voltage: 1V To 6V,; Current: 66 MA
Output Speed: 12000 RPM (https://www.amazon.in/dp/B07YPS3D3L/ref=cm_sw_r_cp_apa_i_duYDFb81K30VN)

Current is too high for an Arduino. Any small transistor (NPN BJT or N-channel FET with low enough Vgs) will do to drive one. Multiply that by 10 and bob's your uncle. Maybe two ULN2003 will be more economic.

Any small transistor, plus a flyback diode, plus (for a BJT transistor) a properly sized current limiting resistor.

I would suggest a pair of ULN2003 chips.  These are 6 darlington transistors in a single chip.   Two chips will give you the ability to connect 12 motors.
Each one needs an IO pin to control it - if you want speed control then you will have to look into adding extra PWM channels. For just ON/OFF control any IO pin will do (even analog ones).
10 motors running at the same time will be up near the limit of the Arduino's 5V pin current supply, so you really should consider a separate external 5V power supply (maybe a USB phone charger) of 1A or more to power everything (connect the power supply to the motors and the 5V pin of the Arduino).

Thanks for your input. But I will have at most only two of them running and I don't need any control except on and off over the motors. This is possible without ULN2003 drivers right?

It is possible to replace the ULN2003 chips with 10 transistors and 10 diodes. You can run it all from the Arduino's 5V pin though instead of an external power supply.

Watch out for the voltage drop from the ULN2003 chips, I think it about 1.4V at load.

@Gil What about it? You read the rated voltage or the motors?

The motor is not a constant output device, it still works by watts of power. The motor will only draw enough current to move its load at a given speed. Lets assum the impedance of the motor is a constant; If we change the voltage we change the wattage and hence the torque and probably speed. "The Arduino a power supply it is not!" On a good day it has a 200ma max capability. This is dependent on the power the regulator can dissipate, dictated by load and the voltage going into the Vin pin.
If we look at the 66mA it draws times 10 motors that is 660 mA is way beyond the Arduino rating of 200ma. Total chip Vcc current (all output pins total and chip overhead): 10 output pin driving 10 motors @ 66 ma is way beyond max for whole chip.


text:
Can an Arduino access a network database?
This is a similar question to a previous question I have asked. Primarily I am looking to find out more about the capability of the Arduino.
Here is the scenario. There is a PC that is connected to a database via local network or internet. Is it possible that by plugging an Arduino in the usb port of this PC the Arduino could read from this database by means of an SQL query? Given that the Arduino would have the correct credentials. I am not asking if the Arduino could Hack into the database. I am asking if it is capable of accessing the database at all. Also this must be done without installing any special program on the PC. If that isn't possible, what type of program is needed? I am not necessarily looking for a tutorial, but if you could point me in the right direction that's be great.
Thank you.

What kind of Arduino?

It's actually a Trinket M0. Not Arduino brand, but I can get a different Microcontroller if necessary.

buy an Ethernet or WiFi shield. nobody reads the database over USB and PC

The M0 has a "native" USB interface. Because of that it can be programmed to appear as any kind of device you can image - as long as you can find (or write) the code to do that.
You could (though I have never tried and don't know what code is readily available for this) program the USB interface to be a USB Ethernet device. Your computer would then see it as a new Ethernet interface.
It would then be trivial to "share" your internet connection in Windows with that new Ethernet interface (nothing to install, but settings on the computer need changing), and your Arduino would then be on the network the same as your computer (just as if you'd given it a WiFi interface or something like that). Then it can connect to the database itself (or to a website that communicates with the database if that is simpler) and do whatever it needs to do.
Step one, of course, will be to find a library that will give you that USB Ethernet interface...
A much simpler option, if you're willing to change your M0 for something else, is to use a chip with a built in WiFi interface, such as the ESP32. There's no need for your computer at all then.

TCP/IP over UART is simpler. as null modem connection. there is a library but I don't know if somebody uses it

Thank you for the response

@Juraj You mean SLIP, or PPP? Simpler to program on the Arduino - harder to set up on the PC end.

https://playground.arduino.cc/Code/SerialIP/

@Juraj I rest my case: the Windows instructions (a PDF) no longer exist (good job I speak Swedish...). And there's no DUNS in home versions of windows any more. So a nightmare to set up...


text:
How can i make my MLX90614ESF scan temperature after the MFRC522 scans the RFID tag?
//THIS IS THE RFID CODE

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

//*****************************************************************************************//
void setup() {
  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();                                              // Init MFRC522 card
    //shows in serial that it is ready to read
}
//*****************************************************************************************//
void loop() {
  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;
  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;
  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  byte buffer1[18];

  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer1, &len);
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  //PRINT FIRST NAME
  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");

  //---------------------------------------- GET LAST NAME

  byte buffer2[18];
  block = 1;

  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer2, &len);
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  //PRINT LAST NAME
  for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i] );
  }

  //----------------------------------------

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//

// AND THIS IS THE MLX90614 CODE
#include <Wire.h>
#include <Adafruit_MLX90614.h>

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

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

  mlx.begin();
}

void loop() {

  Serial.print("*\Body Temperature = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");

  Serial.println();
  delay(500);
}

Please add some text to your question.  What is happening, why it is not what you expected to happen and what you would like to happen.  Humm, from the looks of it, this code likely does not compile because you have multiple functions using the same name.

It appears that you have simply concatenated the code from the RFID tag Sketch and the code from Temperature Sketch together.  This will not work as both programs contain identically named functions. Specifically "setup()" and "loop()".  What you need to do is integrate the code for each "setup()" function into one "setup()" function.  Similarly, you need to do the same with the "loop()" functions.
Assuming you only want to scan the temperature after you have successfully recovered data from the RFID tag, place the Temperature Sketch loop code immediately before the delay in the RFID tag code.

Someone may actually code a solution up for you @Ace Canacan.  I think you should try for your self first.  Also, it is always better if you try something before asking your question here.  More people will be willing to help if they see you have tried a few times before asking a question.


text:
Building your own ESP8266 development board
I was wondering if someone could help me out?
I have been looking for a project that would test my existing skills and force me to learn new ones, and I thought that trying to build my own ESP8266 development board might be the best thing for me to try out.
I got some ESP 12-F boards and some veroboards that support it, it has a space for the ESP-12 and pads that lead to holes you can solder to.
However, I am a little confused at the moment. On a NodeMCU, for instance, you have way more connections than the ESP 12 offers out of the box. Is there a resource or guide that explains how these are broken out so that I can figure out how to provide those connections on my little dev board project? Like on the example here:
https://randomnerdtutorials.com/getting-started-with-esp8266-wifi-transceiver-review/
I get that I need to add the UART logic, I have that on order right now. I am just confused at the moment on how to break out the rest of the pins.
I hope this makes sense, please be gentle on me, this really is my first serious project and I wanted it to be challenging in order to learn.
Cheers,
Rafa

on esp-12 the esp8266 with external flash and supporting circuit is under the metallic cover. NodeMCU has pins which can't be used because the quad SPI for external flash uses them. these pins could be shared only with some SPI devices. the example for this sharing is for LCD.

Take a look at the NodeMCU schematic diagram and compare to ESP-12F module pinout, you will see the differences.


text:
having problems with my arduino bluetooth car project(with L298n Motor Driver)
so the scenario is i am making a bluetooth controlled car(voice control)+obstacle avoidance function.I am using Arduino UNO with L298n motor driver and a HC-05 BT module in the sensors i am using the ultrasonic sensor and a IR sensor for the back and a servo motor is also used to rotate the ultrasonic sensor.so the problem is when i am sending command "turn left" the servo moves left and nothings happens and the other command i.e turn right,move backward,move forward are not working at all.
circuit diagram and code is given if i have done  something wrong with the code or else my motor driver or wiring is creating the issue

#include <NewPing.h>
#include<Servo.h>
#define TRIGGER_PIN A1
#define ECHO_PIN A0
#define MAX_DISTANCE 300
#define IR A2

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Servo myservo;

String voice;

void setup() {
  Serial.begin(9600);
  myservo.attach(8);
  myservo.write(90);
  pinMode(IR, INPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode( 9, OUTPUT);

}

void loop() {
  int distance = sonar.ping_cm();

  if (Serial.available() > 0) {
    voice = "";
    delay(2);
    voice = Serial.readString();
    delay(2);
    Serial.println(voice);

    if (voice == "turn left") {
      left();
    } else if (voice == "left") {
      left();
    } else if (voice == "turn right") {

    } else if (voice == "right") {

    }

  }
  while (voice == "move forward") {
    forward();
  }
  while (voice == "move backward") {
    backward();
  }
}

void forward() {
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    digitalWrite(10, HIGH);
  }
}
void backward() {
  int IR_Sensor = digitalRead(IR);
  if (IR_Sensor == 0) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
    voice = "";
  } else {
    digitalWrite(11, HIGH);
    digitalWrite( 9, HIGH);
  }
}
void left() {
  myservo.write(180);
  delay(500);
  myservo.write(90);
  delay(500);
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);

  }
}

void right() {
  myservo.write(0);
  delay(500);
  myservo.write(90);
  delay(500); {
    int distance = sonar.ping_cm();

    if (distance < 10) {
      digitalWrite(12, LOW);
      digitalWrite(11, LOW);
      digitalWrite(10, LOW);
      digitalWrite( 9, LOW);
      voice = "";
    } else {
      digitalWrite(10, HIGH);
    }
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
  }
}

void Stop() {
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite( 9, LOW);
}

start at the begining ... write a sketch that runs one motor in one direction for one second, stops the motor for one second, then repeats

The code seems to have a few missing lines for logic. Here's a corrected version from my understanding.
#include <NewPing.h>

#include<Servo.h>

#define TRIGGER_PIN A1
#define ECHO_PIN A0
#define MAX_DISTANCE 300
#define IR A2

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Servo myservo;

String voice;

void setup() {
  Serial.begin(9600);
  myservo.attach(8);
  myservo.write(90);
  pinMode(IR, INPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);

}

void loop() {
  int distance = sonar.ping_cm();

  if (Serial.available() > 0) {
    voice = "";
    delay(2);
    voice = Serial.readString();
    delay(2);
    Serial.println(voice);

    if (voice == "turn left") {
      left();
    } else if (voice == "left") {
      left();
    } else if (voice == "turn right") {
      right();
    } else if (voice == "right") {
      right();
    } else if(voice == "move forward"){
      forward();
    } else if(voice == "move backward"){
      backward();
    }

  }

}

void forward() {
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    digitalWrite(10, HIGH);
  }
}
void backward() {
  int IR_Sensor = digitalRead(IR);
  if (IR_Sensor == 0) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
    voice = "";
  } else {
    digitalWrite(11, HIGH);
    digitalWrite(9, HIGH);
  }
}
void left() {
  myservo.write(180);
  delay(500);
  myservo.write(90);
  delay(500);
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);

  }
}

void right() {
  myservo.write(0);
  delay(500);
  myservo.write(90);
  delay(500); {
    int distance = sonar.ping_cm();

    if (distance < 10) {
      digitalWrite(12, LOW);
      digitalWrite(11, LOW);
      digitalWrite(10, LOW);
      digitalWrite(9, LOW);
      voice = "";
    } else {
      digitalWrite(10, HIGH);
    }
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
  }
}

void Stop() {
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
}


text:
L293D motor shield
I have the L293D motor shield on top of my Arduino UNO.
The L293D has a servo attached of 5 volt and a motor of 12 volt there is an external power supply.
If I remove the jumper of the board and power my motor with the 12 volt? Will my servo of 5 volt still have the 5 volt of the Arduino or is this connected to the external 12 volt?

this cannot be answered without examining the motor shield schematic diagram

Or at the very least a link to (or even photo of) the shield in question (there is no "The" L293D shield, there's many shields that have that chip on them) so that we have a chance of working out what you're talking about.

No , your motor will actually get power from outside but the Servo Motor will be powered by arduino even if the jumper removed because the ln298 shield is mounted on the arduino.


text:
Arduino Pro Mini is burned by 12v. Can I save it?
I have this Arduino Pro Mini clone (ATmega328) 5v.
I gave it exactly 12 volts through the RAW power input, but it instantly got hot and started fuming. Fumes were coming out of the area close to the black S4 thingy.
I don't know why, because I thought it can accept up to 12v through that input.
Now when I give it 5v only the middle led is lighting up and it's not connecting to the USB-UART interface anymore.
Is there any chance to save it?

By the description it sounds like you either, hooked the 12v in reverse (damaging the input diode [s5]) or accidentally burned out the power regulator. What happens when you put the 5v (regulated source) to the VCC & GND pins bypassing the regulator?

@Tim_Stewart when I give it 5v through VCC input, the main red light is just lighting up. If I give it 5v through the RAW input, it also lights up, although it is dimmer. In neither case the built-in led (L) is lighting. And also it does nothing when I click on the red button.

@Sergio, what happens if you completely desolder the voltage regulator I circled in my answer I added? Can you then use the Arduino Pro Mini by powering it with a regulated 5V directly to Vcc?

1. Your microcontroller is probably/maybe fine; your tiny little voltage regulator is dead; here's why:
Sergio, yes, you can probably/perhaps save it: your Arduino (the microcontroller--ie: processor at least) is likely just fine, assuming the linear regulator smoked and failed open, meaning it did NOT pass through the raw input voltage to your ATmega328 mcu. It's the linear voltage regulator that is fried! That's this circled component below:

So, desolder that part and throw it away and you can continue using the Arduino just fine. Just power it with a regulated 5V directly to VCC is all and you'll be fine. I've done exactly this on some parts I exploded or smoked the regulator on (see below), and they continued working just fine.
IMPORTANT: if this is a safety-critical part, or a product, throw away the whole Arduino just in case.
Details on the fixes:

Desolder the voltage regular (circled in the image above, and shown desoldered on my Pro Mini in the photo below) and throw the desoldered voltage regulator away.

Power the board now through Vcc with anything between 3.3V and 5V (recommended: a regulated 5V into Vcc, such as the 5V line coming straight out of your USB hub).

Reflash the bootloader with a USBasp programmer (shown in 2nd of the two photos below).

Upload a new blink sketch via the external USB serial UART to blink the built-in LED13. This works fine on my Pro Mini below shown with exploded and desoldered regulator:
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);                       // wait for a half-second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(500);                       // wait for a half-second
}

Unplug the USBasp programmer when done, and continue development with just the external serial UART plugged in.

Here's some photos of my Arduino Pro Mini with exploded voltage regulator that I desoldered. I found it today. The Arduino still works fine! I desoldered the regulator around the year 2014 or so, but just re-flashed the bootloader, uploaded the code, tested it, and took these photos today:
Image 1: Arduino Pro Mini used as a data-logging altimeter in ~2014; photo from today. The voltage regulator exploded (read below), so I desoldered it. Both the power LED (top center of board), and LED13 (bottom-left of board) are ON. The power LED comes on automatically so long as you are powering the board through Vcc and GND from your USB port through your USB UART adapter, and the LED13 is blinking ON here due to the blink sketch above AND by powering the board with Vcc and GND from the USB serial UART to the Pro Mini. Note that the LED13 would NOT light up properly with just the USBasp plugged in, even when it was properly powered and programmed by the USBasp. I think it's because the USBasp was interfering with that pin. Plugging in the external serial UART to the Pro Mini's Vcc and GND fixed that, allowing LED13 to function properly as well while the Pro Mini ran the blink sketch above.

Image 2: External USB serial UART (in the USB hub top port), USBasp programmer wired to program the bootloader (in the USB hub under the USB UART), Pro Mini (bottom left) with power LED ON and LED13 (bottom-left of board) OFF.

On the surface, you didn't do anything wrong! You plugged 12V into the correct pin (RAW, which is the battery-in or voltage in line), and that is within the voltage limits of this part. BUT, what you neglected to consider is the power dissipation capability of this footprint or size of a part. The power dissipation capability is soooo low that realistically, 12V is too much, and will destroy the part.
6 years ago or so I made a couple little data-logging altimeters with the Arduino Pro Mini, connected 12.6V (a fully-charged 3S LiPo battery) to the RAW pin, and 15 seconds later: pop! They exploded! Literally, that little voltage regulator exploded into bits with 12.6V in. After that, I never put more than 8.4V in (a fully-charged 2S Lipo battery), and all was well. Since I was powering it from my main RC plane's 3S LiPo motor battery, this was accomplished by just tapping off of 2 of the 3 cells in the battery by plugging into the correct points on the battery's balance lead. So, I was able to use the same battery but just use 2 of its 3 cells instead of all 3 of them.
These regulators are just so tiny that they can't take much heat is all, and since they are linear regulators, all excess voltage is burned off as heat. Here's a couple example power dissipation calculations to make the point:
Imagine you are drawing 100mA total (0.1A) from this regulator. With 12V plugged in, you have to burn off 12V - 5V = 7V in that regulator chip.
Power_dissipated = Current*Voltage = I*V = 0.1A * 7V = 700mW

700mW is HUGE! Pop! Explosion! Dead voltage regulator chip.
But, if you feed it just 8V this same chip would have to burn off only 8V - 5V = 3V of excess voltage:
Power_dissipated = Current*Voltage = I*V = 0.1A * 3V = 300mW

That's 300mW/700mW = 43% as much power, or 57% less power. These numbers are just for example purposes, but you get the point.
Solution? 1) switch to Arduino Nanos, and/or 2) use a much lower input voltage (ex: 8~9V instead of 12V!). Nanos have MUCH bigger and beefier voltage regulators, and Nanos cost like $1 more when buying the Chinese clones.
2. How to calculate 1) how much power your regulator can dissipate without burning up, and 2) how much current you can therefore draw for different raw input voltages to the voltage regulator:
(Also: I wrote an article on my website covering more of these power, current, and voltage specs--see link here and at bottom.)
By the way, looking at the Pro Mini schematic here, I see that the original board used a MIC5205 linear regulator. The Chinese clone you have certainly uses a different regulator, but let's look up the MIC5205 datasheet for benchmarking purposes. A google search for "mic5205 datasheet" leads me here: https://ww1.microchip.com/downloads/en/DeviceDoc/20005785A.pdf. The device is rated up to 150mA current and up to +16V input voltage, but you must consider power!
The equation for that is hidden on pg 5 here:

Power_dissiplation_max =  P_D_max = (T_J_max – T_A)/theta_JA

theta_JA = thermal resistance from Junction to Ambient = 220 degC/W

T_A = ambient temperature = let's say, 40 deg C (104 deg F)

T_J_max = max junction (internal chip) temperature = +125 degC

So, we crunch the numbers:
P_D_max = (125C - 40C)/220 C/W = 85C / 220 C/W = 0.386W = 386mW max
power.

Final result: this tiny, linear voltage regulator, assuming absolute max junction temperature of +125 C (257 F) [HOT HOT HOT!--not good] and ambient air temperature of 40C (104 F) can dissipate 386mW max power before you risk making it go "pop"!
So, assuming you power it with 12V, how much current can you draw?
Voltage drop across the regulator = V_D = Vin - Vout = 12V - 5V = 7V

Power dissipation in the regulator = P_D = current * voltage drop = I*V_D

Solve for I:
I = P_D/V_D = 0.386W/7V = 0.055A = 55mA current!

With 12Vin and 5Vout, any more than 55mA current draw goes "pop" or smokes the chip!
With 8Vin, however, you could draw:
V_D = 8V - 5V = 3V
I = P_D/V_D = 0.386W/3V = 0.129A = 129mA current

With 8Vin and 5Vout, any more than 129mA current draw goes "pop" or smokes the chip!
So, use a lower input voltage and you can draw much more current! How low can you go? Don't go lower than 5V + dropout voltage. The datasheet on p3 for this regulator shows a max dropout voltage of ~350mV, so stay > 5.35V input to get a regulated 5V output.

That's all for this MIC5205 chip, though. Note that other voltage regulators may have dropout voltages as high as 2~3V, so you'd have to have an input voltage of at least 7V or so to ensure a regulated 5V output. I can't see the numbers well enough on your chip to google for its actual Chinese or whatever datasheet to do the calculations for your chip, but you can use my example calculations above to redo these calculations for any datasheet or part.
Other reading:

Google search for "sot 23-5 power dissipation"

Microchip Application Note AN792: A Method to Determine How Much Power a SOT23 Can
Dissipate in an Application

I also wrote an article on my personal website on 6 Jan. 2014 called "Arduino Power, Current, and Voltage Limitations", here, for more info. on these limitations.

Please explain downvotes. This is one of my more well-thought-out answers, and one where I have real experience with this exact same part and exact same scenario at the exact same input voltage.

Nevermind. I know who downvoted my answer. Enough said. It's not related to the answer quality, educational content, or correctness. Anyone other than that person, please consider the quality and correctness of this answer in making a judgement on whether or not to downvote it or upvote it.

Do not worry about down-votes. The system lets people up or down vote answers as a way of eventually "grading" answers (or questions). A single down-vote means nothing.

Unfortunately I've seen more than one of those cheap voltage regulators fail as a short.

@Pelle, yeah when that is the case, the Atmega328 probably gets killed too.

Thank you for such a thorough answer! I desoldered it completely as you suggested, it still lights up the middle light (but not the built-in one) and also it fails to connect to USB-UART adapter. Sad.

Have you tried reflashing the bootloader? Or, just programming it via ICSP with a USBasp programmer or another Arduino as a programmer?

The lights you are describing don't mean anything to me. I don't have easy access to a Pro Mini right now to play with and I don't know what LEDs you're referring to when you say "middle one" and built-in one. It has a power led that should light when it's on, and an LED on pin 13 which should only light up if you programmed it to. I don't know what program you have loaded, and you may need to reflash the bootloader and reload the program.

I just checked the schematic. The power LED, right under the voltage regulator, should NOT turn on with 5V connected to VCC unless you've soldered the SJ1 jumper closed.

@Sergio, see the new "Details on the fixes" section in my answer now. I found my exact Pro Mini with exploded voltage regulator from > 6 yrs ago and just programmed it today. It worked fine in my case. You may just need a new bootloader on it, or to check your Vcc and GND connections from external USB serial UART to the Pro Mini. I'm hoping your board isn't really dead, but...perhaps it is. Before making that final determination though, try these new steps.

Downvote trolls here too huh? Is there a community on SE that doesn't have them?

Unfortunately, it sounds like it is dead.
I did this early on when I started with arduinos.
In my case I plugged in a "12v 1amp" wall adapter from a linksys router that I didn't check with a DMM to a uno-R3 barrel jack.
The adapter was putting out 22v @ god only knows how many amps. But it had the exact same symptoms I am sorry to say.
I wound up going with a cheap 5v/3.3v selectable breadboard power supply. You might want to look into those for future use, I got mine for less than $3 on eBay.
https://www.ebay.com/itm/1pcs-Breadboard-Power-Supply-Module-Shield-3-3V-5V-MB102-Solderless-Bread-Board/133519600754?hash=item1f16636c72:g:9NcAAOSwZzNfYHel

god only knows how many amps - adapters don't "put out amps". They have a capacity for current. That's like saying I dipped my cup into a pond "god knows how much water was in it". You get out the amount you require. The excess capacity is not a problem.

@nick gammon, the point I was trying to make was the 12v adapter was damaged, I didn't check it. Once that part is blown, does it have the same resistance? (I.e volts / resistance = amps). Am I missing something?

Unregulated adapters may well have a higher voltage under little load. They would be designed to output (in your case) around 12V under the load of the device it is designed for. Regulated adapters output the advertised voltage (or should do) regardless of the load.

Wall adapters are not all the same. They can have AC and DC outputs. The DC outputs can be regulated or unregulated. Assuming 1 12V DC wall adapter unregulated you can get maybe 19Vdc from it depending on the design.Always check first, it is much more cost effective then going to the store to buy a new Arduino and what other devices.


text:
Connect SDRAM to STM32
Well, first of all hello to everything and thanks for reading my question. I am designing a board with STM32F730R8T6 MCU, and I want to connect MT48LC16M16A2P-6A to it which is 4MB SDRAM chip. The connections are pretty basic from what I saw, the thing is, how can I access that memory from my MCU? I mean there is a library or something to use it? and, if someone can send me an example schematic, to connect the memory I would appreciate it. Greetings.

As far as I know, you have to choose variant with FMC module (Flexible Memory Controller) with SDRAM support - that means you have to use 144pin version STM32F730Z8. The 100pin version does have FMC but doesn't support SDRAM.
After resolving this issue, it should be about configuring FMC module for using SDRAM (in STM32CubeMX for example) and the RAM will be available at some memory location according to the MCUs memory layout.


text:
Understanding NRF24L01 specifications
I was reading this tutorial about the NRF24L01 and came across a few terms which I did not clearly understand.

It uses the 2.4 GHz band

Does this refer to the frequency of the EM waves that the device uses to communicate?

If used in open space and with lower baud rate its range can reach up to 100 meters.

I know baud rate refers to how many "groups of bits" are transmitted per second. I don't quite understand why the range increases for a lower baud rate.

The module can use 125 different channels which gives a possibility to have a network of 125 independently working modems in one place. Each channel can have up to 6 addresses, or each unit can communicate with up to 6 other units at the same time.

Here, does a channel mean a single frequency? How is the range of possible channels decided (why 125) and how is the smallest detectable resolution decided (smallest change in frequency which would cause a change in channel)? So does a single unit work on only one frequency or could the same unit communicate at different frequencies at the same time and so be a part of different networks simultaneously? In effect, I am not able to make sense of this paragraph!

It uses the 2.4 GHz band

Does this refer to the frequency of the EM waves that the device uses to communicate?

Yes. It generates (and receives) radio waves in the region of 2.5GHz.

If used in open space and with lower baud rate its range can reach up to 100 meters.

I know baud rate refers to how many "groups of bits" are transmitted per second. I don't quite understand why the range increases for a lower baud rate.

Think of it like talking to someone. If you're stood right next to them you can speak nice and fast and they can understand you. Your speech comes across nice and clear.
However if you're the other side of a quarry you have to shout really loud, and if you talk too fast they can't understand you. You. Have. To. Shout. Slowly. so that they can understand you.
The environment makes a lot of difference to how your speech propagates. In large areas there's lots of echo and other things.  It's similar with RF communications. There's more noise and things that can interrupt communication. By having lower baud rates you're giving the receiver more time to understand what it's receiving and make sense of the data.

The module can use 125 different channels which gives a possibility to have a network of 125 independently working modems in one place. Each channel can have up to 6 addresses, or each unit can communicate with up to 6 other units at the same time.

Here, does a channel mean a single frequency? How is the range of possible channels decided (why 125) and how is the smallest detectable resolution decided (smallest change in frequency which would cause a change in channel)? So does a single unit work on only one frequency or could the same unit communicate at different frequencies at the same time and so be a part of different networks simultaneously? In effect, I am not able to make sense of this paragraph!

There's a number of different factors at play here. First there is the "Bandwidth" of the channel. This is the maximum amount of data that can be squeezed into a particular carrier frequency with a particular amount of "space" around the signal. You can think of the channel width as the diameter of a pipe. The wider the pipe the more water can be pushed through the pipe per second.
You want to slice the RF allocation up into enough channels to give enough concurrent access to lots of devices, but at the same time you want to have enough bandwidth per channel that you can transfer reasonable amounts of data.
It's all a balancing act.
Nordic decided 125 channels was the optimal balance for their application.
One nRF24L01+ can work at one frequency at a time. That's not to say you can't instruct it to change frequencies at any time, but it can only be listening on the one frequency at once. Just like a normal FM radio - you can only listen to one radio station at a time.
But the nRF24L01+ protocol uses addresses within that one chosen channel, so lots of devices can all be on the same channel to talk together, and each is distinct by its address.
The protocol also includes the concept of "pipes" which are virtual wireless circuits between two physical devices. Once you have configured a pipe with an address any other device can communicate with that pipe. You can configure up to 6 pipes, so up to 6 devices can send to the same target at the same time and each devices data is kept separate and distinct from the others. It's kind of like having 6 serial ports all connected to different devices at once.

Not sure where you get the 100 MHz (min? max?) from. Most users of the band use very different bandwidths: 22 MHz (802.11b), 20 MHz (802.11g), 40 MHz (802.11n), 1 MHz (Bluetooth), 2 MHz (BLE), 2 MHz (802.15.4 / Zigbee / Thread)... 100 MHz is the total size of the 2.4 GHz ISM band, but in many regions it's actually slightly smaller than that.

Wikipedia on the ism page. But I probably misunderstood it. It's badly written.

Yes. They call it a band, because the nRF24L01 can operate on frequencies from 2.400GHz to 2.525GHz

It's like talking slower to someone. It makes it easier to distinguish the signal from the noise.

Kind of. Every channel is 1Mhz apart from the next (2.4Ghz + (125 * 1Mhz) = 2.525GHz which is the range specified above). This difference is chosen more of less arbitrarily. The 125 channels is because it has to stay inside the ISM band 2.4-2.5Ghz. Note that the different channels can still interfere with each other, unless they are far enough apart from each other. Just like with WiFi where you had 11 channels, but were advised to only use channels 1, 6, or 11. The NFR can only run at one frequency/channel at a time. You can however change channels while it's running. But its better to have all running on the same channel and use the NRFs pipes to create separate "networks". Or even use the same pipe, but have the packet contain the info on what kind of data it contains.

Note that not all channels may be usable. In the EU (ETSI) region for instance, the 2.4 GHz ISM band stop at 2.4835 GHz, so you can only use channels 1-83 at 1 MHz (up to 1 Mbps) and only half of those at 2 MHz.

@jcaron good point. I wanted to include this, but I couldn't find a good source. It looks like north america is even more restrictive, with a max of 2.473GHz. You definitely want to stay within these limits, and not risk fines or jail.


text:
How to slowly change direction of the stepper motor with AccelStepper?
I know that direction can be changed with
.setSpeed(speed);
... //check input
.setSpeed(-speed);

I need to slowly decelerate and accelerate backwards, so I have to use
.setAcceleration(200);
...
.setMaxSpeed(speed);
... //check input
.setMaxSpeed(-speed);

but documentation told that .setMaxSpeed argument Must be > 0.
So how to properly change direction with deceleration? Probably I have to use .moveTo with some very big values

have you looked at the example code that is included with the library?

The library defines speed as steps per second. It doesn't care about the direction the steps are in. Just like you can't get out of a speeding tickets by always driving in reverse ;-).

I have tested it on real motor, and it works as I want with function .moveTo . Speed slowly changed from +maxSpeed to -maxSpeed acording to Acceleration
#define maxSpeed 1000
#define Acceleration 500
............
void setup(){
  stepper.setMaxSpeed(maxSpeed);
  stepper.setAcceleration(Acceleration);
}
void loop() {
 ............
 if(bDirection!=bDirection_last)
 {
  stepper.moveTo(bDirection?6000000:-6000000);
  ...........
 }
 stepper.run();
}


text:
Why does the following code not cause the led's to flash but rather stay on continuously

int timer = 1000;
int thispin = 5;

void setup() {
  for (int thispin = 5; thispin < 8; thispin++)
    pinMode(thispin, OUTPUT);
}

void loop() {
  for (int thispin = 5; thispin < 8; thispin++)
    digitalWrite(thispin, HIGH);

  delay(timer);
  digitalWrite(thispin, LOW);

  for (int thispin = 7; thispin = 5; thispin--)
    digitalWrite(thispin, HIGH);

  delay(timer);
  digitalWrite(thispin, LOW);
}

I have the above code. I thought that how it was written would cause the led's to flash but they all stay on continuously. Could anybody help to explain what it is i have done wrong?
I am very new to this and I'm just fiddling basically trying to learn.
Thank you!

Added code tags and indentation - it should be more obvious what is done by loops and what is not executed repeatedly by loops. Also  ; thispin = 5; ... is an assigment not comparation.

you only set pin 5 LOW. it is the global thispin

if you coded the program correctly, how long do you think that the low output would last after this line? ... digitalWrite(thispin, LOW); ... in your code, what is the value of thispin?

please review the documentation of the for loop ... it does not work as you think

A = won't work. You have to change it to ==.

You'll only see OUTPUT values during the delay() calls, Everything else, including the restart of loop() is way too fast. In your code, during delay, the pins are all HIGH.

The objective of the code is not clear. It seems the idea is to repeatedly blink 3 LEDs, connected on pins 5,6 and 7. To do so, the code needs slight modification-
int timer = 1000;
int thispin = 5;

void setup() {

  for (int thispin = 5; thispin < 8; thispin++)
    pinMode(thispin, OUTPUT);
}

void loop() {

  for (int thispin = 5; thispin < 8; thispin++)
    digitalWrite(thispin, HIGH);

    delay(timer);

  for (int thispin = 5; thispin < 8; thispin++)
    digitalWrite(thispin, LOW);

    delay(timer);

}

Also, since you wanted to know why the LEDs stay ON continuously with your code-
This is because there is no delay statement after any of the digitalWrite-LOW statements. If there's no delay, the LEDs may turn off for a fraction of a millisecond, which won't be noticeable.

From the given code it is not entirely clear what you are trying to achieve.
If I understood correctly, you want the pins to light up for one second and then go out. First from 5 to 7, and then from 7 to 5.
Try the given code.
int timer = 1000;

void setup()
{
  for (int thispin = 5; thispin < 8; thispin++)
    pinMode(thispin, OUTPUT);
}

void loop()
{
  for (int thispin = 5; thispin < 8; thispin++)
  {
    digitalWrite(thispin, HIGH);
    delay(timer);
    digitalWrite(thispin, LOW);
  }

  delay(timer);

  for (int thispin = 7; thispin >= 5; thispin--)
  {
    digitalWrite(thispin, HIGH);
    delay(timer);
    digitalWrite(thispin, LOW);
  }
}

Also, using the same name for globals variable and  loop iterators is bad style.

Exchange the last lines:
delay(timer);
digitalWrite(thispin, LOW);

It is 2 seconds on and maybe a few hundred nanoseconds on.

In the last for() loop, the limit expression, thispin =5; was probably meant to say thispin <=5;. As it is written, the expression is an assignment, not a test, and it will always be true, because 1) an assignment statement is also an expression having a value equal to the value assigned; and 2) the assigned value, '5', being non-zero, is equivalent to 'true'), so this loop will never end. thispin will get decremented forever and repeatedly set pin 5 to HIGH. It leaves the other pins alone, but they were already high, and the LEDs stay lit, which is what you observed.
(There are a couple of other errors, as noted earlier by previous responders, which will also prevent your code from operating as you expected.)


text:
Arduino Due SerialUSB Resetting
Having this basic example for using the SerialUSB function on the Arduino Due under Windows:
// ARDUINO DUE BLINK LED
void setup(){
  pinMode(13,OUTPUT);
  SerialUSB.begin(2000000);
  while(!SerialUSB){
    digitalWrite(13,HIGH);
    delay(100);
    digitalWrite(13,LOW);
    delay(100);
  }
}

void loop(){
  SerialUSB.println("Hello, World!");
  digitalWrite(13,HIGH);
  delay(100);
  digitalWrite(13,LOW);
  delay(900);
}

I am having trouble understanding which shall be the operating sequence for this use. Normally I follow these steps:

Open Arduino IDE, select Arduino Due (Programming Port) at COM 01, and connect it to PC USB,
Compile and Upload the code,
Open a Serial Monitor App, with COM 02, 2000000 bps or 9600 bps, 8b data, 1b stop, no parity, RTS|CTS flow control.

If I keep the Arduino connected to the Programming Port after trying the Native USB Port, I have to disconnect and connect everything to program it again (??), or disable it through the windows Device Manager.
Which is the proper sequence (and perhaps the code) for doing this the right way?.

You have to have flow control set to hardware for the Arduino to know the port has been opened.

Thanks @Majenko. That solved a big part of the problem. I have updated the question.

Assume the Arduino is already programmed and energized, i.e. from the Barrel 5V Power Source or from a USB Charger (as minimum) at Programming USB Port.
The following should be the proper steps:

If not Programmed: Program the Arduino, either through the Programming USB Port, Native USB Port, etc.
If Native USB Cable to PC is Plugged: Unplug Cable, or Reset Arduino,
Plug Native USB Cable to PC,
Check COM Number for the Native USB Port, i.e. COM01,
If Serial Monitor Connected: Disconnect Serial Monitor,
Connect through a Serial Monitor App, with COM01, any bps, 8b data, No parity, 1b stop, RTS|CTS flow control.

Done. The data flow should start immediately as soon as you Reset.
Check this for a deeper post with another example for debugging.