message:
Arduino pins vs Esp8266MOD

I had used Arduino Uno & RFID but now i want to run same code in Esp8266MOD.
i have installed all the drivers and everything else to run esp8266 in Arduino IDE but i dont know how to connect rfid in esp8266. Can someone please compare which arduino pin & esp8266 pin are similar

     * Typical pin layout used:
     * ------------------------------------------------------
     *             MFRC522      Arduino       NodeMCU
     *             Reader/PCD   Uno/101       ESP8266MOD
     * Signal      Pin          Pin           Pin
     * ------------------------------------------------------
     * RST/Reset   RST          9             ?
     * SPI SS      SDA(SS)      10            ?
     * SPI MOSI    MOSI         11 / ICSP-4   ?
     * SPI MISO    MISO         12 / ICSP-1   ?
     * SPI SCK     SCK          13 / ICSP-3   ?

body:
table filled

     * Typical pin layout used:
     * ------------------------------------------------------
     *             MFRC522      Arduino       NodeMCU
     *             Reader/PCD   Uno/101       ESP8266MOD
     * Signal      Pin          Pin           Pin
     * ------------------------------------------------------
     * RST/Reset   RST          9             any, recommended 5
     * SPI SS      SDA(SS)      10            any, recommended 4, possible 15
     * SPI MOSI    MOSI         11 / ICSP-4   13
     * SPI MISO    MISO         12 / ICSP-1   12
     * SPI SCK     SCK          13 / ICSP-3   14

io 15 is SS if esp8266 is slave. but this pin must be LOW at boot. you can use it as SS if SS pin of reader doesn't pull-up.

io 4 and io 5 are untroubled pins.

io 0 and io 2 are with io 15 boot configuration pins and can be used only if they don't change the required boot state.

io 1 and io 3 are Serial interface

io 16 is RTC pin and is used for wake up from deep slepp

warning: does the reader work with 3.3 V?


sender: user

message:
Testing Conditions on Port Bytes - ignoring certain bits?

Being new to testing byte and bit conditions, I feel like there has to be a better way to test for conditions/values on a byte (read from a port).

For example, I'm reading 8 bits from PORTK. I need to test for a pattern of high bits. (Say, byte value of 207 - bits 7, 6, 3, 2, 1, 0 all high.) Bits 4 and 5 I don't care about. They CAN be high, or can be low. (Using datasheet terminology, they're "`X - Don't Care`".)

I could do an if, and test if the value equals 207, 223, 239, or 255, but that seems messy and like there would be an easier (and cleaner to read) way.

Edit to add: I've looked at Bit Operators, and .. something is telling me I should/could be using one of those. But I'm having a difficult time walking through which one would help me.

Thanks!
-Mike

sender: assistant

body:
You need to use boolean arithmetic.  Use the `AND` operator (`&`) to combine the incoming value AND the "mask" value (the value of the bits you do care about) and see if it equals the mask bit:

    byte wanted = 0b11001110; // 207
    byte incoming = 223; // for example 11011111

    if ((wanted & incoming) == wanted) {
        // whatever
    }

The AND operator compares each bit of the bytes in turn.  If they are BOTH 1 then the result is 1. Otherwise the result is 0.  So the above gives:

    wanted:    11001110
    incoming:  11011111
    AND:       11001110

And the result matches "wanted". If you had some other value for incoming it could look like this:

    wanted:    11001110
    incoming:  01011011
    AND:       01001010

And you can see that the result doesn't match.


body:
There are ways to mask off the don't care bits.
Say your example, 0b11xx1111.
Then

    incomingByte = Serial.read();
    incomingByte = incomingByte || 0b00110000;  // make 4, 5 high
    if (incomingByte == 0b11111111){
    // got all 1s, do something
    }
    else {
     // some 0s received, do something else
    }


message:
Methodology for designing/prototyping LED patterns

Several of my projects go through this time-consuming and tedious phase:

1. design a LED pattern for a geometry of WS2812 LEDs
2. implement it with e.g. FastLED
3. write to Arduino and see results
4. goto step 1

The second step, implementing different ideas in C with FastLED (or similar) takes a lot longer than I'd like it to. How is this step usually solved? Are there higher-level software solutions? Specialised idea-testing hardware?

I'd like to easily try out ideas such as "what if these four LEDs blinked magenta every second, while a gradient was cycling around the gradient over here".

body:
I'm not sure if there are already solutions for it (high chance there are, maybe in some DMX 'simulations'), however, it shouldn't be too difficult to make your own.

Use a programming language you like which can handle graphics, use the same data structure as you would with FastLed, and let the software program (you write) show the pixels on a screen. This means you don't need any Arduino code.

If you split the filling of the pixels and the showing of it on the screen, you can copy the resulting 'filling of the pixels' code on the Arduino.

**Update**
Another solution, if you want to experiment with the actual WS2812, is to program all patterns you want to check with FastLed, and let inputs (via UART or fancy knobs/buttons/menu) decide what patterns (and properties) are executed. The key is to program the patterns in a flexible way (so use functions with parameters for each property, and states for which pattern(s) are executed or executed next if you want to check some sequence).


body:
For designing patterns for visual evaluation, it would be better to just have the arduino/controller be a pass-through from something like a full computer. There is a project called [FadeCandy][1], which allows one to send various patterns to a WS2812 chain using a protocol called [Open Pixel Control][2].

Some options would be to build or buy a FadeCandy board, or to implement the OPC protocol on your own arduino so that you can play around with test patterns and designs in a rapid development environment like Python or just making the raw patterns in a file and dumping that to your device over the serial port or TPC, etc.

Once you have your patterns or design the way you want it, then you can translate it to C code and FastLED, knowing you have a fixed specification you are trying to implement, rather than reflashing an arduino for every iteration.

  [1]: https://github.com/scanlime/fadecandy
  [2]: http://openpixelcontrol.org/


message:
What is the easiest way to count how many global variables are in your sketch code?

I have a fairly complicated sketch with about 1k lines of code. I should also say that I'm not a programmer by trade...

As I go over my code and try to make it more efficient, it'd be good to know how many global variables are in my code and whether/if all of them are necessary as global. So:

1 - Is there an easy way to count how many global variables you've used (again, imagine complex code by a non-coder), and

2 - Is there an easy way in the Arduino IDE to jump to it?

body:
1 - The number of variables is not important, but the number of used memory (in bytes) is important. That is shown at the bottom of the Arduino IDE by the compiler when verifying or uploading a sketch.

2 - It is not possible to go to, for example, the largest global variable. You can use the search function to search for something.

For a small microcontroller, for example a Attiny or Atmega8, every byte that uses memory can be important.

For a Arduino Uno and larger, the optimization is done more globally.

To optimize for ram, look for the hungriest memory eaters:

 - For the Arduino Uno and other avr microcontrollers, the text with
   Serial.println can be put in PROGMEM with the F() macro.
 - Many String
   objects might need a lot of heap memory.
 - Arrays can get large
   quickly.
 - Arrays of large elements (float, struct) can get large even
   more quickly.
 - The SD library uses a lot of ram memory. There is a small version
   of the SD library.
 - Some graphical libraries for displays use a lot of memory.

Try to avoid to save a single byte, unless you check the resulting memory usage. The compiler can optimize code in a way that conflicts with someone trying to save a byte.

 - When an integer is changed into a byte,
   perhaps all the calculations are still done with integers and the
   compiler needs more memory to convert from byte to integer and back.
 - Perhaps that integer was only used in registers and
   did not use a memory location.
 - A 'const' integer uses probably no ram memory at all.

Final tip: Don't be afraid to upgrade to an other Arduino board with more memory. If you project uses almost all the memory, then it is not possible to add something to your project. When the project runs for a while, you might want to add an extra sensor or extra functionality.


message:
What should I use Arduino-Mega or Rasbeery pi?

I am doing a project on Vehicle tracking and security. In my project Micro controller will sense input from sensors and at the same time it has to sense signal from user for tracking purpose and continuously checking the speed limit and boundary. so, there will be 3-4 tasks that would be executing parallel. Can anyone suggest which one is perfect for this kind of project... Arduino-Mega or Rasberry Pi?

body:
A RaspberryPi is essentially a small, low-spec computer. It is mostly an overkill for many small projects. Imagine using a super high-spec computer to play Minecraft. It's just nonsensical.

I'm assuming you'll be connecting to the car battery? Take note of the power requirements of your project. The RaspberryPi has a power requirement of [2.1A at 5V](https://www.raspberrypi.org/products/raspberry-pi-3-model-b/) (which is a lot!), whilst an Arduino has a minimum requirement of [250mA](https://playground.arduino.cc/Learning/WhatAdapter).

Also remember: the RaspberryPi is running an operating system in the background in order to run your code. It will be working on numerous other operations and programs, not just yours. The Arduino will only run your program.

I had a similar project to what it sounds like you're doing. I used an Arduino Mega and had Bluetooth, GPS, and SD card all connected to it. The project worked absolutely fine, and I had lots of spare program space left over should I wish to expand on it. For reference, [feel free to explore](https://www.instructables.com/id/DIY-Telematics-Box/).


message:
Regarding running multiple functions using millis

I have been writing code for measuring when the digital signal comes and goes (ON and OFF respectively). I have done the part calculating a single system's downtime (difference in timings between ON and OFF from the system), but when I'm not able to scale up to multiple systems when I try to copy the same code which worked above. So it would be helpful if anyone could provide some insight into how it can be done plus explaining with the code would help.

My code:

    unsigned long a=0, b=0, difference;
    void setup()
    {
      Serial.begin(9600);
      pinMode(2, INPUT);
      Serial.print("start");
      Serial.print(",");
      Serial.print("stop");
      Serial.print(",");
      Serial.print("minutes");
      Serial.print(",");
      Serial.println("seconds");
    }

    void loop()
    {
     //delay(1000);
     int A = digitalRead(2);
     if(A == LOW)
     {
      b = millis();
     }
     if(A == HIGH)
      {
         a = millis();
         display_output();
       }
     delay(3000);
    }
    void display_output()
    {
     int minutes, seconds, sec;
     difference = a - b;
     seconds = int(difference/1000);
     if(seconds >= 60)
     {
      //sec = seconds;
      seconds = seconds`;
      minutes = minutes+1;
     }
     //minutes = int(seconds/60);
     Serial.print((a/1000)+1);
     Serial.print(",");
     Serial.print((b/1000)+1);
     Serial.print(",");
    // Serial.print(difference);
     //Serial.print(",");
     Serial.print(minutes);
     Serial.print(",");
     Serial.println(seconds);
     //Serial.println(",");
    }

