text:
Why atmega168/328p starts to reset?
First we set fuse bits:
avrdude -c usbasp -p atmega328p -U lfuse:w:0xFF:m -U hfuse:w:0xDF:m -U efuse:w:0x07:m # same for atmega168

In the following examples we use the following commands to compile and burn all the programs:
avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
avr-ld -o serial.elf serial.o
avr-objcopy -O ihex serial.elf serial.hex
avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

Let us burn the following program:
#define F_CPU 16000000UL
#include <avr/io.h>
void main (void) {
  DDRB |= (1<<PB5);
  PORTB |= (1<<PB5);
  while (1);
}

It makes the led to be on constantly. And it stays so for infinite period of time.
Then we burn the following program:
#define F_CPU 16000000UL
#define BAUD 9600
#include <avr/io.h>
char data = 0;
void main(void) {
  // Initialize USART:
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE; // set the speed (Higher bit)
  UBRR0L = UBRRL_VALUE; // set the speed (Lower bit)
  UCSR0B |= (1<<RXEN0); // enable receiver
  UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00); // set mode (8N1)
  DDRB |= (1<<PB5); // enable output on pin PB5 (default led on arduino)
  while(1) {
    while(!(UCSR0A&(1<<RXC0))); // wait until a byte is received
    data = UDR0; // read it
    if (data) PORTB |= (1<<PB5); // set the led on
  }
}

Then we open a terminal (9600,8N1) and press several keys, until the led turns off.
Now we burn the first program again and the led is constantly blinking. The reason for this is that watchdog times gets started when we press the keys in terminal. But why and when WDT gets started? How to make so that it will not start?
It should be noted also that we can disable the blinking only with complete poweroff/poweron - only after that the led lights constantly without blinking, as necessary.
This happens on atmega168 and atmega328p, 100% reproducible.
avr-gcc version 4.8.1 avrdude version 6.1
NOTE: bootloader is not used at all.

void main(void) {   #include <util/setbaud.h>  This caught my eye. It's quite unusual to do an include within the code? I'm not sure if it might cause issues.

Also, I'm not sure how watchdog is related to this question? You can disable it's fusebit?

and your if (data) PORTB |= (1<<PB5); will flip the LED on and off whenever data is set to something. You should reset the value? Even though the while(!( might block it from happening.

One thing that I found whilst experimenting with command line compilation is that for some strange reason no startup code was being linked with my code, so it all went completely screwy.
I finally tracked the problem down to a missing command line flag while linking.
First, you need to link with avr-gcc not avr-ld.  Second, you need to pass the -mmcu=atmega328p flag to the link command so that it knows which startup code to link in.
This is my complete command line sequence for compiling a simple blink program:
avr-gcc -g -mmcu=atmega328p -ffunction-sections -fdata-sections   -c -o blink.o blink.c
avr-gcc -mmcu=atmega328p -Wl,--gc-sections -o blink.elf blink.o
avr-objdump -S blink.elf > blink.dis
avr-objcopy -O ihex -R .eeprom blink.elf blink.hex

You notice I'm making function and data sections too, and then garbage collecting the unused ones - good practice since it can very much reduce the size of your finished program.
I am doing this through a Makefile, which looks like this:
PREFIX=avr-
CC=${PREFIX}gcc
CXX=${PREFIX}g++
LD=${PREFIX}ld
AS=${PREFIX}as
OBJCOPY=${PREFIX}objcopy
OBJDUMP=${PREFIX}objdump

BIN=blink
MCU=atmega328p
OBJS=blink.o

CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions
LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} ${LDFLAGS} -o $@ $?
    ${OBJDUMP} -S $@ > ${BIN}.dis

install: ${BIN}.hex
    avrdude -c usbasp -p ${MCU} -U flash:w:${BIN}.hex -qq

clean:
    rm -f *.o *.elf *.hex

fuses:
    avrdude  -c usbasp -p ${MCU} -U lfuse:w:0xff:m -U hfuse:w:0xd6:m -U efuse:w:0x05:m -qq

No, Like I said in my answer on EE, this has nothing to do with the Bootloader or the WDT. You seem to not understand fundamentally how this whole thing works...

The problem code was reduced to this:
#define F_CPU 16000000UL
#include <avr/io.h>
char data;
void main(void) {
  UBRR0H = 0x00;
  UBRR0L = 0x67; // baud=9600
  UCSR0B = 0x10; // 00010000
  UCSR0C = 0x06; // 00000110
  DDRB |= (1<<PB5);
  PORTB |= (1<<PB5);
  while(1) {
    data = UDR0;
  }
}

This is the code which works:
#define F_CPU 16000000UL
#include <avr/io.h>
void main(void) {
  char data;
  UBRR0H = 0x00;
  UBRR0L = 0x67; // baud=9600
  UCSR0B = 0x10; // 00010000
  UCSR0C = 0x06; // 00000110
  DDRB |= (1<<PB5);
  PORTB |= (1<<PB5);
  while(1) {
    data = UDR0;
  }
}

But I don't know how to explain that char inside main makes the problem disappear...
EDIT
Just for the record, here are two more examples. The first example works with both compilation methods. The second example works only with the second compilation method. The examples differ only with that in the first direct code is used, and in the second it is used via functions.
#define F_CPU 16000000UL
#define BAUD 9600

#include <avr/io.h>
void main(void) {
  char data;
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE;
  UBRR0L = UBRRL_VALUE;
  UCSR0B = (1<<RXEN0)|(1<<TXEN0);
  UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);
  DDRB = (1<<PB5);
  while (1) {
    PORTB ^= (1<<PB5);
    while(!(UCSR0A&(1<<RXC0)));
    data = UDR0;
    UDR0 = data;
    while(!(UCSR0A&(1<<TXC0)));
  }
}

#define F_CPU 16000000UL
#define BAUD 9600

#include <avr/io.h>
void serialSetup(void) {
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE;
  UBRR0L = UBRRL_VALUE;
  UCSR0B = (1<<RXEN0)|(1<<TXEN0);
  UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);
}
void serialSend(char data) {
  UDR0 = data;
  while(!(UCSR0A&(1<<TXC0)));
}
char serialGet(void) {
  while(!(UCSR0A&(1<<RXC0)));
  return UDR0;
}
void main(void) {
  char data;
  serialSetup();
  DDRB = (1<<PB5);
  while (1) {
    PORTB ^= (1<<PB5);
    data = serialGet();
    serialSend(data);
  }
}

This may be related to a strange thing I was seeing when manually compiling that I just couldn't fathom - there seemed to be no crt0 being linked in, except if you had a global variable, which caused just the BSS portion of the crt to exist. If I added another function to the program suddenly that function became the entry point instead of main(). It was all messed up and completely brain melting.  And yet I was calling the same compiler and command line options as compiling for the Arduino API. It made no sense at all.

Actually I just solved my problem - and it will probably solve yours too.  I'll post an answer with the detail.

@Majenko: Yes, it solved the problem!

@Majenko: But I did not understand the reason why it spontaneously starts to reset itself, and what your commands do to fix it. Could you please give some recommendations for further reading to understand what causes the problem and how it is cured?

With the WDT, once it has started firing it's almost impossible to disable it. You can only disable it from "cold" so it never gets a chance to fire.  Also without the proper startup code (crt0) it's anyone's guess what will actually happen with the program when it's run - variables won't be initialized, exception vectors won't be set up, etc etc.

WDT settings will remain unchanged, even after a reset. So the timer will keep running and therefore keep resetting the device. Which causes the blinking. Power cycling will clear the WDT settings.
PS I didn't read the code, as uncommented register writes are pretty much unreadable.


text:
Arduino Ground Current and DC power jack
I have a project where I'm providing power via the DC jack to my Arduino then accessing the DC power via the VIN pin. According to this http://forum.arduino.cc/index.php?topic=453955.0 I am ok to draw up to 1A from the VIN pin. I have measured 400ma out of VIN, so ok on that front.
But according to this http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations I can draw max 400ma, So I'm a bit confused, which is the correct amount of power VIN can supply if the Arduino is being powered via the DC jack?
If I take the first thread as correct and assume it's ok to draw up to 1A from the VIN pin (from the DC power jack), is it ok to ground that current on the Arduino GND pin ? if VIN can supply up to 1A then I assume that it's ok to ground up to 1A, is this correct?
All help appreciated

Going by the schematic here there is an M7 diode (D1) between the power jack and the VIN pin on a Uno (you don't actually say which board you're using, I'm guessing based on the first link).
The datasheet here indicates that the maximum forward current for a M7 diode is 1.0 A. However different manufacturers datasheets seem to disagree as to whether that is a sustained DC current or only rectified current (so 50% load implying ~500mA constant load).
Either way you are looking at a potential 1.1 V drop across the diode so your VIN will be below the supply voltage by up to that much.
If you want to live dangerously you can always replace D1 with a piece of wire (or put the wire across it). You will lose reverse voltage protection on the DC jack, using a supply with it backwards will blow things up, but your current will then be limited by how much current the connector pins and PCB trace can cope with before they melt.

source: Stack Exchange

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

sort: votes


text:
Why do all analog pins measure the same value?
I measure 2 analog pins: A4 and A5. The A5 pin is connected to another Arduino's digital out (through a 10k resistor) which has a simple program: 5ms on and 100ms off. The A4 pin is not connected anywhere.
The analog pins are inited with pinMode(APIN, INPUT), reading is simply performed with the analogRead(APIN) function (there is no delay between the readings). I have tried with delays between the measurements but the results are the same.
The results:
The A5 pin (which is connected) measures the correct value. However, the unconnected A4 pin is clearly interferred by the input of A5. It works like this with another pins, delays between the readings, double use of analogRead()... I even swapped the Arduinos (Arduino Nano and Uno) and the results are the same.
Is it because of that these Arduinos are clones? Or are these Arduinos damaged?

Did you try connecting A4 to VCC or GND? Floating signal can give this behavior.

Thank you, it seems to work. Can I connect a pin directly to VCC or should I use resistor?

If you want to measure a pin (i.e. defined as input pin, either digital or analog), you have to use a pull up or pull down resistor (either internal or external depending on what the MCU GPIOs have).
This resistor makes sure in case there is nothing attached, that the (mostly high ohm) resistor will make sure the nonconnected pin will either give a LOW or HIGH as input (or in case of analog, the minimum or maximum value).
When the pin is connected, the pull down/up resistor will change the result so marginally that it can be ignored.

I believe what you are seeing is the effect of the sample and hold process used by the Arduino analog to digital converter (ADC).
The way the sample and hold circuit in the ADC works is

Connect the pin to an internal, fixed size capacitor
Disconnect the pin
Compare the capacitor voltage against a fixed value

All the analog pins in the Arduino share the very same capacitor, so if such capacitor has no opportunity to discharge another reading will be influenced by the previous one.
Ref.

https://en.wikipedia.org/wiki/Sample_and_hold
http://ww1.microchip.com/downloads/en/appnotes/atmel-8456-8-and-32-bit-avr-microcontrollers-avr127-understanding-adc-parameters_application-note.pdf

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


text:
How to drive a stepper motor, by having it go even steps forward and odd steps back?
I have a question about driving a stepper motor back and forward. Basically I want it to do a total of 24 steps (12 forward and 12 back) but I don't want to repeat the same steps when coming back.
So 2, 4, 6, 8, 10, 12 (step numbers) forward and 11, 9, 7, 5, 3, 1 (step numbers) backwards.
Here is the code I have at the moment and I just cannot get the motor to drive properly.
EDIT: It goes 6 times 2 steps forward, then 5 times backwards and after that it starts to just jerk around. What I want it to do is to go 6 times 2 steps forward (so step 2, step 4, step 6, step 8, step 10, 12) and then come back but fill in the odd steps (step 11, step 9, step 7, step 5, step 3, step 1 and step 0). The idea is that then it doesn't just overlap when going forwards and backwards.
#include <Stepper.h>
#include <TimerOne.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
int backwardsCount = 0;
int stepCount = 0;

void setup() {
  Serial.begin(9600);
  Timer1.initialize(2000);
  Timer1.attachInterrupt(callback);
}

void callback(){
  if(stepCount < 12) {
    myStepper.step(2);
    stepCount += 2;
  } else if(stepCount == 12) {
    myStepper.step(-1);
    backwardsCount = 11;
    stepCount += 1;
  }
  if(backwardsCount > 1) {
    myStepper.step(-2);
    backwardsCount -= 2;
  } else if(backwardsCount == 1) {
    myStepper.step(-1);
    stepCount = 0;
    backwardsCount = 0;
  }
}

void loop() {
}

I'd suggest you to implement this as a small state machine. Moreover, why doesn't it do what you want? What do you expect it to do and what does it do in reality?

I added it to the edit part in the description :)

