body:
What you want for this project is called a [ring buffer][]. Before
reading the rest of this answer, I suggest you stop and take the time to
carefully read the Wikipedia page I am linking to.

Did you read it? Good! Now, yours is a somewhat special case in that you
don't need to continuously keep track of both a read pointer and a write
pointer: you only need the write pointer, as the read happens all in one
big batch.

Once your ring buffer is full, you will start overwriting the oldest
readings, those that are more than 10 minutes old. When the program
is instructed to dump the data, it will send out the whole buffer,
starting with the cell pointed to by the write pointer (the cell that
holds the oldest data point and was about to be overwritten).

There is one special case to take care of. What if the program gets the
command to dump the data while it has less than 20 readings stored?
You could decide that this is a user error, and it's OK for the program
to give garbage. I suggest, however, that the program should be able to
detect this situation, and then only send the valid data. For this, it
needs to store a boolean variable in order to remember whether the
buffer has been filled or not.

Here is an implementation I propose for such a ring buffer, together
with the functions for adding an item and for dumping all the data
through the serial port:

```c++
const uint32_t READING_PERIOD = 30000;  // one reading every 30 s
const int MAX_READINGS = 20;           // 20 readings = 10 min

int readings[MAX_READINGS];  // ring buffer
uint8_t reding_index = 0;    // next available slot
bool readings_full = false;  // did we fill the ring buffer?

static void register_reading(int value) {
    readings[reding_index] = value;
    if (++reding_index >= MAX_READINGS) {
        readings_full = true;
        reding_index = 0;
    }
}

static void dump_readings() {
    // If the buffer is full, then the next avaiable slot is the oldest
    // reading in the buffer.
    if (readings_full) {
        for (int i = reding_index; i < MAX_READINGS; i++)
            Serial.println(readings[i]);
    }
    for (int i = 0; i < reding_index; i++)
        Serial.println(readings[i]);
}
```

Now the main program is quite simple. You time the data taken using the
technique shown in the [Blink without delay][] tutorial. You don't want
to use `delay()` because, when the program is delaying, it cannot
respond to your commands. There is one last question remaining: when it
dumps the data, should it forget it? In other words, if you ask it twice
to dump the data, with less that 10 minutes in between, should it
give repeated data the second time, or should it only provide the fresh
data? In the code below I assume the later option, and thus reset the
buffer, but in the end it is your choice:

```c++
void setup() {
    Serial.begin(9600);
}

void loop() {
    // Periodically take a reading.
    static uint32_t last_reading_time;
    if (millis() - last_reading_time >= READING_PERIOD) {
        last_reading_time += READING_PERIOD;
        register_reading(analogRead(A0));
    }

    // Dump the data on command.
    if (Serial.read() == 't') {
        dump_readings();
        reding_index = 0;       // reset the buffer
        readings_full = false;  // ditto
    }
}
```

[ring buffer]: https://en.wikipedia.org/wiki/Circular_buffer
[Blink without delay]: https://www.arduino.cc/en/tutorial/BlinkWithoutDelay


sender: user

message:
Timing taking longer than expected

This is on a custom Arduino PCB (32u4) that I am programming with a Sparkfun Pocket AVR Programmer. A different program that I was writing wasn't working the way I expected it to, so I tried the "BlinkWithoutDelay" example sketch from the Digital section of the examples.

https://media.discordapp.net/attachments/572565310679547946/650075749851856908/unknown.png
^ So you don't have to look it up yourselves. previousMillis is initialized to 0.

However, the LED seems to alternate states every 4 seconds instead of every 200 ms with this code. I increased the interval from 200 to 400, and the IRL time increased from 4 seconds to 8 seconds, so at the very least it's consistent that way. My first instinct is that the crystal is broken somehow, but I don't think I'd be able to flash the MCU in the first place if it was. So, does anyone have any idea what's happening? For the record, I had 5 of these PCB's assembled, and the first one worked perfectly for 2 months before something else broke. I've had this issue with the second and third PCB I've tried.

sender: assistant

body:
Factor 8 in timing smells like wrong fuses.

Perhaps you don't use an external oscillator, but the internal one?


body: On all of the new boards I had tested (excluding the first one that I said worked), I had not burned the bootloader. Burning the bootloader made the timing normal! If anyone can tell me why that's the case, I'll accept your answer as the "correct" answer.


message:
converting character to strings in transmitter and receiver Arduino

I am using transmitter and receiver but I want to change the data type from character to int

