body:
My project is a head mouse for which I am using two arduino boards . I want to upload a specific program to a specific arduino. How can I do it? And if I need to use a pid or com port id about which the official arduino forum people suggested, how can I retrieve this id? I'm using an Arduino micro and a pro micro if it helps any.

 I need some suggestion on how to load the sketch to arduino through code without actually opening the arduino ide directly.Because it's a client project. And how can I make a specific program upload to the specific arduino one at a time. e.g. "a.ino" to arduino micro and "b.ino" to arduino pro micro. How should I identify the arduino boards through code.As for the OS, I am using Windows 10 64 bit.

title: How to fetch the com port or any id I can use to upload specific program to a specific arduino? e.g. "a.ino" to arduino micro

Answers: 0


body:
found this
http://www.zevendevelopment.com/relayexpander.html
I was looking to control 48 relays in sequential order with external controls for duration and frequency. How do I properly communicate to the boards? Sorry new to this setup.

title: Relay controller with IO expander

Answers: 0


body: I made a smart dustbin using arduino, servo motor, & ultrasonic sensor. It worked pretty well for a few number of days. But once I don't know how but the Arduino 'ON' light started to become dim and switched off. I used a 9V HW battery. So I decided to plug in my arduino with a 7V AC charger, still no luck, the arduino did not turn on nor the ON light. Then I plugged the arduino to my PC, the ON light turned on for 2 to 4 seconds and switched off. I realized it became too when I touched the usb port. The ATMEGA chip did not become hot. Please help?

title: Have I fried my arduino uno?

Answers: 1

body: If the USB chip is hot, you are out of luck.


body:
My idea is to modify a diesel injection system to increase the fueling into the engine.

The signal to an injector is a series of 0.1-1.5ms pulses. I would like to analyse the pulses and then send out my own pulse to extend some of the injection pulses. I want to do this all in real time.

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

Is this possible on an arduino? I have never used one before so I'd like to know if it is possible and what product would be suitable.

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

title: Extending pulses of a square wave signal

Answers: 1

body:
Yes, assuming the calculations are not that time consuming.

The Arduino is 16 MHz, so this is in the us scale which is way within limits. I don't know how critical the rise and fall times are, but even that should be possible.

You need some additional circuitry though, because the Arduino itself cannot handle 12V signals. For the input, you need so called level shifting (from 12 V to 5 V), see [A-Quick-Guide-on-Logic-Level-Shifting][1] for more explanation.

For the output, you need a 12 V signal (or use a voltage booster to 12V), and a transistor (and probably some resistors) that is connected to the Arduino for the signal and to the 12V and the diesel injection system for the 12V.

  [1]: https://www.instructables.com/id/A-Quick-Guide-on-Logic-Level-Shifting/


body:
I have problem with Arduino MEGA, Arduino Deu etc...  Those Development board are having separate MCU except main MCU... Why? For what purpose are they used for?

as FTDI or bootloader chip or protection for main MCU or  what other purpose?

I don't have an idea about that?

what are they called?

Please any one clarify me this?

title: About boot-loader ic used in DEV boards

Answers: 1

body:
There are two different reasons for a second MCU on a development board.

1) If the main MCU has a bootloader for serial upload, but doesn't include USB peripheral and the dev board should have for convenient development an USB port, then the board must include a USB-to-TTL-Serial adapter ('FTDI'). The adapter can be an FTDI USB chip, some other manufacturers USB chip (most common is CH340) or an MCU (with a USB peripheral) programed as USB-to-TTL-Serial with a firmware. Original Arduinos use ATmega 8u2 or 16u2 for this.

2) Some dev boards include a programmer for upload without bootloader. The programmer is a second MCU running a programmer firmware and is wired to programming pins of the main MCU. For example Arduino Zero, M0 Pro or Uno WiFi Rev 2, Nano Every have this concept.


body: how can I use tcrt5000 sensor module instead of TSOP31238 (TSOP1738) IR receiver to get signal from remote control? I want to create remote control for my PC to navigate through my slide shows. Thanks in advance.

title: How can I receive signal from remote control using tcrt5000 sensor module

Answers: 1

body:
The TCRT5000 and the TSOP31238 are very different. The TCRT5000 is actually a reflective distance sensor. It has an IR LED and a simple IR phototransistor, not more. The TSOP31238 in contrast is meant to receive data from IR remotes. IR remotes work with modulation of IR light. The IR LED is pulsed with a frequency of 38kHz (in the case of the TSOP31238). This frequency is modulated with the actual data, meaning there are different time lengths were there is no IR signal and where there is a 38kHz IR signal.

The TSOP31238 detects the IR light with a phototransistor, like the TCRT5000 has. But then the signal is processed with an amplifier, a band pass to filter out all frequencies but the 38kHz and then demodulated, so that you don't see the 38kHz signal on the output, but only the pulse lengths.

The demodulation should actually be the least complex part to build yourself. That can be even done by code. But to get good results, you also need the other parts. You would have to build an amplifier circuit with an opamp. And would have to build the bandpass (for example with an LC element).

You can build these things yourself, **but:** The sensor, that you have, is not meant for receiving IR remote signals. The parts, that you would need to make the signal usable, will cost way more, than just buying a TSOP. Also it will be a lot easier and most likely better working (processing the signal from a phototransistor can be tedious). I suggest, that you buy a TSOP chip fitting to your remote control.


body:
I have the following problem:

My arduino takes analogRead(A0) from a potentiometer whose position I can't adjust directly.

When analogRead(AO) goes to a value X,  I want pin 8 to go HIGH, this causes the circuit to open. and stop A0 getting higher . so I do an if statement:

    if(analogRead(AO)> X) {

    digitalWrite(pin, HIGH)  \\opens the circuit}

    else {
    digitalWrite(pin, LOW)  \close the circuit
     }

The issue I have here, is when then circuit is open,  I would like to change the value of the potentiometer (A0) which is controlled by a motor which is also in the circuit: but doesnt depend on the arduino board.  Given I can't control A(0) then the circuit will remain on A(0) >X forever.

The system going to LOW pin or close circuit, after it reaches HIGH pin for 2 seconds would be great, but then the program goes to the beginning and realizes that still A(0)> X , and goes back to a open circuit state, therefore not allowing me to have the close circuit anymore in order to make A(0) < X  and leave the circuit closed . Maybe something that cyclically turns pin on an off for t mseconds? but this is not ideal as it would cause high wear on the system

Edited the post to be more precise. I hope now its clearer
thanks

---

thank you for your answers, but after playing for a while with your codes, and the ideas behind it, still cannot get it to work.

for instance, Chrisl with your first:

 when potentiometer is at > X, It cuts the circuit which is good, but still doesn't go off until both potentiometer goes to < X and 3 seconds lapse , but this is not going to be possible to achieve anyways    because the value of the potentiometer is fixed on X

THis is what Id need-

if (PinState == HIGH)

after 3 seconds go low,

and not turn HIGH until at least these two conditions are met; analogRead has gone to < X and then analogRead > X ,and in that moment we are back at
PinState HIGH
is  even possible to achieve something like this?

the circuit is something like this:
<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/AZ3cX.png)

<!-- End schematic -->

 UPDATE:
I have using this code, which does almost what I want:
         if(analogRead(A0) > X) {
      unsigned long currentMillis = millis();

    if ((unsigned long)(currentMillis - previousMillis) >= interval) {

       pinState = !pinState;
       digitalWrite(pin, pinState)
       // save the "current" time
       previousMillis = millis();
    }}

When it gets to analogRead(A0)> X the problem of this code is that it switches the pin On and OFF continuosly,

 but instead of switching it off/on after the interval time , I want it to be LOW always. Of course as long as time  is more than interval,and not get to a HIGH, until It has gone back to  analogRead(A0)> X and time is less than interval. And repeat the process... When time is more than interval it will go from where it was digitalWrite(pin, HIGH) to the new state digitalWrite(pin, LOW)

I made this table to be more clear

Table: analogRead(A0) > X?

1-yes -->now check if time in this state is less than interval = 3000:

   1.1-YES, ---> digitalWrite(pin, HIGH)
   1.2- if no ( time is more than interval ) --->  digitalWrite(pin, LOW)

2-  No, analogRead(A0) < X . So -->  keep  digitalWrite(pin, LOW)

*NEW UPDATE:*

The state diagram for the new ranges should be something like this. I hope it is clear. I also removed the delays and replaced  (V < X ) for (V < Y )  , it works great. Thank you Edgar.

Z in the diagram being the variable for the new range, Z << X
[![enter image description here][1]][1]

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

**LAST UPDATE:**

Question Solved by Edgar Bonet

title: pin going high not allowing analog read to change

Answers: 3

body:
Using different threshold values to switch states - a higher threshold to go HIGH and a lower value to go LOW - is called hysteresis. It makes a dead-zone between the two switching values that prevents jitter, or flickering the LED in this case, that would happen with a single switch-point and the analog value was very close to it.

To do that, you just need the second clause of your `if` block, now an `else`, to become an `else if`. So it would look like this (in pseudo-code):

    if analog > 5,
       open the circuit;
    else if analog < 4
       close the circuit;
    // else must be >4 but <5, so do nothing.

> for 3 seconds I make circuit close ... when the system goes more than X again, it does the IF..else
> statement again

Update:

So instead of hysteresis, you want close the circuit for a fixed amount of time? Then try something more like this:

    if millis() - stop_time > 0 && analog > 5,
       save stop_time = (millis()+3000);
       open the circuit;
    end

body:
As I wrote in my comment, you can use `millis()` to solve your problem. First you should ditch the `else` statement, since you don't want the analog signal to turn the output of.

    unsigned long timestamp=0;
    unsigned long interval = 3000;

    void loop(){
        if(millis() - timestamp > interval){
            digitalWrite(pin, LOW);
            if(analogRead(A0) > X){
                timestamp = millis();
                digitalWrite(pin, HIGH);
            }
        }
    }

This code will check, if the time difference between now and the last activation is over 3s. If yes, it will first set the output to LOW. Then it checks, if the analog input is above X. If yes, the output will be set to HIGH and the timestamp will be set to the current time. On the next loop iteration the time difference will be lower than 3s (since we just set the timestamp to now). Thus nothing will change, keeping the output to HIGH for 3s. After that the output will be set to LOW and the code will be sensible to A0 again.

If you the output to just trigger once ever, you can use a simple flag.

    unsigned long timestamp=0;
    unsigned long interval = 3000;
    byte flag=1;

    void loop(){
        if(millis() - timestamp > interval){
            digitalWrite(pin, LOW);
            if(flag && analogRead(A0) > X){
                timestamp = millis();
                flag = 0;
                digitalWrite(pin, HIGH);
            }
        }
    }

The flag is initially set to 1, which actives the `analogRead()` part. Then it is set to zero, which deactivates it.

Note that this code is relatively simply and comes with some caveats, that might or might not matter to you:

- The code will not react to changes in the first 3 seconds after startup, since the timestamp is set to zero initially.
- After about 50 days runtime, the `millis()` counter will overflow. So, if the inner if statement doesn't get triggered for this long, the code will again not be able to react for 3s (until the time has run 3s after the timestamp).

body:
The description you give for the desired behavior is very unclear and
hard to follow. I am going to rephrase what I think I understood in
terms of a [finite state machine][FSM], which is the correct way of
describing this kind of systems. Please, review the description below,
as chances are I did not completely understand what you really want.