body:
First of all, you should notice there is a problem with your logic:

<!-- language-all: lang-c++ -->

     int A = digitalRead(2);
     if(A == LOW)
     {
      b = millis();
     }

Here you are testing the state of the pin. If it's `LOW` you take a
record of the time. This is wrong. What you want to record is the time
at which the inputs **falls**, not when it's `LOW`.
This is called [state change detection][change]. In order to implement
it, you have to compare the pin state that you just read with
_the previous state_. The correct condition is “if the pin was `HIGH`
last time I read it and is now `LOW`”:

    // Global variable:
    int pin_state = HIGH;

    // Within loop():
    int new_pin_state = digitalRead(2);
    if (pin_state == HIGH && new_pin_state == LOW) {  // it just fell
        time_of_fall = millis();
        pin_state = new_pin_state;
    }

Note that this assumes that the default state is `HIGH`. If the pin
turns out to be `LOW` at power-up, then the code will assume it just
fell when the program started.

Next, you have to remove any occurrence of `delay()` from your code.
That will only make your timings wrong. At this point you have
non-blocking code that can easily be adapted to handle multiple input
channels.

Then you have to identify the variables that are channel-specific, and
have a per-channel version of each variable (arrays are useful here).
Then your code only needs to loop through the arrays.

Instead of having multiples arrays, you can make the code cleaner by
grouping all the channel-specific data into a single data structure:

    struct Channel {
        byte pin;
        byte state;
        unsigned long fell, rose;  // times of fall and rise
    };

This way you can have a single array that holds all the data for all the
channels:

    const int CHANNEL_COUNT = 5;

    Channel channels[CHANNEL_COUNT] = {
        { 2, HIGH, 0, 0 },
        { 3, HIGH, 0, 0 },
        { 4, HIGH, 0, 0 },
        { 5, HIGH, 0, 0 },
        { 6, HIGH, 0, 0 }
    };

The code now becomes quite simple: you just loop through the array and
handle one channel at a time:

    void setup()
    {
        for (int i = 0; i < CHANNEL_COUNT; ++i) {
            pinMode(channels[i].pin, INPUT);
        }
        Serial.begin(9600);
        Serial.println("pin,fell,rose,low time");
    }

    void loop()
    {
        for (int i = 0; i < CHANNEL_COUNT; ++i) {
            Channel &c = channels[i];
            byte new_state = digitalRead(c.pin);
            if (c.state == HIGH && new_state == LOW) {  // input fell
                c.fell = millis();
            }
            else if (c.state == LOW && new_state == HIGH) {  // input rose
                c.rose = millis();
                display_channel(c);
            }
            c.state = new_state;
        }
    }

The function `display_channel()` is left as an exercise to the reader
;-) (hint: it's prototype should be
`void display_channel(const Channel &c);` in order to avoid
unnecessarily copying the data structure.

Next step in code modularity would be to turn the `Channel` structure
into a class with a proper constructor, and make `display_channel()` a
method of that class.

[change]: https://www.arduino.cc/en/Tutorial/StateChangeDetection


message:
Arduino ultrasonic sensor project

I'm a newbie at Arduino, and I'm trying to make a project with ultrasonic sensor, I'm using the grove ultrasonic ranger, not the HC-SR04, and I already did test with distance and it worked very well, but now I need help with the code.

I need to create a vector that save the values of the distance to after calculate the speed using distance/time calculus, but the case of my project its to use in open places, so will be times that the distance will be "max" because there's nobody in the range, so I need a condition to exclude those values of the array (the maximum distance printed when the sensor can't feel nothing is 516 cm)
I'm not experienced with Arduino coding, so please help me, in anex is my code for basic scanning.

    #include "Ultrasonic.h"

    Ultrasonic ultrasonic(7);
    void setup()
    {
        Serial.begin(9600);
    }
    void loop()
    {
        long RangeInCentimeters;
        Serial.println("The distance to obstacles in front is: ");

        // two measurements should keep an interval
        RangeInCentimeters = ultrasonic.MeasureInCentimeters();
        if(RangeInCentimeters > 400)
        Serial.print ("distancia nula");
        else
        Serial.print(RangeInCentimeters);//0~400cm
        Serial.println(" cm");
        delay(1000);
    }

body:
If you don't know how many data points will be recorded, look into [vectors](https://stackoverflow.com/questions/9986591/vectors-in-arduino) or an external storage device. Alternatively you could use a [circular array](https://www.geeksforgeeks.org/circular-array/) if you don't mind losing recorded data after a while.

If you know how many data points will be recorded, a basic array will suffice.

As for excluding invalid values:

    // Keep trying to get a valid data point
    While (RangeInCentimeters > 512 && RangeInCentimeters < 400)
    {
     delay(200);  // The minimum value of this delay depends on the sample rate of your sensor
     RangeInCentimeters = ultrasonic.MeasureInCentimeters();
    }

    //... Store data to array/linked list/etc

I changed your max range to 512 because this is likely the max real value (2^9 = 512).


message:
convert 32 bit long to 4 bytes and back again - CAN Bus

So after 2 days attempting this I can't get my head round it.

So I am using CAN bus to transfer accelerometer data and time data (the micros() function if under 71 minutes will output data that can be an unsigned long), however I have to send the data as bytes. I have managed to bit shift a 16-bit int into 2 bytes but I am having trouble extrapolating that method (will add later) to using longs. I am having trouble understanding the union method as I am new to creating my own functions, so, how would you guys accomplish this? As simple as possible please :)

body:
The `union` type is similar to a `struct` except that each of the members of the element occupy the same memory. If you define a `struct` so that it has 2 members -- one 4-byte type and one 4-element array of a single byte type, then you can easily refer to the same data as a whole 4-byte element, or byte-wise as you desire.

    union packed_long {
      long l;
      byte b[4];
    };

This is the type, so you have to declare the variable to be of that type:

    packed_long mydata;

Now, you have two sub-elements of `mydata`: `l` and `b[]`.

To save your `long` value, write to the `l` part:

    mydata.l = myaccel.getY();

To access each of the 4 bytes:

    byte1 = mydata.b[0];
    byte2 = mydata.b[1];
    byte3 = mydata.b[2];
    byte4 = mydata.b[3];

On the receiving end, you take each of the 4 bytes:

    mydata.b[0] = canbus.read();
    mydata.b[1] = canbus.read();
    mydata.b[2] = canbus.read();
    mydata.b[4] = canbus.read();

 As long as you receive the bytes in the same order in which you sent them, you can now access your `long` value in `mydata.l`.

The actual size of different types is dependent on the compiler and architecture, so you may also wish to define your value as a definite-sized variable to ensure you are always working with 32 bits: `int32_t` (signed 32-bit integer) or `uint32_t` (unsigned 32-bit integer).


body:
You can achieve what you want by using [bitshifting][1] and [bit-wise and][2] operators.

Here is an example that lets you extract the individual bytes of your `long` variable. I think it should be straigtforward to extend it to variables of different length:

    void loop() {
      long a=0x12345678, c=0;
      byte b[4];
      Serial.println("Original:");
      Serial.println(a,HEX);
      delay(1000);
      Serial.println("Individual bytes:");
      for (int i=0; i<4; i++)
      {
        b[i]=((a>>(i*8)) & 0xff); //extract the right-most byte of the shifted variable
        Serial.println(b[i],HEX);
        delay(1000);
      }

      for (int i=0; i<4; i++)
      {
        c+=b[i]<<(i*8);
      }
      Serial.println("Reconstructed:");
      Serial.println(c,HEX);
      delay(1000);
    }

Depending on what byte ordering (big or little endian) is expected, you might need to reorder the bytes before sending or after receiving.

  [1]: https://www.arduino.cc/reference/en/language/structure/bitwise-operators/bitshiftright/
  [2]: https://www.arduino.cc/reference/en/language/structure/bitwise-operators/bitwiseand/


body:
A way to send a long is to mask off and send the LSB byte (CAN standard), then shift the next one into LSB position, for 4 bytes:

    uint32_t data;

    // Send to CAN bus LSB-first
    // This method is destructive; data should be a temp if the
    // Arduino is to retain the data after sending it.
    for( uint8_t b = 4; b > 0; --b ){
       sendByte(data & 0xFF);  // send curr byte
       data >>= 8;             // shift that byte away
    }

    // Read from CAN bus
    for( uint8_t b = 4; b > 0; --b ){
       data >>= 8;                 // make room for byte
       data |= (readByte() << 8);  // read next higher byte
    }
    //


message:
Print uint8_t in arduino

I'm learning esp8266 using arduino IDE. I'm still a beginner in development board programming. What I've been trying to do is use a [crypto library][1]. I am trying out AES in arduino and I chose that library because it seemed complete, and was one of the only library that used ECB. My problem is whilst calling the encrypt function, I get confused with the output.