receiver code

    #include <RH_ASK.h>//include radioHead ASK library
    #include <SPI.h> // include dependant SPI libray

     RH_ASK rf_driver; // create ASK object
    int ledon = 13;
    String userid;
    String password;
     //RH_ASK ID1; // create ASK object
    //RH_ASK pass1; // create ASK object

    void setup() {

      rf_driver.init(); //initialize ASK object

      Serial.begin(9600); //setup serial monitor to 9600

      //if(!rf_driver.init())
           //Serial.print("init failed");
    }

    void loop() {

      // set buffer to size of expected message
      uint8_t buf[9];
      uint8_t buflen =sizeof(buf);

      //check if recevied packet is correct size
      if (rf_driver.recv(buf,&buflen))
      {
        int i;
        // message received with valid checksum
        Serial.print("id: ");
        Serial.println((char*)buf);
          userid =(char*)buf;
            Serial.println(userid);

      }

    delay(5000);

       uint8_t buf2[8];
      uint8_t buflen2 = sizeof(buf2);

       if (rf_driver.recv(buf,&buflen))

      {

        int i;
        // message received with valid checksum
        Serial.print("password: ");
        Serial.println((char*)buf);
          password = (char*)buf;
          Serial.println(password);

      }
      delay(5000);

transmitter code

    //Include RadioHead Amplitidue shift keying library
    #include <RH_ASK.h>
    // Include dependatnt ISP library
    #include <SPI.h>

    //create Ampitude shift keying object
    RH_ASK rf_driver;

    void setup() {
     // intialize ASK objct
    rf_driver.init();

    Serial.begin(9600);

      //if(!rf_driver.init())
          //Serial.print("init failed");

    }

    void loop()
    {

      const char *pass= "123456789";
    rf_driver.send((uint8_t *)pass, strlen(pass));
    rf_driver.waitPacketSent();
    delay(5000);

    const char *ID= "A00034732";

    rf_driver.send((uint8_t *)ID, strlen(ID));
    rf_driver.waitPacketSent();
    delay(5000);

body:
You have to properly understand what you are trying to do. (It looks like) you have a decimal representation of a number, encoded as a string of characters. "12345" is not a number but a series of characters. <sub>(Technically each character is a number with a certain ASCII value, the digit "1" has ASCII value 49 for instance.)</sub>

To convert "12345" into the number 12345, the CPU needs to take each character, find its digit value, multiply it by the correct power of 10 and add it to all the others. There are a few built-in ways that do this for you. The easiest is the `atoi()` function, e.g.

    int x = atoi("150");

In your case, try this:

    int userid = atoi((char *) buf);

    Serial.println(userid);


message:
How do I segment Arduino program when line count is so large that code maintenance is difficult?

I'm looking for the Arduino/C++ equivalent of COBOL's 'copy' statement.

I'm working on a program that is approaching 600 lines of code in the TopLevel.cpp source file.  This is hard to manage because I feel like I spend all my time scrolling up and down the source file.  The code in question does not easily lend itself to conversion to a class because it is sections of loop/main.  I've tried using xxx.h (for storage definitions) and yyy.cpp (for code sections).  Those approaches yield error messages, which I think are due to the different timings of the Arduino pre-processor and the compiler code that resolve the #include statements.

Thanks for the help.
--CVTBrakeman

p.s.
I wrote my first program in 1967; the language was GOTRAN on an IBM 1620.  For almost 50 years, I made my living designing/writing COBOL and SAS code on IBM mainframes.  Yes, Y2K was real and I survived it.

body:
This is more like a general programming question than an Arduino
question but, anyway...

You don't need to write classes to sort your code into files. You just
need to think in term of independent pieces of functionality. Each of
those pieces would be implemented in a .cpp file, with the interface
declared in a .h file.

As an example, let's say your Arduino is controlling an hyperdrive.
Managing the dilithium plasma generator is one of those functionalities
that can be separated in its own files. The .h files declares everything
that is needed for _using_ that functionality:

**plasma\_generator.h**:
```c++
// Read the state of the plasma.
float plasma_density();
float plasma_temperature();

// Control the plasma.
void set_plasma_target_temperature(float target_temperature);
void ignite_plasma();
void turn_off_plasma();
void add_dilithium(float amount);
```

Then the .cpp file contains the implementation:

**plasma\_generator.cpp**:
```c++
#include "plasma_generator.h"

// A "static" function is a function private to this module.
static float get_gauge_reading(int gauge_number)
{
    ...
}

// Implementation of a public function, described in the .h file.
float plasma_density()
{
    float raw_reading = get_gauge_reading(42);
    ...
}

...
```

In your main program (or even in other modules, if needed) you
`#include` the .h file and use the functionality defined therein.


body:
There are two ways of doing this:

1. Multiple INO files

The Arduino IDE combines multiple INO files into one single CPP file before compilation. You can split your program across multiple INO files at will. It makes it easier to manage, since you can split your program into logical chunks at will, but you don't have to think much beyond "which file shall I stick this function in?"

2. Create libraries

Some functionality of your program could be placed into a library or multiple libraries. This is kind of like option 1, but you have to think more about C++ syntax and suchlike that with INO files (function ordering, externs, etc). It does have the benefit that you could easily re-use code between programs, though

Personally I usually use option 2 before option 1. If a code is genericisable ("able to be made generic") then it can be made into a library - after all, I may want it later for some other program. However, if all you want to do is split your program into different chunks with each chunk a different topic or area of your program then option 1 is definitely for you.

Alternatively you might consider a different IDE, such as [UECIDE](https://uecide.org) which gives you such things as *function bookmarks&* to make navigation of your code easier.


message:
Compile code error: 'Serial' does not name a type

<!-- language-all: lang-cpp -->

    int LDR_deger = 0;

    int Ledpin1 = 12;
    int Ledpin2 = 11;
    int Ledpin3 = 10;
    int Ledpin4 = 9;
    int Ledpin5 = 8;

    int LDR_pin = 0;

    void setup()
    {

      Serial.begin(9600);
      pinMode(Ledpin1, OUTPUT);
      pinMode(Ledpin2, OUTPUT);
      pinMode(Ledpin3, OUTPUT);
      pinMode(Ledpin4, OUTPUT);
      pinMode(Ledpin5, OUTPUT);
    }
    void loop()

    {
      LDR_deger = analogRead(LDR_pin);
    digitalWrite(Ledpin1,HIGH);
    digitalWrite(Ledpin2,HIGH);
    digitalWrite(Ledpin3,HIGH);
    digitalWrite(Ledpin4,HIGH);
    digitalWrite(Ledpin5,HIGH);

    if (LDR_deger <= 80 && LDR_deger> 30) {
      digitalWrite(Ledpin1, LOW);
    } else{
      digitalWrite(Ledpin1, HIGH);
      if (LDR_deger<= 150 && LDR_deger > 80){
      digitalWrite(Ledpin2, LOW);
      digitalWrite(Ledpin1, LOW);
      }else{
        digitalWrite(Ledpin1, HIGH);
        digitalWrite(Ledpin2, HIGH);
        if (LDR_deger  <= 200 && LDR_deger> 150){
          digitalWrite(Ledpin2, LOW);
          digitalWrite(Ledpin1, LOW);
          digitalWrite(Ledpin3, LOW);
         }else{
          digitalWrite(Ledpin1, HIGH);
          digitalWrite(Ledpin2, HIGH);
          digitalWrite(Ledpin3, HIGH);
          if (LDR_deger <= 1000 && LDR_deger> 300){
          digitalWrite(Ledpin2, LOW);
          digitalWrite(Ledpin1, LOW);
          digitalWrite(Ledpin3, LOW);
          digitalWrite(Ledpin4, LOW);
          digitalWrite(Ledpin5, LOW);
         }else{
          digitalWrite(Ledpin1, HIGH);
          digitalWrite(Ledpin2, HIGH);
          digitalWrite(Ledpin3, HIGH);
          digitalWrite(Ledpin4, HIGH);
          digitalWrite(Ledpin5, HIGH);
         }
           }
         }
       }
      }
    Serial.print("LDR Deger: ");
    Serial.print(LDR_deger);
    Serial.println(" ");
    delay(500);
    }

body:
One reason you are receiving the compile error, is due to the code outside of a function. When you write nice, neat, properly formatted code, these errors are easy to spot. The Arduino IDE has a built in feature that will "highlight" a matching curly bracket (or curly brace?).

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

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

  [1]: https://i.stack.imgur.com/G4uKq.png
  [2]: https://i.stack.imgur.com/eh5hw.png


body:
VE7JRO already has answered your question. Below is not an answer to the question but a better way to program something like you have.

In your case, you need to set 5 pins according. I assume the following lines are just for initialization (and not needed when you set them afterwards to FALSE), as I do not see any delay.

    digitalWrite(Ledpin1,HIGH);
    digitalWrite(Ledpin2,HIGH);
    digitalWrite(Ledpin3,HIGH);
    digitalWrite(Ledpin4,HIGH);
    digitalWrite(Ledpin5,HIGH);

It is much easier for each pin to set the conditions direction; this will reduce all the `if` statements and make it very clear for each pin what the value should be.

First we make some variables to prevent duplication. Actually I normally like using bool but it is not a predefined type. Also I like to have the low range on the left and the high range on the right, and using parenthesis. I added the range 200-300, and lower/upper range:

    int LDR_deger_min_inf_30 =  (LDR_deger <= 30);
    int LDR_deger_30_80      = ((LDR_deger >  30) && (LDR_deger <=   80));
    int LDR_deger_80_150     = ((LDR_deger >  80) && (LDR_deger <=  150));
    int LDR_deger_150_200    = ((LDR_deger > 150) && (LDR_deger <=  200));
    int LDR_deger_200_300    = ((LDR_deger > 200) && (LDR_deger <=  300));
    int LDR_deger_300_1000   = ((LDR_deger > 300) && (LDR_deger <= 1000));
    int LDR_deger_1000_inf   =  (LDR_deger > 1000);

Now you can create a table for each pin (which makes great documentation and a clear overview); I would add it in a comment (if you have no other documentation way):

    // pin min_inf_30 30_80 80_150 150_200 200_300 300_1000 1000_inf
    //  1     HIGH     LOW    LOW     LOW   HIGH      LOW     HIGH
    //  2     .. (fill in yourself)
    //  3     .. (fill in yourself)
    //  4     .. (fill in yourself)
    //  5     .. (fill in yourself)

Now you can write the pins one by one (I only did the first as example):

    digitalWrite(Ledpin1, LDR_deger_min_inf || LDR_deger_200_300 || LDR_deger_1000_inf ? HIGH : LOW);
    digitalWrite(Ledpin2, …);


message:
How to get air speed, which sensor to use?

I want to measure the airspeed on a flying vehicle and get the data with arduino. Note that, there will not be any control mechanism on the flying object, it will be flying mechanicaly/passively, I mean no flight controller or something like that will be present.

However, I could not understand whether there is a sensor to measure the airspeed directly or is airspeed something you analyze by using other datas(temperature, pressure etc.)

I saw there are sensors which are sold as "airspeed sensor" however it is not so common that I cannot find examples in which the incoming data is shown.

Anybody ever experienced with this issue may lighten me.

Thanks in advance.

body: Typically you want to use Pitot tube sensor


message:
ESP32-Cam No Response and Unable to Program - Timed out waiting for packet header

I recently purchased an ESP32-CAM but have had no luck in programming the board or getting any response whatsoever. I first tried to program it using the an FTDI programmer and the Arduino IDE (following the steps from this tutorial: https://randomnerdtutorials.com/esp32-cam-video-streaming-face-recognition-arduino-ide/).

I used this exact wiring diagram: [![wiring diagram][1]][1] but got the Timed out waiting for packet header error message. This was with the jumper on the FTDI on the 3.3V section.

Other things I've tried:
-Moving jumper to 5V, powering ESP from 5V pin
-Powering ESP from external 5V source (Arduino pin)
-Powering ESP from external 3.3V source
-Switching computers (Linux and Windows)
-Programming board directly from Arduino (bypassing FTDI)
-Various combinations of pressing/holding reset button during flash process

The other thing is that there is no LEDs that turn on when the board is powered. I couldn't find a concrete reference online that said an LED turns on when the device is on, but I assume the one LED would at least flash or something. Also monitoring the serial output with putty during boot did not yield any output. I'm all out of ideas and I am just starting to suspect that the board is completely dead. Any ideas would be appreciated, thank you.

  [1]: https://i.stack.imgur.com/eR0fn.png

body:
You're right. There is no LED when you power up your ESP32 cam. So this is normal.

Try to power it with the 5V, so you can power it from your USB instead of the 3.3V regulator of your FTDI. The ESP just need 50mA when in programming mode, so it should not be a problem for your FTDI.

Do you see anything on your serial output? Once you connect it in this way, you should set the baudrate to 115200 on your serial terminal and see some characters.

Then, try to program it.
Once you see the output "...___...", press the reset button! Since you are just connecting RDX and TDX, you have to manually press "RESET" on your ESP32 module.

At this point the ESP will reset and enter in the programming mode.


message:
unable to read RS232 output on Arduino mega with MAX232 shield

I am trying to read data from an RS232 equipped sensor using a serial monitor connected to an Arduino Mega with RS-232 shield but I do not receive any data.

I am unable to detect the exact cause of the problem, as it only occurs when combining sensor and RS232shield/Arduino, while communication works as expected when testing them separately

What works:

- Connecting the sensor to a computer with a RS232-USB converter cable.
- Passing data from the computer through the USB-RS232 converter cable to RS232 shield and back through Arduino USB output.
- Connecting the RS232-pin 2 to port 10 using {SoftwareSerial} library with inverted logic.

What does not work:

- Passing data from the sensor to the computer via the MAX232 and Arduino.

The setup:

 - Arduino Mega 2560
 - Seeed RS232 shield (MAX232 based)
 - Sensor with RS232 output (57600 8N1)

I have connected the RS232 output of the sensor to the shield using an M-M gender changer. The shield and Arduino are connected with three wires: GND-GND , 5V-5V, 232_TX-RX1), and the Arduino connects to a Macbook via USB. The serial monitor on the computer is set to 56700 baud.

I use the following sketch to transfer data from the RS232 shield to Serial:

````
void setup()
{
// Open serial communications at 5700 baud
    Serial.begin(57600);
    Serial1.begin(57600);

// Check whether Serial1 is active
if (Serial1.available())
     while (!Serial1) {
        ;
    }
    Serial.println("Serial 1 is active");
}

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

}
````

body:
I have solved the above and will share the answer as it may be of help to others:

As the Tx indicator LED on the RS232 shield would not light up when connected to the sensor, I checked the voltage difference between pin 2 (Tx) and pin 5 (GND) of the RS232 connector. This turned out to be only 5V, indicating that the protocol used is TTL-RS232 rather than 'true' RS232.

Due to the low voltage, I have connected the RS232 Tx and GND pins directly to the Arduino. With Tx connected to digital port 10, I used the SoftwareSerial library with logic inversion to read the data: `SoftwareSerial mySerial(10, 11, 1)`.

This works!


message:
Counter on my coin acceptor goes up without a coin input, any advice?

I'm working on a project that makes use of a CH926 coin acceptor. The problem we're having is that when I read the serial monitor, the coin value is continuously going up and adding credits when it's supposed to remain at 0 until a coin Is fed into the acceptor.

We've tried a different coin acceptor, different codes, arduinos, wiring, resistors, breadboards, the lot. nothing seems to be solving this problem and we can't determine why, it had been working fine until we tried to tidy up our wiring and untangle it.

we're using a basic code that had worked fine up until we had the issue of the counter value no longer remaining at 0:

    const int coinpin = 2;
    const int ledpin = 3;
    const int targetcents = 100;

    // Variables
    volatile int cents = 0;
    int credits = 0;

    // Setup
    void setup() {

      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(coinpin), coinInterrupt, RISING);
      pinMode(ledpin, OUTPUT);

    }

    // Main loop
    void loop() {

      // If we've hit our target amount of coins, increment our credits and reset the cents counter
      if (cents >= targetcents) {
        credits = credits + 1;
        cents = cents - targetcents;
      }

      // If we haven't reached our target, keep waiting...
      else {
      }

      // Debugging zone
      Serial.print(cents);
      Serial.print(" cents toward current credit and ");
      Serial.print(credits);
      Serial.println(" credit(s) earned so far.");
      delay(1000);

      // Turn off LED
      digitalWrite(ledpin, LOW);

      // Now, write your own cool code here that triggers an event when the player has credits!
      if (credits > 0) {
        // Play music?
        // Spin up a motor?
        // Start a game?
        // It's up to you!
      }

    }

    // Interrupt
    void coinInterrupt(){

      // Each time a pulse is sent from the coin acceptor, interrupt main loop to add 1 cent and flip on the LED
      cents = cents + 1;
      digitalWrite(ledpin, HIGH);

    }