Changing if(backwardsCount > 1){ to else if(backwardsCount > 1){ would fix the 5 instead of 6 "steps" back.

I'm voting to close this question as off-topic because it is based on a false premise.  A rotational motor must pass through all intermediate angles of rotation, so the goal is impossible.  You could change the points at which the motor pauses for a dwell time, but if that is your goal then you need to write the question to say so, and then not abandon it for four months.

Ok, I tried to fix a couple of things from your code.
First of all I implemented a small state machine with two states: going forwards and going backwards. Normally you advance by 2 steps, but when you switch state you go directly to 0 or 11. In my opinion this is the most correct way to handle this problem.
Then I modified the way you trigger a movement. I totally dislike interrupts, specifically when not needed like in this case (at least in my opinion). I used the usual approach with millis(). Please note, however, that I had to put 2 milliseconds as period, but I think this was a mistake from your side (I think you wanted 2 seconds). If this is the case, write const uint16_t moveStepMs = 2000; instead of const uint16_t moveStepMs = 2;. If you want to keep the 2ms, please be aware that 2ms * 6 = 12ms, so it will go back and forth in about 25ms. This means it is too fast for you to see anything (and probably also for the motor to move).
Here is the code. I hope it is clear; I tested it online, but there wasn't a stepper in the simulator so I just used some LEDs (I think it works, anyway).
#include <Stepper.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);

const byte State_MovingForw = 1;
const byte State_MovingBack = 2;

byte currentState;
int8_t position; // Note: max 127 for position

const uint16_t moveStepMs = 2;
unsigned long prevMillis;

void setup() {
    Serial.begin(9600);
    prevMillis = millis() - moveStepMs;
    currentState = 0; // Invalid, so it will trigger a change
}

void executeStep(int8_t numOfSteps)
{
    myStepper.step(numOfSteps);
    position += numOfSteps;
}

void loop() {
    if ((millis() - prevMillis) > moveStepMs)
    {
        prevMillis += moveStepMs;
        byte nextState = currentState;

        // Check for a state change
        switch (currentState)
        {
        case State_MovingForw:
            if (position >= 12)
                nextState = State_MovingBack;
            break;
        case State_MovingBack:
            if (position <= 1)
                nextState = State_MovingForw;
            break;
        default:
            nextState = State_MovingForw;
        }

        if (nextState != currentState)
        {
            // Exit condition: what to do when exiting from one state
            switch (currentState)
            {
            case State_MovingForw:
                executeStep(0 - position); // Reset position to 0
                break;
            case State_MovingBack:
                executeStep(11 - position); // Reset position to 11
                break;
            }

            // Advance to next state
            currentState = nextState;
        }
        else
        {
            // no state change (so move to the next value)
            switch (currentState)
            {
            case State_MovingForw:
                executeStep(2); // Move two steps forwards
                break;
            case State_MovingBack:
                executeStep(-2); // Move two steps backwards
                break;
            }
        }
    }
}

Actually I do want the shaft to step every 2 ms because the idea is to quickly move a mirror attached to the shaft that has a laserbeam pointed on it, creating an illusion like there are multiple laserbeams. I have already tried just stepping 12 steps forward and 12 steps back and the motor can handle that kind of speed. The problem was however that the laserbeams didnt match up and they got doubled. I want to have exactly 12 laserbeams. I used a timer because I need to also control the laser (turn off when the motor is stepping and on when it is still).

Ok, but I think you will need the motor to arrive at the desired position. Maybe this is the issue you are seeing: you are firing the laser when the motor is still moving

Well the motor wasnt moving properly, it actually worked when I used the 'setspeed()' command but that command conflicts with TimerOne for some reason so the timer won't work then. However I will try your and let you know of the result :). Thanks in advance already!

@Mr.Owels if this answer "answered" your question please mark it as accepted, or the community bot will think it is still unanswered and continue pushing it to the homepage

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


text:
Arduino and MatLab with OWI Robotic Arm Edge -- Issue with I2C
I'm working on a project where I want to be able to program a robotic arm in Arduino using MatLab. I've used the Arduino Uno with an Adafruit Motor Shield V2.3 and the OWI Robotic Arm Edge kit. The arm is perfectly assembled and works just fine with the standard remote it comes with. All of the connections with the Adafruit Motor Shield are correctly placed, and the shield has been soldered onto pins that connect to the Uno.
I am absolutely positive that the physical and electronic setup is correct. However, whenever I try to move the motors attached to the shield, none of them register. Below is my code:
a = arduino('COM3', 'Uno', 'Libraries', 'Adafruit\MotorShieldV2')
shield = addon(a, 'Adafruit\MotorShieldV2')
addrs = scanI2CBus(a,0);

dcm = dcmotor(shield, 1);
dcm.Speed = 0.01;
start(dcm)

dcm2 = dcmotor(shield, 2);
dcm2.Speed = 0.2;
start(dcm2)

dcm3 = dcmotor(shield, 3);
dcm3.Speed = 0.2;
start(dcm3)

dcm4 = dcmotor(shield, 4);
dcm4.Speed = 0.2;
start(dcm4)

I believe the issue is with the third line:
addrs = scanI2CBus(a,0);

When I run the code, the shield has the following properties:
shield =

motorshieldv2 with properties:

          Pins: A4(SDA), A5(SCL)
    I2CAddress: 96 (0x60)
  PWMFrequency: 1600 (Hz)

So while the I2C address should be 0x60, the actual value of the addrs variable is a 2x1 cell instead of 0x60, as the project demands/specifies as seen in the workspace:

I'm almost certain that this is the reason behind why none of the motors are being registered, but how can I fix it?
Thanks in advance for any assistance! Please let me know if I need to supply more information.

The documentation in MATLAB for scanI2CBus() notes that the return is a cell array of character vectors
They even give the example:
a = arduino('COM9');
scanI2CBus(a,1)

with result:
ans =
            '0x48'

It appears you will need to parse the cell array into the numeric value or otherwise convert it to a number, perhaps using the MATLAB function hex2dec('hex_value')

Thank you for your help, I'll give it a try as soon as I get home!  I'll also be sure to share my results, hopefully I'll get feedback from my motors. Out of curiosity, is it "allowed" for me to assign the value '0x60' to the I2C address variable?

The I2C address is defined by the device. Your sensor probably has it hard coded or it may be set by hardware jumpers on the sensor. It’s not likely you can change it by just assigning a value to the variable.

I think I found out what the  defecting factor is--the I2C address issue may be due to improper soldering of the Motor Shield to the Arduino itself; I realized that the power of the Motor Shield flickers in and out, so that may be the root of the problem.

Don’t try to power the motor shield from the Arduino.


text:
Receive data from Arduino board to Android application
I'm trying to receive data and print it on a label of my application, but I can not get it. Actually, I have 0 experience with Arduino. It's the first time I see this. I read this tutorial to receive data from an Arduino. In my Arduino I have this code:
#include <SoftwareSerial.h>
const int RX_PIN = 2;
const int TX_PIN = 3;
SoftwareSerial blueTooth(RX_PIN, TX_PIN);
char commandChar;

void setup () {
  Serial.begin(57600);
  Serial.println("Let's start!");
  blueTooth.begin(9600);
  blueTooth.println("Hello, world?");
}

void loop () {
 if (blueTooth.available())
    Serial.write(blueTooth.read());
  if (blueTooth.available())
    blueTooth.write(Serial.read());
}

My Android code is this:
public class MainActivity extends AppCompatActivity {
FrameLayout frame;
GifImageView imagen;
TextView mensaje,debug;
Button boton;
private TextToSpeech talk;
public static StringBuilder sb;
private static final String TAG = "conexionBluetooth";
ConnectedThread mConnectedThread;
BluetoothAdapter blueAdapter;
BluetoothDevice mDevice;
BluetoothSocket mSocket;
Handler handler;

final int MENSAJE_RECIBIDO = 1;
final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String MAC = "00:21:13:02:EA:07";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_main);
    talk = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int i) {
            if(i == TextToSpeech.SUCCESS){
                talk.setLanguage(Locale.US);
                mensajeInicio();
            }
        }
    });
    debug = (TextView) findViewById(R.id.debug);
    mensaje = (TextView) findViewById(R.id.mensajeApp);
    frame = (FrameLayout) findViewById(R.id.androidIc);
    imagen = (GifImageView) findViewById(R.id.imageBluethoot);
    imagen.setVisibility(View.INVISIBLE);
    frame.setVisibility(View.VISIBLE);
    boton = (Button) findViewById(R.id.botonInicio);
    Animation flotarArriba = new TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0.05f
    );
    flotarArriba.setDuration(1000);
    flotarArriba.setRepeatCount(-1);
    flotarArriba.setRepeatMode(Animation.REVERSE);
    flotarArriba.setInterpolator(new LinearInterpolator());
    mensaje.setAnimation(flotarArriba);
    boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boton.setEnabled(false);
            mConnectedThread.write("0");
            Toast.makeText(getApplicationContext(),"Data send to arduino",Toast.LENGTH_LONG).show();
        }
    });
    handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MENSAJE_RECIBIDO:
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, msg.arg1);
                    sb.append(strIncom);
                    int endOfLineIndex = sb.indexOf("\r\n");
                    if (endOfLineIndex > 0) {
                        String sbprint = sb.substring(0, endOfLineIndex);
                        sb.delete(0, sb.length());
                        debug.setText(sbprint);
                        boton.setEnabled(true);
                    }
                    //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                    break;
            }
    }};
    configBluetooth();
    comprobarEstadoBluetooth();
}

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "...onResume - try connect...");

    BluetoothDevice device = blueAdapter.getRemoteDevice(MAC);

    try{
        mSocket = crearSocket(device);
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(),"ERROR!! No se ha logrado crear el enchufe! " + e.getMessage(),Toast.LENGTH_LONG).show();
        finish();
    }

    blueAdapter.cancelDiscovery();

    Log.d(TAG, "...Connecting...");
    try{
        mSocket.connect();
        Log.d(TAG,"Connection OK!!");
    } catch (IOException e) {
        try{
            mSocket.close();
        } catch (IOException e1) {
            Toast.makeText(getApplicationContext(),"Error fatal en el metodo onResume. Incapaz de cerrar conexion: " + e1.getMessage(),Toast.LENGTH_LONG).show();
            finish();
        }
    }
    mConnectedThread = new ConnectedThread(mSocket);
    mConnectedThread.start();
}