This is what I've done so far.

    #include <Crypto.h>
    #include <AES.h>
    #include <string.h>

    AESSmall128 aes128;

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

      uint8_t key = (uint8_t)1234567654321234;

        aes128.setKey(&key, 16);

        uint8_t output = 0;

        Serial.println("before");
        Serial.print(output);

          uint8_t input = (uint8_t)9164567654321234;

        aes128.encryptBlock(&output, &input);
        Serial.println("after");
        Serial.print(output);

    }

    void loop()
    {
    }

When I print `output` it returns `252`. What is 252? Why only 252? It seems really short looking at it. Why doesn't it output strings?
  [1]: https://rweather.github.io/arduinolibs/classAESCommon.html#a2d95f6159abfcd92b5841f9018e44296

body:
The `uint8_t` is exactly 8bits wide, so it can hold values from 0 to 255. Your number however is about 54bits wide.

I think you should use the array.

Also numeric literals are usually int type, so even if you do have enough space for it, it gets wrong value. Something like `uint64_t value = UINT64_C(1234567654321234);` must be used


body:
`uint8_t` is an Unsigned 8-bit Integer, and so the range of values it can represent are 0 to 255.

When you typecast your long/large values to `uint8_t`, you basically only show the least-significant 8-bits.

However, the `decryptBlock()` and `encryptBlock()` functions expect an array of bytes, not a single byte.

The library you link to notes, right in the linked position, that the output and input parameters must be at least `blockSize()` bytes in length. Referencing `blockSize()`, it notes that this function always returns `16`. So you need to pass an array of `uint8_t`s of at least 16 length.

When you define your variables for the key, plaintext, and ciphertext, you need to not define then as a single byte type, but as an array of bytes:

    uint8_t[16] key =    {1,2,3,4,5,6,7,6,5,4,3,2,1,2,3,4};  // This is not a good key, btw
    uint8_t[16] output = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t[16] input =  {9,1,6,4,5,6,7,6,5,4,3,2,1,2,3,4};