any advice on what may be causing this problem?

cheers

body: I'm also complicated by that. The advice I saw [here](https://youtu.be/vW3P6iNCblU) was to connect a COIN wire also against an electric "R" 10K and connect  to the second hole on the left in the Arduino "IOREF" now it works.


message:
reading micro SD card directly from PC

Is it possible to read a microSD card (on a breakout) through the USB port on the arduino? or perhaps another USB port I could attach to the breakout?  Basically, I would like to read data off the card with my laptop without having to go and remove it each time!

body:
It would be very useful, but afaik this is not possible, since the Arduino sketch you write communicates to the PC via the serial interface only.

The IDE/Arduino driver can use the USB to write your sketch and use the USB for communicating, but for sketches the USB (as direct medium) is not possible.

The SD card will not show up as a specific drive/map/folder on your PC.

Since you want to read the SD card, write in your sketch code to transmit the file(s) you want to send to the PC, to transfer them by UART, and on the PC write a program that reads the serial port and processes it.


body:
In general that's possible. But you can't read the sd card through the arduino's usb port. Instead you have to read the sd card via another protocol, e.g. SPI (look for the apropriate library) and send it to the pc via serial. You'll need software on the pc side to write the content that was read from the arduino to a file.

Take a look at the [SD card tutorial][1] to see how to read it.

  [1]: https://randomnerdtutorials.com/guide-to-sd-card-module-with-arduino/


body:
It can't be done with an Arduino, but it can be done with other microcontrollers. You need a microcontroller with a direct USB ("native") connection plus a USB stack that is capable of acting as a USB Mass Storage Device.  Something like the Teensy or chipKIT series of boards can do that.

Then you can write software that will, on command, detach the SD card from your normal sketch operation and re-attach it to the MSD device in the USB stack. You can then read and write to the SD card (though your sketch otherwise cannot access it) as much as you like - then "unmount" the MSD device and detach the SD card from it, at which point your sketch is then free to re-attach itself to the card and start using it again.

Note that the important thing here is that only one functionality can work at a time - either you can read and write the files on the card with your sketch, *or* you can export the device through MSD. Never both. That way leads to filesystem corruption and loss of data.


message:
Arduino UNO R3 + SIM800L / NodeMCU via Hadware Serial. Possible?

I'm using Arduino UNO R3 with NodeMCU and SIM800L module. I have to connect these two devices to UNO and make a serial communication between them: UNO<>SIM800L and UNO<>NodeMCU.

Can I use GPIO0 and GPIO1 of UNO (RX, TX) to communicate with one of above devices?

Thanks in advance.

body:
If all you need to do is communicate between the NodeMCU and the SIM800L, what do you need the Arduino for?

Connect the SIM800L directly to the NodeMCU and program the NodeMCU to do whatever communication is needed for the SIM800L.


message:
Using usb port to communicate with standalone atmega328p circuit

noob here

So I managed to get my circuit to be a standalone circuit (as pictured below). I want to use this circuit as an input to a game on my computer. What I want to know is could this micro-usb breakout board https://www.diyelectronics.co.za/store/breakout-boards/2414-micro-usb-power-switch-breakout-module.html
 be used to communicate with the computer. Where would the data pins (d+/d-) connect to the atmega328?

Any help will be most appreciated
[![circuit ][1]][1]

  [1]: https://i.stack.imgur.com/VJKWZ.png

body:
The ATmega328 does not have any native USB capability, so there is nowhere appropriate to connect D+/D- to the ATmega328.

Assuming you are emulating an Arduino Uno, then something like this:

https://www.jaycar.com.au/arduino-compatible-usb-to-serial-adaptor-module/p/XC4464

is what will come closest to mimicking the USB function on an Uno (ie a serial connection).

This shows how such a device would be connected:

https://www.jaycar.com.au/usb-serial-converter


message:
How to get keyboard input to arduino from the computer its plugged in to?

I have an arduino uno connected to my laptop.
and i need to get keypress info from the laptop's keyboard
with only the arduino sketch and without any program running on the laptop.
Is there a specific library or some way of doing so?

body:
You can't. It's impossible.

Or not as you have requested it, anyway.

The Arduino can only talk over Serial, so you will have to have some software running on the PC that transfers data (however that data is generated) over serial to the Arduino to process.

The only other option will be to have one of the Arduino boards that is capable of acting as a USB Keyboard device, such as a Leonardo, plus either a PS/2 keyboard or a USB keyboard plus a USB Host shield. Your Arduino the receives the keystrokes from the keyboard, processes them, and sends the result on to the PC.


message:
ESP32-CAM interfacing with CCS811+HDC1080+BMP280

I want to measure Temprature, Pressure, Humidity and CO2 in a room with ESP32-CAM & [CCS811+HDC1080+BMP280][1]

Since this module is combination of 3 sensors. Can I integrate it with ESP32-CAM over Software SPI ?

  [1]: https://www.aliexpress.com/item/32871484471.html

body:
No. Those three devices are I2C devices, not SPI devices.

Using that is no different to using three individual sensors all wired to the same I2C bus.


message:
how to read arduino board info serial no programmatically

well I am try to make an project with original arduino. but I want to make this project unique. if my codes are copied and loaded another arduino board, my app should not work. how can make unique app, are there any idea? on Arduino IDE Tools> Get Board İnfo> SN look unique id. but how can read it programmatically.

body:
You can't. The serial number is burned into the ATMega16U2 chip and is only available to the computer over the USB interface.  There is no method for you to get it from the UART interface that connects the two MCUs together.

To stop people copying your code there are two things you need to do:

1. Don't allow anyone access to the source code or any compiled code files, and
2. Enable the "code protection" facility of the ATMega328P.

The latter will stop people being able to read the code from the Arduino. It would also be beneficial to remove the bootloader and program the board directly. That way there is no other possible route for getting at your code.

You enable code protection by setting the correct fuse bits.


message:
Receive socket when in loop arduino (Interupt a while loop with a socket)

I'm currently working on an arduino project. Were the arduino is communicating with a NodeJS server via web sockets.

The socket connection is working fine and has no problems. But the problem I currently have is that I want to be able interupt an infinite while loop with a socket emit from the NodeJS server.

I found a page that had a solution for this problem but only with a button attached to the arduino.

[Link to page (Interrupt with button)][1]

This is the loop I want to be able to interrupt with a socket:

    bool loopRunning = true;

    void rainbow(int wait) {
    while(loopRunning == true) {

          for(long firstPixelHue = 0; firstPixelHue < 3*65536; firstPixelHue += 256) {
            for(int i=0; i<strip.numPixels(); i++) {
              int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
              strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
            }
            strip.show();
            delay(wait);
          }
        }
    }

I want to set loopRunning to false when I recieve a socket emit.

Anyone have any ides how I can implement this?

[Page to the socket functionality that I use][2]

  [1]: https://www.reddit.com/r/arduino/comments/4d7mcq/neopixel_buttoncycler_make_button_interrupt_loop/
  [2]: https://github.com/timum-viw/socket.io-client

body:
There are two ways to handle events: **interrupts** (hardware triggered) and **polling** (software triggered). Interrupts are much more efficient but also more difficult to use. SocketIoClient uses **polling.**

The necessary part of polling is... polling. That is, many times per second, you (or your library) needs to check if anything interesting is happening.

With this library, you have to call `SocketIoClient::loop()` many times a second. That's why `SocketIoClient::loop()` exists. So it needs to be added to your outer `for` loop.

(If your `delay(wait)` takes too long, you may need to break it up into a series of several shorter ones, but I think you can get away with it in this case.)

Then all you need to do is use `SocketIoClient::on()` to perform an action when an event happens. There is an example in the documentation. You will need to make loopRunning into a global variable.


body:
The problem is the while loop trapping execution.  When you have a small section of your loop that you want to stick in, you can do it two ways. You can do what you did with a while loop, that keeps execution stuck inside the while loop with nothing else happening.  Or you can let the loop function be the loop and use flags and if statements to decide what's running.

Imagine this code:

    void loop() {
      if(loopRunning){
         // do the stuff in your while loop
      }
      else {
         // all the other stuff in loop that you don't want running during that
      }
      // all the stuff you want to run regardless, like listening to your socket.
    }

When you do it like that you still get to have the stuff you were going to while loop to happen on it's own without the rest of loop, but you can also have some stuff that runs both ways.  That logic can be extended in all kinds of ways.  Maybe you want that part to always run but the rest of loop to be skipped when loopRunning is false.

    void loop(){
       //  all the stuff that should run all the time (like your socket)
       if(!loopRunning) {
           // all the stuff you would put into a while(!loopRunning) code
           // but wouldn't be able to catch the socket.
       }
    }


message:
Dotstar strip goes nuts when connected to MIDI piano

I've got a Dotstar strip, a piano, and an UNO(w a usb host shield).
I can get and properly translate data from the piano to the UNO, so I'm definitely getting the right information to the board. When i hardcode input values into my code it reacts appropriately, so I know my code works.
However, when I attempt to take data from the USB piano keyboard and light a corresponding LED, the whole strip lights up blue and green and flashes brightly between them. This happens before I even hit a key on the keyboard.
When I hit a key, the correct light lights up for roughly a milisecond before returning to flashing green or blue.

I feel like there's some electrical concept that I'm not getting- I've got the MIDI information correctly making it to the board, and it can correctly control the LEDs. I don't know where it could be getting the data that's causing it to do this.

I think I might need a resistor- I tried to set an AND gate from the SS pin and the data pin, but that didn't do anything.
[![The best image of my wiring that I could make in Paint][1]][1]

Here's the AND gate setup I attempted.
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/1vNoI.png
  [2]: https://i.stack.imgur.com/x7yKA.png

body:
The USB host shield and the LED strip use the same SPI bus. The USB host shield has a cable select line, but the LEDs don't, so they're always listening to the bus, even when the USB shield is using it.
You'll have to add some logic gates on the data and clock lines to the LED strip to turn them on or off, depending on another cable select line for the LEDs.

`LED Clock` = NOT `LED CS` AND `SPI CLK`
`LED Data` = NOT `LED CS` AND `SPI MOSI`