Let's say the system can be in any of these three states:

* In the `V_LOW` state, the input voltage is below the threshold `X` and
  the output is `LOW`. If the input raises above `X`, we set the output
  to `HIGH` and transition to the `V_HIGH` state.

* In the `V_HIGH` state, the input is above the threshold X and the
  output is `HIGH`. If the input falls below `X` we go back to the
  `V_LOW` state. If we remain in `V_HIGH` for three seconds, we switch
  the output to `LOW` and go to the `TIMEOUT` state.

* In the `TIMEOUT` state, the input is above the threshold, yet the
  output is `LOW`. When the input falls below `X` we go to the `V_LOW`
  state.

Below is a state graph for this machine. The states with a gray
background have the output `LOW`, whereas the state with a white
background has the output `HIGH`. Each possible transition is drawn as
an arrow, labeled by the condition that triggers the transition:

[![state graph][1]][1]

Is this the behavior you have in mind? If no, try to describe the
behavior you want in terms of a finite state machine, as I have done
here. If yes, then I suggest you follow chrisl's advice and implement
some hysteresis, by having different thresholds for going into and out
of `V_LOW`.

Anyhow, below is a translation of the FSM above in C++. It may not be
the most efficient way to write it, but I believe it is straightforward
enough to not require any additional explanation:

```c++
void update_output()
{
    static enum { V_LOW, V_HIGH, TIMEOUT } state;
    static uint32_t time_entered_v_high;
    int V = analogRead(A0);

    switch (state) {
    case V_LOW:
        if (V >= X) {
            digitalWrite(pin, HIGH);
            state = V_HIGH;
            time_entered_v_high = millis();
        }
        break;
    case V_HIGH:
        if (V < X) {
            digitalWrite(pin, LOW);
            state = V_LOW;
        } else if (millis() - time_entered_v_high >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V < X) {
            state = V_LOW;
        }
        break;
    }
}
```

[FSM]: https://majenko.co.uk/blog/finite-state-machine
[1]: https://i.stack.imgur.com/KuUA7.png

------------------------------------------------------------------------

**Edit 1**: Here is how to implement the hysteresis: you need to choose a
second, lower threshold, for going back to the state `V_LOW`. Let's call
it `Y`, which is smaller than `X`. Then, both on the diagram and the
code, replace every instance of “V < X” by “V < Y”. That's it. There is
absolutely _nothing_ more to change.

------------------------------------------------------------------------

**Edit 2**: Addressing the updated question. Now the output should go
`HIGH` when the input is out of a defined range. I'll add hysteresis
right away by using _four_ thresholds
V0 < V1 < V2 < V3:

* the input is _in range_ if it is within
  [V1, V2)

* the input is _out of range_ if it is _not_ within
  [V0, V3)

* the ranges [V0, V1)
  and [V2, V3) provide hysteresis.

Note that for consistency I like to have all the intervals closed on the
same side. I will also rename the states `V_LOW` and `V_HIGH` to
`IN_RANGE` and `OUT_OF_RANGE` respectively. Here is the updated code:

```c++
void update_output()
{
    static enum { IN_RANGE, OUT_OF_RANGE, TIMEOUT } state;
    static uint32_t time_exited_range;
    int V = analogRead(A0);

    switch (state) {
    case IN_RANGE:
        if (V < V0 || V >= V3) {
            digitalWrite(pin, HIGH);
            state = OUT_OF_RANGE;
            time_exited_range = millis();
        }
        break;
    case OUT_OF_RANGE:
        if (V >= V1 && V < V2) {
            digitalWrite(pin, LOW);
            state = IN_RANGE;
        } else if (millis() - time_exited_range >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V >= V1 && V < V2) {
            state = IN_RANGE;
        }
        break;
    }
}
```


body: I am making a simple heater with the help of ESP8266 wemos d1 mini. Heaters will use 12V DC power suply and ESP8266 must turn the heater on and off with the help of 5V DC relax. I want to avoid the use of anything else then ESP8366 and relay. I will need 2 such relays. So the question is, can i control 5V output on ESP8266 ? Or do i need to find a 3V DC relay and use that ? If the latter is the case, can i get some ebay link to 3V DC relay ?

title: Control 5V from ESP8266 Wemos D1 mini

Answers: 2

body:
Voltage is only part of what a relay uses.  Check the current requirements for the relay coil/input as well.

For example the common result for "3V relay arduino" will produce results for relay MODULEs that contain something akin to a SRD-03VDC-SL-C relay (labeled on the relay itself).  Spec for the RELAY (separate search by relay part no) yields a data sheet that says the coil resistance is 25 ohms for a 3V and would use 120 mA at that voltage (25 Ohm * .120A = 3).  Note if the same coil were run on 5V it would draw 200 mA (25 Ohm * .200A = 5V).

120 mA is bloody high to be coming from a logic pin which is why the MODULE has more than just the relay.  What the MODULE likely contains is an additional gate device that takes less current that then supplies the relay (with 120mA) from another port.

You might also be looking at a solid state relay that uses less input current but generally has some slight leakage when "Off"

body:
Do *NOT* try to drive a simple relay from an MMU like a ESP8266, Arduino, or Pi. That would likely destroy the digital pin on the MMU, and might destroy the whole processor.

You want a "digital relay module" which has a driver circuit to control the relay, plus some form of isolation to protect the digital pins.

A relay like this would be perfect: https://www.amazon.com/Icstation-3-3V-Optocoupler-Trigger-Development/dp/B01300ZY5M

Note that those come in 1, 2, 4, and 8 channel modules. Such a relay needs an external power supply, and your ESP8266 may or may not be able to provide enough current for the relay from its voltage regulator. Check the current requirements on the relay and the output specs on the ESP8266's voltage regulator.


body:
So I wondered what the difference between the nano and the nano every is and why the nano every is so much cheaper than the nano.

I'm new to the microcontroller business and I would like to know what would be better for what situation.

Answers: 1

body:
The classic Nano has ATmega 328p MCU, same as Uno. The 328p is classic AVR ATmega as used in Arduinos from the start and before in many AVR MCU projects for over 20 years now. There is large knowlege base for this MCUs, many ready codes in form of libraries, snippets, tutorials.

The Nano Every and Uno WiFi Rev 2 use a modern version of the AVR based MCU a so called megaAVR_0-series, an ATmega4809. It uses the same AVR CPU architecture in core of the MCU so the compiler is the same as for 328p and co., but the MCU peripherals configuration is very different then in the classic ATmegas. So the old knowledge base about AVR MCU peripherals doesn't help here.

The lower price is not related to manufacturing costs. The possible reasons are:

1. better price by MCU manufacturer at introduction of the new MCU family to market
2. higher price of classic Nano because it is popular and together with classic Uno founds Arduino as company
3. getting the new chip to Arduino power users to build up the knowledge and code base for the new MCU

To mention some more differences of classic Nano and Nano Every: Nano uses a bootloader for sketch upload and an external USB chip for USB communication. Nano Every doesn't use a bootloader, it has an on board UPDI programmer in form of a small SAMD MCU which serves as USB adapter for serial communication too.