(When passing an array, you don't need to dereference the variable, so call `aes128.setKey(key, 16);`, etc. Omit the `&`)

Each of the 16 bytes can have a value in the range 0 to 255. They do not have to be limited to single-digit numbers; I just copied/translated what you wrote to demonstrate the example. You could set your key in this way:

    uint8_t[16] key =    {66,127,164,72,68,158,148,255,23,36,226,192,198,248,251,221};

You can also refer to bytes with a 2-digit hexadecimal representation:

    uint8_t[16] key =    {0xa6,0x09,0x81,0xc5,0xb8,0xf6,0x9a,0x33,0x75,0x24,0xff,0x79,0xd3,0x48,0x4f,0x1d);

----------

**UPDATE to address strings**

A C-style string is a sequence of bytes, with type `char` to indicate ASCII data, though any byte-wide type could work in theory. The sequence of bytes ends with a value of `0` (i.e., `0x00`, not the ASCII character `'0'`), so you must remember that the termination byte takes up a byte of memory.

To initialize your key with a string:

    const unsigned char[17] key = "helloareyouarehi"; // 16 characters, and 1 byte termination means 17 total bytes reserved in memory.

I have not investigated how the crypto library you are using handles C-style strings, so let's assume it does not acknowledge them at all, and we will have to null-terminate our strings ourselves.

    char[17] output = {0}; // Initialized to all zeros
    char[17] input = "iwanttoencryptme";

    aes128.encryptBlock(output, input);
    output[16] = 0x00; // Just to be safe, put the null terminator in the last slot.

    Serial.print(output);

If the `encryptBlock()` function only changes 16 bytes in the output array, then the 17th (zero) could remain from the initialization, but not knowing whether the function preserves strings, it is better to be safe than sorry.


message:
What is the difference using library of SoftwareSerial.h and ESP8266WiFi.h?

What is the library I should use to upload the sensor data (ultrasonic and Infrared sensor) to the localhost server.

Because I saw some of the online resources using ESP8266WiFi.h library for the ESP01 and some of resources use the softwareserial.h library. So, what is the difference between these two libraries?

body:
The SoftwareSerial is used to communicate with the esp8266 from other MCU. The ESP8266WiFi library is for Arduino sketch running in esp8266.

The esp8266 can be used with firmware as 'network adapter' for your sketch running for example in Arduino Uno. MCU in Uno has only one hardware Serial which is used to communicate with the computer over USB (to upload and use Serial Monitor). To communicate with the esp8266 usually a second Serial interface is created with SoftwareSerial.

But esp8266 can be used as Arduino board with "esp8266 Arduino core". This 'core' contains Arduino libraries to access the WiFi functions of the esp8266 from a sketch running in esp8266.


message:
Equivalent of millis() in Atmel studio

This code It works in atmel studio.But this millis function is starting to run 31-34 miliseconds behind of arduino millis fuction.Why?I am adding picture.

**Picture**: https://imageshack.com/a/img922/3060/umtNJp.jpg

**Update 2**

    #define F_CPU 8000000UL
    #include <avr/io.h>

    #include <avr/interrupt.h>

    #define clockCyclesToMicroseconds(a) ( ((a) * 1000L) / (F_CPU / 1000L) )
    #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
    #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
    // the fractional number of milliseconds per timer0 overflow. we shift right
    // by three to fit these numbers into a byte. (for the clock speeds we care
    // about - 8 and 16 MHz - this doesn't lose precision.)
    #define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
    #define FRACT_MAX (1000 >> 3)
    volatile unsigned long timer0_overflow_count = 0;
    volatile unsigned long timer0_millis = 0;
    static unsigned char timer0_fract = 0;

    volatile uint8_t count;

    ISR (TIMER0_OVF_vect)

    {

     unsigned long m = timer0_millis;
     unsigned char f = timer0_fract;

     m += MILLIS_INC;
     f += FRACT_INC;
     if (f >= FRACT_MAX) {
      f -= FRACT_MAX;
      m += 1;
     }

     timer0_fract = f;
     timer0_millis = m;
     timer0_overflow_count++;

    }

    unsigned long millis()
    {
     unsigned long m;
     uint8_t oldSREG = SREG;

     // disable interrupts while we read timer0_millis or we might get an
     // inconsistent value (e.g. in the middle of a write to timer0_millis)
     cli();
     m = timer0_millis;
     SREG = oldSREG;

     return m;
    }

    int main (void)

    {
     DDRB |= (1<<0);
     TCNT0 = 0;
     count = 0;
     TCCR0B |= (0<<CS02) | (1<<CS01) | (1<<CS00); // PRESCALER 64
     TIMSK0 = (1<<TOIE0);
     sei();

     while(1)
     {
      millis() to uart.

     }

    }

body:
The `millis()` function is defined in the [Arduino Core for AVR architecture][1], specifically the [`wiring.c` file][2].

You can see that timer0 is setup with various parameters for prescaling and interrupt triggering and handling of timer0 overflow such that a variable called `timer0_millis` contains the number of milliseconds since the sketch started.

The `millis()` function basically returns that `timer0_millis` value.

If you wish to make use of the function in AVR Studio, then you would need to include the same kind of timer0 setup and interrupt/overflow handling that the Arduino core does.

  [1]: https://github.com/arduino/ArduinoCore-avr
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c


message:
Connect two or more modules sharing the same pins?

I've found some separate instructions for connecting an SD reader/writer and also instructions for connecting a RFID reader and Piezo Buzzer.  I would like to use both modules and the piezo buzzer together on the same Arduino. See below for the pin wiring details from each instruction I found:

**SD Reader/Writer**

 - 3.3v goes to 3.3v on the Arduino UNO (for power)
 - GND goes to Ground on Arduino UNO
 - D0 goes to pin 12 on Arduino UNO
 - D1 goes to pin 11 on Arduino UNO
 - CLK goes to pin 13 on Arduino UNO
 - D3 goes to pin 10 on Arduino UNO

**RFID Reader**

 - SDA - Digital 10
 - SCK - Digital 13
 - MOSI - Digital 11
 - MISO - Digital 12
 - IRQ - unconnected
 - GND - GND
 - RST - Digital 9
 - 3.3V - 3.3V

**Piezo Buzzer**

 - Red - Pin 8
 - Black - GND

Is using the same pin for more that one module ok?

body:
pins 11 MOSI, 12 MISO and 13 SCK are [SPI bus][1]. You can connect more devices to the bus. A 'slave select' ('cable select') pin determines which device will communicate. In your table both devices use pin 10 for this. You must change one.

I recommend to wire SD reader D3 to pin 4 and in sketch use `SD.begin(4)`.

Note: some cheap SD card adapters block other devices on the bus and can be used only as single device on the bus

  [1]: https://www.arduino.cc/en/Reference/SPI


message:
Arduino Resetting in Automotive Application

I have a complicated problem with my Arduino circuit being reset/crashing, I will try to describe the best I can.

The Setup:

Basically I have a Arduino 328P circuit that is monitoring some temperatures in an automotive environment.  Several one wire temperature sensors connect to the PCB with various distances from 2-10 ft. Each is on a seperate pin.  I have also tried analog LM35 sensors.  The system works outside the car just fine.

The Problem:

When the car is shut off (not the PCB) the Arduino is being reset despite power still being connected.  There is no power spike or loss to the PCB. The car is not actually running, I am just turning the key on and off.

What I have learned:

-When I disconnect the temperature sensors from the PCB, problem goes away.

-It makes no difference if the wires to the sensors are shielded.

-It makes no difference if I use one wire digital or analog sensors.

-It makes no difference if I connect the PCB directly to the battery

-The problem goes away if I run the PCB on a battery not connected to the car. (fully isolated)

-The problem comes back if I ground the PCB to the chassis, but still leave the +12V isolated.

-The chance of a reset changes when the sensors are moved or the length of wire is changed.

-It only resets when the key is turned off, never when turned on.

I tried to explain the best I can without writing a novel.  I think I might need to isolate the ground to my PCB somehow.  The problem is in the ground or the long wires to the sensors.

body:
> There is ***no power spike*** or loss to the PCB. The car is not actually
> running, I am just turning the key on and off.

And did you verify that with a digital scope? I doubt it.

I don't think you understand how ugly the electrical system in a car really is. If there is a coil or relay switched then there **will** be spikes. Do some research on electronics for use in an automobile.

Automotive relays can have a resistor in parallel with the coil to control the level of the back emf when the relay is turned off. You would think that a reversed diode should be used but a diode causes the coil current to discharge too slow and that causes the contact arcing to be extended. A resistor can be used to speed up the discharge but at the cost of a voltage spike on the electrical system.

An Arduino board is not appropriate. There needs to be a lot more protection.And one wire devices are basically an antenna looking for trouble.

https://www.st.com/content/ccc/resource/technical/document/application_note/1f/d7/fc/6d/2e/27/48/98/CD00181783.pdf/files/CD00181783.pdf/jcr:content/translations/en.CD00181783.pdf

https://electronics.stackexchange.com/a/40425/195251

https://en.wikipedia.org/wiki/Load_dump

https://electronics.stackexchange.com/a/163861/195251


message:
Arduino esp8266 interferes with analog sensors

UPDATE: I tried CNY70 sensor and the same error is valid for it too. Even outputs of CNY70 and LDR is the same while ESP8266 plugged in. I think ESP8266 interferes with all analog sensors

I connected my esp8266 and ldr sensor to my seeediuno (clon of arduino by seeedstudio) and ldr returns values like 70 110 105 120 etc. When I directly pointed light to ldr, return values don't change, value scatter randomly between 50-130. When I disconnect esp8266 and switch to arduino diecimila from ardunio ide, ldr sensor works fine. I think esp8266 somehow interferes with ldr sensor. How can I fix this problem?

    #include "ESP8266WiFi.h"
    #include "ESP8266HTTPClient.h"
    [![#define SSID "myssşd"
    #define PASS "mypass"
    #define BID 000001

    const char *host = "api.host.com";

    void setup() {
      //start serial connection
      Serial.begin(115200);
      //configure pin 2 as an input and enable the internal pull-up resistor
      pinMode(2, INPUT);
      pinMode(13, OUTPUT);
      pinMode(A0, INPUT);

      WiFi.begin(SSID, PASS);

      while(WiFi.status() != WL_CONNECTED){
        delay(1000);
        Serial.println("Connecting...");
      }
      //If connection successful show IP address in serial monitor
      Serial.print("Connected to ");
      Serial.println(SSID);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());  //IP address assigned to your ESP
    }

    void loop() {
      //read the pushbutton value into a variable
      int sensorValMeal = analogRead(A0);
      Serial.println(sensorValMeal);
      delay(1000);
    }

This is how my serial prints looks like. You can see the anomally, I added my events as well.

    Connecting...
    Connecting...
    Connecting...
    Connecting...
    Connected to Anaconda
    IP address: 192.168.1.21
    42 <- This is start
    41
    41
    41
    41
    41
    41
    41
    40
    40
    151 <- I turned my phones light to ldr
    78
    85
    84
    89
    92
    69
    97
    99
    100
    96
    104 <- I switched of my phone's light
    63
    103
    103
    108
    108
    109
    109
    114
    111
    112
    111
    103
    112
    113
    114
    112
    116
    104
    116
    116
    101
    117
    118
    118
    108
    122
    80
    109
    118
    123
    124
    125
    124
    114
    127
    127
    127
    98
    126
    127
    124
    114
    125
    127
    125
    124
    127
    98
    127
    126
    104
    127
    127
    126
    118
    128
    127
    92
    123
    126
    127
    128
    127
    111
    130

[![enter image description here][1]][1]
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/6giAT.jpg
  [2]: https://i.stack.imgur.com/JRFW9.jpg

body: You read the analog pin of the esp8266, not the analog pin of the Seeeduino.


body:
You aren't using the Seeduino Arduino clone. You're using (as in writing software for, and programming) the ESP8266.  Every instruction you write affects *only* the ESP8266. The Arduino is nothing more than a power supply (and maybe a USB to Serial adaptor if you use it as such).

To access the analog pins on the Arduino you will need to:

1. Design a communication protocol between the two boards
2. Implement that communication protocol for *both* boards
3. Program *both* boards with their own unique sketches that use the protocol to communicate between them.

The Arduino will gather the data using its sketch, then send the results to the ESP8266 for sending through the internet.

Alternatively put the standard AT firmware on the ESP8266 and use that as the protocol above - then you only have to implement it on the Arduino.


message:
how can i split string data in arduino?

im sending string data via serial with following format ex. :45:60 or such as ":120:57".i got the data shown in Serial.println (secondValue) Serial.println (thirdValue); but i cant convert it to int

    String myString;
    char c;
    int Index1,Index2,Index3, azi;
    String secondValue, thirdValue;
    void setup(){
    Serial.begin(9600);}
    void loop(){
    while (Serial.available()>0)
    {
    delay(10);
    c = Serial.read();
     myString += c;
    }
     if (myString.length()>0)
    {
    Index1 = myString.indexOf(':');
    Index2 = myString.indexOf(':', Index1+1);
    Index3 = myString.indexOf(':', Index2+1);

    secondValue = myString.substring(Index1+1, Index2);
    thirdValue = myString.substring(Index2+1, Index3);

    Serial.println(secondValue);
    Serial.println(thirdValue);

    myString="";
    }
    delay(1000);
    }

body:
All numbers are integers?
If yes, you can use `toInt()` function.

    int secondValueInt, thirdValueInt;

    secondValueInt = secondValueInt.toInt();
    thirdValueInt = thirdValue.toInt();


message:
Why does using ESP8266 in deep sleep mode still drain the battery quickly?

I've made a "weather station" using the ESP8622. To save battery I'm using sleep mode but still the battery is drained after a couple of days. According to [this post](https://openhomeautomation.net/esp8266-battery) it should last at least a year.

I haven't done any measurements yet, wanted to know if there's something obvious that I've missed that could explain why the battery is drained so quickly? Attaching code and an image showing the hardware setup.

    #include "DHT.h"
    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>
    #define DHTPIN D2
    #define DHTTYPE DHT22
    DHT dht(DHTPIN, DHTTYPE);

    const char* ssid     = "xxxx";
    const char* password = "xxxx";

    const char* host = "xxxx";

    void setup() {
      Serial.begin(115200);
      dht.begin();
      delay(10);

      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      readSensorsAndPost();
      ESP.deepSleep(18e8); //30 minutes
    }

    void readSensorsAndPost() {
      float h = dht.readHumidity();
      float t = dht.readTemperature();
      if (isnan(h) || isnan(t)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }
      char charVal[10];
      dtostrf(t, 5, 2, charVal);
      makeAnHttpRequest(charVal);
    }

    bool makeAnHttpRequest(String msg) {
      //send the value
    }

    void loop() {

    }
 [![esp8622 and DHT22][1]][1]

  [1]: https://i.stack.imgur.com/BBYqB.jpg

body:
The example shows a Sparkfun Thing, which the article notes doesn't have extra peripherals. What you show is something different, like a NodeMCU dev board, which typically has a linear regulator, possibly a power LED (which the article notes can be removed).

I see you're using a DHT11 or DHT22, which has a pull-up resistor. The pull-up resistor is constantly using power. Instead of connecting the pull-up to the power rail, you can connect it to a GPIO pin and pull that pin LOW before you go into sleep, which effectively disables the sensor and stops it from drawing power just to keep the data line high.

Safe to say that somewhere there is something drawing power -- have you measured the actual current draw in deep-sleep, or are you only noting that your batteries run low sooner than expected?


message:
is there any real arduino emulators (so I can upload and run machine code on it)

I play with Arduino Micro. I write my programs in directly in machine code, in binary editors (yes, I know that there are more easy ways to program an Arduino, I do it for fun and learning). Often my programs work, but if not, then I would like to run them on an emulator to understand what's exactly going on under the hood. Is there any Arduino emulator that accepts hex files with compiled program and can execute it? I already looked at tools mentioned at https://arduino.stackexchange.com/questions/61/can-i-program-for-arduino-without-having-a-real-board , but as far as I see, they are simulators rather than emulators and I can't use compiled binary programs in them.

body:
There are [many different processors used in making many different types of Arduino boards][1].  So there is no one way to write Arduino machine code.

There are emulator for simpler processors available for the asking.  But, while they work, it is not believe they claim to be totally accurate.

At one point in processor development history, [ICE machines][2] were widely used.  This is where a real processor is modified to allow access to internal controls and registers.  (This actually sounds like the answer to your question.)  However, as processors grew in speed and complexity, this approach grew out of favor.

Currently, most processors are built with extra internal circuitry and interface to break program execution for debugging purposes.  [JTAG][3] is one such industry standard / example.

So, while the question has merit, the common practice is likely not to run code on an emulator, but to run it on the processor using the JTAG interface and an [IDE][4] running on a host-computer / work-station.

  [1]: https://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems
  [2]: https://en.wikipedia.org/wiki/In-circuit_emulation
  [3]: https://en.wikipedia.org/wiki/JTAG
  [4]: https://en.wikipedia.org/wiki/Integrated_development_environment


body:
**Disclaimer**: I have no affiliation with Wokwi (based on [opensource AVR8js engine][1]) except that I have learnt a lot from it.

I just tried it on the free Wokwi Arduino simulator(my favourite Arduino simulator for learning) and it worked in a blink!

**Here is what I did to load the hex file into the Arduino simulator**

 1. Go to the Arduino IDE and open the basic blink example
 2. Change the ON time delay to 100ms (to make sure, the hex file is really loaded into the Arduino simulator and to verify it's working.
 3. Once the modified example is compiled go to the `%temp%` folder
 4. Search for `*.hex` files and find the one which is just the latest one (this is the [only way][2] I found to grab the hex file needed)
 5. Go to [Wokwi Arduino Simulator with any Arduino example][3]
 6. Click on the editor tab in the left
 7. Press function key `F1`
 8. Select the option `Load HEX file and START simulation`
 9. Done - the simulation should run like expected.

I have created a short GIF and I hope you like it (lazy to show step by step)
[![enter image description here][4]][4]

  [1]: https://github.com/wokwi/avr8js
  [2]: https://forum.arduino.cc/t/arduino-ide-and-hex-files/49361
  [3]: https://wokwi.com/arduino/libraries/demo/blink
  [4]: https://i.stack.imgur.com/E9WLR.gif


message:
Is there any working analogue to the pair std::function and std::bind in Arduino?

Both [ArduinoSTL][1] and [StandardCplusplus][2] don't support them. They implement the version that is compatible with c++03 (not c++11).

This functionality is handy when you design libraries that work with callbacks. And you do need them, if your Arduino does more than one thing simultaneously.

I tried also several other options, but none was enough. Most complete thing I found, [Passing capturing lambda as function pointer][3], does not support plain function pointers and does not allow me to hold the `function` object as a member of the structure, because the type of the object depends on the lambda (not only its signature, like in `std::function`).

In particular, I need a functor that

* can store both capturing lambdas and plain function wrappers
* has a type that depends only on the signature of the function, so I can store it as a class member.

  [1]: https://github.com/mike-matera/ArduinoSTL
  [2]: https://github.com/maniacbug/StandardCplusplus
  [3]: https://stackoverflow.com/a/41528436/1261153

body:
We have written a solution, that we published as a Platformio library: https://github.com/fopeczek/function_objects.

Please note, that each functional object does one allocation, and those are not particularly friendly in an embedded environment. I am not even sure, that the Arduino C++ does heap deallocation, so you may be leaking resources if you create and destroy the functional objects in a loop.


message:
Taking String Input from NodeMCU Webpage and Printing it on Serial Monitor

I've started working with NodeMCU recently. I've very little knowledge about this device and how a website works. I'm trying to take a long string input from a website hosted by NodeMCU, store it on a variable and then print in on NodeMCU Serial Monitor.

I've got the following program. Here I only have created a text box for typing. But I don't know how to take that input inside a variable and use it later for serial printing.

    #include <ESP8266WiFi.h>

    const char* ssid = "****";
    const char* password = "*************";

    WiFiServer server(80);

    void setup() {
    Serial.begin(115200);
    delay(10);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
        }
        server.begin();
    }

    void loop() {
        WiFiClient client = server.available();
        if (!client) {
        return;
        }

        Serial.println("new client");
        while(!client.available()){
        delay(1);
        }

        String request = client.readStringUntil('\r');
        Serial.println(request);
        client.flush();

        client.println("HTTP/1.1 200 OK");
        client.println("Content-Type: text/html");
        client.println("");

        client.println("<!DOCTYPE HTML>");
        client.println("");

        client.println("Serial Printer (Put Text here: ): ");
        client.println("

");
        client.println("<input type='text' id='name' name='name' required minlength='0' maxlength='800' size='100'>");
        client.println("");

        delay(1);
        Serial.println("Client disonnected");
        Serial.println("");

    }

body:
Try this. It uses the webserver library. I thought it was cleaner code. I also have a nicer way to include the pure html code.

For your original form go to yourIPaddress/single

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>

    const char* ssid = "MTS61752";
    const char* password = "6900979039";

    ESP8266WebServer webserver(80);

    //------------------------------------------------
    static const char PROGMEM singleLine[] = R"rawliteral(
    <!DOCTYPE html>

    <title>Single Line Input</title>

    <form method="post" action="/save" >
    Serial Printer (Put Text here: ):

    <input type='text' id='name' name='name' required minlength='0' maxlength='800' size='100'>
    <input type="submit" name="clk_action" value="accept">
    </form>

    )rawliteral";

    //------------------------------------------------
    static const char PROGMEM INDEX_HTML[] = R"rawliteral(
    <!DOCTYPE html>

    <title>Clock Settings</title>

    <form method="post" action="/save" >
    Turn on time:
<input name="onTime" type="text" size="16" value="" >

    Turn off time:
<input name="offTime" type="text" size="16" value="" >

    <input type="submit" name="clk_action" value="accept">
    </form>

    )rawliteral";

    //------------------------------------------------
    void handleRoot() {
      webserver.send(200, "text/html", INDEX_HTML);
    }

    //------------------------------------------------
    void handleNotFound() {
      webserver.send(404, "text/plain", "Page not found ...");
    }

    //------------------------------------------------
    void handleSave() {
      String str = "Settings Saved ...\r\n";

      Serial.print("number of arguments ");
      Serial.println(webserver.args());                    // number of arguments

      if (webserver.args() > 0 ) {
        for ( uint8_t i = 0; i < webserver.args(); i++ ) {
          str += webserver.argName(i) + " = " + webserver.arg(i) + "\r\n";

          Serial.println("Arg "+ String(i)+"="+ webserver.argName(i));
          Serial.println("Arg "+ String(i)+"="+ webserver.arg(i));
        }
      }
      webserver.send(200, "text/plain", str.c_str());
    }

    //------------------------------------------------
    void handleSingleLine() {
      webserver.send(200, "text/html", singleLine);
    }

    //------------------------------------------------
    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid, password);
      Serial.println("");

      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());

      webserver.on("/", handleRoot);
      webserver.on("/save", handleSave);
      webserver.onNotFound(handleNotFound);
      webserver.on("/single", handleSingleLine);

      webserver.begin();
      Serial.println("Web server has started");
    }

    //------------------------------------------------
    void loop() {
      webserver.handleClient();

    }