If you're only using two SPI devices, you could do:

`LED Clock` = `USB CS` AND `SPI CLK`
`LED Data` = `USB CS` AND `SPI MOSI`

https://forum.arduino.cc/index.php?topic=644679.msg4363133

**Edit**: Judging from the image, you're asking the exact same question as the one I already replied to on the Arduino forum a month ago. Why do you ask the same question twice if you're not even going to reply?


message:
Convert float to hexadecimal value

I am trying to convert a float value to a 4-byte hexadecimal value.

For example my input is: 58.5. My expected output is: 426A0000 or like 0x42 0x6A 0x00 0x00.

My program is:

    void setup() {
      Serial.begin(9600);
      float z = 128;
      unsigned i;
      unsigned char *chpt;
      chpt = (unsigned char *)&z;
      Serial.print("Float Value             : ");
      Serial.println(z);
      Serial.print("4 Byte hexadecimal Value: ");
      for (i = 0; i < sizeof(z); i++) {
        Serial.print(chpt[i],HEX);
        //Serial.print(" ");
      }
      Serial.println();
    }
    void loop() {
    }

My current output is:

`Float Value             : 128.00`

`4 Byte hexadecimal Value: 00043`

body:
This value looks pretty correct to me. It is stored in little endian thou.

0x43000000 is the actual value.

`Serial.print(x, HEX)` truncates leading zeros. so `00` gets `0`
So your output is `0 0 0 43` which corresponds to the little endian representation of the above.

Make yourself familiar with the floating point representation IEEE-754.

Also try the online [FoatConverter][1].

Try the following:

    char floatString[9];
    sprintf(floatString, "XXxx", chpt[3], chpt[2], chpt[1], chpt[0]);
    floatString[8] = '\0';
    Serial.print(floatString);

  [1]: https://www.h-schmidt.net/FloatConverter/IEEE754.html


message:
Reliably reloading the calibration data of IMU BNO055

I am using the BNO055 IMU and the Adafruit Library.
I want to store the calibration data and load them after the microcontroller is powered off and repowered on.
The Adafruit Library provides an example for storing and restoring but, in actual facts, it does not work. It is always required to recalibrate the magnetometers, but even doing so, the library reperform the whole calibration including the accelerometers.

I would like to simply restore all the calibration data (including the magnetometers) so that no calibration needs to be performed when the IMU starts.

I have read a massive amount of posts on the argument, but I really could not figure out how to reliably load all the calibration data at boot and avoid recalibrating them.

Is there anyone who succeeded and can please share the code?

body:
I found the solution. It is enough to add a function that when reperfoming the calibration of the magnetometer, checks ONLY if the magnetometer is calibrated (while the calibration for the accelerometer and gyroscope is reloaded from the EEPROM).

    void performMagCal(void) {
      uint8_t system, gyro, accel, mag;
      system = gyro = accel = mag = 0;

      while (mag != 3) {

        bno.getCalibration(&system, &gyro, &accel, &mag);
        displayCalStatus();
        Serial.println("");
      }

      Serial.println("\nMagnetometer calibrated!");
    }


message:
Can you use a 128 pin LCD on an atMega?

I found a couple old calculators and their LCD's have about 130 pins.

I was wondering if I can build an LCD driver to reduce the number of I/O pins, because I don't want to use like 14 I/O extenders; or can I make 1 huge extender?

body:
This answer assumes that each LCD segment is controlled by a separate pin (see comment of Juraj).

With a 74HC595 (shift register) you can use SPI to control 8 outputs.
You can daisy chain 4 of them to get 32 outputs with just the SPI pins, to get 128 pins. I assume two pins are for GND and VCC. If you need more than 128 GPIO output pins, than use 5 or more sets of daisy chained shift registers.

Now, since these shift registers use SPI, you can use the slave select to use multiple sets of daisy chained shift registers. I never tried this myself though.

The pins (except GND/VCC) you use is:

- 3 SPI pins (MISO, MOSI, CLK)
- 4 SS pins (one for each set of 4 daisy chained shift registers)

The idea is:

1. Set SS pin to the first set of 4 shift registers
2. Write 32 outputs for the first 32 segment output pins (using the 4 shift registers of the first set)
3. Set SS pin to the next set of 4 shift registers
4. Write 32 outputs for the next set
5. Continue with the next 2 sets (so you can use 32 * 4 = 128 pins)
6. In the next cycle, start with step 1 again


message:
Multiple Loops to control on and off LEDs

I'm new here. I have tried to write a simple code to turn LED's and light them up in specific pattern and being able to switch it off while in loop. So far I've managed to either get them constantly flashing in pattern and not responding to button or when I wrote in seperate void loops each function IDE Arduino throwing me error 'expected 'while' before 'loop1'' and I'm completely stuck and not got a clue what's the problem with code. Anyone could help?

Here's a code:

    const int ledPin =  2;
    const int ledPin1 = 3;
    const int ledPin2 = 4;
    const int buttonPin = 5;

    int programState = 0;

    int buttonState;
    long buttonMillis = 0;
    const long intervalButton = 300;

    long ledMillis = 300;
    const long intervalLed = 500;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(ledPin1, OUTPUT);
      pinMode(ledPin2, OUTPUT);
      pinMode(buttonPin, INPUT);
      digitalWrite(buttonPin, HIGH);
    }

    void loop()
    {
      unsigned long currentMillis = millis();
      buttonState = digitalRead(buttonPin);

     if (buttonState == LOW && programState == 0)
      do{
       programState = 1;
        }
    void loop1(){
    if {programState = 1 && buttonState == HIGH}
     do  {
       programState = 2;
        ledMillis = currentMillis;
        digitalWrite(ledPin, HIGH);
        delay(200);
        digitalWrite(ledPin1,HIGH);
        delay(200);
        digitalWrite(ledPin2,HIGH);
        delay(200);
        digitalWrite(ledPin2,LOW);
        delay(200);
        digitalWrite(ledPin1,LOW);
        delay(200);
        digitalWrite(ledPin,LOW);
        delay(200);
        digitalWrite(ledPin,HIGH);
        delay(200);
        digitalWrite(ledPin1,HIGH);
        delay(200);
        digitalWrite(ledPin2,HIGH);
        delay(200);
        digitalWrite(ledPin2,LOW);
        delay(200);
        digitalWrite(ledPin1,LOW);
        delay(200);
        digitalWrite(ledPin,LOW);
        delay(1500);}
     }
     void loop2(){
     if (programState = 2 && buttonState == LOW)

     do {
      programState = 2;
        digitalWrite(ledPin, HIGH);
        delay(200);
        digitalWrite(ledPin1,HIGH);
        delay(200);
        digitalWrite(ledPin2,HIGH);
        delay(200);
        digitalWrite(ledPin2,LOW);
        delay(200);
        digitalWrite(ledPin1,LOW);
        delay(200);
        digitalWrite(ledPin,LOW);
        delay(200);
        digitalWrite(ledPin,HIGH);
        delay(200);
        digitalWrite(ledPin1,HIGH);
        delay(200);
        digitalWrite(ledPin2,HIGH);
        delay(200);
        digitalWrite(ledPin2,LOW);
        delay(200);
        digitalWrite(ledPin1,LOW);
        delay(200);
        digitalWrite(ledPin,LOW);
        delay(1500);}

     else if  (programState == 2 && buttonState == HIGH)
     do
       {

        digitalWrite(ledPin, LOW);
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
      }
    }
    yield();
    }

body:
You are using the `do` function wrongly:

Like this:

    do{
      programState = 1;
    }

It should be something like:

    do
    {
      programState = 1;
    } while (`some condition`);

Where `some condition` is a condition that repeat the parts in { and } in case `some condition` is true.

However, besides that, it does not make sense normally to assign a variable in a while loop as only statement, since it will be 1 after the first iteration and reassigning it again does not make the value different (`programState` stays at 1).

Also note that in most cases the following form is used (unless you always want the body to be executed at least once):

    while (`some condition`)
    {
      `statements`
    }

Are you sure you need the `do` or `while` statement at all? Otherwise, try to remove the `do` statements and see if that is closer to what you need (I cannot map the code to your requirements). I have the feeling you want to use loops to prevent a lot of code duplication, for that you need to store the `ledPin`, `ledPin1` and `ledPin2` variables in an array and loop over them.

Another way is instead of e.g. the following code:

    digitalWrite(ledPin, HIGH);
    delay(200);

to create a separate function:

    void setPin(int pin, int value)
    {
       digitalWrite(pin, value);
       delay(200);
    }

and call the function by:

    setPin(ledPin, HIGH);

Now you can change all occurences of 'digitalWrite(`some pin`, `some state`); delay(200)' to the single statement above.

Also, I see there is a function `yield` that is not implemented.


body:
In addition to using the `do` construct incorrectly, you are also using an approach that won't work.

You generally should not use a do-while statement in Arduino. That causes your code to "stick" in the body of the do-while statement while the `while` condition is true, which prevents the rest of your code from executing.

You also should not use the `delay()` function if you need to manage timing different things at the same time. (To make a more general statement, you should not use the `delay()` function **at all**. Forget it exists.) There are rare cases (like doing one-time setup of hardware in your `setup()` method.) where using the `delay()` function is appropriate, or **very** short intervals like timing ultrasonic pulses, but the `delay()` function ALWAYS causes your program to come to a complete halt until the delay interval has passed.

You should search on "Arduino blink without delay" and study the example project you find. It outlines how to use the `millis()` function to keep track of timing. With that approach you can time multiple things at the same time. (You'd have multiple "fire time" variables that would remember the `millis()` value at which you want a change to occur, and you get that value of `millis()`, your code would trigger the change (toggling an LED, for example) and then update that "fire time" variable.


message:
Compilation Error - Yellow LED blinking as I have installed & connected Arduino UNO board to Windows XP PC

This is the first time when I have installed Arduino IDE (arduino-1.8.10-windows.exe) in my Win. XP SP-3 OS and it seems that the Arduino IDE software installation is successful without any hitch.

After restarting the PC, connected it  with Arduino Uno board through USB-Printer cable provided with the board and then selected Arduino Uno, Selected Port: COM3 (Arduino/Genuino Uno) - as I have verified in the Device Manager that the Arduino Uno installed in COM3 port.

As soon as I have connected Arduino Uno board to my PC, the yellow LED started blinking slowly. As I have tried uploading the sketch -  File>Examples> 01.Basics>Blink - there is an Error message that says, "Error compiling for board Arduino Uno" - even though the yellow LED still kept blinking without a reasonable act from my side.

So, where have I gone wrong - either in performance or in understanding? And is there any suggestion for making things right?

I thank you.

    // the setup function runs once when you press reset or power the board
    void setup(){

      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);

    }

    // the loop function runs over and over again forever
    void loop(){

      // turn the LED on (HIGH is the voltage level)
      digitalWrite(LED_BUILTIN, HIGH);

      // wait for a second
      delay(1000);

      // turn the LED off by making the voltage LOW
      digitalWrite(LED_BUILTIN, LOW);

      // wait for a second
      delay(1000);

    }