@Override
public void onPause() {
    super.onPause();
    Log.d(TAG, "...In onPause()...");
    try {
        mSocket.close();
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(),"Error fatal en el metodo onPause. Incapaz de cerrar conexion: " + e.getMessage(),Toast.LENGTH_LONG).show();
    }
}

private void enable() throws IOException {
        boton.setText(getString(R.string.finalizar));
        mensaje.setText(getString(R.string.mensajeActivo));
        frame.setVisibility(View.INVISIBLE);
        imagen.setVisibility(View.VISIBLE);
        mensaje2();
        boton.setText(getString(R.string.iniciar));
        mensaje.setText(getString(R.string.pontelos));
        frame.setVisibility(View.VISIBLE);
        imagen.setVisibility(View.INVISIBLE);
        mensaje1();

}

private void mensajeInicio(){talk.speak(getString(R.string.app_name) + getString(R.string.textApp) + getString(R.string.pontelos),TextToSpeech.QUEUE_FLUSH,null);}
private void mensaje1(){talk.speak(getString(R.string.pontelos),TextToSpeech.QUEUE_FLUSH,null);}
private void mensaje2(){talk.speak(getString(R.string.mensajeActivo),TextToSpeech.QUEUE_FLUSH,null);}

private void configBluetooth(){
    Toast.makeText(getApplicationContext(),"Metodo llamado",Toast.LENGTH_LONG).show();
    blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if(blueAdapter != null){
        Set<BluetoothDevice> pairedDevices = blueAdapter.getBondedDevices();
        if(pairedDevices.size() > 0){
            for(BluetoothDevice device: pairedDevices){
                if(device.getName().equals("HC-06")) {
                    mDevice = device;
                    Toast.makeText(getApplicationContext(), "Nombre del dispositivo: " + mDevice.getName() +
                            "\nDireccion MAC: " + mDevice.getAddress() + ".", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

private void comprobarEstadoBluetooth(){
    if(blueAdapter == null){
        Toast.makeText(getApplicationContext(),"ERROR!!! No hay soporte Bluetooth!",Toast.LENGTH_LONG).show();
        finish();
    }else{
        if(blueAdapter.isEnabled()){
            Toast.makeText(getApplicationContext(),"Bluetooth encendido. . .",Toast.LENGTH_LONG).show();
        }else{
            Intent activarBTH = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(activarBTH, 1);
        }
    }
}

private BluetoothSocket crearSocket(BluetoothDevice device) throws IOException {
    if(Build.VERSION.SDK_INT >= 15){
        try{
            final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
            return (BluetoothSocket) m.invoke(device, uuid);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    return device.createRfcommSocketToServiceRecord(uuid);
}

private class ConnectedThread extends Thread {
    private final InputStream mInStream;
    private final OutputStream mOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mInStream = tmpIn;
        mOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[256];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mInStream.read(buffer);        // Get number of bytes and message in "buffer"
                handler.obtainMessage(MENSAJE_RECIBIDO, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
                handler.handleMessage(new Message());
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String message) {
        Log.d(TAG, "...Data to send: " + message + "...");
        byte[] msgBuffer = message.getBytes();
        try {
            mOutStream.write(msgBuffer);
        } catch (IOException e) {
            Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
        }
    }
}
}

I notice the following behaviors:

The application does not crash when it is executed.
When I start the application, the bluetooth module of the Arduino flashes differently. (I guess it's because my app connectswith the board).
Inside the Log Cat, it can be seen that the connection has been made correctly. . .

What could be missing here to print the data received from the Arduino? I do not know if it's me, or the handler method never runs. (public void handleMessage (Message msg))
Also note that in the serial monitor of the Arduino, the value that I command when pressing the button of the application is never printed...
UPDATE
Investigating on the internet about the module of my Bluetooth (HC-06) I found that;

If the light of the module is constantly flashing, it is not paired
with the phone.
If the module light stays on, then it is already connected.

My concern is that when I open my application, to blink constantly, it blinks much slower. . . Could it be that I've never been able to connect?

If you are not connected to the HC-06 and try to work with the socket, the monitor of your Android applications would at least show an error. Habe you checked, if you get an IOException when opening the streams? Your exeption handler is empty

And have you tried this with a bluetooth serial terminal app in your phone? So you can rule out a Problem with the arduino code vor wiring.

Hello,I  follow your advice:
In effect, if I am not connected to the bluetooth (or if I connect, and the bluetooth module is badly connected) the application releases an error. Download what you suggested (Bluetooth termial), I could verify that I am connecting with the module HC-06. But I can not receive data at the end ... @chrisl

Then maybe you use the wrong baudrate. My HC-06 is configured for 9600 baud by standard, but in the web you see several, which use other baudrates by default. Try to use other baudrates (for example 57600 I think). Also you can configure the module for different baudrates by using AT commands

Oh right! I changed that too @chrisl ! Serial and bluetooth begin at 9600 now! I forgot to add that in my answer

I don't think your code is correct:
void loop () {
 if (blueTooth.available())
    Serial.write(blueTooth.read());
  if (blueTooth.available())         <----
    blueTooth.write(Serial.read());
}

Shouldn't you be monitoring Serial.available on this line?

Oh, well, I made the change that you say but nothing happends :/

I could solve it already !!!! It turns out that the bluetooth module was badly connected to the arduino !!!! I can already receive data! thank you very much for your comments, especially chrisl, for your suggestion to use the bluetooth serial monitor app! :)
I had connected the VCC to 5V ... that was what was bothering me, I read on the web that if you have it in 5V, as a self defense, the RX pin is completely blocked. The VCC must be connected to 3.3V.
EDIT: I forgot something very important! had to change the baud of bluetooth to 9600 like Serial! this part was very important too.


text:
Sending Data from ESP8266 to PHP
I want to display the RFID tag value to a html file.
I am using ESP8266 ESP-01 module, EM-18 Reader Module, Arduino Uno and Xampp for hosting PHP.
Right now, I am getting a value of "255" in Arduino whenever I scan a RFID tag. But I am supposed to get the 12-digit alphanumeric RFID tag value.
I have attached the Arduino and also the output screen of the Serial Monitor.
I have my college submission next week so it's urgent. Any help would be appreciated.
#include "SoftwareSerial.h"
String ssid ="Home";
String password="****";
SoftwareSerial esp(2, 3);// RX, TX
String data;
String server = "192.168.0.182"; // www.example.com
String uri = "/testget.php";// our example is /esppost.php
int DHpin = 0;//sensor pin
byte dat [12];
String tag;

void setup() {
  pinMode (DHpin, OUTPUT);
  esp.begin(9600);
  Serial.begin(9600);
  reset();
  connectWifi();
}

//reset the esp8266 module

void reset() {
  esp.println("AT+RST");
  delay(1000);
  if(esp.find("OK") )
    Serial.println("Module Reset");
}

//connect to your wifi network

void connectWifi() {
  String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
  esp.println(cmd);
  delay(4000);
  /*
  if(esp.find("OK")) {
    Serial.println("Connected!");
  }
  else {
    connectWifi();
    Serial.println("Cannot connect to wifi"); }*/
}

byte read_data () {
  byte data;
  for (int i = 0; i < 13; i ++) {
    if (digitalRead (DHpin) == LOW) {
      while (digitalRead (DHpin) == LOW); // wait for 50us
        delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'
      if (digitalRead (DHpin) == HIGH)
        data |= (1 << (12-i)); // high front and low in the post
      while (digitalRead (DHpin) == HIGH);
// data '1 ', wait for the next one receiver
    }
  }
  return data;
}

void start_test () {
  digitalWrite (DHpin, LOW); // bus down, send start signal
  delay (30); // delay greater than 18ms, so DHT11 start signal can be detected
  digitalWrite (DHpin, HIGH);
  delayMicroseconds (40); // Wait for DHT11 response
  pinMode (DHpin, INPUT);
  while (digitalRead (DHpin) == HIGH);
    delayMicroseconds (80);
  // DHT11 response, pulled the bus 80us
  if (digitalRead (DHpin) == LOW);
    delayMicroseconds (80);
  // DHT11 80us after the bus pulled to start sending data
  for (int i = 0; i < 13; i ++)
    // receive tag value data, the parity bit is not considered
    dat[i] = read_data ();
  pinMode (DHpin, OUTPUT);
  digitalWrite (DHpin, HIGH);
  // send data once after releasing the bus, wait for the host to open the next Start signal
}

void loop () {
  start_test ();
  // convert the bit data to string form
  tag= String(dat[12]);
  data = "tag=" + tag;// data sent must be under this form //name1=value1&name2=value2.
  Serial.println(data);
  httppost();
  delay(1000);
}

void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }
  delay(1000);
  String postRequest =
  "POST " + uri + " HTTP/1.0\r\n" +
  "Host: " + server + "\r\n" +
  "Accept: *" + "/" + "*\r\n" +
  "Content-Length: " + data.length() + "\r\n" +
  "Content-Type: application/x-www-form-urlencoded\r\n" +
  "\r\n" + data;
  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.
  esp.print(sendCmd);
  esp.println(postRequest.length() );
  delay(500);
  if(esp.find(">")) {
    Serial.println("Sending..");
    esp.print(postRequest);
    if( esp.find("SEND OK")) {
      Serial.println("Packet sent");
      while (esp.available()) {
        String tmpResp = esp.readString();
        Serial.println(tmpResp);
      }
      // close the connection
    esp.println("AT+CIPCLOSE");
    }
  }
}

Output :

tag= String(dat[12]); doesn't do what you think it does. Also you are trying to read 13 bytes into an array of 12 bytes and cram 13 bits into a byte. And for some reason using pin 0 for the sensor while still using serial.

Please can you help me with the code? I am new to Arduino and I'm really struggling with my grades on the line!

change <13 to <12 and properly convert the byte(/char) array to a String

I did that and I'm getting 254 now. I wrote this: String myString = String(myByteArray); to convert.

Your example code doesn't have myByteArray, so saying you tried that doesn't help anyone understand the context in which you tried it. You can edit your question to include updated code you have tried, etc.

I got it working using the code below:
#include "SoftwareSerial.h"
String ssid ="Home";

String password="%Qwerty@123%";
char input[12];
int count = 0;
SoftwareSerial esp(2, 3);// RX, TX

String data;

String server = "192.168.0.182"; // www.example.com

String uri = "/testget.php";// our example is /esppost.php

int DHpin = 0;//sensor pin

byte dat [12];

String temp;

void setup() {

pinMode (DHpin, OUTPUT);

esp.begin(9600);

Serial.begin(9600);

reset();

connectWifi();

}

//reset the esp8266 module

void reset() {

esp.println("AT+RST");

delay(1000);

if(esp.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network

void connectWifi() {

String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";

esp.println(cmd);

delay(4000);
}

byte read_data () {

byte data;

for (int i = 0; i < 8; i ++) {

if (digitalRead (DHpin) == LOW) {

while (digitalRead (DHpin) == LOW); // wait for 50us

delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'

if (digitalRead (DHpin) == HIGH){

data |= (1 << (7-i)); // high front and low in the post
 }
while (digitalRead (DHpin) == HIGH);

// data '1 ', wait for the next one receiver

}

} return data; }

void start_test () {

digitalWrite (DHpin, LOW); // bus down, send start signal

delay (30); // delay greater than 18ms, so DHT11 start signal can be detected

digitalWrite (DHpin, HIGH);

delayMicroseconds (40); // Wait for DHT11 response

pinMode (DHpin, INPUT);

while (digitalRead (DHpin) == HIGH);

delayMicroseconds (80);

// DHT11 response, pulled the bus 80us

if (digitalRead (DHpin) == LOW);

delayMicroseconds (80);
while(count<12){
input[count] = Serial.read(); // Read 1 Byte of data and store it in the input[] variable
      count++;          // increment counter
      delay(5);}
// DHT11 80us after the bus pulled to start sending data

//for (int i = 0; i < 4; i ++)

// receive temperature and humidity data, the parity bit is not considered
/*for(int x=0;x<12;x++)
for(int i=0;i<12;i++)
//dat[i] = read_data ();
dat[x]=input[i];*/

pinMode (DHpin, OUTPUT);

digitalWrite (DHpin, HIGH);

// send data once after releasing the bus, wait for the host to open the next Start signal

}

void loop () {

start_test ();

    count = 0;      // Reset the counter to zero
    temp = "";
    // convert the bit data to string form
for(int i=0;i<13;i++)
temp += input[i];
Serial.println(temp);
//Serial.println(temp);

data = "tag=" + temp;// data sent must be under this form //name1=value1&name2=value2.

httppost();

delay(200);

}

void httppost () {

esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.

if( esp.find("OK")) {

Serial.println("TCP connection ready");

} delay(100);

String postRequest =

"POST " + uri + " HTTP/1.0\r\n" +

"Host: " + server + "\r\n" +

"Accept: *" + "/" + "*\r\n" +

"Content-Length: " + data.length() + "\r\n" +

"Content-Type: application/x-www-form-urlencoded\r\n" +

"\r\n" + data;

String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

esp.print(sendCmd);

esp.println(postRequest.length() );

delay(500);

if(esp.find(">")) { Serial.println("Sending.."); esp.print(postRequest);

if( esp.find("SEND OK")) { Serial.println("Packet sent");

//while (esp.available()) {

//String tmpResp = esp.readString();

//Serial.println(tmpResp);

//}

// close the connection

esp.println("AT+CIPCLOSE");

}

}}

You can follow this awesome tutorial if you want to connect your RFID RC522 module to PHP. Source Code and a step by step tutorial are provided. You only need NodeMcu and RC522 RFID module.
https://devcraze.com/tutorials/connecting-rfid-scanner-to-php-using-nodemcu-wifi-module/

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


text:
Fast PWM working with int main(void) but not with void setup()
board: Arduino Mega (ATMEGA2560)
I want to generate pulses using timer1 configured as Fast PWM, this is my code which works fine:
#include <avr/io.h>

int main(void)
//void setup()
{

  DDRB |= (1 << DDB5) | (1 << DDB6); // PWM outputs

  ICR1 = 0x7FFF;  // TOP
  OCR1A = 0x3FFF; // 50% of ICR1
  OCR1B = 0x3FFF; // 50% of ICR1

  TCCR1A |= (1 << COM1A1) | (1 << COM1B1);
  TCCR1A |= (1 << WGM11);
  TCCR1B |= (1 << WGM12) | (1 << WGM13);
  TCCR1B |= (1 << CS10);

}

void loop() {

}

I don't understand why it doesn't work if I use void setup() instead of int main(void). I'm working with arduino IDE 1.8.2 and always used void setup(), in this case I used int main(void) because it is used in some turorials I found like this one: https://www.youtube.com/watch?v=O_Yqf_cugwE
EDIT: When I say that it doesn't work, what happens is that instead of having PWM signals I just have a constant 5V output in both OC1A and OC1B pins

Try using = instead of |=.

Using = instead of |= I have now a 0V output instead of 5V. I tried to initialize TCCR1A = 0; and TCCR1B = 0; first.

If you don't define your own main(), your program will be linked with
the main() provided by the Arduino core library, which roughly looks
like this (I am simplifying a little bit):
int main(void)
{
    init();      // Arduino core initialization
    setup();     // user's initialization
    for (;;)
        loop();  // user's main loop
}

The core's init() function configures Timer 1 for 8-bit phase
correct PWM at 490 Hz, which means that, by the time your setup()
runs, the timer's control registers are not in their default state
anymore, and some of their bits are already set to 1. If you then
update these registers using the |= operator, you end up with a mix of
the core's configuration and your own.
This can be fixed either by zeroing these registers first or, more
simply, by setting their values with the = operator, which has the
effect or setting every bit of those registers to the value you want.
The following works whether you use or not the Arduino core library:
#ifdef NOCORE
int main(void)
#else
void setup()
#endif
{
    DDRB   = _BV(PB5) | _BV(PB6);
    TCCR1A = _BV(COM1A1)
           | _BV(COM1B1)
           | _BV(WGM11);
    TCCR1B = _BV(WGM12)
           | _BV(WGM13)
           | _BV(CS10);
    ICR1   = 0x7fff;  // TOP
    OCR1A  = 0x3fff;  // 50% of ICR1
    OCR1B  = 0x3fff;  // 50% of ICR1
}

#ifndef NOCORE
void loop(){}
#endif

Note that:

The control registers are set (=) rather than just modified with
|=
The mode is set before the output compare registers. This is because
setting the output compare registers does not work well when the timer
is in an 8-bit mode.

Thank you for pointing out that the order in which the timer is set up could affect in some way, i had no idea.  With your code it still does not work for me, did you have a chance to test it?

@Mr.C: I tested it (and it works) on an Uno. I had to change DDRB to _BV(PB1) | _BV(PB2) in order to fit the Uno's pinout. Note that on the previous version of my answer I mistakenly left the DDRB setting appropriate for the Uno.

After changing DDRB to _BV(PB1) | _BV(PB2) to the corresponding pins in MEga DDRB to _BV(PB5) | _BV(PB6) it works perfectly, i didnt notice that. Thank you so much @Edgar Bonet, after your explanation about the core's init function it is more clear for me now why it was not working with void setup().


text:
Changing parameters in Arduino without the IDE
I’m installing Arduino-based well monitors in my local community.  Each well is different and has slightly different parameters and several hardware variations.  Currently, when I need to make a program change I have to uninstall the Arduino, bring it back to my computer, reprogram it, then reinstall it.  I’m developing these units as I go so there are various refinements that arise as well. I’d love to be able to reprogram a unit in place.  It seems like it could be done with another Arduino but I don’t currently have the skills for that.  The second, less flexible, method would be to use dip switches to select various options.  This option is attractive but would limit me to only the options that I know of at programming time.  Is there a third option I haven’t thought of?  Has anyone else tried programming one Arduino from the other?
Edit: I’m primarily using Unos but I’m working on a low power version that will use a Mini Pro. The units are accessible as far as USB cables and such. However I don’t own a laptop.

Please tell us what arduino board you use. Can you connect a (usb) cable to it? Can you connect a laptop to the arduino without removing it from the well? Perhaps you can write a command line interface and store values in eeprom. Then you can connect a laptop to the arduino and change values. Update your question with the extra information please.

You could maybe adapt this: https://www.gammon.com.au/bootloader

i would use an esp8266's SPIFFS to store the config; then you can program it from your phone.

Sounds like you need a Standalone programmer. I offer one, it loads the target device from a program you select on SD card.  Up to 256 programs can be stored on 1 card.
Check it out here  www.crossroadsfencing.com/BobuinoRev17/Programmer.html


text:
How to change the value within a variable using math?
I'm up to Lesson 11 in the TopTechBoy tutorial: https://www.youtube.com/watch?v=afurKLOqqSg
Lesson 11 : http://www.toptechboy.com/arduino/lesson-11-arduino-circuit-to-dim-led-with-potentiometer/
I can use the analogRead() to fill a variable with a value and Serial.printld it out, but I want to be able to increase that integer by × 4.887585533
int pinV; // This empty variable will be filled with an integer value between 0 and 1023.
int receiverPin=0; // This is the RX pin, a ‘receiver’ that connects to the USB to Serial interface.
int ResultsPerSec=500; // The Arduino reads and prints out a result every half second.
float printingValue; // Another empty variable that is given the pinV value to multiply and print.
void setup() {
  Serial.begin(9600);
  pinMode(receiverPin,INPUT);
}

void loop() {
  pinV=analogRead(receiverPin);
  // Each Volt has a value of 204.6 (4.88 mV per integer of the 1023 available)
  printingValue = (pinV *4.887585533);
  // 5,000 mV divided by 1023 possible values = is 4.887585533 mV per integer
  // The Arduino can count from 0 to 5 Volts in 4.887585533 mV increments.
  // 1,000 mV divided by 4.887585533 mV = 204.599999989 integers out of the 1023 available equal 1V
  // Each integer of the 1023 possible values that analogRead() outputs can be increased by 4.887585533
  // This shows the real Voltage in millivolts (mV).
  Serial.println(printingValue);
  delay(ResultsPerSec);
}

This is actually acceptable as far as the IDE is concerned, but it doesn't work as intended. I'm getting outputs in the thousands, when it should be printing 0 in the Serial monitor. How do I do this properly?

I just got a reply from someone from one of the threads on https://8ch.net/tech/catalog.html
It turns out that the Digital pins (0,1,2,3,4,5,6,7,8,9,10,11,12,13) are not capable of reading Analog voltages. Pins A0 to A5 need to be used instead. Also, if not voltage is supplied, the Arduino will print random numbers in the Serial Monitor.

0 as parameter of analogRead is A0. you used A0. if pin is not connected to a circuit or ground it is called 'floating'

The page you linked to clearly shows analogue pin A0 being used for the reading. You seem to have thought that pin 0 (on the other side of the board) would be an acceptable alternative.

Its great how I can turn my Arduino into a voltmeter (As long as its below 5V). You can touch two wires on either ends of an AA battery and and see its voltage. But I wonder if the math is correct? Its been said that the float can only hold up to 7 numbers after the decimal (4.887585533 counts nine).

The voltage you should print is 5e3/1024*analogRead(A0). Ignore the tutorial using 1023: the datasheet is the only authoritative reference. 2. Floats do not hold decimals: they are binary, whith a machine epsilon of 2^(−23) ≈ 1.19e-7. The ratio 5e3/1024 is an exact float. 5e3/1023 is not, and the compiler rounds it to the nearest float, namely 4.88758563995361328125. The rounding error is inconsequential given the low resolution of the measurement.

https://gph.is/1dogvB3


text:
Motor is vibrating in one direction
When I test this program, the motor starts vibrating when proxy1 is low and proxy2 is high. The displayed text also goes wrong.

#include <LiquidCrystal.h>
LiquidCrystal lcd(8,9,4,5,6,7);

int ir1=22;
int ir2=26;

int led1=23;

int motor=24;
int motor2=25;

int proxy1=0;
int proxy2=0;

void setup() {
  pinMode(ir1,INPUT);
  pinMode(ir2,INPUT);

  pinMode(led1,OUTPUT);

  pinMode(motor2,OUTPUT);
  pinMode(motor,OUTPUT);
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.clear();
  lcd.println("Everything Is In");
  lcd.setCursor(0,1);
  lcd.println("Order...........");

}
void loop(){
  proxy1=digitalRead(ir1);
  proxy2=digitalRead(ir2);
if((proxy1==LOW)&&(proxy2==HIGH))
{
  lcd.setCursor(0,0);
  lcd.clear();
  lcd.println("Rule Violated!");
  digitalWrite(led1,HIGH);
  digitalWrite(motor2,HIGH);
  digitalWrite(motor,LOW);

}
if((proxy1==LOW)&&(proxy2==LOW)) {
  lcd.setCursor(0,0);
  lcd.clear();
  lcd.println("Everything Is In");
  lcd.setCursor(0,1);
  lcd.print("Order");
  digitalWrite(led1,LOW);
  digitalWrite(motor2,LOW);
  digitalWrite(motor,HIGH);
  delay(2000);
  digitalWrite(motor2,LOW);
  digitalWrite(motor,LOW);
}
else
{
  lcd.setCursor(0,0);
  lcd.clear();
  lcd.println("Everything Is In");
  lcd.setCursor(0,1);
  lcd.print("Order");
  digitalWrite(led1,LOW);
  digitalWrite(motor2,LOW);
  digitalWrite(motor,LOW);
}
}

reverse the wires on the motor and test again ... also, please ask a question

Sounds like EMI


text:
L298N motor driver issue
I am facing the same issue with my motor driver. Initially I ran the code and connected the L298N with Arduino and it worked fine. At that time motors were running absolutely fine. But when I ran it sometimes later then the motors are not running. However the motors are getting power but I think thy are getting very less power from the Motor Driver.
I directly ran motors from Arduino +5V pin and the motors were running fine. Is there something wrong with my L298N motor driver?
One more thing I checked the power for all the pins for L298N motor Driver and all pins are working fine.
Here is my complete program:

const int MOTOR_RIGHT = 1;
const int MOTOR_LEFT =  2;
const int MR_CONTROL_PIN_A = 8;
const int MR_CONTROL_PIN_B = 9;
const int ML_CONTROL_PIN_A = 10;
const int ML_CONTROL_PIN_B = 11;

void setup() {
  // These two pins will act as output pin

  pinMode(MR_CONTROL_PIN_A,OUTPUT);
  pinMode(MR_CONTROL_PIN_B,OUTPUT);
  pinMode(ML_CONTROL_PIN_A,OUTPUT);
  pinMode(ML_CONTROL_PIN_B,OUTPUT);
  Serial.begin(4800);

}

void loop()
{
  // put your main code here, to run repeatedly:

  forward(MOTOR_RIGHT);
  forward(MOTOR_LEFT);
  delay(5000);
  stopMotor(MOTOR_RIGHT);
  stopMotor(MOTOR_LEFT);
  delay(1000);
  backward(MOTOR_RIGHT);
  backward(MOTOR_LEFT);
  delay(5000);
  stopMotor(MOTOR_RIGHT);
  stopMotor(MOTOR_LEFT);
  delay(1000);

}
/////////////////////////////////////////////////////////////////////
//Forward

  void forward(int motorNo)
  {

  Serial.print("\r\n Forward : ");
  Serial.print(motorNo);

  switch(motorNo)
  {
    case MOTOR_RIGHT:
    digitalWrite(MR_CONTROL_PIN_A,HIGH);
    digitalWrite(MR_CONTROL_PIN_B,LOW);
    break;

    case MOTOR_LEFT:
    digitalWrite(ML_CONTROL_PIN_A,HIGH);
    digitalWrite(ML_CONTROL_PIN_B,LOW);
    break;

  default:
    Serial.print("\r\n Error :Invalid Motor No ");
    Serial.print(motorNo);
   }
  }

//////////////////////////////////////////////////////////////////////
  void backward(int motorNo)
  {
   Serial.print("\r\n Backward : ");
   Serial.print(motorNo);
  switch(motorNo)
  {
    case MOTOR_RIGHT:
    digitalWrite(MR_CONTROL_PIN_A,LOW);
    digitalWrite(MR_CONTROL_PIN_B,HIGH);
    break;

    case MOTOR_LEFT:
    digitalWrite(ML_CONTROL_PIN_A,LOW);
    digitalWrite(ML_CONTROL_PIN_B,HIGH);
    break;

  default:
    Serial.print("\r\n Error :Invalid Motor No : ");
    Serial.print(motorNo);
   }

  }

///////////////////////////////////////////////////////////////////////
  void stopMotor(int motorNo)
  {
   Serial.print("\r\n STOP : ");
   Serial.print(motorNo);
  switch(motorNo)
  {
    case MOTOR_RIGHT:
    digitalWrite(MR_CONTROL_PIN_A,HIGH);
    digitalWrite(MR_CONTROL_PIN_B,HIGH);
    break;

    case MOTOR_LEFT:
    digitalWrite(ML_CONTROL_PIN_A,LOW);
    digitalWrite(ML_CONTROL_PIN_B,LOW);
    break;

  default:
    Serial.print("\r\n Error :Invalid Motor No : ");
    Serial.print(motorNo);
   }

  }

Is there something wrong with my L298N ? How can I test it?

Can the driver chip provide enough current to drive your motor continueously?

Actually that's what the problem is ...it is not providing enough current to move the motor. I can feel the spark in motor when power up and connected with L298N via Arduino but the motor is not rotating.

How much current does your motor need? As I remember the L298N has a quite bad efficiency, because it uses bipolar transistors instead of MOSFETs

I don't think you are supposed to run a motor from the 5V regulator on the Arduino. Try using a separate power supply for the motor driver.

The specified minimum voltage for the motors is 2.5 volts higher than the logic supply.
You need to use a separate supply for the motor that is higher than the logic power.

I am directly supplying power to L298N from the +9v battery but still finding same issue. Arrengement is like this :
+12V L298N Pin connected to Battery,
GND L298N pin connected to both Battery and Arduino GND,
+5V L298N pin connected to +5V of Arduino.

9 volt batteries have very low capacity. That could be the cause of your problem. Replace the battery with a power supply with higher capacity. Or other bigger batteries that add up to around 9 volts.


text:
Problem controlling a Stepper motor with AccelStepper
I have an Arduino connected to a stepper motor with an Easy Driver as follows:

I am controlling the position of the stepper motor using the Serial. This is my code:
#include <AccelStepper.h>
AccelStepper stepper(1, 9, 8);

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(10000);
  stepper.setAcceleration(5000);
}

void loop()
{
  char c;
  if(Serial.available())
  {
   int steps = Serial.parseInt();
   Serial.print(steps);
   stepper.moveTo(steps);

  }
  stepper.run();
}

The code works well but I'm facing a problem, when I set a high position value, it starts turning in the opposite direction, like if there was a limit on the steps. Does anyone know why it starts turning to the opposite direction?
I have tried to solve this problem by using:
if (stepper1.distanceToGo() == 0)
         {
            stepper1.setCurrentPosition(0);
         }

so I can set lower values to the serial. But the problem goes back again when the value goes up to the power of 6 (like 1000000).
Any idea?
Thanks!

Per a comment from the developer of AccelStepper, the line  AccelStepper stepper(1, 9, 8); should be written as                 AccelStepper stepper(AccelStepper::DRIVER, 9, 8); for clarity

Ints on vanilla Arduinos are 16 bits, and signed, which means they hold values from -2^15 to +2^15-1, so of course you cannot assign 10^6 to one of them. Use unsigned long (4 bytes), or, better yet, specify the length explicitly by using uint32_t.

could you post me the reference of this?

This has always been the case for 16-bit processors. Plus, it's in the adruino documentation. Plus, you can verify it for yourself by writing a one-line program.


text:
Confusion with ATmega328P and 3.3V/8MHz
Firstly, I have tried to set the bootloader to be 8MHz internal oscillator.
I have tried the board setup from here - https://github.com/oshlab/Breadboard-Arduino.
And also the breadboard-1-6-x.zip setup from here - http://www.arduino.cc/en/Tutorial/ArduinoToBreadboard.
Burning the bootloader in both cases seems to work, with fuse settings of -Uefuse:w:0x05:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xE2:m (using Arduino IDE 1.6.7):
avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: 1 bytes of efuse verified
...
avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xDA:
avrdude: load data hfuse data from input file 0xDA:
avrdude: 1 bytes of hfuse verified
...
avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xE2:
avrdude: load data lfuse data from input file 0xE2:
avrdude: 1 bytes of lfuse verified

When I try and run the test sketch (below) at these voltages:

3.3V it fails (tried multiple 3.3V sources, all fail).
4.23V (3xAA rechargeable batteries) it works.
4.8V (3xAA alkaline batteries) it works.
5V it works.

To try and determine if it was my power sources or the bootloader that was the problem I uploaded this test sketch on my ATmega328P, an Arduino Nano (all Nanos are 16MHz?) and a 16MHz Arduino Pro to see if the red LED (with 100 Ohm resistor for ATmega328P) lights up in about the same time. This test sketch also does not work at 3.3V, and must be run at 5V to work.
(edit) When running this test sketch at 3.3V I see no 3.3V logic level on any output pin with my multimeter.  When running at 4.23, 4.28, 5V I see this logic level on all output pins.
(update) When connecting the +ve of the LED directly to 3.3V, the LED lights up.  So the 3.3V source has enough power to light the LED directly.
So I assumed that because my ATmega328P circuit has no crystal in it (and the Nano and Pro Mini are 16MHz), these loops would execute in different amounts of time?  But no, the loops do execute at the same speed (3 and a bit seconds) - so is my Nano/Pro Mini underclocked, or my ATmega still running at 16MHz but without a crystal??  Rather confused.
Thanks.
(update) I tried a second ATmega328P, same problem.
(code edited to use 14 output pins)
void setup() {
  for (int p=0; p<14; p++) pinMode(p, OUTPUT);
}

void loop() {
  // waste some time.
  int y = 0;
  for (int i = 0; i < 11; i++) {
    for (int j = 0; j < 11; j++) {
      for (int k = 0; k < 101; k++) {
        y+=analogRead(A0);
      }
    }
  }
  for (int p=0; p<14; p++) digitalWrite(p, y % 2);
  for (int p=0; p<14; p++) digitalWrite(p, HIGH);
  delay(1000);
  for (int p=0; p<14; p++) digitalWrite(p, !(y % 2));
  for (int p=0; p<14; p++) digitalWrite(p, LOW);
  delay(1000);
}

It was a brownout fuse problem.
Changing boards.txt from:
atmega328bb.bootloader.extended_fuses=0x05
to
atmega328bb.bootloader.extended_fuses=0x02
solved it for me (*).
The chip and red LED now work at 3.01V  (1xAA alkaline and 1xAA rechargeable) and 3.19V (2xAA alkaline).
(*) not sure why I had to invert the bits (0000 0010=0x02 versus 0000 0101=0x05) when compared to the tables below.

Calculating those fuses by hand is error prone - I've already lost an AtMel chip to getting it wrong. http://www.engbedded.com/fusecalc/ will do the hard work for you.

Yeah, thanks for the warning.  Any idea why the default BOD value of 0x05 doesn't work for me and 0x02 does?  Seems as though I have to flip the bits.  If I set to 0x07 that also works (presumably BOD disabled, but bits not flipped!)

I don't know. This is for efuse? Can you read it back?

If you are using an LED to indicate that your sketch is running, then that may be the problem.
For example, if you have a fairly average red LED, it might have a forward voltage of 2.0v @ 20ma (refer to your spec sheet for your particular LED). Putting these values into the LED calculator, it would tell you that you need a 150 ohm resistor. You might have tested this, and seen the LED light up.
Then, if you drop the voltage to 3.3v, your LED might be either very dim, or (more likely!) not light up at all. Putting 3.3v into the same web page, it shows you need a smaller resistor, 68 ohm, for the same LED.
P.S. - I just noticed your paragraph about the green LED - a "true green" LED might have a voltage drop of 3.3v, which means for 5v you would need a 100 ohm resistor (as described in your paragraph); for a 3.3v supply you would need a 1 ohm resistor instead. This is pretty certainly your problem

Thanks for your answer. I've swapped from green to red and see the same issue.  I've also updated the sketch (qn edited) to use 14 digital pins (0..13) and don't see a 3.3V level on any of those pins, but I will see 5V.

If you are powering your circuit off a cell battery, you might find that your battery cannot supply enough current. To test this, use a multimeter to measure the voltage of the battery, while your circuit is connected (and possibly, or possibly not, running). If the voltage drops below 2.7v (as defined by your fuses - use the AtMel Fuse Calculator page to see what your fuses mean), your chip will shut down, causing the voltage to rise back, turning the chip back on, and round it goes.The battery may even take a while to recover (I think last time this happened to me, it took about 10 seconds -I thought I'd destroyed the battery).
This is fairly common issue with motors (which draw a lot of power), but depends on your exact battery, and the exact load.
If this happens, you might get away with using multiple batteries in parallel (connect all the + sides together, to the + side of your circuit; all the - sides together to the - side of your circuit). Most battery holders are in series, which means they boost the voltage instead; you will have to do your own wiring for this.

Thanks for your answer.  Given what I am seeing (no 3.3V logic levels at all), I am wondering if it's brownout detection or something.  The 328P seemingly won't get going at anything less than 4.8V (although I've not measured 3.3V-4.8V).  Also, I have no idea why the 328P runs the test sketch at the same speed at the Nano and Pro Mini.

Hy all,
I´m facing the same issue. Had an ATMEGA328P-PU with 8Mhz Oscillator on a breadboard that did not work with 3.3V (stabilized) as a supply. At 5V things work as expected.
Finally I got things running with extended fuses set to xxxxx110, which sets BOD to 1.8V. I coud verify that my ATMEGA328P-PU does not run with fuses set to xxxxx101 = 2,7V (max. 2.9V). The supply is about 3.4V and has blocking condensators, so it cannot be a supply issue.
Best regards, Eckehard


text:
how to use hx-53 (IR Transmitter Infrared Sensor Module) with ESP32?
ESP32 tx2 (pin17) and rx2 (pin16) uses 3.3v based signals.
HX-53 data connect to tx2, gnd to gnd and vcc to vin(5v).
But as i can understand HX-53 data input should be 5v based.
How can i solve this problem?
HX-53: https://www.amazon.com/Electronic-Infrared-Emission-Transmitter-Arduino/dp/B07PJC7WSQ
Best regards.
GA

Either level shift chip or a voltage divider. Can you provide a link to the HX-53? Havent found it

The HX-53 look like a IR LED and a current limiting resistor on a small PCB.
It also has a LED and a resistor in series for indication when the invisible IR diode is on or off.
So you can change the resistor to a lower value to match the 3,3 volt output from the ESP32.
Resistor values:
221 = 220 ohm   = IR LED
102 = 1000 ohm  = SMD indicator LED

So replace the 220 ohm with something near 75 ohm.
HX-53

In my case HX-53 worked without any changes on Wemos Di mini, but angle/range to trigger was very small. I did as advised @MatsK, solder a 100 ohm resistor in parallel to 221. So now I have 68,75 ohm resist on 221, but angle/range almost did not increase. Can I make more lower the resistance on 221 (to 30-40 ohm) to increase transmit power even more?
Sorry what I write this as an answer, I can't comment.

@Bleach - If you have a new question, please ask it by clicking the https://arduino.stackexchange.com/questions/ask button. Include a link to this answer if it helps provide context.

I happen to have one just like yours. I was trying to use it on my Arduino to send commands to my AC like a remote but as it turns out, the Vcc pin on the HX-53 breakout board appears to be a dummy and doesn’t connect to anything as far as i know. By right there should be a transistor circuit driving that LED. As it is now, not only is there insufficient current from the signal pin to drive that IR LED for signal bursts, but the red SMD LED in series with the resistor is also stealing some of the current away from the IR LED. In the end, I had to buy a BJT, a standalone IR LED, some resistors and design my own transistor circuit to drive it.
On the transistor’s collector side I had a connection to Vcc and the IR LED in series with a resistor. On the base side was a connection to the signal pin and a resistor. The emitter was connected directly to Ground. Values of the resistors you use will depend largely on the Vcc, the LED max forward current, the specs of the transistor you choose and available current from the power supply.
Hope this helps.


text:
How to connect ESP8266 to my home WiFi securely
I'm working on a home automation project using NodeMCU ESP8266. Most of the example projects I see online provide their WiFi SSID and password in plain text at the beginning of the code by storing them into some variable
Is there a secure way of doing that? I'm worried if my ESP8266 gets hacked by someone online, they'll now have my WiFi SSID and the password. Is there a way of encrypting this information before passing it to ESP8266. Or is there a way of creating a separate WiFi password which will only be used by the ESP8266?

this may help https://www.esp8266.com/viewtopic.php?t=13977

If the credentials are hardcoded the attacker will have to read out the flash through the internet (which is almost impossible, I guess). Even after that s(he) has to be at your home to login to your wifi, which is very unlikely as long as you are not a person of interest. Providing an interface to the credentials might be more vulnerable than hardcoding them. By the way, the esp supports flash encryption.

An interesting question. This is not a forum - just a comment section.  But consider that this information is only valuable in close proximity to your house as most wifi is not long range.  And if this really was a risk there are other barriers you can put up like MAC filter on your router.  So why is this a concern?  (BTW, don't use the same password for your router's admin and your router's SSID!)


text:
global volatile variable not being updated in ISR
Running on atmega168p, I've got an interesting behavior I can't explain. A global volatile var that's called pos over here is not updated as it should. Once I add some code below the assignment, it starts working.
#define ENCODER_DO_NOT_USE_INTERRUPTS
#include <Encoder.h>

Encoder myEnc(A2, A3);

void setup() {
  Serial.begin(115200);
  while (!Serial); Serial.println("Started.");
  PCMSK1 |= bit(PCINT10) | bit(PCINT11) | bit(PCINT12);
  PCIFR  |= bit (PCIF1);   // clear any outstanding interrupts
  PCICR |= bit(PCIE1);
}

volatile int pos  = 0;
int oldpos = 0;

void loop() {
  if (oldpos != pos) {
    oldpos = pos;
    Serial.println(pos);
  }
  delay(100);
}

// PCINT10, PCINT11
ISR(PCINT1_vect) {
  pos = myEnc.read();
  //  adding digitalRead(A0)
  // or even Serial.println(pos) updates the var correctly
}

Switching from int to byte doesn't change anything. Encoder library is https://github.com/PaulStoffregen/Encoder. Any clues?

It looks like ISR is being fired only once. bummer.

I think it would be better to use a library that support PCINT interrupts instead of hacking it onto a library that doesn't. For example, https://github.com/kr4fty/EncoderPCI looks like it supports PCINT.

Related: 3 ways to ensure atomic access  on Arduino/AVR microcontrollers: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278

@kotique, you have unmanaged race conditions in your code. I've addressed them and given a thorough explanation here: https://arduino.stackexchange.com/a/77512/7727. I can't say those are the only problems, but you definitely have race conditions. Making the volatile variable an int8_t won't fix them, they are still there. Give it a shot with my corrections I describe in my action and see what happens now.

Well, the long awaited answer to this question is simple - the library that I've tried to use in my code was over-optimizing things by going full ASM and interfering with my stuff. Using C version straightened things up.
For anyone getting strange behaviour I recommend taking a quick glance at the lib's code you're using, maybe it's not your fault after all.

Sounds like a dodgy library, if it interferes with C++ code. It perhaps is meddling with registers without telling the compiler.

You are using pos outside of the interrupt without turning the interrupt off.  pos is two bytes, so it takes the Arduino more than one cycle to read in that variable no matter how it is handled.  If an interrupt occurs during that time, you get a corrupted value.
You need to have a cli() and then make a copy of pos to another variable and then a sei() and then use that copy in your calculations in loop.

Or use a int8_t if that’s possible.

You should've read till the end of the question, which states "Switching from int to byte doesn't change anything."

How to recognize and fix race conditions in Arduino by using atomic access guards:

Switching from int to byte doesn't change anything. Encoder library is https://github.com/PaulStoffregen/Encoder. Any clues?

Your code here:
void loop() {
  if (oldpos != pos) {
    oldpos = pos;
    Serial.println(pos);
  }
  delay(100);
}

has an unaddressed race condition, which leads to undefined behavior and data corruption. Making oldpos into a uint8_t or int8_t, each of which is 1 byte, instead of int, which is 2 bytes, won't fix it, because you need the whole section from if (oldpos != pos) { through Serial.println(pos); to be atomic so that the value of pos you use to enter the if block does not get changed by the interrupt while you are in the if block. I'll explain more later. This is reminds me of a problem I had a few years back, here: C++ decrementing an element of a single-byte (volatile) array is not atomic! WHY? (Also: how do I force atomicity in Atmel AVR mcus/Arduino).
So, let's walk through a case where making a 2-byte variable into a 1-byte variable WILL solve the problem, first, to ensure we understand why one might think making it a 1-byte variable is the solution.
Let's look at this example. It has a race condition and undefined behavior. Can you spot it?
volatile uint16_t isr_counter = 0;

void setup()
{
    // enable the ISR here
}

// Any ISR
ISR()
{
    my_var++;
}

void loop()
{
    Serial.println(isr_counter); // <== race condition!
}

The answer is that isr_counter is a 2-byte variable, and AVR microcontrollers have 8-bit (1-byte) CPUs, so, it is possible that as isr_counter is being read in loop() to be printed, 1 of the 2 bytes is read out correctly to be printed, then the ISR fires, changes the variable, and gives control back to the main loop. The 2nd byte, now not what it was supposed to be, is read out, leading to a corrupted variable! Ex: let's assume isr_counter was 0xFFFF, or 65535, at the moment it is supposed to be printed, and lets say the low byte is read out correctly as 0xFF, then the ISR fires, the variable is incremented to 0x0000 since it overflows, then the control goes back to the main loop, and the 2nd byte is read out, it is now corrupted. What will be printed would be the contents of the variable containing 0x00FF, or 255, when what should have been printed out was 65535, and the next value after that to be printed out would have been 0. And what if the high byte was read out correctly before the low byte? (I'm not sure which order AVR mcus read the bytes), then your corrupted value would be 0xFF00, or 65280, when what should have been printed out was 65535 (0xFFFF), and the next value after that to be printed out would have been 0 (0x0000).
So, simply making the variable a uint8_t magically solves this race condition for this one particular case because 8-bit variables on 8-bit CPUs are read or written atomically, which means "as an atomic, or whole, single, unit, not broken up or corrupted by interrupts or other threads". All operations which take 1 single CPU instruction cycle are automatically atomic, because they cannot be interrupted.  For any multi-instruction-cycle code block which we need to be atomic, we must force it to be atomic by using what I call "atomic access guards". Reading a 1-byte variable on an 8-bit CPU, or writing a 1-byte variable on an 8-bit CPU, is 1 instruction, so it is naturally atomic. Incrementing or decrementing a 1-byte variable, however, is NOT an atomic operation, since the variable must be read, modified, and written. Reading a 2-or-more-byte varible on an 8-bit CPU, or writing a 2-or-more-byte varible on an 8-bit CPU, is also NOT atomic, since it takes one instruction per byte. This means just reading a 2-byte variable or writing a 2-byte variable can be interrupted by an ISR in the middle of the operation, which leads to data corruption if you do not use atomic access guards!
Now, your case: would making pos into a 1-byte variable as volatile int8_t pos = 0; solve the race condition? No, not at all. Let's look at your code again, this time imagining that pos is an int8_t instead of an int (which is int16_t on AVR Arduino):
void loop() {
  if (oldpos != pos) {
    oldpos = pos;
    Serial.println(pos);
  }
  delay(100);
}

Let's walk through a potential scenario: pos is 7. oldpos is 6. So, oldpos != pos is true, and you enter the if statement. Now, right as you enter, the ISR fires, pos is changed by the ISR to 6 (or to any other number--it's still a race condition and undefined behavior), oldpos is now set to 6, which is what it already was, and you have data corruption because it should have been set to 7! Note that when I say this is undefined behavior in this case, I simply mean we cannot predict what will happen. This is buggy code. Code should always be predictable. Undefined behavior is a bug! Note also that when talking about "undefined behavior" according to C or C++ standards, we mean "the standard doe not define what will happen", which means your code may act one way on one architecture or with one compiler, and differently on another architecture or with a different compiler. This is not what I am talking about here. Here, when I say "undefined behavior" I don't mean "according to the C or C++ standard", I mean, "according to the rules of logic."
The solution to fix your race condition is to enforce atomic access using what I like to call "atomic access guards". On multi-threaded systems, this means to use locks, mutexes, and semaphores. On single-threaded systems, such as this, it means to disable any interrupt which could interfere and cause the race condition (you can think about interrupts interacting with the main loop as a parallel to one thread interacting with another thread, so it is as though you had a multi-threaded system just by having a single-threaded system + interrupts). For AVR microcontrollers, disabling interrupts to act as atomic access guards is usually done by disabling global (or all) interrupts. BUT, disabling interrupts introduces jitter by delaying the processing of the ISR, so it should be done for as short of a time period as possible! That means you should just disable interrupts, make copies of volatile variables, and re-enable interrupts. This is an important point though: sometimes, in the case of using a 1-byte volatile variable, using a copy of your variable, which can NOT be changed at any moment by an ISR, also, in and of itself, acts as a form of "atomic access guards" and solves the problem all by itself. I'll post an example of this below.
But: DANGER DANGER! It's a "best practice" to always back up the interrupt state, disable interrupts, then restore the interrupt state, rather than just turning interrupts off then back on all the time. Why? Because what if you write a function which sometimes gets called from within an ISR itself? If you enable interrupts inside an ISR, you just enabled nested interrupts, which leads to more race conditions. If you know exactly what you are doing and you want nested interrupts, this is fine! But, chances are one is just making a mistake here and accidentally enabling nested interrupts without even realizing it, leading to really-hard-to-track down data corruption due to nested interrupts. Safety-critical systems can crash and hurt people when this happens, so we can't ever allow unmanaged race conditions.
So, do it like this:

Force atomicity in loop() by backing up the interrupt state.
Make copies of the volatile variables.
Then restore the global interrupt state.
Use only the copy of the varible in the rest of your code. This (using the copy) is also a form of "atomic access guards" all by itself for later code blocks using the variable because using the copy instead of the volatile variable means that the variable can NOT be changed at any moment by an ISR. This enforces atomicity as well!

Making a copy of the volatile variable and nothing else, while interrupts are disabled, minimizes time where interrupts are disabled, making your code the best it can possibly be! It should now look like this:
1 of 3: THE BEST WAY!:
volatile int pos  = 0; // assume this variable is still an `int`, which is 2-bytes

void loop() {
    uint8_t SREG_bak = SREG; // back up the global interrupt state
    noInterrupts(); // disable interrupts
    // make copies of your volatile variables here
    int pos_copy = pos;
    // restore interrupt state, turning them back ON if they were ON before,
    // or leaving them OFF if they were OFF before.
    SREG = SREG_bak;

    // Now do what you want with the copy, using pos_copy ONLY,
    // to avoid race conditions! (ie: using this copy here enforces
    // this entire block to be naturally atomic now, and by itself
    // is a form of "atomic access guards", as explained above.)
    if (oldpos != pos_copy) {
        oldpos = pos_copy;
        Serial.println(pos_copy);
    }
    delay(100);
}

Solved!
Let's look at 2 other examples, however, for completeness.
Here, we force the whole if statement block to be atomic. This looks correct at first, but has two problems: 1) [a true bug] Serial.println will block forever if the outgoing serial buffer is full, as it relies on interrupts to empty it, and if interrupts are off, that will ever happen, and 2) [an undesirable effect leading to performance issues, but not a bug] it keeps interrupts off for a longer time period than is necessary. The code above was best: it kept interrupts off the absolute minimum time possible by just making copies of the volatile variables, and it ensured this whole if statement block was atomic by simply using the copy there, which automatically acts as an "atomic access guard" by itself and enforces atomicity in the if statement block.
2 of 3: this still has 2 problems: one is a bug, and one is a performance issue but not a bug:
volatile int pos  = 0; // assume this variable is still an `int`, which is 2-bytes

void loop() {
    uint8_t SREG_bak = SREG; // back up the global interrupt state
    noInterrupts(); // disable interrupts

    if (oldpos != pos) {
        oldpos = pos;
        Serial.println(pos);
    }

    // restore interrupt state, turning them back ON if they were ON before,
    // or leaving them OFF if they were OFF before.
    SREG = SREG_bak;

    delay(100);
}

And lastly, what if the volatile variable was a 1-byte variable? Well, then you could simplify to this, since reading a 1-byte variable is naturally an atomic operation!
3 of 3: this works too (without bugs and without performance issues), but ONLY if your volatile variable here is 1-byte!:
// this variable is now a 1-byte variable, which has naturally atomic read and
// write operations! (but not increment or decrement)
volatile int8_t pos  = 0;

void loop() {
    // Make copies of your volatile variables here.
    // Being a 1-byte variable on an 8-bit (1-byte) CPU architecture, this operation
    // is already naturally atomic, so no need for "atomic access interrupt guards".
    int8_t pos_copy = pos;

    // Now do what you want with the copy, using pos_copy ONLY,
    // to avoid race conditions! (ie: using this copy here enforces
    // this entire block to be naturally atomic now, and by itself
    // is a form of "atomic access guards", as explained above.)
    if (oldpos != pos_copy) {
        oldpos = pos_copy;
        Serial.println(pos_copy);
    }
    delay(100);
}

For 3 other ways to create atomic access guards in 8-bit AVR-based Arduinos, see my answer from 2016 here: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278.
Last comment: Paul Stoffregen is one of the most-expert in Arduino in our day. I'm sure he makes mistakes, but my default is to trust anything he's written. He's a most-excellent software developer and engineer: one of the absolute best in the entire world. Look for bugs in what he writes, and let him know if you found any, but you have unaddressed race conditions here, so that's what I'd look at first.
References:

My own race condition problem: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why
My own race condition solution, demonstrating 3 (or 4, depending on how you look at it) ways to enforce "atomic access guards" on AVR-based 8-bit Arduinos: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278

I agree about making the copy (as in your example using pos_copy) however for a one-byte variable you wouldn't need to disable interrupts, as copying from one byte to the "copy" would be atomic. However it could be a subtle bug-in-waiting if someone one day decides to make pos two bytes without realizing why you had not put the atomic access guard there. Perhaps a comment would help in that case.

In your example, the delay(100) wouldn't work if interrupts were off so perhaps saving and restoring SREG is overkill. You could just turn interrupts back on. If they somehow get turned off elsewhere then the delay will fail, and you would need to address that.

You are right on the 2nd comment, but I think it's just a best practice sort of thing, since frequently I wrap this stuff up into functions which I intend to be called in or out of ISRs.

Regarding your 1st comment: however for a one-byte variable you wouldn't need to disable interrupts, as copying from one byte to the "copy" would be atomic., I agree with you on this point: as copying from one byte to the "copy" would be atomic., but disagree with you on this: for a one-byte variable you wouldn't need to disable interrupts, because what needs to be atomic is from the if statement down through the serial print, inclusive. That whole block needs to be atomic, or else you evaluate the if statement on one variable state but do something with it (and print it) on another.

In other words, the atomic access guards for the 1-byte variable are still required to ensure that what you are using inside the if block is also what you used to decide to enter the if block in the first place, no?

@NickGammon, I'm interested in your response to my last two comments here if you get a chance.

Yes, but, what can you do? If you make it guarded, it still might change, but you won't realize it. Making a copy, and comparing to another byte, is the best you can do. That whole block needs to be atomic, or else you evaluate the if statement on one variable state but do something with it (and print it) on another. - not at all. You are evaluating the copy, and printing the copy.

@NickGammon, your response here indicates we are actually agreeing and saying the same thing & just not realizing it. not at all. You are evaluating the copy, and printing the copy. What I am saying is that making the copy is the adding of atomic access guards around that whole block. We are agreeing.I realize we are agreeing on the 1-byte variable thing too. I'm saying his original code will not work even if he uses a 1-byte variable. I thought you disagreed with me, but you disagreed with something else. I'll update my answer to make what I'm saying more clear.I'm pretty sure we agree.

Answer updated. This answer is ridiculously thorough for this question. I think I should move it to a wiki style question someday, where I both ask the question and provide the answer. This topic of race conditions and atomic access and stuff comes up all the time and needs a thorough, canonical answer like this to address it and to which we can point people whenever they have a question or problem which requires it, and that's what I've tried to make this answer.


text:
How do I find my 1N 4007 diodes?
I am a beginner to Arduino, and a relative beginner to electronics in general. I have the official Arduino Starter Kit. I've looked through my bag of components looking for a black diode but was unable to find it among all of the LEDS & the other black components.

Maybe show us some pictures of what you do have...

What is Google?

They are stuck next to a string of resistors.

1N4007 are usually black with a white stipe indicating the cathode. Use a magnifying glass and you should be able to see the marking.

This is image of 1N4007 diodes. I think now you can find them easily.

While the ArduinoStarterKit page at arduino.cc lists “5 Diodes [1N4007]” as part of it, and has a picture where 5 diodes apparently appear slightly left of center in the top row, several other pictures that come up in a google images search for official Arduino Starter Kit apparently don't show the diodes.  Eg, as at arduino starter kit.  But 4 Best Starter Kits for Arduino Beginners does show them.
Note, unless you are working with medium to high AC voltages (eg above 50 V) you can substitute 1N4001 - 1N4004 which have lower PIV ratings but also slightly lower forward voltage drop.  For many beginning projects, 1N4148 signal diodes will be adequate and perhaps less expensive.


text:
HD44780 Extended non-display DDRAM?
According to page 10 of this PDF https://www.sparkfun.com/datasheets/LCD/HD44780.pdf
The HD44780 has enough DDRAM to operate an 80 character display. A 16x2 display has 32 characters meaning we have 48 characters of free DDRAM. Is there anything in the Arduino's LiquidCrystal library which allows direct access to this DDRAM space? The HD44780 datasheet says it can be used as generalised RAM.

Most libraries (and adapters) assume write only access to the LCD. The 80 character buffer is actually to allow smooth scrolling of text line.

I haven't used that particular library but I have used the ddram and cgram as memory / buffets. So the feasibility is never in question.
The downside with this approach is speed and real estate. Those devices are slow by mcu standard. You then have to provision for the rw pin and the data pins - both read and writes. That's what you should check for in the library.
But it is workable for sure.


text:
Need ESP32 to use 3 serial ports
I have a project that needs 3 serial ports on my ESP32 Dev 38-pin MCU. Two of them are for Nextion touch displays and the other is for a GPS.
The problem from what I understand is that the ESP32 has 3 hardware serial ports, of which only 2 can be used. GPIO 1 and 3 can not be connected to the display during upload and the software serial that is in Arduino IDE 2.0.4 is not compatible with an ESP32.
Can anyone tell me how I can use 3 serial ports?
Thanks.

use ota to upload sketches, it's faster, safer,  and more flexible anyway. you can also use a software serial, mos def.

It's easy to remap any of the ESP32 serial port pins to other pins, so you're not bound to the standard pinout.

Welcome Richard, your question is interesting and a common problem in the Arduino arena. I simply use a SPI or I2C board that outputs RS232. I stumbled across them a few years back and used several, they worked great. I do not remember what they were called but here is a link to one of the many that are available: "https://andino.systems/extensions/rs232"This was the first search term I used: arduino SPI to RS232 module". Here is another link for the Pi: "https://forums.raspberrypi.com//viewtopic.php?t=146908&p=1083915#p1024636"

Not a full answer, but, depending on your GPS model, you might be able to use I2C instead.

Yes it is possible to assign any GPIO pins to serial using HardwareSerial library for up to 3 UART Connections. See this link for reference: https://copperhilltech.com/blog/esp32-programming-three-serial-ports-uarts-using-the-arduino-ide/
I'm playing with 2 nextions and esp32 also. would be great to chat with you and brainstorm

    #define UART1_ODU_BAUD_RATE 2400
    #define U1RXD 32
    #define U1TXD 33

Use this for UART Init in the setup
    // UART1 Configuration
      uart_config_t Configurazione_UART1 = {
        .baud_rate = UART1_ODU_BAUD_RATE,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_EVEN,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_APB,
      };
      uart_param_config(NUMERO_PORTA_SERIALE, &Configurazione_UART1);
      esp_log_level_set(TAG, ESP_LOG_INFO);
      uart_set_pin(NUMERO_PORTA_SERIALE, U1TXD, U1RXD, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
      uart_driver_install(NUMERO_PORTA_SERIALE, BUF_SIZE, BUF_SIZE, 20, &uart1_queue, 0);
      xTaskCreate(UART_ISR_ROUTINE, "UART_ISR_ROUTINE", 2048, NULL, 12, NULL);
      //vTaskDelete(NULL);

Create a ISR function
    static void UART_ISR_ROUTINE(void *pvParameters)                //uart1
    {
      uart_event_t event;
      size_t buffered_size;
      bool exit_condition = false;
      String ODU_PAC_ONE_Temp = "";

      ODU_PAC_ONE = "";

      while (1) {
        if (xQueueReceive(uart1_queue, (void * )&event, (portTickType)portMAX_DELAY)) {
          if (event.type == UART_DATA) {
            uint8_t UART1_data[128];
            int UART1_data_length = 0;
            ESP_ERROR_CHECK(uart_get_buffered_data_len(UART_NUM_1, (size_t*)&UART1_data_length));
            UART1_data_length = uart_read_bytes(UART_NUM_1, UART1_data, UART1_data_length, 100);

            for (byte i = 0; i < UART1_data_length; i++) {
                ODU_PAC_ONE_Temp += (int) UART1_data[i];
            }
          }
          else if (event.type == UART_FRAME_ERR) {

          }
        }
        if (exit_condition) {
          break;
        }
      }
      vTaskDelete(NULL);
    }

You will get your data in here (int) UART1_data[i]

This answer might benefit from a bit of explanation. In what way is this better than a simple port remap?


text:
Alter baud rate after being certain events
I'm using my HC-05 (Master) to receive strings from a sensor (Slave). Each string is supposed to have 7 items divided by ',' like so:

a,b,c,d,e,f,g

But it isn't always received in such a manner. Sometimes it's 1.5 of a string or 2 strings in 1. I have tested the sensor with its native software and others, so the sensor shouldn't be the problem. So I believe it may be a baud rate issue. I tried to increase the HC-05's baud rate to 115200, but wasn't able to test anything because I need to use AT commands at the beginning of the program and for that the baud rate has to be 38400.
Is there any way to change the baud rate for Serial after the fact?
PS: I'm using a Mega 2560 and the sensor has a sample rate of 8Hz.
#include <SoftwareSerial.h>
#include <SD.h>

String test="";
char aux;
File myFile;

void setup() {
  pinMode(22, OUTPUT);
  digitalWrite(22,HIGH);
  Serial1.begin(38400);
  Serial.begin(38400);
  Serial.println("To begin capture press any key and enter");
  while(!Serial.available());
  Serial1.println("AT+INIT");
  while(!Serial1.available());
  Capture();
}

void Capture() {
  while(!Serial1.available());
  for(int i=0;i<2;i++) {
    delay(125);
    while(Serial1.available()) {
      aux=Serial1.read();
      Serial.print(aux);
    }
  }
  Serial.println("END");
}

void loop() {
}

I doubt that baud rate is the problem.  You might be overflowing a buffer, however.  Nobody here can say for sure without seeing the actual code.  Edit question, paste in the code, highlight it, and press ctrl-K to mark the code as code

If you have a MEGA then why use SoftwareSerial? Use one of the several available HardWare UARTpresent on the chip instead.

Don't use delays in serial code.  If you want intact messages, your program will need to collect data until you find something that defines their end, like a newline.  Bluetooth is going to be packetized so your data will likely be bursty - a bunch of characters then some time before any more.  You'll need to consider the burst boundaries arbitrary, what matters instead are the end conditions (newline or whatever) within your data.  Those could even occur in the middle of a burst.

Well the sensor I use has a sampling rate of 8Hz so every 125ms it will sample and send a string, thats the reason behind the delay(). I wasn't using it before and it would either give me trash or nothing, so should i use while(!Serial1.available()) since I need to be sure there is something there.

Your code should be event driven, not delay driven.  As already explained the arrival time and grouping of data after the bluetooth will not be regular or meaningful.  Your code needs to look for a condition within the data, such as a newline or other end marker, or else your code needs to not care where one message ends and another starts, deferring that to something else (human, another program yet to be mentioned, etc)

Thanks @ChrisStratton, I was able to fix it by making it more event driven but now there is an other problem. I need to write the strings to a .txt file in an SD card, but if I try to do it in that while receiving the strings it causes the same previous problem. So it has to be stored in an array to be written after I've received all the strings, but the array needs to be at least 480 in size. When I tried this nothing was written in the .txt file, it's probably a memory leak. Any thought on how to fix this? Should I make a new thread?

I think it would be better if you post your "another problem" as an another question, considering the original question is answered.

To answer your specific question, yes you can alter the baud rate after an event.  Just use a Serial.end() then a Serial.begin() with the new baud rate.

Though this is not the problem.

I agree but that's the question he asked.

Then what is the problem?

The actual issues are already explained in comments on the question; basically a complete misimplementation of serial data handling.