message:
Routing Matrix with a large number of I/O

Lets say that i would like to make a 128x128 routing matrix with an arduino uno,

Since i am unexperienced i think of using two 4051’s for 8x8 patching and because i want to persist the patch, controlling them with two quad d type flip flops, then repeat the circuit to reach 128x128 patching capibility. Then my output count would be sufficent in arduino uno.

I think this would work but sounds unelegant to me.
Do you have another advice for me to achieve this task?

Actually what I would like to achieve is a big digitally controlled patching matrix for my own analog synth circuits at home. So analog signals will be present and should have the avalibility to patch anything to anything.

body:
I would use a port expander that uses I2C for communications. One example is the PCA9555. You can add up to eight by setting the address bits (A0-A2). This will give you up to 64 outputs to control the selection bits of the 4051s.

[![enter image description here][2]][2]

While this is all intelectionally possible, from a logic perspective, I have concerns about how this can be practically implemented. I think you need to go into more detail on what you plan to do. What the purpose is.

Also, there are larger chip for do analog matrix switching. AD75019 is one example. https://www.analog.com/en/products/ad75019.html

They are more expensive but cost should not be the primary factor. Getting a design to work is more important.

Do a search for "Crosspoint Switch Array" for more chips like this.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/5N2DQ.png
  [2]: https://i.stack.imgur.com/QW4UA.png


message:
Is it possible to combine a HC-05 Bluetooth module and a shrinked arduino ATtiny45/85 to control a motor, LEDs, or other components?

I'm thinking of making a tiny RC toy project that is controlled through Bluetooth with most components at its tiniest size. I'm a complete beginner in this area so i'm not completely familiar with lots of components so please don't mind me if i sound dumb and uneducated. Anyway...

If it's possible: how many components can i use with the ATtiny45/85? or should i go with the atmega8.

I have a m20 mini motor, a micro servo and a few leds. This doesn't include other components that i havent purchase such as dc driver module and HC-05 Bluetooth module.

If not possible: what other options I can do to create my project.