body:
The yellow LED may be flashing because there may be a "Blink" LED program pre-installed on the Arduino.

To diagnose the "Error compiling for board Arduino Uno", we need to see the sketch you are trying to upload, and detailed error messages. If you go to `Arduino > Preferences`, check the "compilation" and "upload" checkboxes beside `Show verbose output during:`. `Display line numbers` is another checkbox you could enable.


message:
I need some help getting data from a rangefinder

I have wired up my range finder (CJVL53L0XV2) to a breadboard for testing and have run the arduino example code for the rangefinder. The rangefinder works, but I do not know how to take the distance that the range finder shows on the serial monitor, example: distance measured 44mm, and turn that information into a variable that the rest of my program could use.

I am not sure how to "grab" data from the sensor and turn that data into a variable that I can then manipulate. I have tried to dissect the example code, but it seems to be taking data and using functions that do not exist anywhere but in some files in the arduino library that I can't identify or access.

Below is the code that I have been trying to reverse engineer.
```
[code]
Adafruit_VL53L0X lox = Adafruit_VL53L0X();
int pbl = 9;
void setup() {
  pinMode(pbl, OUTPUT);
  digitalWrite(pbl, HIGH);
  delay(1);
  Serial.begin(115200);

  // wait until serial port opens for native USB devices
  while (! Serial) {
    delay(1);
  }

  Serial.println("Adafruit VL53L0X test");
  if (!lox.begin()) {
    Serial.println(F("Failed to boot VL53L0X"));
    while(1);
  }
  // power
  Serial.println(F("VL53L0X API Simple Ranging example\n\n"));
}

void loop() {
  VL53L0X_RangingMeasurementData_t measure;

  Serial.print("Reading a measurement... ");
  lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!

  if (measure.RangeStatus != 4) {  // phase failures have incorrect data
    Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
  } else {
    Serial.println(" out of range ");
  }

  delay(100);
}
[/code]
```

body: measure.RangeMilliMeter was the key to it all. After experimenting for several hours, I finally got it.


message:
Trying to measure distance using an ultrasound sensor

I am relatively New to Arduino and need your help. Actually i made a code and the problem is that the ultrasound sensor doesn't work at all. It isn't displaying the distance between the object and and the sensor. Can you help me please!
Here is my code:

note: the code has some motor cotrol commands

~~~
int enableBridgePin = 10;
int forwardPin = 11;
int backWardPin = 9;
int tickPin = 2;
const int trig = 5;
const int echo = 6;

int dt;
int distance;

float rotationSpeed[50];

void setup() {
  pinMode(enableBridgePin, OUTPUT);
  pinMode(forwardPin, OUTPUT);
  pinMode(backWardPin, OUTPUT);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);

  digitalWrite(forwardPin, LOW);
  digitalWrite(backWardPin, LOW);

  interrupts();
  digitalWrite(enableBridgePin, HIGH);
}

void loop() {
  analogWrite(enableBridgePin,255);

  digitalWrite(forwardPin, HIGH);
  digitalWrite(backWardPin, LOW);

  distancefonction(dt, distance);
  if(distance>5){
   detachInterrupt(digitalPinToInterrupt(tickPin));
   digitalWrite(forwardPin, LOW);
   }

}

int distancefonction(int dt, int distance)
{
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  dt = pulseIn(echo, HIGH);
  distance = 0.034/2*dt;
  Serial.println(distance );}
~~~

body:
You have declared `int distance` outside of any method. That means it's available from all methods. Some people call it a *global* variable.

However, you have a method `int distancefonction(int dt, int distance)` which receives `int distance` as a parameter. This results in an ambiguity: if you refer to `distance` within the method like

    distance = 0.034/2*dt;

should this now refer to the *parameter `distance`* or the *global variable `distance`*?

The answer is: you can't decide. The C/C++ standard has decided for you and the answer is: the parameter will take precedence and thus hide the global variable. This thing is also called "shadowing".

What does it actually mean?

0. The global variable `distance` has an undefined value at the start of the program. Let's assume the value is 0.

0. `distancefonction()` is called, passing `distance` as a parameter. This will create a copy of the value 0 on the stack.

0. the function will calculate the distance and update the variable on the stack.

0. The `Serial.println()` statement within the function accesses the variable on the stack and will print the correct distance.

0. Once the function is complete, the code in `loop()` will access the global variable `distance`, which still has the old value, because only a copy has been updated.

What is the solution?

Of course there are several solutions.

0. The simplest fix is probably to remove the parameter `int distance` from `distancefonction`. Thus the function will not receive a copy and instead operate on the global variable.

0. Another solution is to let `distancefonction` return the actual distance. The method signature already indicates that you wanted to return a value: the `int`from `int distancefunction(...)` says that. At the moment, the function does not return anything. You could write `return distance;` at the end. This approach could eliminate the global variable completely.


message:
choosing prober controller to measure engin speed changes

In order to monitor engine speed changes in real time, sensor is detecting the motion of few magnets around a disk driven by the motor.
1st approach Hall effect sensor signal is regulated by LM393 comparative IC, resulting digital clean signal, connected as input to a selected pin then measuring the timing changes between of the signals to calculate the speed changes.
2nd approach is to connect hall sensor directly without modeling to a micro controller ADC, then process the digital noisy unclean signal which require much processing power than 1st approach.
Better approach are welcome, but the question is how to choose proper controller specs for such task

body:
The first option is way better than the second. Measuring a voltage with the ADC takes time and you don't really need the analog values in your code. (Though depending on the actual values you might not need a comparator befor it. The digital input pin acts as Schmitt Trigger. The only requirement for this is, that the signal range is greater than 0.3*Vcc to 0.7*Vcc.)

About the needed controller: That greatly depends on the speed, that the motor is running at (e.g. the frequency of pulses), and the way you are measuring it.