body:
I am a new the world of Arduino. I found on YouTube, how to build a light controller [(https://www.youtube.com/watch?v=WvG9c84ApFA&t=39s).][1] I follow every step but it doesn't work. Here are some pictures and a rough schematic. (I don't have a Arduino, it is a Egeloo mega 2560)[enter link description here][1]

[![elegoo Arduino mega 2560 r3][2]][2]

[![shematic][3]][3]

[![board two][4]][4]

[![enter image description here][5]][5]

  [1]: https://www.youtube.com/watch?v=WvG9c84ApFA&t=39s.
  [2]: https://i.stack.imgur.com/ARyB8.jpg
  [3]: https://i.stack.imgur.com/JyYPn.jpg
  [4]: https://i.stack.imgur.com/zggRz.jpg
  [5]: https://i.stack.imgur.com/NtSMu.jpg

title: Made a light controller for the holidays

Answers: 0


body: How should I convert date format(dd-mm-yyyy) to timestamp value . Can anyone suggest code how to convert and where to put code .

title: how to convert date to timestamp?

Answers: 1

body:
It is good for you?

    struct tm tm;
    time_t fecha;
    if ( strptime(timestamp, "%Y-%m-%d %H:%M:%S", &tm) != NULL )
      fecha = mktime(&tm);
    else

    // Another thing


body:
Mega 2560

I am reading in values from 3 pots then mapping them to values between 0 - 255

    #define REDPIN   7
    #define GREENPIN 8
    #define BLUEPIN  9

    int red_pot   = A0;  // analog pin used to connect the potentiometer
    int green_pot = A1;
    int blue_pot  = A3;

    void setup() {

      pinMode(REDPIN,   OUTPUT);
      pinMode(GREENPIN, OUTPUT);
      pinMode(BLUEPIN,  OUTPUT);

      Serial.begin(38400); //Debug port
      Serial.setTimeout(50);
    }

    void loop() {

      int red, green, blue;

      red   = analogRead(red_pot);
      green = analogRead(green_pot);
      blue  = analogRead(blue_pot);

      Serial.print(" r = ");
      Serial.print(red);

      Serial.print(" b = ");
      Serial.print(blue);

      Serial.print(" g = ");
      Serial.print(green);
      Serial.print("\n\n\n");

      // map values
      red   = map(red,   20, 650, 0, 255);
      green = map(green, 20, 570, 0, 255);
      blue  = map(blue,  20, 570, 0, 255);

      Serial.print("red map : ");
      Serial.print(red);

      Serial.print(" green map : ");
      Serial.print(green);

      Serial.print(" blue map : ");
      Serial.print(blue);
      Serial.print('\n\n\n');

      analogWrite(REDPIN,   red);
      analogWrite(GREENPIN, green);
      analogWrite(BLUEPIN,  blue);
    }

`red` & `green` behave as expected but `blue` is not, from the serial monitor...

When blue is at its lowest value,

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

When blue is at its highest value,

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

I have changed `blue`'s analog pin assignment but the same issue.

Any clues what's happening?

**EDIT #1**

I thought it might be some `int` sign error so I changed the `map` operation to,

    blue  = map(abs(blue), 20, 670, 0, 255);

It made no difference.

  [1]: https://i.stack.imgur.com/WYylz.png
  [2]: https://i.stack.imgur.com/k0rFC.png

title: Mapping values from analog input giving unexpected values?

Answers: 1

body:
Note that the Arduino function "map" is really this:

    long map(long x, long in_min, long in_max, long out_min, long out_max) {
      return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
    }

...so, if you pass a "minimum from" value which is less than the actual value you are mapping from you will get a negative number given your "minimum out" is zero.

In several of your examples you have set the minimum to 20 but pass a value of 19.  If your program is intolerant of negative numbers (for instance, how would a negative number effect the PWM hardware), consider testing for lower than minimum and higher than maximum values before using the map function.


body:
I have been using Tinkercad's Circuits web application to create my Arduino circuits and apply my Arduino code (c++) for testing.

Despite the amazing product they have and the fact it's free, I find myself very disappointed at times.  Don't get me wrong, Tinkercad has a bunch of great products that I use all the time (like "3d Designs").  I just feel like "Circuits" needs work or maybe even a different dirrection.

I have been dealing with some of the following issues...

 1. **An extremely slow interface creating my circuit:**

    I have seen it do a bunch of random things that could use some TLC in the interface.  Sometimes objects get stuck and you have to disconnect them from everything before you can move them.  Sometimes using a breadboard, objects that seem connected to a pinhole does not make a connection and need to be connected to the breadboard using a wire.  There are a bunch of little quarks I see.  None are a show stopper and I can work around them but the slow interface makes me hate dealing with a web app.  It makes me really want a PC app instead.

 2. **The lack of support updating the Arduino compiler:**

    It's a very old version and they are not in a hurry to upgrade it.  I have contacted support a bunch about issues with the compiler not compiling code that works perfectly fine in the Arduino IDE.  Classes need to be defined in a specific way, enums need to be defined in an old way that makes the source look ugly etc.  Also, I have let them know when debugging it's about impossible to find out where your bug is because it does not tell you a line number it had a problem on.  It tries to highlight the line with little success in my tests.  I have suggested to them that maybe they could introduce a new option to choose the compiler version to use for each project this way old designs do not break etc.  I didn't get any feedback on the feedback I submitted.  So I guess that is a no go.

 3. **The simulation time:**

    This is the worst offender by far!  This is the main reason I want to look for different software to replace Tinkercad Circuits.  When simulating code on my circuit design the simulation runs in milliseconds (NOT real-time).  I have my code set to do something in 15 seconds.  Seems like it will happen in no time...  NOPE!  I have to wait about 15 minutes to see the results!!

So back to my original question...  Is there a PC application out there that does the same thing as Tinkercad Circuits?  I want to be able to design an Andrino circuit and then test code with it.

title: Are there any alternatives to Tinkercad Circuits that is PC application based instead of web app based?

Answers: 2

body: I'll try to find such PC app, but I can't find anyone. When I give up to find such app, I wrote my own arduino emulator via qt. My app is include arduino app and compile them as part of the qt app. Thank's to #ifdef macros i'm change the arduino.h . My emulator is not let you add scheme elements, but add you advantage to watch pin states and sets values to them. You can correct your project and emulate your own functions and algorithms. There it is https://github.com/ravenclawprog/arduino_mobil

body:
I work with the wokwi Arduino simulator

 - It is faster
 - It uses the latest Arduino IDE for compilation
 - It almost runs in real-time. For example, your job of 15 seconds might get executed at about the 17th or 20th second.

Please give it a try. here are some references
[![enter image description here][1]][1]

Links: https://wokwi.com and https://wokwi.com/arduino/libraries
[![enter image description here][2]][2]
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/1hDAq.png
  [2]: https://i.stack.imgur.com/YB1l6.png
  [3]: https://i.stack.imgur.com/HsqED.png


body:
Here is my sketch:
<!-- language-all: lang-cpp -->

    #include<ESP8266WiFi.h>

    char* ssid = "xxxxxxxx";
    char* pass = "xxxxxxx";

    void setup() {
     WiFi.begin(ssid,pass);
     Serial.begin(9600);
     while(WiFi.status()!=WL_CONNECTED)
     {
      Serial.print(".");
      delay(500);
      }
      Serial.println("");
      Serial.print("IP Address: ");
      Serial.print(WiFi.localIP());
    }

Here is the error:

    Traceback (most recent call last):   File "C:\Users\ASUS\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2/tools/upload.py", line 25, in <module>
        esptool.main(fakeargs)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 2653, in main
        esp.connect(args.before)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 460, in connect
        last_error = self._connect_attempt(mode=mode, esp32r0_delay=False)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 440, in _connect_attempt
        self.sync()   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 379, in sync
        timeout=SYNC_TIMEOUT)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 322, in command
        self.write(pkt)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 285, in write
        self._port.write(buf)   File "C:/Users/ASUS/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/pyserial\serial\serialwin32.py", line 323, in write
        raise writeTimeoutError serial.serialutil.SerialTimeoutException: Write timeout the selected serial port
    serial.serialutil.SerialTimeoutException: Write timeout  does not
    exist or your board is not connected

title: Error when compiling code NODE MCU ESP8266-12E module in Arduino ide

Answers: 1

body:
The section

    void loop() {
    }

Is missing in the code, add it and recompile and.....


body:
It's been days now I'm trying to figure out how arrays work in Arduino IDE.
For better understanding, I assembled some pieces of code I found here and there to write this sketch:
<!-- language-all: lang-cpp -->

    #define arrayLength(x) (sizeof(x) / sizeof(int)) //array size

    typedef struct {
      int note;
      int duration;
    } BUZZER_NOTE ;

    class Buzzer {

      public:

        BUZZER_NOTE notes[];  //-- Funny how the same declaration tried below DOES work if it's inside a class

    };

    void setup() {

      Serial.begin(9600);

    //  BUZZER_NOTE notes[];  //-- Compilation error:

      int *bob;               //-- Declaring this way, shows no compilation errors, but prints out strange values
    //  int bob[];            //-- Compilation error: "storage size of 'bob' isn't known"

      int bob1[] = {10, 20};
      int bob2[5] = {10, 20, 30, 40, 50};
      int bob3[] = {60, 70, 80};

      bob[0] = 10;
      bob[1] = 20;
      bob[2] = 30;
      bob[3] = 40;
      bob[4] = 50;
      bob[5] = 60;
      bob[6] = 70;   //-- No matter how many indexes I create, it will always show lenght of 2

      test(1);       //-- Calls the first function below, as expected
      test({1});     //-- Also calls the first function below, when the second one (with the array parameter) is expected

      test(bob);     //-- Length: 1 (expected 5); Size: 2 (?????) ; First Element: 163 (expected 10);
      test(bob1);    //-- Length: 1 (expected 2); Size: 2 (?????) ; First Element: 10  (ok);
      test(bob2);    //-- Length: 1 (expected 5); Size: 2 (?????) ; First Element: 10  (ok);
      test(bob3);    //-- Length: 1 (expected 3); Size: 2 (?????) ; First Element: 60  (ok);

    }

    void loop() {
    }

    void test(int a) {
      Serial.println("Called int function");
      Serial.println();
    }

    void test(int a[]) {
      Serial.println("Called array function");
      Serial.print("Length: ");
      Serial.println(arrayLength(a));
      Serial.print("Size: ");
      Serial.println(sizeof(a));
      Serial.print("First Element: ");
      Serial.println(a[0]);
      Serial.println();
    }

The code above prints out these lines:

    Called int function    // as expected

    Called int function    // expected array function

    Called array function  // as expected
    Length: 1              // expected 5
    Size: 2
    First Element: 163     // expected 10

    Called array function  // as expected
    Length: 1              // expected 5
    Size: 2
    First Element: 10      // as expected

    Called array function  // as expected
    Length: 1              // expected 3
    Size: 2
    First Element: 10      // as expected

    Called array function  // as expected
    Length: 1              // expected 5
    Size: 2
    First Element: 60      // as expected

My goal for now is to achieve something like this:

    int bob[]; // this gives a compiler error: "storage size of 'bob' isn't known"
    bob = {10, 20, 30, 40};

    test(bob);

    void test(int arr[]) {
      for (int i = 0; i < FIND_ARR_LENGTH_SOMEHOW; i++) {
        Serial.print("Index i: ");
        Serial.println(arr[i]);
    }

Question: How can I declare an array without mention its size, fill it up with as many indexes I want, then pass it to a function that will be able to process all the contents?

I know I could declare an array and keep its length to pass as a second parameter, but there must be a way to get an array length.

Thanks in advance.

title: How do arrays work?

Answers: 4

body:
>     BUZZER_NOTE notes[];  //-- Funny how the same declaration tried below DOES work if it's inside a class

It doesn't really. C++ language prohibits that. It is just a non-standard quirk of GCC compiler used by Arduino IDE, which happens to support C-style [*flexible array members*][1] in C++ code.

>     //  BUZZER_NOTE notes[];  //-- Compilation error:

Of course. You are not allowed to use *incomplete types* in object definitions. And an array of unspecified size is an incomplete type. A widely used exception from this rule is an `[]` array declared with an *initializer*. In that case the array size is assumed to be implicitly specified by the initializer.

>     int *bob;               //-- Declaring this way, shows no compilation errors, but prints out strange values

Of course. This is not an array at all. It is a pointer. And it doesn't point anywhere. It is invalid. You are not allowed to even access such pointer.

>     //  int bob[];            //-- Compilation error: "storage size of 'bob' isn't known"

See above.

>      int bob1[] = {10, 20};
>      int bob2[5] = {10, 20, 30, 40, 50};
>      int bob3[] = {60, 70, 80};

These are properly declared arrays. As I said above, the `[]` declaration is allowed since you are declaring your array with an initializer.

>     bob[6] = 70;   //-- No matter how many indexes I create, it will always show lenght of 2

This does not make any sense at all. You cannot "create indexes" in an array. Array size is fixed at the point of declaration. There's no way to shrink or expand it, there's no way to "create" or "remove" indexes.

But in this example `bob` is not even an array. It is a pointer. And since it is a garbage pointer that doesn't point anywhere, you are not allowed to access it with *any* indexes.

Once you make your `bob` to point to some valid block of memory, you will be able to access it as `bob[3]` and such, as long as you stay withing the bounds of that block of memory.

>     test({1});     //-- Also calls the first function below, when the second one (with the array parameter) is expected

Several mistakes here.

Firstly, you second function does not have "array parameter". In parameter declarations `int a[]` is equivalent to `int *a`. It is a *pointer* parameter, not an array parameter.

Secondly, since the beginning of times in C and C++ you could use a scalar value in `{}` to initialize a scalar object

    int a = { 42 }; /* <- this has always been legal in C and C++ */

So, the first function is obviously a candidate in this case. The rules of C++ language dictate that `{1}` initializer can be used as an initializer for an `int` value or `std::initializer_list<int>` object, but for a pointer. Which is why the first function is called.

You can force it to produce a temporary array through array-type alias and functional-cast syntax

    using ARR = int[];
    test(ARR{1});

but in GCC you will run into a GCC bug preventing you from forming pointers and references to temporary arrays (Clang will accept it).

>     void test(int a[]) {
>       ...
>       Serial.print("Length: ");
>       Serial.println(arrayLength(a));

This makes no sense. This "array length" trick

    #define arrayLength(x) (sizeof(x) / sizeof(int))

only works with *arrays*. Your `a` inside `test` is not an array. It is a pointer. It is completely pointless to apply this `sizeof` trick to a pointer.

> My goal for now is to achieve something like this:
>
>     int bob[]; // this gives a compiler error: "storage size of 'bob' isn't known"
>     bob = {10, 20, 30, 40};

Not possible. When defining an array, you always have to specify a fixed compile-time size. And arrays in C and C++ are not copyable, not assignable. If you want to copy data between arrays, you have to either do it manually, element by element, or use a library-provided routine that does the same.

`{}`- initializers can be used with arrays, but only at the point of declaration. Not later. You can do something like

    using A = int[5];
    A a;
    std::memcpy(a, A{1, 2, 3, 4, 5}, sizeof(A));

but this will run into the same GCC bug I mentioned above.

On a related note: standard library provides `std::array` template - a thin wrapper for raw arrays. `std::array` objects are copyable and assignable through a pretty much the same syntax as you used

    std::array<int, 5> a;
    a = { 1, 2, 3, 4, 5 };

But they are still arrays of fixed compile-time size.

>     void test(int arr[]) {
>       for (int i = 0; i < FIND_ARR_LENGTH_SOMEHOW; i++) {

Not possible. Your `arr` is a pointer. It is not possible to extract "array size" information for a pointer, since that information simply does not exist. If you want to "FIND_ARR_LENGTH_SOMEHOW" you have to either develop your own convention for finding that length or simply pass that length to the function through a separate parameter.

  [1]: https://stackoverflow.com/questions/3047530/flexible-array-member-in-c-structure

body:
This is more of a general programming question, but since there are some special pitfalls for microcontrollers/Arduinos I will answer the question.

> How can I declare an array without mention its size, fill it up with as many indexes I want, then pass it to a function that will be able to process all the contents?

Short answer: You cannot. An array has always a fixed size, that cannot be changed during the lifetime of the array.

Long answer: Though every array has it's fixed size, you can create new arrays with a size, that is not known at compilation time. For this you would need dynamic memory allocation like done with the `new` keyword:

    BUZZER_NOTE *notes = new BUZZER_NOTE[x];

with the size of the new array `x`. `notes` is here a pointer to the array (actually a pointer to the first element of the array). If you don't know, how to deal correctly with pointers, you should google for a tutorial about it, there are plenty on the web. So, if your defined array is full and you want to add more elements, you have to define a new array with bigger size, copy the old content and delete the old one (actually that is what happens inside the `String` class).

To actually get the easy way of adding more elements, without copying the whole content, a C++ programmer would use a linked list. This defines an element class, that contains a variable for the content of the element and a pointer to the next element in the list. So to iterate through the linked list, you would start at the first element and follow the pointers through the list to the end. (Again you can read more about this concept on the web)

**BUT:** You should not use any of these things on an Arduino, especially not on the ones with very limited RAM (like Uno, Nano, ...). When you do dynamic memory allocation, memory fragmentation will happen. Take the example from above. You have a dynamically allocated array with your data. Now you want to store more data. You define a new and bigger array. For the simplicity of explanation, it will be allocated directly after the first array in the memory. You copy the content and delete the first array to free the memory. Now there is free space in your memory with the size of the first array. Now you want to again add more data, so you define a new and bigger array. This array cannot fit into the free space at the start, since the space to not big enough. This memory space is now dead, because it cannot be used for your data.

In real cases, you would allocate and delete variables with varying sizes throughout your sketch. This leads to the point, that you will get many holes in your memory, which are too small to fit your data in. On a PC this is not a big problem, since you have a lot of RAM and the OS can reorganize the data to fit better. But on the Arduino you have only very limited RAM and no OS, so you quickly run out of RAM. Your sketch will stop to work at that point, since there is no usable memory left on the device.

You instead should go the harder way and just use fixed arrays, that are big enough to hold the biggest amount of data, that you expect.

---

And since AnT didn't cover this completely:

    bob[6] = 70;

This line cannot work correctly for 2 reasons: First you only declared `bob` as a pointer, but this pointer does not point to a valid memory address. You would have to create a corresponding array with the `new` keyword as shown above, or let it point to an existing array. Currently you try to write to an invalid or random memory address.

Secondly the compiler cannot know, how many items the array has, that `bob` should point to. This is just not an information, that the compiler has. So it will not prevent you from writing higher indices, than are in the array. But effectively the memory write either fails, because the address of the non-existent element is invalid, or you will overwrite data from some other variables --> Very dangerous! It is your responsibility to ensure, that you don't write data, where it does not belong.

And keep in mind, that microcontrollers don't have something like exceptions. Thus some things, that would through an exception on a PC will stop the microcontroller from working, or it will just do the crazy stuff, that you told him to do (where accessing memory outside of the array would through a runtime error on the PC).

body:
The C arrays are tricky and they're described in every C tutorial. The other answers adresses mistakes / questions in comments, but none of them shows how it can be done:
<!-- language-all: lang-cpp -->

    struct BuzzNote {
      int note;
      int duration;
    };

    const BuzzNote melody[] = {
      {10, 200}, { 45, 300}, {90, 200}, // ...
    };

    void test(BuzzNote const * arr, size_t len) {
      for (size_t i = 0; i < len; ++i) {
        Serial.print(i);
        Serial.print(". ");
        Serial.print(arr[i].note);
        Serial.print(' ');
        Serial.println(arr[i].duration);
      }
    }

    // using template for determining size of array
    // (and as a bonus it won't work with plain pointers)
    template<typename T, size_t size>
    size_t GetArrLength(T(&)[size]){return size;}

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

    void loop() {
      test(melody, GetArrLength(melody));
      delay(10000);
    }

I'm using template version of getting array length (it won't compile with pointers, as pointer isn't array).

And this version stores data in RAM (and waste it). If you don't have spare space in ram, you'll have to dig into PROGMEM variables/arrays. But it's the quest for another day :D

body:
Ok, after reading and reading the answers and links about my question, I ended up using a function as suggested. Something like:

    void foo(char* myArray, int size) {}

But I ended up finding another solution to the problem, which is a little more complicated:

    #define arrayLen(x) (sizeof(x) / sizeof(x[0]))

    char myArray[64] = "my array test with a long value in it";

    void setup() {

      Serial.begin(9600);
      while (!Serial);

      // IMHO, it would be nice if the compiler would accept these two sintaxes
    //  myArray = "my array test with a long value in it";
    //  "my array test with a long value in it".toCharArray(myArray, 64);

      Serial.print("Value before: ");
      Serial.println(myArray);
      Serial.print("Size before: ");
      Serial.println(arrayLen(myArray));

      String temp;
      temp = myArray;

      foo(temp);

      Serial.print("Value after: ");
      Serial.println(myArray);
      Serial.print("Size after: ");
      Serial.println(arrayLen(myArray));

    }

    void loop() {}

    void foo(String str) {
      for (int i = 0; i < str.length(); i++) {
        Serial.print("Index ");
        Serial.print(i);
        Serial.print(": ");
        Serial.println(str.charAt(i));
      }
    }

I know I have a bad habit to use Strings instead of array of chars (coming from other languages), but in this example, memory limitation issues won't be significant because the String will be freed from memory after execution of setup() and foo().

There is another thing I would like to share (not directly related to my previous question), that I believe could be useful for other people.
This little sketch shows how to use the same String technique to manipulate the contents of a char array, passed by reference to an external function. Here it goes:

    #define arrayLen(x) (sizeof(x) / sizeof(x[0]))

    char myArray[64] = "my array test with a long value in it";

    void setup() {

      Serial.begin(9600);
      while (!Serial);

      Serial.print("Value before: ");
      Serial.println(myArray);
      Serial.print("Size before: ");
      Serial.println(arrayLen(myArray));

      String temp;
      temp = myArray;

      foo(temp);
      temp.toCharArray(myArray, 64);

      Serial.print("Value after: ");
      Serial.println(myArray);
      Serial.print("Size after: ");
      Serial.println(arrayLen(myArray));

    }

    void loop() {}

    void foo(String &str) {
      str = "abcde";
    }

Results (just as expected):

    Value before: my array test with a long value in it
    Size before: 64
    Value after: abcde
    Size after: 64

It may look awful to the eyes of a C++ programmer, but hey, it works!

Thanks again for all the answers/comments.


body:
I am reasonably new to arduino and even newer to Processing so still struggle with trouble shooting my code.

The intention of my sketch is have Processing receive IR codes from the arduino and execute different AppleScript applications accordingly.

It works sometimes! However I would really love it to work all the time :)

-The AppleScript apps definitely work and have been successfully launched

-The processing monitor has been printing the 'Val' variable consistently

The issue is that even though processing is reading from the serial port and assigning the IR codes printed there to the 'val' variable, it only sometimes executes the conditional

I added a delay to my arduino sketch to slow down how much data was entering the port and make it easier for Processing to read but it's inconsistent.

Any help would be greatly appreciated!

Arduino code:

```
#include <boarddefs.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include <IRremote.h>
#include <IRremoteInt.h>

int RECV_PIN = 10;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  Serial.begin(9600);
  Serial.print("Hello");
  irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
  if (irrecv.decode(&results))
    {
     Serial.println(String(results.value,HEX));
     delay(100);
     irrecv.resume(); // Receive the next value
    }
}

```

Processing Code

```
import processing.serial.*;

Serial myPort;  // Create object from Serial class
String val;     // Data received from the serial port
String Down = "890";
String Up = "8188A2C8";
String CH1 = "E10";
void setup()
{
  // I know that the first port in the serial list on my mac
  // is Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  {
  if ( myPort.available() > 0)
  {  // If data is available,
  val = myPort.readString();         // read it and store it in val

   print(val);

    if(val.equals(Down) == true)
    {launch("/Applications/QlabDown.app");
  }
  if (val.equals(Up) == true) {
    launch("/Applications/QlabUp.app");
  }
  if (val.equals(CH1) == true) {
    launch("/Applications/CH1.app");
  }
}
}
}
```

title: Arduino and Processing- Conditionals only executing sometimes in response to IR codes

Answers: 0


body:
I'm working on a project aimed on sending alerts via SMS. I signed up for a SMS service that works via HTTP requests (REST standard). I need, then, to send data as JSON, so that their server processes the data and sends the SMS message to a list of recipients.

I am working with an ESP8266 board. I have tried some code, but I couldn't do the JSON part properly, given I have little knowledge on HTTP requests and HTTP libraries for Arduino. I managed to test things using python code (with which I am much more familiar).

In short, I have this piece of code in python that works quite perfectly:
```python
payload = {'sender': '558499999999','content': 'Just a message', 'groupName': 'Recipients_list'}
request = requests.post('https://cheap.sms.sending.guys/sendcontactmessage',
       data=json.dumps(payload),
       headers={'content-type': 'application/json', 'auth-key': 'My_authentication_key'})
```
I tried to write something that does the same thing on a ESP8266, but it is not working and I can't figure the correct way to do it. The code I tried was the following:
```
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

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

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

  //TESTING JSON CREATION
  Serial.println("Starting JSON");
  StaticJsonBuffer<69> jsonBuffer;
  char json[] = "{\"sender\":\"558499999999\",\"content\":\"Just a message\",\"groupName\":\"Recipients_list\"}";
  JsonObject& root = jsonBuffer.parseObject(json);
  if(!root.success()) {
    Serial.println("parseObject() failed");
  } else {
    Serial.println("JSON OK");
  }

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print("Connecting... ");
  }

  //TESTING POST
  //headers={'content-type': 'application/json', 'auth-key': 'My_authentication_key'}
  String sms_service_URL = "https://cheap.sms.sending.guys/sendcontactmessage";

  Serial.println("TESTING POST");
  //Declare an object of class HTTPClient
  HTTPClient http;

  if (WiFi.status() == WL_CONNECTED) {
    //Specify request destination
    http.begin(sms_service_URL);
    http.addHeader("Content-Type", "application/json");
    http.addHeader("auth-key", "My_authentication_key");

    String data;
    root.printTo(data);
    //Send the request
    int httpCode = http.POST(data);

    //Check the returning code
    if (httpCode > 0) {
      //Get the request response payload
      String payload = http.getString();
      //Print the response payload
      Serial.println(payload);
    }
    //Close connection
    http.end();
    Serial.println(httpCode);
  }
}

void loop() {

}

```
I am aware that the arduino code is pretty lame. I was just in a trial-failure process, lol.

I'd appreciate any suggestions

title: How to send JSON on a http POST request using an ESP8266?

Answers: 0


body:
I am planning to build an rc car based on arduino uno. I will use 3S 11.1 V Li-po to power whole circuitry. So my question is;

First, can arduino be powered directly with 11.1V from its Vin pin? Would it be a problem or not? If it is OK, then no need to answer the bold part below.

**If it is not, then one solution comes to my mind is to use a voltage regulator which will convert 11.1 V to 5 V. But while choosing a regulator, I saw that max output current is one of the important specs. So what is the minimum amount of current needed to run Arduino UNO?**

title: How much current needed to power arduino uno?

Answers: 1

body:
The maximum voltage at the Vin pin is 12V, so using your battery is fine!

Considering the current consumption:
The arduino itself will usually source less than 200mA, but your whole setup will probably sink more than that.


body:
I would like to run my esp32 on coin cell batteries, tho it needs at minimum 3v, that means if there just is too much resistance in the vires or anything else, stuff like Bluetooth will make it brownout,

So what is the best way to step up 3v to 3.5v?

title: 3v to 3.5v step up?

Answers: 3

body:
Generally, to step up voltages you can use a boost converter.
But I doubt that using coin cells to supply an esp32 is a good idea, because they probably won't last very long and are relatively expensive. Even if you use sleep modes, the voltage margin will be small (of course, that depends on the boost converter).

body: Why not use *three* button cells and a buck converter to lower the voltage from 4.5V down to 3V?

body:
To be honest you are better off stepping *down* rather than stepping *up*. Simply because step down converters tend to be a higher efficiency and can deliver more current than a step up converter.

With step up converters you effectively convert current into voltage. With step down it's the other way around - voltage into current.  Since button cells have very very little current capacity stepping up will reduce it even more and starve the ESP32 of power. By stepping down you increase the current.

Two 3V button cells in series will provide nominal 6V and about 40mA current. By adding a step down converter to 3.3V you are almost halving the voltage, but at the same time almost doubling the current.  Adding a third cell in series will give you even more current output.

It is possible to get some incredibly tiny and high efficiency step-down modules. I myself [make and sell one](https://www.ebay.co.uk/itm/183933078163) based around the TPS82130SILT which has the ability to run at as low as 3.7V with a 3.3V output (it has a "pass through" mode which allows a zero dropout voltage, but I include a protection diode with 0.4v drop). That means you get the entire 6V to 3.7V range out of your batteries before the voltage starts to droop (assuming the batteries still operate at 1.85V).


body:
This is a bit of a newbie question, but here it goes anyway. So basically I want to send a keystroke using the DigiKeyboard library, but with shift held down. I looked through the code and saw this comment in scancode-ascii-table.h:

```
//Format: most signifficant bit indicates if scan code should be sent with shift modifier
remaining 7 bits are to be used as scan code number.
```

I dont really understand where to specify this, whether it's when you call the sendKeyStroke function, or somewhere in the code. Help appreciated.

title: How to send keystroke with shift modifier?

Answers: 1

body:
I never used this library, but in the header file there are this constants for modifiers:

    #define MOD_CONTROL_LEFT    (1<<0)
    #define MOD_SHIFT_LEFT      (1<<1)
    #define MOD_ALT_LEFT        (1<<2)
    #define MOD_GUI_LEFT        (1<<3)
    #define MOD_CONTROL_RIGHT   (1<<4)
    #define MOD_SHIFT_RIGHT     (1<<5)
    #define MOD_ALT_RIGHT       (1<<6)
    #define MOD_GUI_RIGHT       (1<<7)

and a function

    void sendKeyStroke(byte keyStroke, byte modifiers)

so I would use this to send a key with Shift like this

    sendKeyStroke(KEY_F2, MOD_SHIFT_LEFT);


body:
    #include <Keypad.h>

    #include<LiquidCrystal.h>

    #include<EEPROM.h>

    LiquidCrystal liquid_crystal_display(9,8,7,6,5,4,);

    char password[4];

    char initial_password[4],new_password[4];

    int i=0;

    int relay_pin = 10;

    char key_pressed=0;

    const byte rows = 4;

    const byte columns = 4;

    char hexaKeys[rows][columns] = {

    {'1','2','3','A'},

    {'4','5','6','B'},

    {'7','8','9','C'},

    {'*','0','#','D'}

    };

    byte row_pins[rows] = {A0,A1,A2,A3};

    byte column_pins[columns] = {A4,A5,3,2};

    Keypad keypad_key = Keypad( makeKeymap(hexaKeys), row_pins, column_pins, rows, columns);

    void setup()

    {

      pinMode(relay_pin, OUTPUT);

      liquid_crystal_display.begin(16,2);

      liquid_crystal_display.print(" DIYhacking.com");

      liquid_crystal_display.setCursor(0,1);

      liquid_crystal_display.print("Electronic Lock ");

      delay(2000);

      liquid_crystal_display.clear();

      liquid_crystal_display.print("Enter Password");

      liquid_crystal_display.setCursor(0,1);

      initialpassword();

    }

    void loop()

    {

      digitalWrite(relay_pin, HIGH);

      key_pressed = keypad_key.getKey();

      if(key_pressed=='#')

        change();

      if (key_pressed)

      {

        password[i++]=key_pressed;

        liquid_crystal_display.print(key_pressed);

          }

      if(i==4)

      {

        delay(200);

        for(int j=0;j<4;j++)

          initial_password[j]=EEPROM.read(j);

        if(!(strncmp(password, initial_password,4)))

        {

          liquid_crystal_display.clear();

          liquid_crystal_display.print("Pass Accepted");

          digitalWrite(relay_pin, LOW);

          delay(2000);

          liquid_crystal_display.setCursor(0,1);

          liquid_crystal_display.print("Pres # to change");

          delay(2000);

          liquid_crystal_display.clear();

          liquid_crystal_display.print("Enter Password:");

          liquid_crystal_display.setCursor(0,1);

          i=0;

        }

        else

        {

          digitalWrite(relay_pin, HIGH);

          liquid_crystal_display.clear();

          liquid_crystal_display.print("Wrong Password");

          liquid_crystal_display.setCursor(0,1);

          liquid_crystal_display.print("Pres # to Change");

          delay(2000);

          liquid_crystal_display.clear();

          liquid_crystal_display.print("Enter Password");

          liquid_crystal_display.setCursor(0,1);

          i=0;

        }

      }

    }

    void change()

    {

      int j=0;

      liquid_crystal_display.clear();

      liquid_crystal_display.print("Current Password");

      liquid_crystal_display.setCursor(0,1);

      while(j<4)

      {

        char key=keypad_key.getKey();

        if(key)

        {

          new_password[j++]=key;

          liquid_crystal_display.print(key);

        }

        key=0;

      }

      delay(500);

      if((strncmp(new_password, initial_password, 4)))

      {

        liquid_crystal_display.clear();

        liquid_crystal_display.print("Wrong Password");

        liquid_crystal_display.setCursor(0,1);

        liquid_crystal_display.print("Try Again");

        delay(1000);

      }

      else

      {

        j=0;

        liquid_crystal_display.clear();

        liquid_crystal_display.print("New Password:");

        liquid_crystal_display.setCursor(0,1);

        while(j<4)

        {

          char key=keypad_key.getKey();

          if(key)

          {

            initial_password[j]=key;

            liquid_crystal_display.print(key);

            EEPROM.write(j,key);

            j++;

          }

        }

        liquid_crystal_display.print("Pass Changed");

        delay(1000);

      }

      liquid_crystal_display.clear();

      liquid_crystal_display.print("Enter Password");

      liquid_crystal_display.setCursor(0,1);

      key_pressed=0;

    }

    void initialpassword(){

      for(int j=0;j<4;j++)

        EEPROM.write(j, j+49);

      for(int j=0;j<4;j++)

        initial_password[j]=EEPROM.read(j);

    }

title: I get the following error when I typed the below code. " Stray'\302" in the programme .I tried to sort it but failed

Answers: 0


body:
I'm not sure this is the right site, but I've spent several hours trying to figure out why I suddenly cannot upload to my Leonardo (actually, a "Pro Micro" with a 32u4) after upgrading to macOS Catalina.

Initially I thought the board was just dead, but I can program it without issues from a Windows machine. I also worked just fine with it a few days ago, before the update to Catalina. Now I'm getting this output:

    Arduino: 1.8.10 (Mac OS X), Board: "Arduino Leonardo"

    Sketch uses 10226 bytes (35%) of program storage space. Maximum is 28672 bytes.
    Global variables use 1000 bytes (39%) of dynamic memory, leaving 1560 bytes for local variables. Maximum is 2560 bytes.

    avrdude: ser_recv(): read error: Device not configured
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: ser_drain(): read error: Device not configured
    avrdude: ser_send(): write error: Device not configured
    avrdude: ser_recv(): read error: Device not configured
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: ser_send(): write error: Device not configured
    avrdude: ser_recv(): read error: Device not configured
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: ser_recv(): read error: Device not configured
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: ser_send(): write error: Device not configured
    avrdude: ser_recv(): read error: Device not configured
    avrdude: butterfly_recv(): programmer is not responding
    Found programmer: Id = ""; type = �
    Software Version = .�; Hardware Version = �.�
    avrdude: ser_send(): write error: Device not configured
    avrdude: ser_recv(): read error: Device not configured
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: ser_send(): write error: Device not configured
    avrdude: ser_recv(): read error: Device not configured
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: buffered memory access not supported. Maybe it isn't
    a butterfly/AVR109 but a AVR910 device?
    avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

    avrdude: ser_send(): write error: Device not configured
    avrdude: ser_recv(): read error: Device not configured
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: programmer did not respond to command: leave prog mode
    avrdude: ser_send(): write error: Device not configured
    avrdude: ser_recv(): read error: Device not configured
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: programmer did not respond to command: exit bootloader
    avrdude: ser_close(): can't reset attributes for device: Device not configured
    the selected serial port avrdude: ser_close(): can't reset attributes for device: Device not configured
    does not exist or your board is not connected

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

My Mega2560 as well as Due work just fine. I even tried re-burning the bootloader into the Pro Micro using the Mega, which worked fine but didn't solve the issue.

I also tried getting into the bootloader mode, by tapping the reset (actually, using a wire to pull RST to GND) button twice. It changes the error to

    Found programmer: Id = ">>> SPI"; type = SSoftware Version = >.>;
    Hardware Version = >.
    avrdude: error: buffered memory access not supported.
    Maybe it isn't a butterfly/AVR109 but a AVR910 device?
    avrdude: initialization failed, rc=-1
    Double check connections and try again, or use -F to override this check.

The bootloader trick is not required on Windows, it just works.

title: Cannot upload to Leonardo after update to macOS Catalina

Answers: 0


body:
I'm reading the voltage with voltage divider:

![schematic](https://i.stack.imgur.com/WqACt.png)

 | *Arduino is connected to both USB and a 9V adapter.*

    float r1 = 100000;
    float r2 = 9980;
    float adc, voltage, analog;
    void setup() {
      Serial.begin(9600);
      analogReference(EXTERNAL);
      pinMode(A0, INPUT);
    }

    void loop() {
      for (int i = 0; i < 256; ++i) {
        analog += analogRead(A0);
      }
      analog = analog / 256;
      adc = analog * 1.228 / 1023;
      voltage = adc / (r2 / (r1 + r2));
      Serial.print(analogRead(A0));
      Serial.print(", ");
      Serial.print(analog);
      Serial.print(", ");
      Serial.print(adc);
      Serial.print(", ");
      Serial.print(voltage);
      Serial.println(" ");
      delay(100);
    }

Here's the accuracy test result:

    Input | Arduino | Difference
     1V      0.89V     -110mV
     2V      1.90V     -100mV
     3V      2.92V     -80mV
     4V      3.93V     -70mV
     5V      4.95V     -50mV
     6V      5.97V     -30mV
     7V      6.98V     -20mV
     8V      8.00      0
     9V      9.01      +10mV
     10V     10.02     +20mV
     11V     11.04     +40mV
     12V     12.06     +60mV

*The input voltages measured by DMM and was spot on voltage, like 1.000V.*

I didn't test voltages above 12V but it seems the difference is gonna increase by 20mV with each 1V increase, that means at 50V voltage reading is gonna be off by ~1V!

Even with 10bit resolution of Arduino I should have had steady accuracy with some percentage of difference(right?), but as you can see the result shows that the reading is not steady at all!

Why the voltage difference decrease/increase when voltage changes at the input?

title: Arduino 10bit ADC is not accurate?

Answers: 2

body:
Yes, you are right that the Arduino ADC is not accurate.  If you read the datasheet ([ATMega328P](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf) section 28.9, ADC Characteristics) you can see a lot of "error" and "non-linearity" characteristics.

These all add up to inaccuracies in your readings.  For example the "Offset error" at your VREF could be as much as ±4.4mV, and the "Gain error" the same. Non-linearity can be as bad as 2mV, etc.

The Arduino ADC is not meant to be accurate. It's meant to be simple and cheap to implement. (It is a "Successive Approximation ADC" - approximation here is the keyword...) If you want a higher accuracy then there are more suitable ADC chips available that give that accuracy.

body:
As stated by Majenko, the ADC can _in principle_ have all sorts of
errors. However, if you look at your data, you should notice that the
error is essentially linear with the voltage. This means that the
non-linearity error is quite small, and you are mainly seeing the offset
and gain errors. This is fortunate, because these errors are easy to
remove, given good calibration data.

The table you wrote in in your question happens to be a perfectly good
calibration table. By fitting a straight line to it you can get a
calibration function, and then correct the readings simply by adding
this to your code:

```c++
voltage = 0.9848815 * voltage + 0.125354;
```

Or you could instead figure out the correction at the ADC level and
replace
```c++
adc = analog * 1.228 / 1023;
```
by
```c++
adc = (analog + offset) / scale;
```
where `offset` and `scale` are computed from the calibration.

------------------------------------------------------------------------

**Edit**: Here is how I extracted the calibration coefficients from the
data.

First, I saved the data in a text file calibration.tsv and cleaned it up
to remove the units and add a comment marker (#) in front of the column
labels:
```text
#Input | Arduino | Difference
 1      0.89     -110e-3
 2      1.90     -100e-3
...
```

Then I looked at the data with [gnuplot][]. Since I want to know how to
correct the readings, I plot the amount I have to add (minus column 3)
v.s. the Arduino reading (column 2):
```gnuplot
plot 'calibration.tsv' using 2:(-$3)
```
At this point it appears it's linear with what looks like mostly
quantization noise. I model this as a line of equation `a*x+b`, and
compare the line with the data:
```gnuplot
a = -1e-2
b = 0.12
plot 'calibration.tsv' using 2:(-$3), a*x+b
```

The line is quite off the data, but it's a reasonable first
approximation. Now I ask gnuplot to perform a least squares fit, then
take another look:
```gnuplot
fit a*x+b 'calibration.tsv' using 2:(-$3) via a, b
replot
```

Now the fit looks quite good. When it completed the fit, gnuplot
displayed:
```text
Final set of parameters            Asymptotic Standard Error
=======================            ==========================
a               = -0.0151185       +/- 0.0002953    (1.953%)
b               = 0.125354         +/- 0.002173     (1.734%)
```
so now I know I can correct the data with:
```c++
voltage += -0.0151185 * volatage + 0.125354;
```
which is equivalent to what I wrote above.

[gnuplot]: http://gnuplot.info/


body:
I have a project which essentially involves WiFi, a web server, and an LED. I'm using the Inbuilt LED on my ESP8266 for testing at the moment. I am using the Arduino IDE for programming.

I had a problem where my code would crash after connecting to WiFi. By commenting out functions in my loop, I narrowed down the crash problem to my function that handles the LED. Here I ran into a problem, commenting out each block of code individually, and even a few at once, I wasn't able to prevent the crash. There must be more than one line causing the crash. Commenting out the entire function was the only thing that worked.

After hours of troubleshooting, I was left at the stage where I had the contents of all the if statements and loops and such commented out.
Here is what left me utterly confused. Here is the if statement:

    if(webSocketActive){
        Serial.println("websocket is active, setting brightness");
        analogWrite(LED_BUILTIN, 1024 - lightBrightnessAdjust);
    } else {
        //other stuff with more if-statements that are empty
    }

At this point, if I comment out the analogWrite line, the program works fine. But if I leave it like this, it crashes after connecting to WiFi. (I didn't post my entire program because it is over 1000 lines long).

The baffling part about all this is, webSocketActive is never set to true prior to this point in the code... The Serial.println() never does anything, meaning the ESP definitely doesn't execute the instructions inside the if statement. But, for some inexplicable reason, simply having the analogWrite() uncommented crashes the program, even if it never executes that line.

I've also had other issues where putting some sort of Serial.print() function in the loop to repeatedly run somehow doesn't make the code crash. Could someone let me know what is going on?

title: Unused lines of code causing program to crash

Answers: 3

body:
I think I might know the problem (maybe you've fixed it after two weeks) but your ```analogWrite(Pin, Val)```might end up being out of range, remember that analogWrite only takes an int of 0 to 255 therefore if your ```lightBrightnessAdjust``` variable is lower than 769 then we will get an int above the accepted input range of analogWrite().

I know the code never actually runs but it still compiles and maybe Arduino doesn't like even a possible error.

Maybe I didn't explain it very well but [here](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/)'s the Arduino documentation for it.

Another possible solution could be perhaps you could try defining ```int amount = 1024-lightBrightnessAdjust;``` variable beforehand and then entering the variable into analogRead because it could be fussy about doing math inside the function params (just a thought)

body:
 - Overwriting an array could clobber that functions return address.
 - Allocating from the heap, enough memory for the up-growing heap and the down-growing stack to collide, could cause or create the conditions for clobbering function-local data, function return-return address, or heap data, including the heap meta-data required to de-allocate that heap-block.
 - Writing through an uninitialized or overwritten pointer can cause about any memory corruption you can imagine; and the result can be data dependent and/or data-memory map dependent, and quite possibly non-repeatable.
 - Clobbering the interrupt vector of an enabled interrupt can cause improperly jumping into any part of your code, and is *quite likely* to be unrepeatable.

There's too much we don't know about the unseen rest of your code to do much more than speculate on possible points-of-failure.

body: Turns out that the MDNS.begin() in setup and the MDNS.update() in the loop was, presumable, causing some sort of undefined behaviour, since the code didn't always crash. I commented out these two lines, and the code works fine now, minus the MDNS.


body:
I am controlling some LEDs via the USB serial port using a Tkinter/Python3x script to debug what I suspect is a hardware problem.

    from tkinter import *
    import serial

    usbport = 'COM3'
    ser = serial.Serial(usbport, 9600, timeout=1)

    def init():
        print("Started")

    class App:

        def __init__(self, master):

            frame = Frame(master)
            frame.pack()
            self.scale1 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(1), bd=5, bigincrement=2, length=360, width=30, label='RED')
            self.scale1.set(128)
            self.scale1.pack(side=LEFT)
            self.scale2 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(2), bd=5, bigincrement=2, length=360, width=30, label='GREEN')
            self.scale2.set(128)
            self.scale2.pack(side=LEFT)
            self.scale3 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(3), bd=5, bigincrement=2, length=360, width=30, label='BLUE')
            self.scale3.set(128)
            self.scale3.pack(side=LEFT)
            self.centre = Button(frame, text="Centre All", command=self.centre)
            self.centre.pack(side=TOP)

        def getBright(self, slider):

            if slider==1:
                brt = self.scale1.get()

            if slider==2:
                brt = self.scale2.get()

            if slider==3:
                brt = self.scale3.get()

            ser.write(255)
            ser.write(slider)
            ser.write(brt)

        def centre(self):

            for LED in range(0, 4):

                ser.write(255)
                ser.write(LED)
                ser.write(128)

            self.scale1.set(128)
            self.scale2.set(128)
            self.scale3.set(128)

    init()
    root = Tk()
    app = App(root)
    root.mainloop()

On the Arduino Mega 2560 side I read in from serial a start byte, LED label & a brightness value...

    int user_input[3];
    int start_byte;
    int LED;           // which LED to pulse? r=1 g=2 b=3
    int brightness;
    int i;

    // LED pins
    #define REDPIN 7
    #define GREENPIN 8
    #define BLUEPIN 9

    void setup()
    {

      // LED outputs
      pinMode(REDPIN, OUTPUT);
      pinMode(GREENPIN, OUTPUT);
      pinMode(BLUEPIN, OUTPUT);

      Serial.begin(9600);
    }

    void loop()
    {
      if (Serial.available() > 2) {

        start_byte = Serial.read();
        if (start_byte == 255) {

          for (i = 0; i < 2 ; i++) {
            user_input[i] = Serial.read();
          }

          LED = userInput[0];
          brightness = user_input[1];

          switch (LED) {

            case 1:
              analogWrite(REDPIN, brightness);
              break;

            case 2:
              analogWrite(GREENPIN, brightness);
              break;

            case 3:
              analogWrite(BLUEPIN, brightness);
              break;

          }
        }
      }
    }

Now I would like to see what is actually being sent via the serial port to the Arduino using the serial monitor (yes I know I can just print the values in the Python terminal that's not what I'm asking).

The problem is that the Arduino Serial Monitor is locked out. I'm guessing this is a Windows thing (Win10 x64)? Has anybody here come across this?

title: Serial monitor when port is being used by another application

Answers: 1

body:
Serial data can only go to one place at a time. Either your Python program can receive the data, or the Serial Monitor can receive the data. Similarly the serial port can only receive data from one place at a time.

So Windows prevents you doing something invalid by locking you out of the serial port when something else is using it.

This is normal, and entirely desired functionality.

Your simplest option is to just print what you receive in your Python program.


body:
I have a nextion display. I want to implement this issue of it. Start the program. If for example I don't touch the display for 15seconds, it should to turn off its brightness. If I touch the screen on any point, it should to increase its brightness.

For this I m build this code:

In PreinitializeEvent of page 0, I have insert this code:

    tm0.tim=0
    tm0.en=1
    dim=30

In Touch Release Event of page 0, I have insert this code:

    dims=100

But if I try to start the program, the brightness is always the same. Not increase.

/EDIT

I use Nextion Edito 0.58
[![enter image description here][1]][1]

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

title: Increase or decrease the brightness of Nextion display

Answers: 1

body:
*The original question has been improved (which is appreciated) to include the IDE which the poster is using.  In this stackexchange.com space we primarily concern our selves with answering questions about developing using the Arduino IDE. While the Nextion Editor looks interesting, some may consider it off topic.*

*For those who come here interested in controlling the brightness of their Nextion Display and are using the Arduino IDE, there is this answer:*

There appears to be several Nextion Arduino Library efforts to choose from.  If you are using [this Nextion Display Library][1], [here is the example code][2] which set the screen brightness.  The part of the code which sets the screen brightness is rather simple and resides in the Arduino loop() function.  In the loop() function the brightness is set repeatedly as the program continues to run:

    void loop() {
      int brightness = analogRead(A0);
      int bright = map(brightness, 0, 1024, 0, 100);
      String dim = "dim=" + String(bright);
      myNextion.sendCommand(dim.c_str());

    }

*For those of you using the [Nextion editor][3] and the [Nextion Arduino Libraries][4], there is [this github.com Issue][5] which talks about adding multiple missing Nextion features including a screen brightness function. This issues appears to still be OPEN (Bad support? / Bad house-keeping?). But is over a year old so may have be incorporated.  If so, here is the example code from that link:*

    /**
    * Set the brightness of the display.
    *
    * @param buffer - number (0 - 100).
    */
    bool setBrightness(byte buffer);

  [1]: https://github.com/bborncr/nextion
  [2]: https://github.com/bborncr/nextion/blob/master/examples/DimScreen/DimScreen.ino
  [3]: https://nextion.tech/nextion-editor-ver-0-58/
  [4]: https://github.com/itead/ITEADLIB_Arduino_Nextion
  [5]: https://github.com/itead/ITEADLIB_Arduino_Nextion/issues/43


body: I am currently using I2C serial communications with arduino as slave and raspberry pi as the master. I am sending sensor data from arduino to raspberry pi. I need to reset the I2C connection once the sensor readings cross a threshold. I tried setting the TWCR =0 but it throws a Error 121 Remote I/O error on the raspberry pi when I do that. I also read that one way is to set TWCR =0, but for this I need to execute the Wire.begin(), Wire.onRequest(), and Wire.onReceive() again. Can you please tell me how to run these again since they are put in setup function. Does it mean I need to restart the Arduino program again? Or can I put these in void loop()? Thanks for the help.

title: Reset I2C connection with arduino as slave

Answers: 1

body:
You have a misconception about how I2C works. Unlike Serial (UART) I2C is a strictly master-slave interface. The slave cannot do anything without the master, since only the master controls the clock. Thus you don't need to reset the I2C interface to stop the transmission from the slave to the master.

When the master requests data from the slave the following happens: First the master sends the address of the targeted slave, including the direction bit set for "reading from slave". The slave with this address reacts with an acknowledgement (ACK) and start to transmit one byte. This byte get's acknowledged by the master. When the master decides, that it has received enough data, it does not acknowledge (NACK), which let's the slave stop it's transmission. Then the master sends a STOP condition to stop the I2C transmission.

I don't know, how you implemented the I2C communication on the Pi. Normally, when you initiate a read transaction from the master, you provide a number of bytes, that you want to request from the slave. The I2C module/library will then request data from the slave, until is has received all the requested bytes.

Thus you don't need to reset the I2C connection on the Arduino. The master totally controls the communication. When you end the transmission on the master, the slave cannot send further data.

Setting TWCR to zero in the middle of transaction will disrupt the I2C communication protocol. Thus you get an error on the Pi, that states an error in the I2C communication protocol. Just use the correct implementation of the I2C protocol to end the transmission correctly.


body:
I'm very new to Arduino and especially the forum so please let me know if I am on the wrong topic or anything.

Anyways let me get straight to the point. I am working on a school project where I need to create a robot head that can move and talk using the Arduino Uno. I have the speech files as a .wav and from what I gathered you need an sd card reader connected to the Uno to read .wav files. So I purchased the Arduino MKR Zero, but after I got the board I realized that it is a standalone board, not a file reader for the Uno. This project is due next week so I need to figure out how to make the MKR Zero read the files and play them off the speakers but have it timed and programmed off the Uno. Is this possible with the hardware I have?

Here is a picture of my setup:
[![enter image description here][1]][1]

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

title: Getting an Arduino Uno and MKR zero to communicate

Answers: 1

body:
Let the MKR Zero play the wav files. It has DAC on A0 and [AudioZero library][1] to play wav files from SD card.

You can use Serial communication to command the Zero from Uno. In Uno use hardware Serial or create SoftwareSerial to send commands to Serial1 of MKR Zero. You can then test the MKR first with commands sent from Serial Monitor.

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


body:
I recently designed a PCB to hold an Arduino Nano, IMU and other components. I'm using this platform as the fly computer of a homemade drone. This is one of my first PCB designs and I'm not an expert, so perhaps I'm missing something obvious here.

Now let us get to the problem. I started by testing each component, the Arduino (CPU), CPU + IMU, CPU + HC-05, **CPU + HC-05 + RTX(RC receiver)**. At this last point, the Arduino stopped responding, the RX TX and POW LEDs stay ON all the time. I can't upload new software to it.

I noticed that the ATmega328 was extremely hot! I tried powering the Arduino from the +5V and same result (LEDs stuck ON).

During testing, I had a 3SLiPo battery connected to the PW(top right) of the PCB, and the Arduino was also connected to my PC through the USB port.

Do you see any issues with the PCB design itself?

List of the components tested:

 - [Arduino NANO][1]
 - [HC-05][2]
 - [FlySky receiver][3]
 - R1 1k
 - R2 2K
 - C1 10uF

[![PCB][4]][4]

Thanks.

  [1]: https://www.amazon.co.uk/gp/product/B072BMYZ18/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1
  [2]: https://www.amazon.co.uk/gp/product/B01G9KSAF6/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1
  [3]: https://uk.banggood.com/Flysky-2_4G-6CH-FS-iA6B-Receiver-PPM-Output-With-iBus-Port-p-978603.html?gmcCountry=GB&currency=GBP&createTmp=1&utm_source=googleshopping&utm_medium=cpc_bgcs&utm_content=garman&utm_campaign=pla-gbg-rm-all-purchase-pc&ad_id=323612825005&gclid=Cj0KCQjw84XtBRDWARIsAAU1aM1AM1Ph1Cm8yNHLWvU-pMwuvPlnXu8sYHjvopMMNbMzBF3utqVHO5EaAprFEALw_wcB&cur_warehouse=UK
  [4]: https://i.stack.imgur.com/nghCT.png

title: Why did it blow up?

Answers: 0


body:
I have an Arduino Uno board and a SparkFun ccs811 sensor. I tried to reproduce the howto from the SparkFun homepage ([https://learn.sparkfun.com/tutorials/ccs811-air-quality-breakout-hookup-guide?_ga=2.45231532.967238096.1560976781-258902726.1560976781][1]), including the error states part.

I uploaded one picture of the wiring (updated). I also tried to use an alternative hardware connection with SDA to A4 and SCL to A5, as mentioned in the code comments (see homepage).

However, it is just not working, and I always get this error code in the serial monitor `beginCore exited with: I2C_ERROR`

Here is my code (without the top comment block):

    #include <Wire.h>

    #include "SparkFunCCS811.h" //Click here to get the library: http://librarymanager/All#SparkFun_CCS811

    #define CCS811_ADDR 0x5B //Default I2C Address
    //#define CCS811_ADDR 0x5A //Alternate I2C Address

    CCS811 mySensor(CCS811_ADDR);

    void setup()
    {
    Serial.begin(9600);
    Serial.println("CCS811 Basic Example");

    Wire.begin(); //Inialize I2C Harware

    //It is recommended to check return status on .begin(), but it is not
    //required.
    CCS811Core::status returnCode = mySensor.begin();
    Serial.print("beginCore exited with: ");
    switch ( returnCode )
    {
    case CCS811Core::SENSOR_SUCCESS:
     Serial.println("SUCCESS");
     break;
    case CCS811Core::SENSOR_ID_ERROR:
     Serial.println("ID_ERROR");
     break;
    case CCS811Core::SENSOR_I2C_ERROR:
     Serial.println("I2C_ERROR");
     break;
    case CCS811Core::SENSOR_INTERNAL_ERROR:
     Serial.println("INTERNAL_ERROR");
     break;
    case CCS811Core::SENSOR_GENERIC_ERROR:
     Serial.println("GENERIC_ERROR");
     break;
    default:[enter image description here][2]
     Serial.println("Unspecified error.");
    }

    if (returnCode != CCS811Core::SENSOR_SUCCESS)
    {
    Serial.println(".begin() returned with an error.");
    while (1); //Hang if there was a problem.
    }
    }

    void loop()
    {
    //Check to see if data is ready with .dataAvailable()
    if (mySensor.dataAvailable())
    {
    //If so, have the sensor read and calculate the results.
    //Get them later
    mySensor.readAlgorithmResults();

    Serial.print("CO2[");
    //Returns calculated CO2 reading
    Serial.print(mySensor.getCO2());
    Serial.print("] tVOC[");
    //Returns calculated TVOC reading
    Serial.print(mySensor.getTVOC());
    Serial.print("] millis[");
    //Simply the time since program start
    Serial.print(millis());
    Serial.print("]");
    Serial.println();
    }

    delay(10); //Don't spam the I2C bus
    }

[![enter image description here][3]][3]

  [1]: https://learn.sparkfun.com/tutorials/ccs811-air-quality-breakout-hookup-guide?_ga=2.45231532.967238096.1560976781-258902726.1560976781
  [3]: https://i.stack.imgur.com/2EpDK.jpg

title: Sparkfun CCS811 Air Quality Sensor is just not working

Answers: 1

body: You need to solder those headers to the breakout. Just inserting them into the plated-through-holes doesn't give a reliable connection.


body:
I have a Arduino MKR Zero set up with a sd card in it and a speaker hooked up to the ground and DAC0. I have a .wav file on it called "test.wav" and it is 8 bit mono 88200hz recording. I am using the AudioZero example to try to play this audio file off the speaker but it is not working. When I upload and run the code and open the Serial Monitor to check to see if it has any errors or sucesses reading the files it is just blank. It uploads the code all fine, but the Serial Monitor says nothing at all and the speaker doesnt play anything. Did I set it up wrong somehow?

Here is the code that it is running:
```/*
  Simple Audio Player for Arduino Zero

 Demonstrates the use of the Audio library for the Arduino Zero

 Hardware required :
 * Arduino shield with a SD card on CS4
 * A sound file named "test.wav" in the root directory of the SD card
 * An audio amplifier to connect to the DAC0 and ground
 * A speaker to connect to the audio amplifier

 Arturo Guadalupi <a.guadalupi@arduino.cc>
 Angelo Scialabba <a.scialabba@arduino.cc>
 Claudio Indellicati <c.indellicati@arduino.cc>

 This example code is in the public domain

 http://arduino.cc/en/Tutorial/SimpleAudioPlayerZero

*/

#include <SD.h>
#include <SPI.h>
#include <AudioZero.h>

void setup()
{
  // debug output at 115200 baud
  Serial.begin(115200);

  // setup SD-card
  Serial.print("Initializing SD card...");
  if (!SD.begin(SDCARD_SS_PIN)) {
    Serial.println(" failed!");
    return;
  }
  Serial.println(" done.");
  // hi-speed SPI transfers
  SPI.setClockDivider(4);

  // 88200 sample rate
  AudioZero.begin(2*44100);
}

void loop()
{
  int count = 0;

  // open wave file from sdcard
  File myFile = SD.open("test.wav");
  if (!myFile) {
    // if the file didn't open, print an error and stop
    Serial.println("error opening test.wav");
    while (true);
  }

  Serial.print("Playing");

  // until the file is not finished
  AudioZero.play(myFile);
  AudioZero.end();

  Serial.println("End of file. Thank you for listening!");
  while (true) ;
}

title: Audio Zero not responding on MKR Zero

Answers: 1

body: To use the Serial monitor with Arduino MKRZERO, use SerialUSB instead of Serial, i.e. SerialUSB.println("something");


body:
I am having a compilation error saying invalid useof template-name 'Timer without an argument list.

![arduino code ](https://i.stack.imgur.com/Qog93.png)

title: Trying to create a delay function whilst performing other functions, using Timer.h libraries. Arduino uno

Answers: 1

body:
Read, play with, and understand the Arduino **BlinkWithoutDelay** basic example.
*Understand* means learn that it does not only apply to blinking, but to any time related action without blocking the main loop().

It's better learning the basics than using libraries in a wrong way.


body:
I'm trying to upload the sketch on a Mega 2560 via the serial port 0 using another microcontroller.

To better undestand the process, I decided to first observe what avrdude is doing while it is uploading a hex file. To do this, I'm using another arduino (ESP32) with the following sketch:

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

    void loop()
    {
     while (Serial2.available()) {
      Serial.print(Serial2.read(), HEX);
      Serial.print(":");
     }
    }
ESP32's `Serial`(`serial0`) is connected to PC via USB, and Serial2 is connected to Mega's `Serial`(`serial0`), the one connected to PC via USB, used by avrdude.
[![enter image description here][1]][1]
According to [this][2] answer the first things avrdude is sending over the serial interface are:

    STK_GET_SYNC / CRC_EOP  (0x30/0x20)

But this is not what I receive through ESP32:

    1B:1:0:1:E:1:14:1B:2:0:C:E:10:C8:64:19:20:0:53:3:AC:53:0:0:31:1B:3:0:8:E:1D:4:4:0:30:0:0:0:33:1B:4:0:8:E:1D:4:4:0:30:0:1:0:35:1B:5:0:8:E:1D:4:4:0:30:0:2:0:37:1B:6:0:8:E:1D:4:4:0:50:0:0:0:56:1B:7:0:8:E:1D:4:4:0:50:0:0:0:57:1B:8:0:8:E:1D:4:4:0:50:0:0:0:58:1B:9:0:8:E:1D:4:4:0:58:8:0:0:59:1B:A:0:8:E:1D:4:4:0:58:8:0:0:5A:1B:B:0:8:E:1D:4:4:0:58:8:0:0:5B:1B:C:0:8:E:1D:4:4:0:50:8:0:0:54:1B:D:0:8:E:1D:4:4:0:50:8:0:0:55:1B:E:0:8:E:1D:4:4:0:50:8:0:0:56:1B:F:0:5:E:6:80:0:0:0:99:1B:10:1:A:E:13:1:0:C1:A:40:4C:20:0:0:71:C0:0:0:81:C0:0:0:7F:C0:0:0:7D:C0:0:0:7B:C0:0:0:79:C0:0:0:77:C0:0:0:75:C0:0:0:73:C0:0:0:71:C0:0:0:6F:C0:0:0:6D:C0:0:0:6B:C0:0:0:69:C0:0:0:67:C0:0:0:65:C0:0:0:63:C0:0:0:61:C0:0:0:5F:C0:0:0:5D:C0:0:0:5B:C0:0:0:59:C0:0:0:57:C0:0:0:56:C0:0:0:53:C0:0:0:51:C0:0:0:4F:C0:0:0:4D:C0:0:0:4B:C0:0:0:49:C0:0:0:47:C0:0:0:45:C0:0:0:43:C0:0:0:41:C0:0:0:3F:C0:0:0:3D:C0:0:0:3B:C0:0:0:39:C0:0:0:37:C0:0:0:35:C0:0:0:33:C0:0:0:31:C0:0:0:2F:C0:0:0:2D:C0:0:0:2B:C0:0:0:29:C0:0:0:27:C0:0:0:25:C0:0:0:23:C0:0:0:21:C0:0:0:1F:C0:0:0:1D:C0:0:0:1B:C0:0:0:19:C0:0:0:17:C0:0:0:15:C0:0:0:13:C0:0:0:11:24:1F:BE:CF:EF:D1:E2:DE:BF:CD:BF:0:E0:C:BF:22:E0:A0:E0:B2:E0:1:C0:1D:92:A9:30:19:1B:11:0:5:E:6:80:0:0:80:7:1B:12:1:A:E:13:1:0:C1:A:40:4C:20:0:0:B2:7:E1:F7:4C:D0:C2:C0:7B:CF:1F:92:F:92:F:B6:F:92:11:24:2F:93:3F:93:8F:93:9F:93:AF:93:BF:93:80:91:5:2:90:91:6:2:A0:91:7:2:B0:91:8:2:30:91:4:2:23:E0:23:F:2D:37:20:F4:1:96:A1:1D:B1:1D:5:C0:26:E8:23:F:2:96:A1:1D:B1:1D:20:93:4:2:80:93:5:2:90:93:6:2:A0:93:7:2:B0:93:8:2:80:91:0:2:90:91:1:2:A0:91:2:2:B0:91:3:2:1:96:A1:1D:B1:1D:80:93:0:2:90:93:1:2:A0:93:2:2:B0:93:3:2:BF:91:AF:91:9F:91:8F:91:3F:91:2F:91:F:90:F:BE:F:90:1F:90:18:95:78:94:84:B5:82:60:84:BD:84:B5:81:60:84:BD:85:B5:82:60:85:BD:85:B5:81:60:85:BD:80:91:6E:0:81:60:80:93:6E:0:10:92:81:0:80:91:81:0:82:60:80:93:81:0:80:91:81:0:81:60:80:93:81:0:80:91:80:0:81:60:80:93:80:0:80:91:B1:0:84:60:80:93:B1:0:80:91:B0:0:81:60:1B:13:0:5:E:6:80:0:1:0:84:1B:14:1:A:E:13:1:0:C1:A:40:4C:20:0:0:91:0:80:91:91:0:81:60:80:93:91:0:80:91:90:0:81:60:80:93:90:0:80:91:A1:0:82:60:80:93:A1:0:80:91:A1:0:81:60:80:93:A1:0:80:91:A0:0:81:60:80:93:A0:0:80:91:21:1:82:60:80:93:21:1:80:91:21:1:81:60:80:93:21:1:80:91:20:1:81:7A:0:80:91:7A:0:81:60:80:93:7A:0:80:91:7A:0:80:68:80:93:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:1B:15:0:8:E:1D:4:4:0:50:0:0:0:45:1B:16:0:8:E:1D:4:4:0:50:0:0:0:46:1B:17:0:8:E:1D:4:4:0:50:0:0:0:47:1B:18:0:8:E:1D:4:4:0:58:8:0:0:48:1B:19:0:8:E:1D:4:4:0:58:8:0:0:49:1B:1A:0:8:E:1D:4:4:0:58:8:0:0:4A:1B:1B:0:8:E:1D:4:4:0:50:8:0:0:43:1B:1C:0:8:E:1D:4:4:0:50:8:0:0:44:1B:1D:0:8:E:1D:4:4:0:50:8:0:0:45:1B:1E:0:3:E:11:1:1:19:

I can't find 30:20 anywhere. What am I missing?

The baud rate is 115200 everywhere which I believe is the right one. The link is good because if I send char 'A' from PC over the serial connected to Mega, I get `41:` via ESP32 on the other side, which is correct.

  [1]: https://i.stack.imgur.com/vYyfA.jpg
  [2]: https://arduino.stackexchange.com/a/15937/59845

title: Monitor serial0 while code is being uploaded

Answers: 0


body:
I am having a behavior I cannot explain while using arduino mega as a I2C slave for a raspberry pi master.

I am showing here an idealised program that shows the issue. I experience pretty much the same behavior in the real application (a keyboard firmware). What I am doing is the following:

- the arduino issues an interrupt on pin 23 at evert loop to inform the raspi that there's some data to be read.
- the raspi sends a request as master to the arduino.
- arduino receives the request in the Wire handler, and issues a reply of 32 bytes. I fill these 32 bytes with a uint8 counter just as a check.
- the cycle starts again.

This is the code for the raspi

```
import time
import RPi.GPIO as GPIO
import smbus

GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

bus = smbus.SMBus(1)
address = 0x42

def callback(channel):
    data = bus.read_i2c_block_data(address, 0x00, 32)
    print(data)

GPIO.add_event_detect(4, GPIO.RISING, callback=callback)

while True:
    time.sleep(1)

GPIO.cleanup()
```

and this is the code of the arduino

```
#include <Wire.h>

byte IRQ_PIN = 23;

volatile unsigned int counter;

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

    pinMode(IRQ_PIN, OUTPUT);
    digitalWrite(IRQ_PIN, LOW);
    Wire.begin(0x42);
    Wire.onRequest(requestEvent);
    Wire.onReceive(receiveData);

}

void signalMaster() {
  noInterrupts();
  irq();
  interrupts();
}

void irq() {
  digitalWrite(IRQ_PIN, HIGH);
  digitalWrite(IRQ_PIN, LOW);
}

void requestEvent() {
  byte buf[32];
  counter++;
  memset(buf, counter, 32*sizeof(byte));
  Wire.write(buf, 32);
}

void receiveData(int byteCount){
  while(Wire.available()) {
    Wire.read();
  }
}

void loop() {
  signalMaster();
  delay(1);
}
```

As you can see, the point is that I am banging the I2C really, really fast, and the loop is very tight and fast. This is the point of the exercise and the problem to solve arises from this.

Now, once in a while I get an occasional IO error with the raspi python code. This code occasionally fails once, and then everything resumes to normal, but once in a while, it completely breaks down and never recover.

I attached a logic analyser to it, and this is what I found. D3 is the interrupt pin. The others the I2C bus. In a normal transaction, I can see everything working properly (disregard the different content of the response, it was an earlier run)

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

and a zoom in to the master request and the reply:

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

When I have a permanent failure, however, the picture is very different

[![enter image description here][3]][3]

Zoom in:

[![enter image description here][4]][4]

This makes little sense to me. Why would it perform a data write, and who is writing 0x85FF... in my buffer?

Thanks

  [1]: https://i.stack.imgur.com/xsC9y.png
  [2]: https://i.stack.imgur.com/9nlUA.png
  [3]: https://i.stack.imgur.com/fE2vQ.png
  [4]: https://i.stack.imgur.com/Fzd9k.png

title: I2C communication between arduino and raspberry pi breaks under stress for unclear reasons. Why?

Answers: 1

body:
Use a logic level conversion IC.
[![enter image description here][1]][1]

picture source http://msx-elektronika.pl/en/logic-level-converter

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