body:
The ATTiny has 5 usable pins (6 if you decide to reuse the Reset pin). Since it doesn't have UART hardware, you need to use a SoftwareSerial library to communicate with the HC-05. This takes 2 pins. To drive a motor, you need at least 1 pin. If you need to control it's speed (instead of just on and off), you would need to generate a PWM signal. Either through hardware timer or by code. (The ATTiny has 2 timers. When you want to use PWM with hardware timer, you need to make sure, that the SoftwareSerial library doesn't want to use the same timer). For the servo it's similar. The servos position is encoded by pulse lengths. (Make sure, that the used library doesn't want to use an already used timer)

Unless you use techniques as multiplexing or matrixes (which are not that useful for a small number of LEDs), you need 1 pin per LED.

Depending on what exactly you want to achieve, you will pretty fast run out of pins. Since you are a beginner you should start with a chip with more pins. If you don't know, how exactly your project will be in the end, better by a chip with maybe double the pins, that you think you need. Develop, until you really know, what functionality your project should have, what not and what you need to achieve that. Based on this you can choose the correct chip, that is as small as possible. Also consider using SMD parts in the finished version. There are mostly much smaller, but also more difficult to solder.


message:
LCD lights up but shows no text

I've connected an [LCD display](https://www.aliexpress.com/item/1pcs-LCD12864-128x64-Dots-Graphic-Blue-Color-Backlight-LCD-Display-Module-raspberry-for-arduino/32837371446.html) to an Arduino Uno following the instructions from the [Adafruit LCD lesson](https://learn.adafruit.com/adafruit-arduino-lesson-11-lcd-displays-1/breadboard-layout).

[![Fritzing diagram][1]][1]

I've used the code sample described in the Adafruit lesson.

What happens after I connect the Uno to the USB cable is that the LCD lights up, but no text is displayed.

I've checked all connections and they look good. I am not 100%sure I have connected the [potentiometer](https://www.aliexpress.com/item/10-PCS-High-Quality-WH148-B10K-Linear-Potentiometer-15mm-Shaft-With-Nuts-And-Washers-Hot/32818514911.html) correctly, as this is the symptom I usually found online.

Could this also be a bad solder job? It's my first attempt and I guess it did not go that great.

[![Soldering detail][2]][2]

Here are some more images, maybe someone with more experience can spot the error.

[![enter image description here][3]][3]
[![enter image description here][4]][4]
[![enter image description here][5]][5]
[![enter image description here][6]][6]

----

*Update*: here's what the board looks like once connected

[![enter image description here][7]][7]

and after removing the ethernet shield I get some weird flashes from time to time, only when I switch the potentiometer to maximum on one side, see video at https://i.imgur.com/ZclD2xz.mp4 .

_Update 2_: I realised that this is a 20-pin LCD screen and re-reading the datasheet and some online tutorials I switched digital wire connections to pins to the LCD 7-10 (DB0-DB3) - same result and then 11-14 (DB4-DB7) - garbled output, shown below. Still no idea what is wrong.

[![Garbled output after correcting pin connections][8]][8]

  [1]: https://i.stack.imgur.com/c777a.jpg
  [2]: https://i.stack.imgur.com/lw6vP.jpg
  [3]: https://i.stack.imgur.com/jxKUU.png
  [4]: https://i.stack.imgur.com/cix8Z.png
  [5]: https://i.stack.imgur.com/mq3Jz.png
  [6]: https://i.stack.imgur.com/Kf0ea.png
  [7]: https://i.stack.imgur.com/7lqQz.png
  [8]: https://i.stack.imgur.com/x9MH8.png

body:
From provided picture it is visible that your display is **not alphanumeric display** (with most popular HD44780 driver). **It is a graphical display** (most popular: KS0107 or KS0108 or ST7920). You can count horizontal pixels and vertical ones in the picture to confirm its resolution.
Without too many problems you can drive it with your Arduino. Try to use some of 128x64 Arduino libraries. Also, check the rear of the display for any part number to confirm the driver (search in google).
 Good luck!


message:
Why to store a function parameter value in a class private variable?

I'm just curious, I'm going through a C++ library for the mcu2.4 TFT display.

And this method I notice when I run through C++ libraries.

Which is when a parameter is passed through a function, it's stored in a private variable; like this one:

    HCTFT::HCTFT(byte DisplayType)
    {
     _Display = DisplayType;

What's the benefit of this method? What's the similar method when I want to do it in C code?

body:
The reason is that _Display will be used probably after its construction.

So you pass the byte during construction, and afterwards the value is available during the object's lifetime.

In C you probably will do this by:

- Passing the variable (byte DisplayType) in each function where the value is needed (you can use this way in C++ too but it's cumbersome in both C/C++ to pass the variable in all functions needed).
- Storing it in a global variable (static for that .c file); this is the typically C method.

*** Added explanation ***

Such a variable is called class variables and are mostly made private. The reason is that other objects cannot change the value directly. The only way to change a variable is:

1. By initializing it in the class constructor (like in your example).
2. Within the class itself (by any method).
3. By a typical Set method (like SetDisplayType). This method can check if the value passed is within a range, and there is only one entry point in this class to change it.

To retrieve the value, typically a GetDisplayType method should be created which is public. The variable itself is private.


body:
Michel Keijzers explained pretty well the purpose of that idiom. Just to
complement his answer, you can do exactly the same in C, only with a
slightly different syntax:

<!-- language: lang-c -->

    typedef struct {
        byte _Display;
        // ...
    } HCTFT;

    HCTFT_construct(HCTFT *this, byte DisplayType)
    {
        this->_Display = DisplayType;
        // ...
    }

Now, every function that receives a pointer to an `HCTFT` (a HCTFT
“method”) has access to that data as a member of the struct.


body:
That is more *Object Oriented Programing* question than the Arduino related.

Encapsulation is one of the fundamentals of OOP and it's basically you'll provide some interface to the object and the outside world doesn't have to know anything about it's internals (so it's not possible to change it into inconsistent state).


message:
Converting of 32 bit signed hex value to dec

Using Seed studio CAN shield to read and convert CAN data to dec value.

Example of expected result:

Full CAN message is 70 3B F1 FF 00 00 00 00 , using little endian first 4 bytes gives: FFF13B70 , which should be equal to converted dec value of -0.967824 (using factor of 0.000001).

Here is code to extract the text value I am using.

    CAN.readMsgBuf(&len, buf);
    unsigned char len = 0;
    unsigned char buf[8];
     {
               String reg0 = String (buf[0], HEX);
               String reg1 = String (buf[1], HEX);
               String reg2 = String (buf[2], HEX);
               String reg3 = String (buf[3], HEX);
               Serial.print(reg3);
               Serial.print("\t");
               Serial.print(reg2);
               Serial.print("\t");
               Serial.print(reg1);
               Serial.print("\t");
               Serial.print(reg0);
               Serial.print("\t");
               String regsumm = (reg3 + reg2 + reg1 + reg0);

         Serial.println(regsumm);
      }

As result I got only text string which couldn't be converted into dec. Any other ways how do it?

body:
You have taken completely the wrong tack. You don't want to convert your data into text and then convert it back into data again - it's already data.

You can combine your first four buffer bytes into a single 32-bit signed integer with just:

    int32_t val = ((int32_t)buf[3] << 24) | ((int32_t)buf[2] << 16) |
                  ((int32_t)buf[1] << 8) | (int32_t)buf[0];

That gives you the value -967824, which is 0xFFF13B70 in hex notation, or `11111111 11110001 00111011 0111000` in binary.  All of them are the same thing and are just a number.

You can then multiply that result by your "factor" into a float variable:

    float dec = val * 0.000001;

Chances are it won't give you -0.967824 due to the nature of floating point values, so you may be better off keeping it as -967824 and working in "micro-units" instead of "units".


body:
Since the bytes you received in the buffer are in little endian order,
and your Uno is itself little endian, you don't even need to move bytes
around: you can just reinterpret the bytes you already have as an
`int32_t`:

    union {
        uint8_t bytes[8];
        int32_t numbers[2];
    } buffer;
    unsigned char len = 0;

    CAN.readMsgBuf(&len, buffer.bytes);
    Serial.println(buffer.numbers[0] * 1e-6, 6);

This prints `-0.967824` to the serial port.

Note that this code will not work as expected on a big endian platform.
If you want something portable, the usual solution is to build the
result using bit shifts, as in Majenko's answer.


message:
Rescuing an Arduino With a Broken Setup()

I may have bricked my Arduino Pro Micro by writing a broken code into the setup() function. When I plug my Pro Micro into my PC, I see it register a COM port for a brief moment before it disappears. Grounding and ungrounding the RST pin causes the device to appear in my control panel again for a brief moment. Attempting to upload the blink example from the Arduino IDE fails, since the COM port disappears before the process can complete.

Is there an alternate way of flashing code to the arduino which I could possibly use to fix this? I have a working Pro Nano I could use if needed.

body:
You can try running the code upload command directly using a precompiled hex file.

Here is how.

Go to preferences in Arduino IDE

Set the `Show verbose output during: upload` option.

`Upload` the blink sketch. (arduino does not have to be connected)

After the compilation, check the log window at bottom of the IDE.

You will find a line like this:

    E:\arduino\hardware\tools\avr/bin/avrdude -CE:\arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\xxxxxxx\AppData\Local\Temp\build918c1e88f8d0a4c453f8bdfce4cccd30.tmp/Blink.ino.hex:i

That is the actual code upload command.

Copy the command line and paste it into a windows CMD window.

Edit the COM port to match your Arduino.

Reset the Arduino and immediately press `Enter` to run the command line.

You may get lucky and the upload "squeaks" through.

You can also move the hex file to another folder so that it is always available for doing a quick recovery.

You could also create a BAT file so that double-click on the icon runs the upload.


body:
After Majenko's suggestion I tried looking into USB ASPs, and then did research about whether you can use an arduino as an ASP. Sort of. I'm not sure if an ASP is exactly the same thing as an ISP, but I used an Arduino Nano as an ISP to program the Arduino Pro Micro.

To do this, I opened the ArduinoISP example sketch and burned it to the Nano (over USB). Then I connected it to a breadboard, along with the Pro Micro. Connected the following pins:

    nano pin          micro pin
    13                15 (SCK)
    12                14 (MISO)
    11                16 (MOSI)
    10                RST
    5v                5v
    GND               GND
It is important to connect a capacitor from Nano RST to GND. I was told to use a 10uF capacitor but I had a 1uF on hand that worked just fine. Then I opened up the Blink example sketch, set up the Arduino IDE for programming the Pro Micro, and set programmer to "Arduino as ISP". Hold shift, click upload, problem solved. Pro Micro is running Blink and I can now recognize it and program it over USB.

So I agree with Majenko; someone faced with this problem should buy a hardware programmer. But only if you don't have a spare Arduino ;)


message:
Regarding turning exact 180 degrees using an MPU6050

I want to turn robot exact 180 degrees by using an MPU6050. This is the code I tried. Can anyone help me?

    #include <MPU6050_tockn.h>
    #include <Wire.h>

    #define enA 9
    #define in1 4
    #define in2 5
    #define enB 10
    #define in3 6
    #define in4 7

    MPU6050 mpu6050(Wire);

    void setup() {
      Serial.begin(9600);
      Wire.begin();
      mpu6050.begin();
      mpu6050.calcGyroOffsets(true);
      setupmotor();

    }

    void setupmotor(){
        pinMode(enA, OUTPUT);
      pinMode(enB, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);

    }

    void loop() {
    updatempu();

    while(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
           turn();
      }

    }

    void updatempu(){
        mpu6050.update();
      Serial.print("\tangleZ : ");
      Serial.println(mpu6050.getAngleZ());

    }

    void turn(){
      Serial.println("turn");
            digitalWrite(in1, LOW);
        digitalWrite(in2, HIGH);
          digitalWrite(in4, LOW);
        digitalWrite(in3, HIGH);
          analogWrite(enA, 100); // Send PWM signal to motor A
      analogWrite(enB, 100);
    }

    void stp(){
        Serial.println("stop");
            digitalWrite(in1, LOW);
        digitalWrite(in2, LOW);
          digitalWrite(in4, LOW);
        digitalWrite(in3, LOW);

    }

body:
As I understand, you want the robot to position itself automatically at either 180° or -180° and stay there. When an outer force get's applied to the robot - turning it out of the target positions - it should again try to reach the target positions.

The first problem was pointed out in the comments and your own code correction seems ok to tackle that:

    if(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
        stp();
    } else {
        turn();
    }

But I see a second problem: In the real world sensor mostly have some kind of noise imposed on their signal (not necessarily meaning electrical noise). For example if you shake the table, where the robot stands on. Or - more importantly in my opinion - The motor, that you use, might not stop fast enough. The MPU might return a value of 179° or 181° when it should be at 180°, because the motor could stop the robot fast enough (inside the time span it needs to travel 1°). In your current logic, this would trigger another turn command. Since you are only turning in one direction, this can create an instable system, which will turn infinitely.

This kind of problem is often solved by using a feedback loop control (of course in combination with the ability to control/turn into both directions). A good and useful example is a PID control (Proportional, Integral, Differential: This is how the control is mathematically structured), where there are already Arduino libraries for it (like [this one][1]). If you want it easier, you can define a range of angles, which are acceptable for your positioning (where it should stop) (for example 175° to 185°). The size of the range, that you need, would depend on the mechanics of your robot and the motor. Note, that this also has drawbacks, but it might be easier for now, depending on what exactly you want to achieve.

---

As Tom pointed out in his comment, you also get trouble with your first approach, if the method `getAngleZ()` returns not an integer, but a float, which it indeed does. You can see this in the source code of the used library [here][2]. The line

    float getAngleZ(){ return angleZ; };

tells us, that the return type of the method is `float`. The problem with this type is, that it cannot represent every rational value inside it's range. There are gaps between two following float values. The values inside this gap cannot be represented by float. Instead a value nearby will be used (Actually I'm not sure, how this is been done. Probably by going to the next lower value, like with `int`). This also means, that not every integer is representable by float. Even if the Z angle is exactly 180°, the float value may be something like `179,98`. But since `179,98` is not equal too `180` the statement

    mpu6050.getAngleZ() == 180

would never become true. Of course the mentioned solutions above apply here too.

  [1]: https://playground.arduino.cc/Code/PIDLibrary
  [2]: https://github.com/tockn/MPU6050_tockn/blob/master/src/MPU6050_tockn.h


message:
Can a push button be used for TFT LCD screens?

I am trying to link my TFT LCD touch screen to a few push buttons. May I enquire why my code is not working? I'm trying to link the screen and the button so I'm trying to make the image display a flower if the button is not pushed and the tiger only if pushed.

At the moment this code ends up displaying both images at once and the button whether or not the button is pushed.

My components include a 2.8" TFT LCD screen and an Arduino Mega
<!-- language-all: lang-cpp -->

    #include <SD.h>
    #include <SPI.h>
    #include <LCD_GUI.h> //Core graphics library
    #include <LCD_KBV.h> //Hardware-specific library

    LCD_KBV mylcd(ILI9341,A3,A2,A1,A0,A4); //model,cs,cd,wr,rd,reset

    #define BLACK   0x0000
    #define BLUE    0x001F
    #define RED     0xF800
    #define GREEN   0x07E0
    #define CYAN    0x07FF
    #define MAGENTA 0xF81F
    #define YELLOW  0xFFE0
    #define WHITE   0xFFFF

    #define PIXEL_NUMBER  (mylcd.Get_Display_Width()/4)
    #define FILE_NUMBER 4
    #define FILE_NAME_SIZE_MAX 20

    const int buttonPin = 41;
    int buttonState = 0;

    uint32_t bmp_offset = 0;
    uint16_t s_width = mylcd.Get_Display_Width();
    uint16_t s_heigh = mylcd.Get_Display_Height();
    //int16_t PIXEL_NUMBER;

    char file_name[FILE_NUMBER][FILE_NAME_SIZE_MAX];

    uint16_t read_16(File fp)
    {
        uint8_t low;
        uint16_t high;
        low = fp.read();
        high = fp.read();
        return (high<<8)|low;
    }

    uint32_t read_32(File fp)
    {
        uint16_t low;
        uint32_t high;
        low = read_16(fp);
        high = read_16(fp);
        return (high<<8)|low;
     }

    bool analysis_bpm_header(File fp)
    {
        if(read_16(fp) != 0x4D42)
        {
          return false;
        }
        //get bpm size
        read_32(fp);
        //get creator information
        read_32(fp);
        //get offset information
        bmp_offset = read_32(fp);
        //get DIB infomation
        read_32(fp);
        //get width and heigh information
        uint32_t bpm_width = read_32(fp);
        uint32_t bpm_heigh = read_32(fp);
        if((bpm_width != s_width) || (bpm_heigh != s_heigh))
        {
          return false;
        }
        if(read_16(fp) != 1)
        {
            return false;
        }
        read_16(fp);
        if(read_32(fp) != 0)
        {
          return false;
         }
         return true;
    }

    void draw_bmp_picture(File fp)
    {
      uint16_t i,j,k,l,m=0;
      uint8_t bpm_data[PIXEL_NUMBER*3] = {0};
      uint16_t bpm_color[PIXEL_NUMBER];
      fp.seek(bmp_offset);
      for(i = 0;i < s_heigh;i++)
      {
        for(j = 0;j<s_width/PIXEL_NUMBER;j++)
        {
          m = 0;
          fp.read(bpm_data,PIXEL_NUMBER*3);
          for(k = 0;k<PIXEL_NUMBER;k++)
          {
            bpm_color[k]= mylcd.Color_To_565(bpm_data[m+2], bpm_data[m+1], bpm_data[m+0]);
            m +=3;
          }
          for(l = 0;l<PIXEL_NUMBER;l++)
          {
            mylcd.Set_Draw_color(bpm_color[l]);
            mylcd.Draw_Pixel(j*PIXEL_NUMBER+l,i);
          }
         }
       }
    }

    void setup()
    {

        Serial.begin(9600);
        pinMode(buttonPin, INPUT);
       mylcd.Init_LCD();
       mylcd.Fill_Screen(BLUE);
       //s_width = mylcd.Get_Display_Width();
       //s_heigh = mylcd.Get_Display_Height();
       //PIXEL_NUMBER = mylcd.Get_Display_Width()/4;
       if(PIXEL_NUMBER == 60)
       {
           strcpy(file_name[0],"flower.bmp");
           strcpy(file_name[1],"tiger.bmp");
           strcpy(file_name[2],"tree.bmp");
           strcpy(file_name[3],"RedRose.bmp");
       }
       else
       {
           strcpy(file_name[0],"01.bmp");
           strcpy(file_name[1],"02.bmp");
           strcpy(file_name[2],"03.bmp");
           strcpy(file_name[3],"04.bmp");
       }
      //Init SD_Card
       pinMode(10, OUTPUT);

        if (!SD.begin(10))
        {
          mylcd.Set_Text_Back_colour(BLUE);
          mylcd.Set_Text_colour(WHITE);
          mylcd.Set_Text_Size(1);
          mylcd.Print_String("SD Card Init fail!",0,0);
        }
    }

    void loop()
    {

     buttonState = digitalRead(buttonPin);

        File bmp_file;
        if (buttonState == HIGH)
        {bmp_file = SD.open(file_name[0]);
          } else {bmp_file = SD.open(file_name[1]);
          }

           if(!bmp_file)
           {
              mylcd.Set_Text_Back_colour(BLUE);
             mylcd.Set_Text_colour(WHITE);
             mylcd.Set_Text_Size(1);
             mylcd.Print_String("didnt find BMPimage!",0,10);
             while(1);
            }

              draw_bmp_picture(bmp_file);
             bmp_file.close();
             delay(2000);
         }

body:
First of all, I suggest you to keep your source code tidy, this makes a lot easier to _follow_ the flow.

As I don't know the library you are using, I'm assuming you have tested loading one single image works as expected in which case you probably need to wipe the screen before drawing a new image: I can't tell for sure because you didn't mention which library you are using (a link would have helped).

If there's a function named `clear`, `emptyBuffer` or similar, then you should call it before drawing the image, otherwise, you probably have to draw a filled rectangle in the same area where you are going to put your image.


message:
How to read a PWM OUTPUT PIN value?

How to get a pwm pin value that is in pinMode OUTPUT?

[How to get a digital OUTPUT PIN value:][2]

    #define pin 3

    void setup()
    {
      pinMode(pin, OUTPUT);
      Serial.begin(9600);
    }

    void loop()
    {
        delay(1000);
        digitalWrite(pin, HIGH);
        Serial.println(bitRead(PORTD,pin));
        delay(1000);
        digitalWrite(pin, LOW);
        Serial.println(bitRead(PORTD,pin));
    }

[![enter image description here][1]][1]

For testing reasons, I want to get PWM output pin value.

**Incorrect sketch:**

    #define pin 3

    void setup()
    {
      pinMode(pin, OUTPUT);
      Serial.begin(9600);
    }

    void loop()
    {
        delay(1000);
        analogWrite(pin, 100);
        Serial.println(pulseIn(pin, HIGH)); // value of the PWM output pin
    }

This sketch was created for example only.
I don't know PWM value because PWM value will be generating dynamically.
Could you explain how to get a PWM output pin value, please?

  [1]: https://i.stack.imgur.com/W9Ril.png
  [2]: https://stackoverflow.com/a/6171551

body:
>  I want to get PWM output pin value.

The pin will either be 0 or 1.

> analogWrite(pin, 100);

It will be 1 for 100/256 (39%) of the time, and 0 the rest of the time.

---

Why do you want to do this?


body:
According to the source code implementation of `analogWrite` function
([https://arduino.stackexchange.com/questions/45309/arduino-analogwrite-source-code-explanation][1]).

You can use `OCRnx` register for reading PWM value.

  [1]: https://arduino.stackexchange.com/questions/45309/arduino-analogwrite-source-code-explanation


message:
Debug-logging without using Serial.print and without WiFi

In order to transmit text from the Arduino board to the HC-05 Bluetooth module, I have use `Serial.print`. However, I don't see a way to debug the code without using `Serial.print` to test the other features of the software. Is there another way to transmit text from the Arduino to the computer, and from the Arduino to the HC-05, simultaneously (and without WiFi)?

body:
Yes, what version of Arduino are you using?

 - For **Arduino Mega**, you can use `Serial.println` for writing debug data and `Serial1.println` for communication with HC-05. (See Example: [MultiSerial Example][1])
 - For **other Arduino boards**, you can use `Serial.println` for writing debug data and SoftwareSerial library for communication with HC-05. (See Example: [SofwareSerial][2])

  [1]: https://www.arduino.cc/en/Tutorial/MultiSerialMega
  [2]: https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


message:
Why does my 16x2 LCD displays weird letters and can't insert key from keypad?

I'm a newbie on Arduino here, and this is my first project on 16x2 LCD, 4x4 keypad and others. So, the story is, after I uploaded the program for my group's Arduino alarm clock to the Arduino board, the LCD displays black boxes on the first row of the LCD. But after soldering the LCD pins again and connect the Vo to the 10k ohm potentiometer, the LCD can display the "welcome" part properly. This can be seen in the two pictures below.
[![Welcome To][1]][1]

[![TIMe Project][2]][2]
However, after a while, there are weird letters appearing on the second row of the LCD, blinking from the first picture below to the second picture again and again. Plus, I couldn't input any key from the keypad to the LCD, since the display's stuck at there.
[![weird letters show up][3]][3]

[![weird letters show up again][4]][4]
I'm not sure if there's any problem in the circuit or in the programming. I'm quite confused here. Below is the code I uploaded to the Arduino board. Thank you in advance.
<!-- language-all: lang-cpp -->

    #include <EEPROM.h>
    #include <Keypad.h>
    #include <DS1307.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <LiquidCrystal.h>

    DS1307 rtc(SDA, SCL);
    LiquidCrystal lcd(A3, A2, A1, A0, 5, 4);
    Time t;

    #define buz 3

    int Hor, Min, Sec, h, m, s;
    int ASCII = 48;
    char* tim;
    char* dat;
    const char key = 0;
    char buffer[2];
    const byte numRows= 4;
    const byte numCols= 4;
    char keymap[numRows][numCols]=
    {
      {'1', '2', '3', 'A'},
      {'4', '5', '6', 'B'},
      {'7', '8', '9', 'C'},
      {'*', '0', '#', 'D'}
    };
    byte rowPins[numRows] = {12, 11, 10, 9};
    byte colPins[numCols]= {8, 7, 6, 5};
    Keypad myKeypad= Keypad(makeKeymap(keymap),rowPins, colPins, numRows, numCols);

    void setup() {
      Wire.begin();
      rtc.begin();
      pinMode(buz, OUTPUT);
      lcd.begin(16, 2);
      welcome();

      rtc.setDOW(SATURDAY); //Set Day-of-Week to SUNDAY
      rtc.setTime(10, 54, 0); //Set the time to 12:00:00     (24hr format)
      rtc.setDate(7, 1, 2017); //Day, Month, Year
    }

    void loop() {
      t = rtc.getTime();
      Hor = t.hour;
      Min = t.min;
      Sec = t.sec;
      tim = rtc.getTimeStr();
      dat = rtc.getDateStr();
      char key = myKeypad.getKey();

      if (key == 'C'){
        digitalWrite(buz, LOW);
        EEPROM.write(2, ASCII+6);
        EEPROM.write(3, ASCII);
      }

      if(key == '#'){
        lcd.setCursor(0,0);
        lcd.print("Enter New Time");
        lcd.setCursor(0,1);
        int j =0;
        int i=0;
        while( j<6)
        {
          if(i==2 || i == 5){
            lcd.print(":");
            lcd.display();
            i++;
          }
          key=myKeypad.getKey();
          if(key)
          {
            lcd.print(key);
            lcd.display();
            EEPROM.write(j,key);
            j++;
            i++;
          }
        }
      }

      changealarm();
      checkalarm();
      timedate();
    }

    void checkalarm(){
      if( Hor == h && Min == m)
      {
        delay(3000);
        lcd.setCursor(0,1);
        lcd.print("Hold C");
        digitalWrite(buz, HIGH);
        delay(3000);
      }
    }

    void changealarm(){
      buffer[0]=EEPROM.read(0);
      buffer[1]=EEPROM.read(1);
      h = atoi(buffer);
      buffer[0]=EEPROM.read(2);
      buffer[1]=EEPROM.read(3);
      m = atoi(buffer);
      buffer[0]=EEPROM.read(4);
      buffer[1]=EEPROM.read(5);
      s = atoi(buffer);
    }

    void timedate(){
      lcd.setCursor(0,0);
      lcd.print("Time: ");
      lcd.print(rtc.getTimeStr());

      lcd.setCursor(0,1);
      lcd.print("Date: ");
      lcd.print(rtc.getDateStr());
      delay(3000);
      lcd.setCursor(0,1);
      lcd.print("Alarm: ");
      lcd.print(h);
      lcd.print(".");
      lcd.print(m);
      lcd.print(".");
      lcd.print(s);
      delay(3000);
    }

    void welcome(){
      lcd.setCursor(0,0);
      lcd.print("Welcome");

      lcd.setCursor(0,1);
      lcd.print("To");
      delay(3000);

      lcd.setCursor(0,1);
      lcd.print("TIMeProject");
      delay(3000);
    }

  [1]: https://i.stack.imgur.com/Lsf6v.jpg
  [2]: https://i.stack.imgur.com/0oSVj.jpg
  [3]: https://i.stack.imgur.com/e5vaT.jpg
  [4]: https://i.stack.imgur.com/2e4Ft.jpg

body:
In your `changealarm()` function, you call `atoi(buffer)`, and `buffer` is defined as `char buffer[2]`.

`atoi()` expects a c-style string, which is null-terminated, and you have to include space for the null termination character (`'\0'`, `0`, `0x00`, etc.), but you write to both allocated spaces in the `changealarm()` function. If your 2nd byte of each EEPROM space (1, 3, 5) is non-zero, then your have an unterminated string.

`atoi()` expects a null-terminated string, and so the behavior is unexpected. Probably `atoi()` is running into other memory. If the string being sent is not representable by a `int` type, then the behavior of `atoi()` is *undefined*.

----------

A quick fix would be to increase the size of `buffer` and guarantee null termination:

    char buffer[3];  // Make the buffer 3 bytes long
    [...]
    void changealarm() {
      buffer[2]=0;   // Set the 3rd byte to zero to null-terminate

      buffer[0]=EEPROM.read(0);
      buffer[1]=EEPROM.read(1);
      h = atoi(buffer);
      buffer[0]=EEPROM.read(2);
      buffer[1]=EEPROM.read(3);
      m = atoi(buffer);
      buffer[0]=EEPROM.read(4);
      buffer[1]=EEPROM.read(5);
      s = atoi(buffer);
    }


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

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


message:
Avrdude verification error after months of successful use

I have a 2560 that I've been working with for a while (over a year for sure), programming it with an avrisp mk2. No issue this whole time, then suddenly, a couple of days ago it starts failing with

    avrdude: verification error, first mismatch at byte 0x0002
             0x01 != 0x95
    avrdude: verification error; content mismatch

And very obviously not flashing (there's logic that blinks the LED on boot, and the LED isn't blinking anymore).

The first time this happened, the board appeared completely dead - the programmer wouldn't recognize it, and refused to flash it. After a few days and *magic* it started recognizing it again, and going through the motions of flashing my firmware, but the verification error persists. The location of the error hasn't changed, nor has the two values (0x01 vs 0x95).

Any ideas what this could be?

body:
Still don't know why, but now have a fix. Re-running the 'Burn bootloader' command from Arduino allowed me to then burn my firmware. Not sure if the issue is with fuses somehow being changed, or what, but this seems to have fixed the issue.

One more fun fact - I tried the same thing on a brand new Mega - same effect. First trying to burn my firmware resulted in a verification error (at a slightly different address), then burned bootloader and re-burned my firmware successfully. Wondering if an update to boards.txt or avrdude came through and changed something.


body:
**TLDR:** Make sure that -D flag is not used when calling avrdude to upload your app using the ISP programmer.

After burning the bootloader on a bare ATmega328p chip using the Arduino IDE and an Arduino Uno as ISP, I am running into the same problem that the OP mentioned with this message:

    avrdude: verifying ...
    avrdude: verification error, first mismatch at byte 0x0094
             0x68 != 0x6a
    avrdude: verification error; content mismatch

Right after burning the bootloader, I can upload an application using this avrdude command (yours would vary slightly due to port name, etc.):

    avrdude -C/etc/avrdude.conf -v -patmega328p -cstk500v1 -b19200 -P/dev/ttyACM0 -D -Uflash:w:main.hex:i

However, if I change the application code, recompile, and rerun the same avrdude code again, then I get the verification error mentioned by the OP.

In my case, I have confirmed that the -D flag is the problem. In fact, if I remove the -D flag in the avrdude command above, then I can change, compile, and upload my code as many times as I want.

Note that this is different when using the Arduino IDE to program an Arduino Uno directly (using serial communication through the bootloader), where the -D flag is used

    avrdude -C/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:main.hex:i

since you wouldn't want to erase the bootloader on the Arduino Uno. Somehow using the -D flag is OK in that case.