- The easiest Arduino way is to attach an interrupt to the pin and increment a counter variable in it. Reading and resetting the variable in regular time ranges (using `millis()` will give you the pulse frequency and thus the speed. For this you don't need much extra functionality in the microcontroller. One with external interrupts or pin change interrupts is sufficient (almost all microcontrollers have those).

- Another way is to utilize a hardware timer as counter. You can configure a timer of a microcontroller to get it's clock source from a pin. If you connect your sensor output to it, the counter will increment on every edge (falling and rising). The first timer of an Arduino is used by the Arduino core as time-keeper. You can use it to get the time component. Configure the second timer as counter, set it's value to zero, then start the timer and track the time passed using `millis()`. When the measurement time has passed, you read the counter value, reset it to zero and start a new measurement. While the hardware timer counts the pulses, you can calculate the speed with the number of pulses and the time passed and do whatever you want with it. This approach of course needs at least 2 timers (which most microcontrollers have, I think).

Of course the general speed of the microcontroller, meaning it's clock frequency, is also a concern. But this only becomes relevant, as you reach high pulse frequencies.

This answer is a general overview on how to go on. For a more specific answer, you should edit your question to also be more specific. For example you could include the expected pulse frequency.


message:
sending specific date's data from data logger shield to serial port

I was wondering if it is possible to save lots of data( exp: one year data) in data logger shield and then read them from serial port without ejecting the SD card... this part of my question is fine... the main subject is that i want to read specific date's data from the logger... To explain this better, lets say you have a humidity sensor and saved it's data for a year. Now you want to send the last 6 month's data to your phone via bluetooth. Is it possible?
Also, i wanted to use the circular buffer but that doesn't seem like a good idea because it's costly... any ideas will be such a great help.

body:
I see a few questions (reading specific data from an SD) and the circular buffer; I think these are two different 'problems'.

**Reading specific data from an SD**

It depends how you save your data. Do you make one big file, or you create daily a new file for example?

Assuming the last, it's relatively easy, just sent the file contents of the files within a certain date.

In case you have a big file, you need to parse the file, in specific the time stamps you have to include in the file, and send everything within certain dates.

If this takes too long parsing, you could create a second file that contains the starting points (e.g. byte offset) for every day. So e.g. Jan 1 -> 0 means Jan 1 starts at byte 0, Jan 2 -> 3633 starts at byte 3633; you can use some kind of `seek` function to start reading the data file starting from date; and continuing also checking the end date's byte offset.

You can get the time stamp of a file:

    void dateTime(uint16_t* date, uint16_t* time)
    {
        DateTime now = rtc.now();
        // return date using FAT_DATE macro to format fields
        *date = FAT_DATE(now.year(), now.month(), now.day());
    }

You can start reading from a certain position in a file by using the `fseek` function, see https://www.arduino.cc/en/Reference/FileSeek.

**Circular buffer**

This relates to sending bytes (via a peripheral/bluetooth). It is not costly at all. What you do is create a circular buffer (e.g. 50 bytes or whatever). Than you start writing bytes into it (which you copy from the SD file increasing the buffer space. Than you start sending bytes from it, decreasing the buffer space.

I never used Bluetooth, so I don't know how the packet (and size) is sent; if you can just sent packages of a certain or fixed length,  you don't need a circular buffer, just keep reading e.g. 50 bytes, put it in a fixed array, send it, and load it again etc until all bytes are sent.


message:
Trouble trying to turn a stepper while a button is pressed down

So i'm currently coding a little device that rotates a step motor round one 8th of a full revolution every time a button is pushed. the motor is attached to a question reel with 8 questions on it, each one is viewable through a little window covering the reel after each button press. the thing im concerned about is that if even one of the question sections is slightly larger or smaller than the others, it will cause the question to become misaligned with the window after a certain number of run throughs.

in order to combat this I want to have a back up code that simply rotates the stepper while the button is held down. this will allow me to manually reset the reel to its proper positioning should the questions become misaligned. im not achieving this however, and was hoping someone may be able to detect where the issues are in my code?

    #include <Stepper.h>

    #define STEPS 2048

    Stepper myStepper(STEPS, 8, 10, 9, 11);

    const int  buttonPinBlue = 6;

    void setup() {

      myStepper.setSpeed(5);
    }

    void stepp() {

     myStepper.step(1);

      pinMode(buttonPinBlue, INPUT);
    }

    void loop() {

     if (buttonPinBlue == HIGH) {

      Serial.print("pin is high");

       stepp();
      }

    }

also just as a side note, the stepper runs fine using the 'define steps' value and the speed that I've set here, the issue appears to be that the button press is not being detected

body:
You don't set the pin itself:

Change

    if (buttonPinBlue == HIGH) {

to

    if (digitalRead(buttonPinBlue) == HIGH) {

Also you don't have to set the pin every time, only one time is enough: in function `setup` should be the following line (and it can be removed from the function `stepp`:

    pinMode(buttonPinBlue, INPUT);

Note that if you want to use a 'click' to move to the next item, you have to debounce the button; on the Arduino site check for button debouncing: https://www.arduino.cc/en/Tutorial/Debounce


message:
Attiny85, high output impedance, dim leds

I designed what I thought should be a very simple badge using the Attiny85 SU, schematic below: [![Tiny with leds on each gpio pin][1]][1]

The problem is the tiny doesn't seem to be sinking current properly. For testing I switched to a 20 PU on the breadboard and 100 ohm load resistors. At 3v supply this should give approximately 30 mA per pin, well under the rated 40 mA per pin and 200 mA total. However with the loads connected only pin 6 sinks any significant current, and appears to be higher impedance than it should be (1.6v across the resistor for 16 mA). The other pins seem to be very high impedance, they drop to ~7 mV (70 microamps) when the loads are connected. With the load resistors disconnected they function normally (digitalWrite HIGH = supply voltage - junction drop).

I'm using pinMode [this was a problem] (OUTPUT, N) [/this was a problem, should be (N, OUTPUT)] to set up pin N, and digital writes for on/off. I've been able to drive transistors before using an exactly similar setup, although admittedly these have much lower current requirements.

Anybody know what's going on here?

EDIT: Turns out I had accidentally swapped the order of OUTPUT and N in the pin mode command. Not sure why the compiler had no problems with this, but I am at least getting useful outputs now.

I'm gonna leave this up out of curiosity/etc, because I'm still getting higher impedance than I'd have expected on the outputs. With the 100 ohm load resistor, I'm only getting about 16 mA (expect closer to 25). Supply voltage from the CR2032 is ~2.48v under load.

Based on the graph on the [datasheet][2] (figure 22-19, PG 182), at 25 c ambient (currently 20) I should expect a voltage drop from VCC to output somewhere on the lower end between 400 and 600 mV when supplying 15 mA, but my readings at 16 mA above represent a voltage drop of almost 900 mV across the Tiny. Additionally the LEDs drop 2v at 10 mA, for which you'd expect approximately 300 mV drop across the tiny according to the graph, but mine is dropping almost 500 mV. I'm not sure if this is something in my setup or if the characteristic curves on the datasheet simply aren't that accurate for production models.

  [1]: https://i.stack.imgur.com/6gyoJ.png
  [2]: https://www.mouser.com/datasheet/2/268/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATti-1315542.pdf

body:
The answer to the main problem was that I had used pinMode(mode, number) where the actual syntax is pinMode(number, mode). Presumably modes can be selected by number and the compiler though I wanted to set an undefined pin to mode number.

TL;DR the correct syntax is pinMode(4, OUTPUT) to set PB4 (pin 3) to output.

The problem of higher than expected output impedance remains, though the outputs are now quite usable. As detailed in the edit, I'm still experiencing voltage drops across the microcontroller nearly 2x higher than I'd expect from the graph on the datasheet for a given current.


body:
You already found your problem. I am answering only to provide some
insight on why you were experiencing the symptoms you had.

`pinMode()` takes two integer arguments (two `uint8_t` to be precise).
The names `INPUT`, `OUTPUT` and `INPUT_PULLUP` are just macros for 0, 1
and 2 respectively. This is why the compiler accepts your code with the
arguments swapped.

On the AVR microcontrollers, setting a pin's output register to `HIGH`
on a pin that is configured as input has the effect of turning on the
internal pullup. Thus

```c++
digitalWrite(pin, HIGH);
```

has the same effect as

```c++
pinMode(pin, INPUT_PULLUP);
```

on an input pin. When you do this, the pin will source (not sink) a very
small current. The pullup resistance is typically of the order of
30 kΩ, and this is why you get such a small current.


message:
ARDUINO flashing lights

I'm making a circuit with my Arduino so that when it receives a '1' or
'2' or 'a' it turns on or off the LEDS. But I wanted the lights to
flash and do not know how to do loops in loops or if that's what I
need to do at all. Any help would be very much appreciated and the
code will be below.

    //-----------------ELECTRONICS-----------------//

    int left = 11;
    int stoP = 12;
    int right = 8;

    //variables
    int Received = 0;
    int left_state =0;
    int stoP_state = 0;
    int right_state = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(left,OUTPUT);
      pinMode(stoP,OUTPUT);
      pinMode(right,OUTPUT);
    }

    void loop() {

      if (Serial.available() > 0)
      {
        Received = Serial.read();
      }

    ////////////////LEFT//////////////////

    if (left_state == 0 && Received == '1')

    {
      digitalWrite(left,HIGH);
      Received = 0;
      left_state = 1;
    }

    if (left_state == 1 && Received == '1')

    {
      digitalWrite(left,LOW);
      Received = 0;
      left_state = 0;
    }
    ///////////////////////////////////

    ///////////////stop////////////////

    if (stoP_state == 0 && Received == 'a')

    {
      digitalWrite(stoP,HIGH);
      Received = 0;
      stoP_state = 1;
    }

    if (stoP_state == 1 && Received == 'a')

    {
      digitalWrite(stoP,LOW);
      Received = 0;
      stoP_state = 0;
    }

     ////////////////////////////////

     ///////////right///////////////

    if (right_state == 0 && Received == '2')

    {
      digitalWrite(right,HIGH);
      Received = 0;
      right_state = 1;
    }

    if (right_state == 1 && Received == '2')

    {
      digitalWrite(right,LOW);
      Received = 0;
      right_state = 0;
    }
    }

body:
As chrisl already mentions, you have to use the `millis` function.

Besides setting a pin HIGH, you keep a variable for each state for the start time and set it when the corresponding state is set to 1:

    unsigned long left_start_time = millis();

Than within the loop you check for each state when it is 1 (on or actually flashing) and switch the pin on or off, example:

    if (left_state == 1)
    {
        digitalWrite((millis() - left_startTime % 400) < 400 / 2) ? HIGH : LOW);
    }

What this does is for the first half of the 400 ms period (time % 400 < 200) to be HIGH, and the last half (time % 400 >= 200) to be LOW.

Improvements:

- Do not use 400 but a constant value.
- Do not use separate variables for left/right/stop, but put them in a structure, keeping the state, time, pin, and activation key ('1', '2', 'a') together.
- If you do the above, you can make your program more simpler (and avoid code duplication) by parameterize your code.


message:
Cryptic compiler errors

I'm getting the error:
```
    left_hand:3:20: error: expected ']' before ';' token
     #define HAND_ROWS 5;
                        ^
```
on this code:
```++
    #include <Keyboard.h>

    #define HAND_ROWS 5;
    #define HAND_COLS 6;
    #define ROW_PINS {9, 8, 7, 6, 5};
    #define COL_PINS {10, 16, 14, 15, 18, 19};
    #define LOOP_SPEED = 10;

    const char keymap[HAND_ROWS][HAND_COLS] = {{0xB1, '1', '2', '3', '4', '5'},
                                               {0xB3, 0x81, 'q', 'w', 'e', 'r'},
                                               {'6', 0x80, 'a', 's', 'd', 'f'},
                                               {'7', 'z', 'x', 'c', 'v', 'b'},
                                               {'h', 'j', 0x82, ' ', 'k', 'l'}};
    boolean pressedKeys;
    int keymapIndex;
```

help, please? This makes no sense to me...
If I try to use Keyboard.LEFT_SHIFT and equivalent constants for the hex-codes in the keymap, they tell me 'expected unqualified-id before numerical constant'
What does this even mean? I'm so lost...

body:
You mustn't terminate a `#define` with a `;`.  Semicolons are for C and C++ statements. `#define` is a *preprocessor* statement.

`#define` creates a literal string replacement, so when you use it you end up with:

    const char keymap[5;][6;] = {...

which is, of course, wrong.


message:
millis and micros always returns 0 (or other constant)

On an Arduino Uno, I have a sketch akin to this:

    void setup()
    {
        // Generate some PWM signal on Pin 5, using Timer 0.
        pinMode(5, OUTPUT);
        TCCR0A = 0b00110011;
        TCCR0B = 0b00001000;
        OCR0A = 0x80;
        OCR0B = 0x20;
        TIMSK0 = 0b00000100;

        Serial.begin(115200);
    }
    void loop()
    {
        // Just write the result of millis to the terminal.
        unsigned long ms = millis();
        char s[100];
        sprintf(s, "%lu\r\n", ms);
        Serial.print(s);
    }

Setup timer 0 to generate a PWM signal, setup the serial port, constantly print the result of `millis()` to the terminal.

The numbers printed to the console do not increase as expected, but stay "0".
Similarly, if I use `micros`, "4" is printed constantly.

How's that?

body:
`millis` and `micros` appear to use timer 0 internally. Using that timer to also generate a PWM signal messes with their ability to function properly.
The solution is to either use a different timer to generate the PWM signal, or to roll a custom equivalent of those functions.

Why does the official arduino documentation not specify that `millis` and `micros` occupy timer 0?

Why are there no Google results mentioning timer 0 when searching for "arduino millis returns 0", "arduino millis constant", "arduino millis not counting" and the like? (There are results with the same symptoms, but for different reasons.)

Who knows.


message:
Why does Arduino IDE take so long to open?

I have Arduino IDE, version 1.8.10 (Windows 10 x64, 8GB RAM, i5-7200 @2.5GHz) on a network drive mapped to D:, on a 100Mbit wired network and fast file server.

If I navigate to the network shared folder and launch 'arduino.exe', it takes at least 2 minutes for the IDE to appear.

This seems totally unreasonable considering the entire arduino.exe file is only 395kB. Seems more likely the IDE is waiting for something until a timeout occurs, before finally loading up the IDE.

What can be causing this and how can I diagnose it?

As an aside, it seems the compilation process takes longer than it should too, even for programs that use no external libraries and are very short.

body:
The simple answer is "libraries".

Every time you start the application, all files inside your library folder are parsed.

And this is not done over your OS, but over the Java-Virtual Machine.

So it is not just slow, it is ultra-slow! Since your antivirus will probably also check each file.

Once, all files was read (maybe 1/2 of the time spent by your Arduino start), all your sketch folders are parsed.

At the end Windows devices and Arduino specific libraries are loaded.

On my Arduino IDE (is installed locally), on each starts, the Arduino IDE checks about 300.000 files. I need up to 20 seconds to load everything, before I can use the IDE.

## What can you do?
### Base

- do not waste the library folder with unused libraries
- NEVER put some documentation or non-Arduino files in your sketch folder, as they are all parsed by the IDE
- disable the Antivirus for the folders:
  - Arduino
  - libraries
  - sketch

### Advanced
If you open always the same project, you can for example edit the "preferences.txt" file.

If you remove some parameters from the preferences.txt, you will be able to lauch your IDE much faster. I created an application that statrs your Arduino IDE with personalized settings:
https://github.com/Adrianotiger/ArduinoIDE_Launcher

This application can remove some preferences like:

 - boardsmanager
 - last.* settings
 - recent sketches

when the Arduino starts, so it will be launched faster. But if you set the preference `sketchbook.path`, you can start your Arduino IDE 3-4 times faster. Just place the folder with your project libraries and you can start the IDE much faster.


message:
Reading port register and print

I am playing with port registers directly to improve speed on a Arduino micro. I have no problem **writing** them, like

    PORTF &= B11101111

However, when I try to **read** and print it, things get funny and I hope to know why.

Observation 0:

    byte dat = PORTF;
    Serial.print(dat,BIN);

produces a single 0, where I am expecting 8 0's as for a byte. And, even when I check that a digitalRead correctly gets a 1 from PF5 or A2,

Observation 1:

    byte dat = PORTF;
    Serial.print(dat,BIN);
    Serial.print(dat,BIN);

produces a compiler error like

    ...cores\arduino\Print.cpp: In function 'println.constprop':
    ...cores\arduino\Print.cpp:143:1: internal compiler error: Segmentation fault
    }
    ^

body:
The function `Serial.print()` and it's siblings cuts all leading zeros. So `0b00001111` get's displayed as `1111` and `0b00000000` as `0`. So you actually get what you expect. It's just printing different.

Also, when reading `PORTF`, you actually read the output state of the pins, as you have set it before. If you want to read the real input level of the pins, you should read `PINF` instead.

Though I don't know, where that segmentation fault came from.


message:
When does the ADC take the reading?

I'm experimenting with the "2 pin capacitance meter" and trying to make it more accurate. Currently I've made the Arduino read 62.5 ns intervals but this means the time for the ADC to read is taking up a bigger part of the interval. I'm currently using a prescaler value of 8 on the ADC. Unfortunately reading continuously isn't really an option so I am limited to around 8us of read time instead of 6.5us. This isn't that much of a problem since I know that the read will take near 8us from experiments, however I do not know when during that 8us interval the actual reading takes place.

So that is my question, does the adc take the average value during those 8us, does it "lock" the bits at the beginning or when exactly does the reading occur?

Link to capacitance meter, specifically the third one: http://www.circuitbasics.com/how-to-make-an-arduino-capacitance-meter/#comment-363733)

body:
The ADC is a "Successive Approximation" type ADC.  It works by:

1. Taking a snapshot of the incoming voltage in a small capacitor
2. Generating a reference voltage
3. Comparing the voltage in the capacitor to that reference voltage
4. Refining the reference voltage
5. Go back to 3 until you have the accuracy you desire.

There's lots of "time" involved there:

* The capacitor can only store the voltage accurately for so long before the self-discharge (leakage current) causes the voltage to drop (this defines the maximum amount of time you can take to do a reading)
* Each refining of the reference voltage and comparison thereof takes one ADC clock tick. There are a few "setup" clock ticks as well. This defines the minimum number of ADC clocks that you need to take a reading (13)
* The DAC and comparator take a certain amount of time to operate each clock tick - this limits the maximum clock frequency the ADC can run at.

So you have a "sweet spot" of speed (like the "[goldilocks zone](https://www.abc.net.au/news/science/2016-02-22/goldilocks-zones-habitable-zone-astrobiology-exoplanets/6907836)" of the solar system). Set the ADC too slow or try and get too high a resolution out of it and you lose accuracy due to voltage droop on the capacitor. Set it too fast and the DAC can't keep up and you lose accuracy due to the comparison voltage not being right.

Well, that's the internals. Then on top of that you have the Arduino API. That adds an entire other layer of complication. `analogRead()` is a *blocking* operation.  It:

1. Congfigures the IO pin (if needed)
2. Turns on the ADC (if needed)
3. Configures the ADC MUX to the right channel
4. Starts a conversion
5. Sits there twiddling its thumbs for a while
6. Reads the conversion result
7. Returns it to you

And it does that (except maybe 1 and 2) every time you take a reading.  That's fine for reading a potentiometer, or an LDR, etc. But rubbish when you want to do fast, time-based, readings.

Instead you need to push the envelope a little and step away from the Arduino API.  Much of what the ADC does is done without intervention of the CPU. Manually configuring the ADC to read continuously and trigger an interrupt when the conversion is done, and then using that interrupt to grab the result of the comparison and start a new one (or use a timer interrupt to read the previous result and trigger a new reading) will give you much more control over the ADC and exactly when things happen.

So, now to answer your main question of "when during that 8us interval the actual reading takes place.", in the context of how the ADC works:

**At the moment the SAH capacitor is detached from the MUX to start the comparison sequence**.

When exactly is, though, is subjective.  If you use the Arduino API (`analogRead()`) then it's at some point near the start of the function call, but not *at* the start of it.

If you configure it manually and trigger it from within a timer interrupt, it's *on the second (out of 13) falling edge of the ADC clock after ADSC has been set HIGH*.

There are also "Free Running" and "Auto Trigger" modes whose timing is the same as for a single conversion.  Note that the first conversion performed in any mode imposes a "run-in" clock sequence where the ADC MUX and reference voltage DAC are initialised.

All this timing can be found in figures 23-4 and 23-5 on page 209 of the [ATMega328P datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf).  On page 210 there is a handy table that gives you how many ADC cycles from the start of a conversion the Sample And Hold occurs and how long the conversion takes in clock cycles.

For best throughput you want to use "Free Running" mode and read and store the ADC result in the interrupt the ADC triggers.  For most accurate and controllable timing you want to use Auto Triggered mode with a timer for the trigger source, and again read the result in the ADC interrupt.


message:
Atmega328p Uploads via ISP but not bootloader

I'm trying to upload a bootloader to my atmega328p on a custom pcb containing external oscillator at 16MHz. It is possible to upload program via ICSP pins using Arduino as ISP (Official Arduino Uno) but not possible to upload a bootloader. This pcb needs bootloader as it will be used via FT232RL interface.

I've tried to upload bootloader at 115200 baud rate but that did not read any device signature. Also exact definition of my IC is "ATMEGA328P-AU TQFP-32 8-bit 20MHz", if it helps.

P.S That exact definition says it is 20MHz but I suspect that's correct as I don't entirely trust that shop.

Thanks in advance

Upload log

    Sketch uses 1626 bytes (5%) of program storage space. Maximum is 32256 bytes.
    Global variables use 192 bytes (9%) of dynamic memory, leaving 1856 bytes for local variables. Maximum is 2048 bytes.
    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbmodem14101 -b115200 -D -Uflash:w:/var/folders/9z/8cpdsm0518x0b85yx7n4y_0c0000gn/T/arduino_build_452635/sketch_dec06a.ino.hex:i

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/deniz/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

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

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

             Programmer Type : Arduino
             Description     : Arduino
             Hardware Version: 3
             Firmware Version: 4.4
             Vtarget         : 0.3 V
             Varef           : 0.3 V
             Oscillator      : 28.800 kHz
             SCK period      : 3.3 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f (probably m328p)
    avrdude: reading input file "/var/folders/9z/8cpdsm0518x0b85yx7n4y_0c0000gn/T/arduino_build_452635/sketch_dec06a.ino.hex"
    avrdude: writing flash (1626 bytes):

    Writing | ################################################## | 100% 0.27s

    avrdude: 1626 bytes of flash written
    avrdude: verifying flash memory against /var/folders/9z/8cpdsm0518x0b85yx7n4y_0c0000gn/T/arduino_build_452635/sketch_dec06a.ino.hex:
    avrdude: load data flash data from input file /var/folders/9z/8cpdsm0518x0b85yx7n4y_0c0000gn/T/arduino_build_452635/sketch_dec06a.ino.hex:
    avrdude: input file /var/folders/9z/8cpdsm0518x0b85yx7n4y_0c0000gn/T/arduino_build_452635/sketch_dec06a.ino.hex contains 1626 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.21s

    avrdude: verifying ...
    avrdude: 1626 bytes of flash verified

    avrdude done.  Thank you.

Bootloader log (P.S. all sync attempts happen at the same time)

    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -P/dev/cu.usbmodem14101 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/deniz/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/cu.usbmodem14101
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x60
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x66
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x78
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1e
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x06
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x7e
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe6
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x80
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x98
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x80

    avrdude done.  Thank you.

body:
The first issue might be in Upload log. There is mentioned `programmer = arduino` (in version before edit). That means you might be uploading code into the wrong Arduino. So there is no ArduinoISP sketch and it won't work (getsync() errors)

Check if the upload is working between two arduinos, that should opted out wrong wiring on the programmer side and so on.

And as it's self made board, there might be some issues with wiring, omitting bypass capacitors (as it turned out in chat discussion - it was the main issue)


message:
Make OTA work with Arduino Uno Wifi

I just bought a Arduino Uni Wifi Rev. 2, with the itention of doing over the air uploads to the devices.

By reading the official [Gettings started with the Arduino Uno Wifi](https://www.arduino.cc/en/Guide/ArduinoUnoWiFi) guide, I thought the process was just to power the devices, connect to the SSID, then browse to it's IP and set it up.

But it seems like this is not the case, and that others have made this same mistake. This Arduino device doesn't create network by default, we have to upload a sketch that connects to our wifi.

So I have two questions.

1. **What Arduino board are they referencing in the guide linked above, that we can just connect to out of the box?**
2. **How can I get OTA support for my particular board?**

body:
>What Arduino board are they referencing in the guide linked above, that we can just connect to out of the box?

[The first Uno WiFi][1] was made in 2016 by arduino.org. It is retired and not available in stores.

> How can I get OTA support for my particular board?

The OTA support for Uno WiFi Rev. 2 is ready or almost ready, but the required additions are not merged in GitHub firmware and library repository even if they wait some months now. It looks like Arduino focuses on something else.

  [1]: https://github.com/jandrassy/UnoWiFiDevEdSerial1/wiki


message:
How to check if two device has the same address on I2C?

I start a new project with Arduino UNO and MCP23017 expander. Using this, I can connect 8 chips on Arduino, by selecting different addresses ( from 0x20 to 0x27 ).
My question is, if I connect two MCP23017 chips with the same address, there is any way to see somehow that I have two chips with the same address ?
I am using a standard I2C scanner in Arduino code, but is nt return me if I have multiple chips with the same address, he see only one chip for example !

Can you please help me with some ideas to check how man chips are connected with the same address?

body:
It's my understanding that duplicate I2C addresses prevent the master from communicating from the slaved devices, so the answer is no.

Instead, connect the devices one at a time, run the I2C scanner, note the address for each, and take note of any duplicate addresses.


body:
If both devices are the same, are configured the same, and respond the same, then it is impossible to tell if there is one, two, or four hundred.

However if there are differences between the two devices you will get corrupt data.

I2C is an open-drain protocol. For a device to send a 0 it pulls the data line low. For it to send a 1 it lets the pullup resistor pull the line high.

So if you have two devices and they both send a 1 you get a 1. If they both send a 0 you get a 0. But if one sends a 1 and the other sends a 0 then the 0 will "win" and you will see a 0.

Since most devices, when powered up, revert to some pre-defined default state, chances are you will always see multiple devices of the same type on a single address as just one device.

One possible way around it is to have some control signal that is unique to each device which will cause them to only respond one at a time. For example, you might choose to pull all the RESET pins of the slaves LOW and raise each one in turn to see what address the device is on. If you then see two that respond on the same address then you know you have a conflict and can report it as such.

Another possibility is to connect the address control pins to IO pins and communicate with all the slaves on the same address - but you only set one slave's address to the "live" address at a time. That also gives you the ability to have far more than just 8 slaves.


message:
Button circuit draws all power away from LEDs

I'm very new to Arduino, so please forgive me if I don't know the proper terms for things.

Whenever I press the button on the board, the LEDs all shut off.

[![Button Not Pressed][1]][1]
[![Button Is Pressed][2]][2]

I can't host the image files on imgur, and I don't know how well Flikr will work with it.

Now:

The resistors being used are 220 ohm resistors for the LEDs. The one for the button is a 10k ohm resistor.

This also happens without a resistor in place. I tried simply replacing the button with a wire from the positive to a row, with a wire leading from there to another row, back to ground.

What do I do to fix this?

  [1]: https://i.stack.imgur.com/IBf0f.jpg
  [2]: https://i.stack.imgur.com/EYObv.jpg

Edit: Sorry about the images being extremely low quality, they've been updated.

Here's the code, but it's mostly irrelevant:

```c++
//DEFINE STUFF BABYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
int ButtonState2 = 0;
int ButtonState1 = 0;
int ButtonState0 = 0;
const int ButtonPin2 = 2;
const int ButtonPin1 = 1;
const int ButtonPin0 = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(3, OUTPUT);
  digitalWrite(13, LOW);
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
  digitalWrite(8, LOW);
  digitalWrite(7, LOW);
  digitalWrite(6, LOW);
  digitalWrite(5, LOW);
  digitalWrite(4, LOW);
  digitalWrite(3, LOW);
  pinMode(ButtonPin2, INPUT);
  pinMode(ButtonPin1, INPUT);
  pinMode(ButtonPin0, INPUT);
  Serial.print(78);
}

void loop() {
  // put your main code here, to run repeatedly:
  ButtonState2 = digitalRead(ButtonPin2);
  ButtonState1 = digitalRead(ButtonPin1);
  ButtonState0 = digitalRead(ButtonPin0);
  if (ButtonState2 == HIGH){
    digitalWrite(13, HIGH);
    }
    else{
      digitalWrite(13, LOW);
      }
}
```

body:
As per your statement, `wire from the positive to a row, with a wire leading from there to another row, back to ground`.

That describes a short circuit between V+ and ground.

Remove either the ground wire or the positive wire.


body:
You have your switch shorting both pin 1 and V+ to ground when you press the switch. Do *not* do that.

**The resistor you have isn't doing anything at all**. It isn't really a meaningful part of your circuit. It is in the middle of one of the rows of your breadboard. All the pins in the same side of one row of the breadboard are connected to each other.

In your breadboard, every row, from 1 to 30, is divided into columns a-e and columns f-j. All the pins a-e in a row are connected to each other, and all the columns f-j are connected to each other. You have one end of your resistor in row 7, column g, and the other end in row 7, column h. So the resistor is short-circuited by the breadboard, and doesn't serve any purpose.

It's as if both ends of your resistor are connected to different points on a wire. If you were to measure the resistance between the leads of that resistor as it's connected, you'd get zero ohms.

You need to rearrange your wiring so you have a wire coming from +5V to one row of your breadboard. Let's call that the +5V row. Have a 10K resistor with one lead into another pin in that row, and then put the other end of the resistor into another row. Let's call that the pull-up row. (It's weakly connected, through a 10K resistor, to +5V. Now plug your switch into that row, also. Finally, run a wire from the opposite side of the switch and into ground.

Make sure to configure the pin as an INPUT.

If you set it up as an OUTPUT, set it to HIGH, and close the switch, you'll short the pin output to ground, probably destroying that pin's output driver. **DON'T DO THAT.**

Now, when the switch is open, the pull-up resistor weakly connects the pin to +5V, so you get a HIGH signal. When you close the switch, it shorts the pin to ground, pulling the input LOW.

Note that you could skip the connections to +5V and set the pin to INPUT_PULLUP mode instead. INPUT_PULLUP mode connects the pin to +5V internally, through a high ohm resistor.


message:
PWM using timer3 for servo control won't generate any output

I'm making a program for a small robot arm controlled by four servos.
Problem: I need for PWM outputs, timer1 has three so i need to use timer3 for the last one

The main program and the timer1 outputs work great, the robot arm is functional. My problem is in the initialization of the PWM's. The PWM for timer1 is set to phase-correct, 64 pre-scaling and using WGM1[0-3] to 1010 so that i can use ICR1 as the top value, leaving OCR1[0-2] for counting up so output is on OCR[0-2].

According to the ATMEGA 2560 data book I should be able to initialize an identical PWM with timer3 with just one output in just the same way, but it just won't give me any output at all on OC3A.

Any help is greatly appreciated! :)

PS this is for a class project, so no servo libraries, and no major changes to the program (the current code is already approved by my professor, also the due date is in 24 hours so i don't have the time. Yes I know that sounds like trouble, but the project is technically done, I'd just really really like to get a full range of motion on my little Plexiglas robot)

PWM.c:

```c
// INITIALIZE PHASE CORRECT PWM ------------------------------------------------------------------------------
void initPWM()
{
 DDRB |= (1<<DDB7);  // Output pin 5 OC3A
 DDRB |= (1<<DDB5);  // Output pin 11 OC1A
 DDRB |= (1<<DDB6);  // Output pin 12 OC1B
 DDRB |= (1<<DDB7);  // Output pin 13 OC1C

 // Initialize TIMER1 for OC1A, OC1B, OC1C:
 TCCR1A |= (1<<COM1A1)|(1<<COM1B1)|(1<<COM1C1)|(1<<WGM11);     // Clear OCnA on compare match (non inverting mode), Phase correct ICRn top Mode
 TCCR1B |= (1<<WGM13)|(1<<CS11)|(1<<CS10);                     // Phase correct ICRn top Mode, Pre-scaling 64 for 50Hz signal
 // Initialize TIMER3 for OC3A
 TCCR3A |= (1<<COM3A1)|(1<<WGM31);        // Clear OCnA on compare match (non inverting mode), Phase correct ICRn top Mode
 TCCR3B |= (1<<WGM33)|(1<<CS31)|(1<<CS30);                     // Phase correct ICRn top Mode, Pre-scaling 64 for 50Hz signal

 // TIMER1 Top and bottom value:
 ICR1 = 5000;
 TCNT1 = 0;
 // TIMER3 Top and bottom value:
 ICR3 = 5000;
 TCNT3 = 0;

 // Start PWM in OCR = 200 (mid value for servo)
 OCR3A = 200;
 OCR1A = 200;
 OCR1B = 200;
 OCR1C = 200;

}
```

body:
I can see nothing wrong in your program except this:

```c++
DDRB |= (1<<DDB7);      // Output pin 5 OC3A
```

This is setting pin PB7 as an output, whereas
digital pin 5 (OC3A) is PE3.


message:
How to know my Arduino core version and its location on my Ubuntu laptop?

**Bakground:**

When compiling a demo project about e-paper, I got this problem
```
./GxEPD/src/GxIO/GxIO_SPI/GxIO_SPI.h:39:5: error: ‘SPISettings’ does not name a type
     SPISettings _spi_settings;
     ^
```
which on the Internet, people often say your Arduino core is not up-to-date and the one installed from
```
sudo apt install arduino-core
```
is ancient. And you have to install the latest version.

Regardless of whether this solves my original problem or not, I want to have the latest Arduino core on my  laptop.
From arduino.cc I grabbed a zipped file and ran `./install.sh` which did not provide enough results to know what it exactly did. Now, I am concerned that I have multiple installation in several places.

**Main question:**

When I run my make file and it is processed by `arduino-mk`, which version of `arduino-core` is it referred to and where is it located?

I am looking for a full proof method. I do not want to open somewhere from `/` directory accidentally. Because maybe this is not the `arduino-core` in use.

body:
The ancient version installed by apt lives in
`/usr/share/arduino/hardware/arduino/cores/arduino`.

If you download and unpack a recent version, it will stay wherever you
left it. For example, I have an Arduino core in
`/home/edgar/Downloads/arduino-1.8.10/hardware/arduino/avr/cores/arduino`.
The installation script doesn't really install those files. It does
install some icons and desktop shortcuts, but neither the core nor the
Arduino IDE. Instead, it assumes the downloaded package will stay
wherever it was when you ran the script.

If you want a somewhat cleaner installation, I suggest you move the
package to `/opt`, recursively chown it to root, and run the setup script
there. The core will then be in
`/opt/arduino-<version>/hardware/arduino/avr/cores/arduino`.