body:
LED is not turning on with the following code. Have tried multiple LED's and double checked wiring. What's wrong? Using an uno.

    int ldr = A1;
    int  ldrVal = ldr;
    int led = 6;
    int lvalue = 900;

    void setup() {
      pinMode(led, OUTPUT);

      Serial.begin(9600);

    delay(1000);

    }

    void loop() {

    Serial.println(analogRead(ldrVal));
    if (ldrVal > lvalue) {

    digitalWrite(led, HIGH);
    }
    delay (50);

    if (ldrVal < lvalue)
    {
      digitalWrite(led, LOW);
    }
    delay (1000);

    }

title: LED not turning on with following code

Answers: 2

body:
Apart from the bad indentation and the bad variable naming, which makes your code not only look ugly, but messy and poorly readable, you have multiple problems in your few lines of code.

One problem is the variable `lvalue` never gets set, meaning its value remains `900` no matter what's the value you are reading through `analogRead()`.

A second mistake is your `ldrVal`, which should represent the boundary between *lit* and *powered off*, is set to `A1`, which in turn is a *macro define* for a valid integer, but a very small value (less than `20`).

In other words the code that should decide to turn on/off the LED continously compare 900 and 20 with no opportunity for those values to change: not surprising the LED won't change state, do you agree?

BTW, `50ms` is a very short time interval: if you want to be able to see the LED turn on and then off, increase the delay to 200 or more.

body:
Your code is wrong. `analogRead(ldrVal)` does not read the analog pin's value and store it into ldrVal, it is a function who's result is the analog pin value.

Try this edit:

    void loop() {

    int newValue = analogRead(ldrVal);
    Serial.println(newValue);
    if (newValue > lvalue) {  //Check newValue, not ldrVal
        digitalWrite(led, HIGH);
    }
    delay (50);

    if (newValue < lvalue)
    {
        digitalWrite(led, LOW);
    }
    delay (1000);
    }


body:
I'm trying to build a tiny project. After I program the board, to power the dev board - how can I power it to run the code?

__Question:__

- I was curious as to how I would be able to power the [ATtiny85 USB Mini Dev Board][1] by using a [90mAh 3.7V LiPo][2] battery which is connected to a [TP4056 5V micro USB Lipo battery charger][3]? The power is regulated to 5V by a  [3v to 5v 1a USB Charger DC-DC Converter][4] feeding the 5V pin on the ATtiny85.
- If now, how else can I power the [ATtiny85 USB Mini Dev Board][1] with a rechargeable battery?

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

__Old Circuit__
[![enter image description here][6]][6]

---

__Final Circuit__

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

  [1]: https://www.electrodragon.com/product/attiny85-usb-mini-dev-board-digispark-compatible/
  [2]: https://www.ebay.com.au/i/113322553296?chn=ps
  [3]: https://www.ebay.com.au/itm/1-2-5-10-TP4056-5V-Micro-USB-Lithium-Bat-Charging-NEW-Improved-LiPo-Charger-Mod/182632018873?hash=item2a85b773b9:m:m0nABi0ToNRyNEbNtzeAAFQ:rk:1:pf:0
  [4]: https://www.ebay.com.au/p/2pcs-3v-to-5v-1a-USB-Charger-Dc-dc-Converter-Step-up-Boost-Module/1663444523?iid=191674152965&chn=ps
  [5]: https://i.stack.imgur.com/EiUF6.png
  [6]: https://i.stack.imgur.com/jxD4u.png
  [7]: https://i.stack.imgur.com/eGiHo.png

title: Powering a Tiny Arduino Project

Answers: 1

body:
The old circuit will not work as you expect. While the ATtiny85 can run happily with 2.7 to 5.5V in this setup it expects 5V. I assume this is due to the high CPU clock setting. To run stable at a high CPU clock it requires 4.5V.

The VIN pin is connected to a linear regulator that has a 2V drop-out. Thus the supplied voltage has to be at least 2V about the target voltage. That is why the shopping page states a 5V (direct) or 7-35V (regulated at VIN) power supply.

Your LiPo charger already has a boost converter built in that boosts the battery voltage (3.0 - 4.2V) to 5V. No need to use a separate DC-DC boost converter here.

Just connect OUT+ to 5V and you are done.


body:
Editing here to clarify. The headline asks the question but the example given was not ideal. This was a more general Q than about the example code.

Compilers have *sequence points*, places where you can be assured that the equations have been evaluated etc and no lingering effects will occur: the compilation is stable. When I couldn't test the original example I went looking for theory, and came across SE/SO posts where there was some discussion about issues like:

       int a = 1;
       int b = a++ - a++ + a++;

What would you expect the values of a and b to be after this? It turns out it hinges on whether the arithmetic operators are sequence points. Apparently this was not well settled in early versions of C, and in other languages (like Java) the results may differ yet again.

I now understand that an expression like `(item++ > max)` contains no sequence points -- the `>` operator does not trigger evaluation, but assignment operators and *some* arithmetic operators do.

//================================

Original Q:

I've read several Qs here concerning `x++` vs `++x` but I don't see this specific case. I'm still something of a C novice here.

Do these two code fragments do the same thing?

      // assume itemNum == maxItem on entry

    if (++itemNum > maxItem) itemNum = 0;

    if (itemNum++ > maxItem) itemNum = 0;

I gather that when the increment takes effect depends on the occurrence a 'sequence point' but I don't know if the comparison creates such an inflection.

title: When does a pre/post increment occur?

Answers: 1

body:
Both ++x and x++ increment the value of x. The difference is whether you evaluate the value of x in your expression (formula) before or after incrementing it.

    int x1 = 0;
    int y1 = 0;

    int x2 = x1++; //Post-increment: Move current value of x1 (0) to x2, THEN increment x1
    int y2 = ++y1; //Pre-increment: Increment y1. Then move the NEW value of y1 (1) to y2.

In the above, x2 will be 0, and y2 will be 1.

The same logic applies to your if expression. If you use pre-increment, your if statement makes its decision on the new value after incrementing it.

If you use post-increment, the if statement makes its decision based on the value **before** it's incremented.


body:
I'm trying to create a small handheld console with 6 buttons and an I2C 0.96" OLED display:
https://i.stack.imgur.com/gWqZP.jpg

The directional buttons use the analog pin and different resistors technique to save space while the two remaining buttons use a digital pin each.
However, despite using the same libraries as other projects, the sketch seems to run very slowly, resulting in a lowered screen refresh rate.

Here is the code:

    #define wid 64  // Defines half of the width of the screen for graphic reference
    #define hei 32

    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    Adafruit_SSD1306 display;  // Create display

    int av;
    const float sp = 3;
    float pos[2]={0,0};  // Cursor position

    void setup() {
       delay(100);  // Gives the screen time to setup
       display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // Initialize display with the I2C address of 0x3C
       display.clearDisplay();
       display.setTextColor(WHITE);
       display.display();   // Clears the screen of any remaining images
      }

    void loop() {
      av=analogRead(A0);  // Reads the directional input
      av=inputRefine(av); // Assigns it to a direction
      switch (av)         // Changes the cursor position accordingly
      {
        case 1:
        pos[1]-=sp;
        break;

        case 2:
        pos[0] += sp;
        break;

        case 3:
        pos[1] += sp;
        break;

        case 4:
        pos[0] -= sp;
        break;
      }
      display.clearDisplay();

      display.setCursor(5,5);
      display.print(millis());  // Prints the system time on the corner of the screen

      display.drawCircle(wid + pos[0], hei + pos[1], 5, WHITE);  // Draws a circle on the cursor position
      display.display();
      }

    int inputRefine(int av)
    {
      int a=0;
      if (av>500&&av<600) a=2;
      else if(av>1000) a=3;
      else if(av>920&&av<950) a=4;
      else if(av>680&&av<720) a=1;

      return a;
    }

What is slowing the execution down?

EDIT: Even commenting out any unnecessary line doesn't remove the lag
EDIT 2: The problem might reside in the screen itself. Unfortunately, I don't have a backup one. I'll order one as soon as possible and test this theory.

title: Slow refresh rate on I2C OLED screen

Answers: 1

body:
Solved by updating the Adafruit sdd1306 library and the Adafruit GFX library

EDIT: Why am I being downvoted?


body:
I have a Nextion 7 inch enhance type display.
I have enabled sleep using `thsp = 120` and `thup = 1` line of code. Now display become sleep mode after 2min, if there is no any touch event.

But, this sleeping is completely turn off the display.

I have several pages and I want to reset to a specific page, if there is no any touch event in any page instead of sleep function.

Greatly appreciate if someone can give a solution for this.

title: Custom sleep function for Nextion

Answers: 2

body:
I solved the problem using a Nextion timer. (tm0)

I got a timer and change `tim` value. ( unfortunately Nexion allow to maximum to 65535mS). `vscope` should be `globle`, otherwise you cant use timer in every page.

I reset the timer in page touch event. In timer event I put this code.

    if(tm0.tim==60000) //reset time in mS
    {
       page 0 //specific page to load
    }

body:
The Nextion screen has a command for this. It is called [wup][1] and defines the id of page that the screen should go to on wake from sleep. The default is set to 255, which means that the display wakes up on the page it was on before the sleep event.

    16 wup Wake Up
     Page wup=2, n0.val=wup
    Sets which page Nextion loads when exiting sleep mode
     min is 0, max is # of last page in HMI, or default 255
     When wup=255 (not set to any existing page)
    – Nextion wakes up to current page, refreshing components only
     wup can be set even when Nextion is in sleep mode

  [1]: https://nextion.itead.cc/resources/documents/instruction-set/#s6


body:
When trying to flash my sketch, I see many errors such as:

     ***failed;
     ***failed;
     ***failed;
    avrdude: Error: butterfly programmer uses avr_write_page() but does not
    provide a cmd() method.
     *** page 127 (addresses 0x7400 - 0x747f) failed to write

And also:

    avrdude: error: programmer did not respond to command: set addr

How can I successfully flash my sketch?

Answers: 1

body:
After much frustration in trying things, I came across [this forum post](https://forum.arduino.cc/index.php?topic=129647.msg3039571#msg3039571) which advised:

    sudo systemctl stop ModemManager.service

If this works, disable the service from starting next boot:

    sudo systemctl disable ModemManager.service

It seems like setting `ENV{ID_MM_DEVICE_IGNORE}="1"` in a `udev` rule is insufficient.


body:
I have a project which uses a 128x64 oled display. I have to use the U8GLIB as the available displays change from SSD1306 to SSH1106 depending on when you buy it which that library covers both displays.
I don't want the program for the display to eat up the memory of the arduino so I use u8glib instead of u8g2! for this project I need to display numbers 0 to 9, decimal point, omega (ohm symbol) and metric prefixes such as μ,m,k,M, etc...
I first tried to create a bitmap font (.bdf) and convert it to a C file because that was what was hinted at on a few posts. There were no tutorials and after messing about with the different formats and trying to add the font to the library I just gave up because I couldn't figure it out. Instead I decided to use this website which generates bitmaps from TTF files:
https://littlevgl.com/ttf-font-to-c-array

Now I can use those bitmaps and have my few characters which use very little memory (about 20% as opposed to more than 70% using a complete symbols font in u8g2!) but this makes things really awkward as I have to translate every number I get into separate digits and then into a bitmap! also I can only use font sizes which have a height in multiples of 8 because for some weird reason this library expects width in number of bytes and height in number of pixels!

> cnt: Number of bytes of the bitmap in horizontal direction. The width
> of the bitmap is cnt*8.

so I can do fonts of size 48 for example, but not 50 or 52 which would be more suitable for my application!
I'm not sure if anyone else has had this issue but there must be a way to display the characters you want without destroying your entire memory space like u8g2 does! Just getting to this point took me 2 days (on the left there is a 0.96" SSD1306 and on the right there is a 1.3" SSH1106):

[![enter image description here][1]][1]
Please help if you have any idea on how to deal with this library as it's driving me insane at the moment!

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

title: I need help with U8GLIB library

Answers: 1

body:
While this may not exactly answer your question, there may be some information about [u8g2lib][1] that you have not seen. The library source code is linked here: [u8g2lib][1]

Within that repository is the [FAQ documentation][2] which includes such gems as:

> [Q: U8g2 requires a lot of memory. How to reduce this?][3]
> - Visit https://github.com/olikraus/u8g2/wiki/u8g2optimization
> - Disable U8g2 features if possible (see u8g2.h)
> - Limit the font size. If possible avoid "f" fonts, instead use "r" or "n" fonts
> - If the I2C interface is not required, then uncomment #define U8X8_HAVE_HW_I2C in U8x8lib.h   (Background: Due to a problem in
> Wire.h, the I2C Arduino lib is always included)

and

> [Q: How can I generate my own font.][4] A: The font must be available in
> bdf file format. Then use bdfconv to generate the font data. The font
> data can be pasted into an existing file of your project. There is
> also a nice Windows Bitmap Font Editor "Fony"
> (http://hukka.ncn.fi/?fony)  which can export .bdf files. A copy of
> Fony 1.4.7 is available here:
> https://github.com/olikraus/u8g2/tree/master/tools/font/fony

The [tools/font][5] directory includes several utilities, including what looks like one that [converts OTF fonts to BDF format][6]

Once you get a BDF format font, you use [bdfconv][7] to create the C file that holds the font array. One of the arguments for bdfconf is the `-m 'map'` option. You can place in there a list of Unicode ranges that limit which characters get included. So, you can create a font that has ONLY the characters you need.

For example `-m '45-46,48-57,77,107,109,181,937'` gets you minus, decimal, 0-9, 'M', 'k', 'm', mu, omega. Unicode character map at https://unicode-table.com/en/

The benefit to creating a font is that the u8g2lib library itself does all the mapping to bitmaps and calculating the character widths, etc. so you don't have to.

  [1]: https://github.com/olikraus/u8g2
  [2]: https://github.com/olikraus/u8g2/blob/master/doc/faq.txt
  [3]: https://github.com/olikraus/u8g2/blob/master/doc/faq.txt#L167
  [4]: https://github.com/olikraus/u8g2/blob/master/doc/faq.txt#L206
  [5]: https://github.com/olikraus/u8g2/tree/master/tools/font
  [6]: https://github.com/olikraus/u8g2/tree/master/tools/font/otf2bdf
  [7]: https://github.com/olikraus/u8g2/blob/master/doc/faq.txt#L213


body:
I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.   At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

I'm new to working with these types of break out boards, so I found an online project that I'm using as a starting point:

[Streaming audio from ESP8266 to pyaudio working in Arduino IDE][1]

I figure I start troubleshooting my popping sound issue by inspecting the UDP packets my ESP8266 code.  Below is the source code I'm working from:

 #include <ESP8266WiFi.h>
 #include <WiFiUdp.h>

 const char* ssid = "change this";
 const char* password = "change this";
 int contconexion = 0;

 WiFiUDP Udp;

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

   pinMode(5, OUTPUT);  //D1 Led de estado
   digitalWrite(15, LOW);

   WiFi.mode(WIFI_STA); //para que no inicie el SoftAP en el modo normal
   WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED and contconexion <50) { //Cuenta hasta 50 si no se puede conectar lo cancela
     ++contconexion;
     delay(250);
     Serial.print(".");
     digitalWrite(5, HIGH);
     delay(250);
     digitalWrite(5, LOW);
   }
   if (contconexion <50) {
       //para usar con ip fija
       IPAddress Ip(192,168,1,180);
       IPAddress Gateway(192,168,0,1);
       IPAddress Subnet(255,255,255,0);
       WiFi.config(Ip, Gateway, Subnet);

       Serial.println("");
       Serial.println("WiFi conectado");
       Serial.println(WiFi.localIP());
       //digitalWrite(5, HIGH);
   }
   else {
       Serial.println("");
       Serial.println("Error de conexion");
       //digitalWrite(15, LOW);
   }
 }

 void loop()
 {
   Udp.beginPacket("192.168.0.26", 1234);

   for(int i=0; i<1024;i++){
     int old=micros();

     float analog = analogRead(A0);
     if (analog > 255) {
       analog = 255;
     }
     else if (analog < 0){
       analog = 0;
     }
     Udp.write(int(analog));
     Serial.print(int(analog));
     Serial.print(",");
     while(micros()-old<87); // 90uSec = 1Sec/11111Hz - 3uSec para los otros procesos
   }
   Serial.print(";;;;;");
   Udp.endPacket();
   delay(5);
 }

Notice near the bottom of the file, I print out each analog value separated by a comma, and each data packet separated by five semicolons.

Can someone suggest a way for me to re-construct these series of integers into a sound file that I can inspect via listening with my own ears?  Then I can tell if the sound data being sent is complete?  Or let me know if there's a better way to test if all the data packets are being sent correctly.

**UPDATE**

I tried to create a wav file by doing this:

 - Take the list of all integers from `Serial.print(int(analog))` and paste it into a file. I make sure all integers are space delimited (ie. no more commas or semicolons)
 - I copied the file over to a linux machine that had ffmpeg installed
 - I ran the command `ffmpeg -f u8 -ar 11111 -ac 1 -i myfileofintegers -y test.wav`

When I listen to the test.wav file, I just hear a series of rapid popping noises.  Not sure if I created the wav file properly?

  [1]: http://www.sinaptec.alomar.com.ar/2017/09/proyecto-1-esp8266-microfono-espia.html

title: How to re-construct audio from series of analog integer input?

Answers: 1

body:
> I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.

You have described several problems; one needs to break big problems into small problems:

 1. Sample the audio
 2. Send it to another computer
 3. Decode and playback the sound

> At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

This sounds like you have got your timebases messed up; it is likely that you aren't recording enough data or playing it back incorrectly. N.b. it looks like you are recording ~92ms of audio data each 'packet' and if you get a series of pops at 2hz you are likely playing less than 1/10 of a second of audio for ever 5/10 of time, so your speaker moves for 1/10th of a second then stays still for 4/10ths and repeats; this produces your 2hz popping noises.

Your code has some other problems as well:

 - Serial.print() is **Slow!** Don't use it where performance matters!
 - Intertwining sampling and sending
 - Incorrectly scaling the analog reading
 - 11.1khz can only record signals up to 5.5khz

Lets start with the audio sampling. We have some sort of audio circuitry presenting a signal to an analog input, we need to sample it regularly and uniformly! The code presented is trying to sample at 11.1 kHz, but only does so for 1024 samples before hitting a discontinuity. We do not have circuitry dedicated to this so we will have to use the ADC circuitry on the Arduino.

First thing you will want to get you sampling regular and continuous. You will want to use an interrupt on the Arduino for this. The interrupt should take a single sample from the ADC and add it to a buffer or signal the main loop to read/buffer it.

This interrupt will need to fire regularly at the sample rate or the data will be ruined.

Second the audio circuitry should prepare the signal so that it is between 0-5v with a ~2.5v bias, this will use the ADC hardware to its fullest.

so in Pseudo code:

    // include any libs etc.
    // set up variables ect.
    void interupt_sample();
    // register and attach interrupt
    void setup() {
    //do your setup etc.
    }
    void loop() {
    // if(new_sample) add_to_buffer(new_sample);
    // if(buffer_full) send_and_flush_buffer();
    }


body:
I did this little experiment to count the number of cycles per second in two different configurations:

1-The variable a is initialized at zero and incremented by one each cycle of the loop.
 -The value of a is written each cycle
 -at millis() = 1000, the incrementation ends, and the value of millis() is written to check the precision of timing.

Code:

    long a = 0;
    int v = 1;

    void setup() {

    Serial.begin(9600);

    }

    void loop() {

    if (v == 1){
    a = a + 1 ;

    Serial.println(a);

    if (millis() >= 1000){
    Serial.println(millis());
    v = 0;}

    }
    }

Result:
1
2
.
.
.
227
1000

2-Same as 1, but the value of a is written only at the end.

Code:

    long a = 0;
    int v = 1;

    void setup() {

    Serial.begin(9600);

    }

    void loop() {

    if (v == 1){
    a = a + 1 ;

    if (millis() >= 1000){
    Serial.println(millis());
    Serial.println(a);
    v = 0;}

    }
    }

Result:

1000
265174

-So, 227 cycles for 1, and 265174 for 2, is this correct, and can such a simple modification slow the cycling by 1000?

title: Number of cycle depending on the number and type of statements

Answers: 3

body: When the serial buffer (64 bytes) is full the `print` waits until bytes are send away at 9600 baud.

body:
Writing via the serial interface takes a lot of time (just consider the baud rate you selected).
You should always keep in mind that changing the amount you are printing might change your programs behaviour.
That means, your 2. configuration is (more) reliable.

body:
You could use micros() as well to increase resulution to 4uS, vs 1000uS.
Up the speed to 115200, that should show some improvement as well.


body: I have resorted to creating bitmaps for each number and a few letters for a 128x64 Oled module. This was to save memory and get around limitations of libraries such as the u8glib. If I had linux I could use the tools they provided to fix some of these but that's out of the question for now. I wanted to know if there's a simple way of mapping each character to it's bitmap so a function similar to XXX.print(); be used, in order to parse the characters and display the corresponding bitmaps automatically. That would make my life so much easier! thanks!

title: Displaying characters as bitmaps

Answers: 1

body:
I would split it down into functions.

First write a function which takes a character and a pair of coordinates, then draws the bitmap corresponding to that character at the given coordinates on the screen.

Then you want a function that is the "next level up". You just pass it a single character, and it remembers the current coordinates and uses those with the character to call the first function. It's then the job of this function to move the coordinates to the next character location ready for the next time it's called.

Finally you want an outer layer (or a few outer layer) functions that take different data types (`const char *` for example) and send each character in turn to the second function above.

If you were to make a class to wrap it all in you could inherit the `Print` class. That means you just need to provide the `size_t write(char)` function which is equivalent to the second function above (of course you still need the first function). The wrappers for different data types are then all provided for you.


body:
I have an ESP12e and running a basic blink code on it. The problem is that GPIO13 of esp12e wont turn on. I have noticed that this has happened from time to time. Earlier I thought that the ESP was faulty so i just changed them. But now I have a lot of 10 ESPs and all of them have the same problem. Pin 13 wont turn on setting to HIGH.

What could be going wrong? Is there something that I am missing?

**EDIT:**
However, on the same piece of esp12, for some test, i tried putting the gpio12 to input and that worked.

**Code:**

    void setup() {
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }

    void loop() {
      digitalWrite(LED_BUILTIN, LOW);
      delay(1000);
      digitalWrite(LED_BUILTIN, HIGH);
      delay(2000);
    }

title: ESP12e pin 13 won't set to output/won't work

Answers: 0


body:
I have A1 set to be an input, have the program read it, and then print to the serial monitor. My question is, when the circuit is not receiving power, but is grounded, and is still connected to A1, when do I see an output pattern of, for example:

    0,0,0,0,7,23,16,9,4,0,0,0,0,3,18,21,15,0,0,0.....

I have a different detector inputing to A0 and if I don't have A1 connected then I get a reading that is similar to what I would see if I was actually reading A0 (around 900). Then if I plug back into A1 the value drops to around 350. When A0 is unplugged and only A1 is plugged in I only get noise (ie the pattern above in the code section).

title: Oscillating Output from Arduino Pins when not in use, why?

Answers: 1

body: I'm thinking along the same lines as CrossRoads and dandavis above. Would you be able to post a circuit diagram? If you haven't grounded the input, it could be floating or picking up noise from the surrounding environment. A 5k pulldown resistor may fix the problem, depending on what your circuit looks like and the environment its in.


body:
i'm using arduino to dimmer 9 led strips with different output pins after an FFT audio analysis gives results at 60Hz = 16ms. [FFT is performed by a PC and sent to arduino using a RF24 module]

I started the project using SoftPWM on pins D2->D9 & A4 with a lower frequency update but now i'm having problems increasing the frequency update. I have already wired 6 copies of that board and i'm looking for a software solution

To diagnose the problem i performed a test sending a pwm value and zero at a certain frequency, if the frequency is high you can only see a lower emitted power

If I set the pwm once I have a stable signal (led intensity)
If I set the pwm every ~10ms (10ms on @ certain pwm, 10ms at pwm=0) I have an unstable intensity, repeating the test on the pin 6 with a normal analogWrite i don't have the problem. With 10ms i clearly see it blinking at a random frequency (~20Hz=50ms), with 15ms I only see it random fluctuating

I'm using arduino Pro mini - 5V - 2kB
Without signals arduino performs 16k cycles/second (most without changing anything), with a 10ms signal it runs at 14k cycles/second so it seems not a load problem.

Can someone help me regarding this problem?

 - Should I change library
 - Should I move to a lower level to rewrite a more performing library
 - Should I use only 6 std pwm, draw again the board, print them again, weld all components again, and test it again?

Thanks!

PS: I can't create the SoftPWM tag for a reputation problem, can a moderator do that?

title: SoftPWM update limitations

Answers: 1

body:
The problem is not a SoftPWM limitation but a physical one. SoftPWM have a PWM cycle at 60Hz, that makes impossible to update output faster than 34mS and that explain why I see low frequency trying to change the state with every 10 ms.

[![Aliasing][1]][1]

Hardcoding the IRS I can reach a much faster PWM cycle, keeping the same PWM frequency I have roughly 60% less of CPU used. With a full CPU load and latest version of the code I can reach ~600Hz PWM cycle. I decided to use a ~300PWM cycle to have enough CPU to perform other tasks (mainly handle RF24 to receive packets @ 60Hz and, if needed, forward them too other bases)

Even at higher frequencies average intensity is not stable, but higher the frequency more stable the result. That can be explained because the eye "average" incoming light and that average is not very stable

[![avg alias][2]][2]

Since leds are used to produce visual effects I don't need a very accurate output, and 300Hz are enough. (I also don't have big mosfets and I don't want to stress them with higher frequencies)

  [1]: https://i.stack.imgur.com/c2ctk.png
  [2]: https://i.stack.imgur.com/XX3S3.png


body:
I have a lot of Arduino Pro Micros that I can't program through the Arduino IDE.

I'm on Windows.

I'm using the SparkFun Pro Micro board information downloaded from SparkFun's website.

I've tried manually reassigning the Pro Micro's COM port in the device manager. It seems to be no different whether I'm at COM1 or COM255.

If I use an Arduino ISP or USBASP to burn the bootloader onto the problematic Pro Micro, it responds for usually one or two more USB programmings but that's about it.

When they get into this problematic state, they are still running their code (I can see the Blink sketch flashing my LED for instance), they just can't be reprogrammed. I can even still open their Serial communications.

Verbose output during the uploading process on first attempt yields the following:

    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    PORTS {COM1, COM2, } / {COM1, COM2, } => {}
    Uploading using selected port: COM2
    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -PCOM2 -b57600 -D -Uflash:w:C:\Users\Thompson\AppData\Local\Temp\arduino_build_668056/BareMinimum.ino.hex:i

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

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM2
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

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

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
    avrdude: butterfly_recv(): programmer is not responding

That last line is where it freezes for an indefinite period. I close and reopen the Arduino IDE and try to reupload, and this is my result:

    processing.app.debug.RunnerException
         at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:160)
         at cc.arduino.UploaderUtils.upload(UploaderUtils.java:82)
         at processing.app.SketchController.upload(SketchController.java:736)
         at processing.app.SketchController.exportApplet(SketchController.java:703)
         at processing.app.Editor$DefaultExportHandler.run(Editor.java:2039)
         at java.lang.Thread.run(Thread.java:748)
        Caused by: processing.app.SerialException: Error touching serial port 'COM2'.
         at processing.app.Serial.touchForCDCReset(Serial.java:107)
         at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:144)
         ... 5 more
        Caused by: jssc.SerialPortException: Port name - COM2; Method name - openPort(); Exception type - Port not found.
         at jssc.SerialPort.openPort(SerialPort.java:167)
         at processing.app.Serial.touchForCDCReset(Serial.java:101)
         ... 6 more

This exact same message (with a different COM number of course) plays out on any Windows machine I try this with.

In the above example I was trying to upload the Bare Minimum example.

Are all of my Pro Micros dead? Is there something wrong with the IDE? Is there an alternative IDE I can get a second opinion from?

EDIT: An update; I've gotten Atom installed with PlatformIO and I was able to write a few sketches to an Arduino Pro Mini. I attempted the same sketches on the Arduino Pro Micro and got the same error and freeze: `programmer is not responding`

title: Arduino IDE can't program my Arduino Pro Micro

Answers: 1

body: After experimenting some more, it looks like this issue is related to a one second watchdog that I have enabled in my sketch. After removing the watchdog, I've had no problems (so far) with uploading code.


body:
I am trying to use a Wemos D1 R2 to connect to my NEO-6M GPS module. I am able to make the module work fine with an Arduino UNO. I'm having significant trouble with the D1. Based upon other posts I have read here, I have included the appropriate Pins_Arduino.h include file and used the aliased settings. Here is the code I am using:

    #include <Pins_Arduino.h>
    #include <SoftwareSerial.h>
    #include <TinyGPS++.h>

    // The serial connection to the GPS module
    SoftwareSerial ss(D2, D3); // Here are the aliased pins
    TinyGPSPlus gps;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      ss.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      while (ss.available() > 0){

        gps.encode(ss.read());
        if (gps.location.isUpdated()){
          //int value = analogRead(lightPin);
          //Serial.print("Light= ");
          //Serial.println(value);
          Serial.print("Latitude= ");
          Serial.print(gps.location.lat(), 6);
          Serial.print(" Longitude= ");
          Serial.println(gps.location.lng(), 6);

          Serial.println(gps.time.value());

          // Hour (0-23) (u8)
          Serial.print("Hour = ");
          Serial.println(gps.time.hour());
          // Minute (0-59) (u8)
          Serial.print("Minute = ");
          Serial.println(gps.time.minute());
          // Second (0-59) (u8)
          Serial.print("Second = ");
          Serial.println(gps.time.second());
          // 100ths of a second (0-99) (u8)
          Serial.print("Centisecond = ");
          Serial.println(gps.time.centisecond());
        }
      }
    }

I have ensured that I have the RX and TX pins correct, even reversing them to test the connection. Am I doing something wrong with the pins? Or do I have to just drop seven and punt on the D1 and get an ESP8266 shield for my UNO?

To help explain the ultimate purpose of this project, plan to use an esp8266 based web server to pull geographic based data from other sensors on the board. If I can't get the GPS to work here, I'll need to re-engineer my project.

Thanks. I apologize if this is a duplicate question, but my petrified brain just isn't searching correctly if it is.

**Update:**

If I use an Arduino UNO, everything works fine. I tried using the WeMos D1 R2 over the weekend and received data for about 5 seconds and then it stopped. I used pins D4 and D5 for RX and TX respectively. I'm not sure if the data was in the serial buffer when I uploaded a new Sketch or if it was actually returned from the GPS.

I'm going to punt on making the WeMos board work for now and ordered an ESP-01S to use with my Arduino UNO. I'm also reaching out to a supplier for assistance on this. Thanks for the help.

I'm going to leave this open for now in case someone else can provide some insight.

title: Using SoftwareSerial on a Wemos D1 to get data from a GPS Shield

Answers: 0


body: Would any one know how many Force-Sensitive Resistors that a Arduino Uno can handle being hooked up to at one time?

title: Arduino Uno Force-Sensitive Resistor

Answers: 0


body:
**Update**

Here the update regarding the code I tried to program. I have a stepper with an attached disc with little holes every 45 degrees where a microswitch can rest into (hole is the exact size of the microswitch; and be in off position then). I would like the stepper to move 45 degree (until hole 1) and then (as a first step) wait for 3 seconds and then move another 45 degree to hole and stop etc.

As a next step I would like the same to be controlled via serial from another software. So I can send to serial a "move" command and then the same as described above will happen once the Arduino get the "move" command.

Below my attempt. It does do the homing, but not very smoothly and the next step (just moving 3 seconds) is a very rough movement. Here my qestions:

1. How can I make this move smoothly ?
2. How should I adapt this code to make the stepper stop once it is in the hole ?
3. How can I make the microswitch get out of the hole after it rests in there ?

Thank you very much for your help !

**Code**

    #include "AccelStepper.h"

    int M2dirpin = 4;  //Motor Y direction pin
    int M2steppin = 5; //Motor Y step pin
    int M2en=12;  //Motor Y enable pin
    #define home_switch 9 // Pin 9 connected to Home Switch (MicroSwitch)

    // AccelStepper Setup
    AccelStepper stepperX(1, 5, 4);   // (1,2,3) = (Dedicated Board, STEP, DIR)
    // Stepper Travel Variables
    long initial_homing = -1; // Used to Home Stepper at startup

    void setup() {

      pinMode(home_switch, INPUT_PULLUP);
      pinMode(M2dirpin,OUTPUT);
      pinMode(M2steppin,OUTPUT);
      pinMode(M2en,OUTPUT);
      digitalWrite(M2en,LOW);
      Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
      stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
      stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper

      // Start Homing procedure of Stepper Motor at startup
      Serial.print("Stepper is Homing . . . . . . . . . . . ");

      while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
        stepperX.moveTo(initial_homing);  // Set the position to move to
        initial_homing--;  // Decrease by 1 for next move if needed
        stepperX.run();  // Start moving the stepper
        delay(20);
      }

      stepperX.setCurrentPosition(0);  // Set the current position as zero for now
      stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
      stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper
      initial_homing = 1;

      while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
        stepperX.moveTo(initial_homing);
        stepperX.run();
        initial_homing++;
        delay(20);
      }

      stepperX.setCurrentPosition(0);
      Serial.println("Homing Completed");
      Serial.println("");

     // Move 10 steps forward from the limit switch (to get out of the switch)
      while (stepperX.currentPosition() != 10)
      {
        stepperX.setSpeed(10);
        stepperX.run();

    }
    }
    void loop()
    {
    stepper1();
    }

    void stepper1()
    {
      stepperX.move(22);
      unsigned long startMillis = millis();
      while( millis()-startMillis<3000 )
    {
      stepperX.run();
    }
    }

**Old question:**
I apologize for the high level, pseudo code question, but I am trying to understand conceptional how I can achieve the following:

I have 3 steppers (1 circular motion, 2 linear motion) which I would like to stop **every time** at the exact same position. The first stepper should rotate e.g. 45 degrees and stop, after which the second stepper should push down (like a linear actuator) stay at that position for a certain time and move back to the initial position, after that the 3rd stepper should also (linear motion) move to certain position and return.
These three steps would than repeat for a very long time.

Do Steppers accumulate errors in position and if yes how can I make sure that this is not happening ?

I read abut "homing" and tried microswitches, but wasn't able to combine it with the three stepper setup. Also 3D printers should always stop exactly at the same place and therefore I assumed there must be a solution for this.

Is there a template code I can start from that is similar to the setup described ?

How can I make sure these steps are done strictly after each other.

Again I apologize for the high level question, but all my attempts so far to solve this failed.

Thank you !

title: Controlling 3 Steppers exactly

Answers: 1

body:
**About errors with stepper motors:** Stepper motors introduce errors depending on the forces, that act upon them. For example: If your stepper does not have enough power to accellerate the attached weight, it will loose steps when trying (meaning that the rotor does not do a step despite the coils being controlled for the step). (The same of course also goes for deacceleration or moving against a barrier) Since you only know the position bei counting the steps, that you "send" to the motor, you get an error.

You have basically 2 options to prevent this from happening:
1. Choose the correct strength for motors for your application and don't overburden the motors at any moment in operation.
2. You can attach a rotary encoder to the rotor, so that you can check, if the rotor really moved the number of steps, that you instructed it to do. (Here be sure, that the numbers of steps for rotary encoder and motor match, or calculate correctly, if they don't). The position in your program would then only be updated based on the rotary encoder. This solution is more difficult, since you need extra parts and good code, that will not miss any of the rotary encoder pulses.

**About Homing:** Yes, this can be used to prevent the accumulation of errors during a longer operation. Also this is often used, so that the device does not have to constantly save it's current position to peristent storage. If the power is cut off, the device will forget it's position and calibrate it again after powered on again by using the end switches. Also this means, that in the powered off state it's not a problem, when the motor is moved away from it's position by outer forces.

It is unclear, how precise you need the application to be and what errors are really introduced. It may be sufficient for you to just get the position of the motors by homing, when you power your device on, and then simply letting it work. If that's not sufficient, you might do a homing cycle after every sequence. The same goes for the rotary encoder solution. It might be an overkill here, depending on the exact properties of the application.

**Template code:** I simply googled "Arduino stepper homing" and found some articles about it, which also contain example code. That should enable you to write code for your own application. Since you didn't really described, what your setup is, we cannot see, if this really fits your application. But Homing is the same everywhere.

**Steps strictly after each other:** You can just write your program to finish one part and then go on to the next (blocking code). Or, if you want it to be more elaborate and flexible, you can use non-blocking code (like in the `BlinkWithoutDelay` example of the Arduino library) with a finite state machine. The states could be the 3 parts of your program, or divided further. In each state you are doing only 1 thing and change to the next state, when finished. The code in each state should be non-blocking, so that it only does something, when it needs to, and else let's the program continue (for example: When moving a stepper at a certain speed, you are doing 1 step, then waiting a bit, then doing the next step and so on. While waiting you can do other things.)

You didn't mention, what your problems with the limit switches were, so we cannot help you with that. Thus this answer is as high level as your question. Hope, that helps.


body:
I made a small set up to log temperature on SD card, everything is running smoothly until it reach 9:06:01 of logging that is  32761 seconds. I know that corresponds roughly to the maximum value of an integer. But I made all my variables unsigned long.
Here is the code in the loop and the if condition to log or not. The timer is computed with currentTime (unsigned long) and startTime (unsigned long). So even if logCount*freq are both integers, they should reach maximum value after 32761 seconds, then the if condition should always be true.

    void loop() {
     String date;
     unsigned long timer;
     int freq = 60;

     sensors.requestTemperatures();
     tempC1 = printTemperature(insideThermometer, 18);
     tempC2 = printTemperature(outsideThermometer, 19);

     // start serial port
     Serial.begin(9600);

     mainMenuDraw();
     operateMainMenu();

     CurrentTime = millis();
     timer=(CurrentTime - StartTime)/1000;
     date = TimeShowFormatted(CurrentTime - StartTime);

     if (timer > logCount * freq and StopStatus == 0) {
      logCount += 1;
      LastLoggedDate=date;
      DataLogg(date);

     }
    }

title: Arduino stops logging data after ~32761 seconds

Answers: 1

body:
Instead of comparing absolute times you should use the following:

    unsigned long now = millis();

    if(now - time_last_log >= freq){
        logCount += 1;
        LastLoggedDate=date;
        DataLogg(date);
        time_last_log = now;
        // or if you really want fixed intervals
        // time_last_log += freq;
    }

This is guaranteed to be overflow proof.


body:
I'm mapping a potentiometer from 0-1023 to 1000-120000 (1 sec to 2 minutes) for a timer, like:

    maxDelay = map (pot2, 0, 1023, 1000, 120000);

Both variables are integers. Now I would like to convert/round values to counts of 10 seconds (a count of thousands), so if I have anything from 1001-5000 this would be rounded to 1000 (1sec), and if I have 5001-10000 it would be rounded to 10000 (10 secs), then 20sec, 30sec, etc...until it reaches 120secs. I know I could have a few "if" statements but I'm trying to figure out the right way of doing these maths. Thanks.

title: How to map integer values and round to a count of tens/thousands?

Answers: 1

body:
I didn't yet compiled it, but something like this should work:

    #include <Math.h>

    int converter(int x)
    {
        if(x <= 5000)
            return 1000;
        else
            return (int)(round(x / 10000.0) * 10000.0);
    }


body:
I am using multiple ATMEGA328Ps  (4 ATMEGA328P) (OR Arduino Unos). The distance between two farthest ATMEGAs is 14 meters (One is Master Device and Other is Node), and other 3 are connected to each other at a distance of 3 meters from the Master Device.
I have a case where i cannot use Wireless communication hence i will have to go Wired. I am also looking to achieve the Mesh topology if possible.

There are many examples on the internet regarding this case but still i am not be able to choose/compare which would be more reliable.

Please suggest me the best solution to work on this.
Thanks.

title: Multiple Atmega328p wired communication

Answers: 0


body:
I hope someone can help me. I'm building a GSM water level meter that runs on solar power, using an Arduino Pro mini, a DS3231 RTC, a JSN-SR04T - ULTRASONIC SENSOR, and a SIM800L along with a DFrobot DFR0535 solar power manager and 3.7V battery.

My project worked fine before I added the RTC; it connects to the Blynk server, gets the readings from the ultrasonic sensor, and posts them, before going to sleep.

I added the RTC in order to use it to wake up the Arduino using the interrupt signal and save some power during the evenings and no sun.

Even this works, but the interrupts stop after about 30 mins of firing. At the moment its configured to fire every 5 mins. My serial output looks like this:

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

So at this point the sketch works 100% and does exactly what I need, but unfortunately it stops after a few minutes. Do I need a pull up resistor somewhere maybe?

Any ideas?

Below is my sketch. Any help will be greatly appreciated.

```c++
    #include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
    #define interruptPin 2 //Pin we are going to use to wake up the Arduino
    #include <DS3232RTC.h>  //RTC Library https://github.com/JChristensen/DS3232RTC
    #include <NewPing.h>
    #define BLYNK_PRINT Serial
    #define TINY_GSM_MODEM_SIM800
    #include <TinyGsmClient.h>
    #include <SoftwareSerial.h>
    #include <BlynkSimpleSIM800.h>
    #define SIM800_TX_PIN 9
    #define SIM800_RX_PIN 8
    #define uS_TO_m_FACTOR 60000000   // Conversion factor for micro seconds to minutes
    char auth[] = "a892d375xxxxxx0d5c086d6b1";
    char apn[]  = "";
    char user[] = "";
    char pass[] = "";
    const int MAX_DISTANCE = 120;                       //max distance to measure
    const int Diameter1 = 110;                                //internal Diameter of tank 1 in cm
    const int Depth1 = 110;                                 //total depth of tank 1 in cm , from sensor to base inside
    const unsigned int Period = 60000;    //period between pings, in milliseconds. i.e  1 munute = 60,000. max 65535. Want longer? use unsigned long
    const int PingPin1 = 6;                          //     GPIO5,  D1
    const int EchoPin1 = 7;                        //     GPIO4,  D2
    const int Area1 = PI * ((Diameter1 / 2) * (Diameter1 / 2));          //area of base of tank 1
    int Litres1, Distance1, WaterDepth1, Decimal, Persentage, battLevel, csq, kill;
    String gsmTime, gsmTime1;
    #include <SoftwareSerial.h>
    SoftwareSerial SerialAT(SIM800_TX_PIN, SIM800_RX_PIN);
    TinyGsm modem(SerialAT);
    //BlynkTimer timer;
    NewPing sonar = NewPing(PingPin1, EchoPin1, MAX_DISTANCE);
    //RTC Module global variables
    const int time_interval = 5; // Sets the wakeup intervall in minutes

    void setup() {
      Serial.begin(115200);//Start Serial
      delay(1000);

      pinMode(LED_BUILTIN,OUTPUT);//We use the led on pin 13 to indecate when Arduino is A sleep
      pinMode(interruptPin,INPUT_PULLUP);//Set pin d2 to input using the buildin pullup resistor
      digitalWrite(LED_BUILTIN,HIGH);//turning LED on

      // initialize the alarms to known values, clear the alarm flags, clear the alarm interrupt flags
        RTC.setAlarm(ALM1_MATCH_DATE, 0, 0, 0, 1);
        RTC.setAlarm(ALM2_MATCH_DATE, 0, 0, 0, 1);
        RTC.alarm(ALARM_1);
        RTC.alarm(ALARM_2);
        RTC.alarmInterrupt(ALARM_1, false);
        RTC.alarmInterrupt(ALARM_2, false);
        RTC.squareWave(SQWAVE_NONE);
         time_t t; //create a temporary time variable so we can set the time and read the time from the RTC
        t=RTC.get();//Gets the current time of the RTC
        RTC.setAlarm(ALM1_MATCH_MINUTES , 0, minute(t)+time_interval, 0, 0);// Setting alarm 1 to go off 5 minutes from now
        // clear the alarm flag
        RTC.alarm(ALARM_1);
        // configure the INT/SQW pin for "interrupt" operation (disable square wave output)
        RTC.squareWave(SQWAVE_NONE);
        // enable interrupt output for Alarm 1
        RTC.alarmInterrupt(ALARM_1, true);
    }

    void loop() {
     delay(5000);//wait 5 seconds before going to sleep. In real senairio keep this as small as posible
     Going_To_Sleep();
    }

    void Going_To_Sleep(){
        sleep_enable();//Enabling sleep mode
        attachInterrupt(0, wakeUp, LOW);//attaching a interrupt to pin d2
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep
        digitalWrite(LED_BUILTIN, LOW); //turning LED off
        time_t t;// creates temp time variable
        t=RTC.get(); //gets current time from rtc
        Serial.println("Sleep  Time: "+String(hour(t))+":"+String(minute(t))+":"+String(second(t)));//prints time stamp on serial monitor
        delay(1000); //wait a second to allow the led to be turned off before going to sleep
        sleep_cpu();//activating sleep mode
        Serial.println("just woke up!");//next line of code executed after the interrupt
        myFunction();
        t=RTC.get();
        Serial.println("WakeUp Time: "+String(hour(t))+":"+String(minute(t))+":"+String(second(t)));//Prints time stamp
        //Set New Alarm
        RTC.setAlarm(ALM1_MATCH_MINUTES , 0, minute(t)+time_interval, 0, 0);

      // clear the alarm flag
      RTC.alarm(ALARM_1);
      }

    void wakeUp(){
      Serial.println("Interrrupt Fired");//Print message to serial monitor
       sleep_disable();//Disable sleep mode
      detachInterrupt(0); //Removes the interrupt from pin 2;

    }

    void myFunction() {
      pinMode(13, OUTPUT);
      digitalWrite(13, HIGH);
      SerialAT.begin(57600);
      delay(1000);// make GPIO8 output low
      Serial.println("Initializing modem...");
      modem.restart();
      Blynk.begin(auth, modem, apn, user, pass);
      delay(1000);
      Distance1 = sonar.ping_cm();                                       //get distance to the top of the water tank 1
      if (Distance1 >= Depth1 || Distance1 == 0 )  Distance1 = Depth1;                   //check it does not go negative
      WaterDepth1 = Depth1 - Distance1;                     //calculate the depth of the water
      Litres1 = ((Depth1 * (PI * (sq(Diameter1 / 2)))) - (Distance1 * (PI * (sq(Diameter1 / 2))))) / 1000;
      Persentage = (Litres1 / 1000.00) * 100;
      battLevel = modem.getBattPercent();
      csq = modem.getSignalQuality();
      Blynk.virtualWrite(V1, WaterDepth1);
      Blynk.virtualWrite(V2, Litres1);
      Blynk.virtualWrite(V3, Litres1 / 10);
      Blynk.virtualWrite(V4, Persentage);
      Blynk.virtualWrite(V5, battLevel);
      Blynk.virtualWrite(V6, csq);
      Serial.println();
      Serial.println();
      Serial.println("Water depth: " + String(WaterDepth1));
      Serial.println("Water distance: " + String(Distance1));
      Serial.println("Litres: " + String(Litres1));
      Serial.println("Percentage: " + String(Persentage));
      Serial.println("Battery: " + String(battLevel));
      Serial.println("Signal Qlty: " + String(csq));
      delay(100);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }
```

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

title: Arduino Pro mini does not wake up after a few interrupts from DS3231

Answers: 0


body: Hello I am trying to make a drone by using Arduino as a microcontroller both for remote controller and the drone. And I have thought for using NRF module. But I came to know it only can transmit data to 1000 m maximum but I need the range around 8 km maximum. What can I do for increasing the range of my drone? Or is there some way to increase range of NRF module?

title: Upgrading NRF module for drone

Answers: 1

body:
If I search I see plenty of examples of RF with 40 miles, e.g.:

- [XTend 900 1W RPSMA - 40 Mile Range][1]
- [XBee-900-Datasheet][2]

Possibilities to increase the range:

- More powerful transmitter
- External / better antenna(s)
- Better receiver
- Using directional communication (might be hard with a drone which flies/moves)

  [1]: https://www.sparkfun.com/products/retired/9411
  [2]: https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-900-Datasheet.pdf


body:
I am trying to let a stepper find home (via microswitch) after power up. After that make it move 45 degrees (or the equivalent in steps) and wait for 3 seconds. Below is the code i found/adapted.

The setup part kind of works, but does not run smoothly.

The stepper1() part does not work at all (only jerking movements).

I would also like the motor to be disable when it waits which in my understanding should be achieved by `digitalWrite(M2en,HIGH);`but when I place this at the beginning and end (LOW, HIGH) of stepper1() it never worked. Any ideas would be great.

    #include "AccelStepper.h"

    int M2dirpin = 4;  //Motor Y direction pin
    int M2steppin = 5; //Motor Y step pin
    int M2en=12;  //Motor Y enable pin
    #define home_switch 9 // Pin 9 connected to Home Switch (MicroSwitch)

    // AccelStepper Setup
    AccelStepper stepperX(1, 5, 4);   // (1,2,3) = (Dedicated Board, STEP, DIR)
    // Stepper Travel Variables
    long initial_homing = -1; // Used to Home Stepper at startup

    void setup() {

      pinMode(home_switch, INPUT_PULLUP);
      pinMode(M2dirpin,OUTPUT);
      pinMode(M2steppin,OUTPUT);
      pinMode(M2en,OUTPUT);
      digitalWrite(M2en,LOW);
      Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
      stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
      stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper

      // Start Homing procedure of Stepper Motor at startup
      Serial.print("Stepper is Homing . . . . . . . . . . . ");

      while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
        stepperX.moveTo(initial_homing);  // Set the position to move to
        initial_homing--;  // Decrease by 1 for next move if needed
        stepperX.run();  // Start moving the stepper
        delay(20);
      }

      stepperX.setCurrentPosition(0);  // Set the current position as zero for now
      stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
      stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper
      initial_homing = 1;

      while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
        stepperX.moveTo(initial_homing);
        stepperX.run();
        initial_homing++;
        delay(20);
      }

      stepperX.setCurrentPosition(0);
      Serial.println("Homing Completed");
      Serial.println("");

     // Move 10 steps forward from the limit switch (to get out of the switch)
      while (stepperX.currentPosition() != 10)
      {
        stepperX.setSpeed(10);
        stepperX.run();

    }
    }
    void loop()
    {
    //stepper1();
    }

    void stepper1()
    {
      stepperX.move(22.5);
      stepperX.run();
      delay(3000);
    }

title: How to Home a stepper and make it move 45 degree after that

Answers: 1

body:
You need to call `run` more often. From the [documentation](http://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#a608b2395b64ac15451d16d0371fe13ce):

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

So a single `run` call and then a delay, will make the motor move only one step. So you need to rewrite for example:

    stepperX.run();
    delay(3000);

to

    unsigned long startMillis = millis();
    while( millis()-startMillis<3000 )
    {
      stepperX.run();
    }

Secondly, `move` only works on integers, `stepperX.move(22.5);` will actually become `stepperX.move(22);`

Lastly, why are you using a totally different method from the rest, to move the motor 10 steps? I'd use a moveTo(10), like you are using everywhere else.


body:
![DHT11](https://i.stack.imgur.com/eiCeu.jpg)

I am trying to get my DHT 11 from the official arduino store to work (https://store.arduino.cc/grove-temperature-humidity-sensor).

I am following this guide right here:
http://wiki.seeedstudio.com/Grove-TemperatureAndHumidity_Sensor/

But I'm only getting invalid output of 0 humidity and 0 degrees.

I hope the image helps in identifying my problem.

On a side note, my sensor looks like a part is missing which is very strange and makes me doubt the right product was sent to me.

Some more information:
- Black to GND
- Red to 5v
- White is wmpty
- Yellow to d2
- Using an arduino Uno
- Output does not change whether the sensor is actually connect or not.
- Total noob at this.

Help would be appreciated a lot!

![sensor detail](https://i.stack.imgur.com/MERWr.jpg)

title: DHT 11 temp. And hum. Sensor always 0 values

Answers: 1

body:
You haven't bought a DHT11 module but the *Grove - Temperature&Humidity Sensor (High-Accuracy & Mini) / TH02* module.

![module](https://camo.githubusercontent.com/2d556d0497a63f9ecdab0cd23bc7a05eaa0bd43b/68747470733a2f2f73746174696373332e736565656473747564696f2e636f6d2f696d616765732f70726f647563742f47726f766525323054656d25323048756d25323041636375726163792532304d696e692e6a7067)

Thus you should use the example code [here](https://github.com/Seeed-Studio/Grove_Temper_Humidity_TH02) or follow the guide at [seedstudio wiki](http://wiki.seeedstudio.com/Grove-TemptureAndHumidity_Sensor-High-Accuracy_AndMini-v1.0/).

Datasheet of the sensor: https://www.silabs.com/documents/public/data-sheets/Si7005.pdf


body:
I would like to control a DC motor's speed using the PWM output from my motherboard header.

Here's the standard pinout for a 4-wire PC fan header:

```
╔═══╦════════╦═════════════════╦════════╗
║ # ║  Name  ║   Description   ║  Wire  ║
╠═══╬════════╬═════════════════╬════════╣
║ 1 ║ GND    ║ Ground          ║ black  ║
║ 2 ║ +12V   ║ Fan Power       ║ yellow ║
║ 3 ║ SIGNAL ║ Fan RPM         ║ green  ║
║ 4 ║ PWM    ║ Digital Control ║ blue   ║
╚═══╩════════╩═════════════════╩════════╝
```

Since my DC motor doesn't have a PWM input, I thought of using an `ATmega328P` in my custom board to read the PWM output of the fan header -- pin 4 -- so that I can use a motor driver to control my motor's speed.

However, I'm not sure how I should read the PWM signal from the motherboard.

1. What is the `HIGH` voltage level of PWM output?
   Do I need a voltage divider resistor for it?

   A source for the fan control specifies this to be **5.25V** at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.

2. Should I use [`pulseIn()`][1] function for the 25kHZ (21~28kHZ range) PWM output?
   Can the ATmega328p handle this frequency range?

I prefer to use Arduino's bootloader with the wiring library, but if you have AVR-specific examples that I could follow, I'd appreciate it.

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

title: How to read a 25 kHZ PWM signal from PC fan header?

Answers: 1

body:
> Should I use pulseIn() function for the 25kHZ (21~28kHZ range) PWM output?
Can the ATmega328p handle this frequency range?

No, and No; 1/25000 = .000040 or 40 microseconds (μS) and the [documentation][1] for pulseIn() says:

> Works on pulses from 10 microseconds to 3 minutes in length

However the PWM frequency is the maximum on time, at 50% you will have a square wave that is HIGH for 20 μS and low for 20 μS. pulseIn will not work if the PWM duty cycle goes below 25%

What you want to do is put an 'accumulator' (an RC filter) between the PWM output and an analog input pin, and read the voltage off of that.

However since you want to

> ... control a DC motor's speed using the PWM output from my motherboard header

and the fanspeed header is already designed to do this, you just use the PWM signal to drive a transistor that drives the motor, the motor itself will act as an accumulator here; no micro controller needed!

> ... so that I can use a motor driver to control my motor's speed.

you will need to generate an extremely similar, almost certainly identical, PWM signal to drive your motor controller/driver

> A source for the fan control specifies this to be 5.25V at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.

Trust your documentation or test it if you don't trust the docs!

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/


body:
I am using the Timer library here with the Adafruit feather m0:
https://github.com/JChristensen/Timer
https://playground.arduino.cc/code/timer
I cannot figure out why I am getting the error:

no matching function for call to 'Timer::every(int, void (&)())'

Here is that part of the code:

    void setup(){
          everyAlt = t.every(100, readAltimeter);
          everyLaunch = t.every(500, detectLaunch);
          t.oscillate(blueled, 500, HIGH);
        }

        void readAltimeter(){
          alts[altPlace] = bmp.readAltitude()-zeroAlt;
          altPlace++;
        }

        void detectLaunch(){
          tempSpeed = 0;
          int x = 0;
          while (x < 5){
            tempSpeed += abs((alts[x]-alts[x+1])*10);
          }
          if (tempSpeed/5 > 5){
            t.stop(everyLaunch);
          }
        }

I am pretty new to arduino so any help would be much appriciated!

title: No matching function call for timer?

Answers: 1

body: Had the wrong version. Correct version downloaded from the current master: github.com/JChristensen/Timer


body:
recently bought an UNIROI Smart Car kit.
(UNIROI Smart Robot Car Kit Arduino Robot Kit with 4 Wheel Drive, Arduino UNO R3 Board, Ultrasonic Sensor, Infrared Tracking Module (No Welding Required) https://www.amazon.co.uk/dp/B07CWS344R/ref=cm_sw_r_cp_tai_wQExCbHT0YM8K)

I bought some extra things with it to make it more interesting, but the problem is is that I need to connect more pins to the Arduino but they are all taken up by the car. What I have noticed is that there are these extra pins along the side of the Arduino board as you can see here: https://i.stack.imgur.com/7nhBO.jpg

I know you guys don’t have it in hand, but I thought I’d give it a shot to see if any of you know I can use those pins.
The description of the car also quotes
“Extended Pin Interface. The chassis is designed with
extended pin interface for Arduino UNO, only need to solder pins for using, more convenient to develop
and build your own robot car kit”

Appreciate any help you guys got.

title: Question on a car kit I bought

Answers: 1

body:
It seems that you'll have to do some extended modifications to the design. In fact, all Arduino Pins (D0 - D13, A0-A5) are connected to components on the board and thus in use.

Schematics and Code: https://mega.nz/#F!Xbg1FA5L!qGah_HlLFJ_NKxv7ILLY2g folder "5 SCH".

[![schem][1]][1]

This means that the only way that you'll get new components into this project are:

* removing components  and re-programming the firmware to not use them
 * e.g., the two tracking-sensors left&right -> A2 and A3 are free
 * e.g., the speaker pin (D13). Who needs a speaker?
* restructuring components
   * e.g. for the analog sensors: instead of using the Arduino's analog pins, throw a I2C ADC module (e.g. [ADS1115](https://www.adafruit.com/product/1085)) in the build and change the firmware to get the analog values via that new module; making this project use an I2C bus will free all analog pins and cost 2 pins (SCL + SDA). The I2C bus has the additional benefit of being able to connect more than one device to it -- you can e.g. put a I2C GPIO expander (e.g. MCP23017) on it to gain 16 more digital I/O -- more than the Uno had to begin with.

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


body:
I want to recieve Data with Virtuino from my Arduino Uno 3 (Ethernet Shield) via Ethernet.

Does Arduino Uno 3 support virtual pin? If so - is there a link with the Syntax I need?

Thank you very much

title: Does Arduino Uno come with Virtual Pin support?

Answers: 1

body:
Virtual pins are, as the name gives away, *virtual*, thus not related to the hardware you are using. Imagine you have a board with 100 pins, you have 100 physical pins and can add 1 million virtual pins (memory permitting).
In other words, the question doesn't seem to make sense to me.

**UPDATE**
If you need a bootstrap on *how* virtual pins are defined and used you could give a look at the examples published by the authors, like [these][1]

If that's not enough, please provide additional information on what problem you are facing and which solutions you have already attempted.

  [1]: https://virtuino.com/downloads/examples/bluetooth_example_03_virtual_memory.zip


body:
if I were to use a code with the following format,
```
//some loop
digitalWrite(STEP_PIN,HIGH);
digitalWrite(STEP_PIN,LOW);
//
```
each loop would make the motor move at one step. With this loop I can also make the motor move at 200 or other integer steps. However, is it possible to make the motor move at decimal steps such as 0.4?

title: How do you make a stepper motor move at decimal (such as 0.5) steps?

Answers: 0


body:
I have two nRF24L01 modules (I tried 2 with antenna and 2 without antenna) paired with their power base module and connected to two different Arduino Mega 2560 boards.
I'm able to send from one module to another up to 32 byte of data and get the acknowledge without any problems. But when I switch them, when I try to send data from receiver and receive it on the sender I have nothing. No data received, no acknowledge sent as response.

As I said before, first part of this code works well, but when it comes to the second part, which is after `delay(1000);` there's silence...

my code is:

**Receiver**

    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #include "printf.h"

    // Set pipes
    const uint64_t pipe01_ = 0xE8E8F0F0A1LL;
    const uint64_t pipe02_ = 0xE8E8F0F0A2LL;
    const uint64_t pipe03_ = 0xA3LL;
    const uint64_t pipe04_ = 0xA4LL;
    const uint64_t pipe05_ = 0xA5LL;
    const uint64_t pipe06_ = 0xA6LL;

    RF24 radio(9, 53);

    void setup()
    {
        Serial.begin(115200);
     delay(250);
     radio.begin();
     radio.setChannel(0x57);
     radio.setPALevel(RF24_PA_LOW);
     radio.enableAckPayload();
     radio.openReadingPipe(1, pipe01_);
     radio.openWritingPipe(pipe02_);
     radio.enableDynamicPayloads();
     radio.startListening();
    }

    void loop()
    {
        if (radio.available())
        {
         char newMessage[33];
            memset(newMessage, 0, sizeof(byte) * 33);
            while (radio.available())
            {radio.read(newMessage, 32);}

            Serial.println("newMessage: " + String((const char*)newMessage));
            delay(1000);
            radio.stopListening();

            char response[32] = "1234567890qwertyuiopasdfghjklzxc";
            radio.write(response, 32);
         unsigned long ack = 0;
         if (radio.isAckPayloadAvailable())
         {
          radio.read(&ack, sizeof(ack));
                Serial.println("ack: " + String(ack));
         }
            radio.startListening();
        }
    }

**Sender**

    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #include "printf.h"
    // Set pipes
    const uint64_t pipe01_ = 0xE8E8F0F0A1LL;
    const uint64_t pipe02_ = 0xA2LL;
    const uint64_t pipe03_ = 0xA3LL;
    const uint64_t pipe04_ = 0xA4LL;
    const uint64_t pipe05_ = 0xA5LL;
    const uint64_t pipe06_ = 0xA6LL;

    RF24 radio(9, 53);

    void setup()
    {
        Serial.begin(115200);
        delay(250);
        radio.begin();
        radio.setChannel(0x57);
        radio.setPALevel(RF24_PA_LOW);
        radio.enableAckPayload();
        radio.openReadingPipe(2, pipe02_);
        radio.openWritingPipe(pipe01_);
        radio.enableDynamicPayloads();
        radio.stopListening();

        char message[32] = "qwertyuiopasdfghjklzxc1234567890";
        radio.write(message, 32);

        radio.startListening();
    }

    void loop()
    {
        if (radio.available())
        {
            char respMessage[33];
            memset(respMessage, 0, sizeof(byte) * 33);
            while (radio.available())
            {radio.read(respMessage, 32);}

            Serial.println("respMessage: " + String((const char*)respMessage));
        }
    }

Please help me.

title: nRF24L01 using sender as receiver and vice versa with RF24 library

Answers: 1

body:
**Update:** It was working yesterday, but today... same thing as with "delay()". What's wrong with these radio-modules??

I have discovered that the `delay()` function was causing this abnormal behavior.

So I have implemented periods instead of `delay()` and now I'm able to switch operating mode between "receiver" and "transmitter". Moreover, I have discovered few additional conditions that must be met (read the comments for the code).

Below is working sample code where transmitter sends some large message. Receiver gets it, waits 2 secs, then responds with another large message and gets the acknowledge for this message:

**Sender**

    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #include "printf.h"
    const uint64_t pipe01_ = 0xE8E8F0F0A1LL; //Writing pipe must be full address if acknowledges will be used
    const uint64_t pipe02_ = 0xE8E8F0F0A2LL; //At least one of reading pipes must be full adress
    const uint64_t pipe03_ = 0xA3LL;
    const uint64_t pipe04_ = 0xA4LL;
    const uint64_t pipe05_ = 0xA5LL;
    const uint64_t pipe06_ = 0xA6LL;
    RF24 radio(9, 53);

    void setup()
    {
        Serial.begin(115200);
        delay(250);
        radio.begin();
        radio.setChannel(0x57); //not necessary. But must be equal at both sides
        radio.setPALevel(RF24_PA_LOW); //not necessary. But must be equal at both sides
        radio.enableAckPayload(); //For ability to change the Ack Payload with writeAckPayload()
        radio.openReadingPipe(2, pipe02_); //At least one of reading pipes must be full adress
        radio.openWritingPipe(pipe01_); //Writing pipe must be full address if acknowledges will be used
        radio.enableDynamicPayloads(); //If not set, size will be of fixed length. Default fixed length is 32 bytes

        /*Must run this if "startListening()" will be used anywhere in the code below.
        nRF24L01 remembers it's state even if Arduino was restarted*/
        radio.stopListening();
        Serial.println("Sending the message...");
        char message[32] = "qwertyuiopasdfghjklzxc1234567890"; //some test message
        radio.write(message, 32); //Send message over the predefined "writing pipe"

        Serial.println("Waiting for response...");
        radio.startListening(); //Resets TX buffer and switches radio module's mode to "receiver"

        uint16_t ack = 123;
        radio.writeAckPayload(2, &ack, sizeof(ack)); //Custom ACK payload must be set after "startListening()". Because "startListening()" resets TX buffer
    }

    void loop()
    {
        if (radio.available())
        {
            char respMessage[33];
            memset(respMessage, 0, sizeof(byte) * 33);
            while (radio.available())
            {radio.read(respMessage, 32);}

            Serial.println("respMessage: " + String((const char*)respMessage));
     }
    }

**Receiver**

    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #include "printf.h"

    #define period_  2000

    // Set pipes
    const uint64_t pipe01_ = 0xE8E8F0F0A1LL; //At least one of reading pipes must be full adress
    const uint64_t pipe02_ = 0xE8E8F0F0A2LL; //Writing pipe must be full address if acknowledges will be used
    const uint64_t pipe03_ = 0xA3LL;
    const uint64_t pipe04_ = 0xA4LL;
    const uint64_t pipe05_ = 0xA5LL;
    const uint64_t pipe06_ = 0xA6LL;

    unsigned long checkPoint = 0;
    bool messageReceived = false;
    RF24 radio(9, 53);

    void setup()
    {
     Serial.begin(115200);
     delay(250);
     radio.begin();
     radio.setChannel(0x57); //not necessary. But must be equal at both sides
     radio.setPALevel(RF24_PA_LOW); //not necessary. But must be equal at both sides
     radio.enableAckPayload(); //For ability to change the Ack Payload with writeAckPayload()
     radio.openReadingPipe(1, pipe01_); //At least one of reading pipes must be full adress
     radio.openWritingPipe(pipe02_); //Writing pipe must be full address if acknowledges will be used
     radio.enableDynamicPayloads(); //Writing pipe must be full address if acknowledges will be used
     radio.startListening(); //If not set, size will be of fixed length. Default fixed length is 32 bytes
    }

    void loop()
    {
     if (radio.available())
     {
      char newMessage[33];
      memset(newMessage, 0, sizeof(byte) * 33);
      while (radio.available())
      {radio.read(newMessage, 32);}

      Serial.println("newMessage: " + String((const char*)newMessage));
      checkPoint = millis();
      messageReceived = true;
     }

     unsigned long timePassed = millis() - checkPoint;

     //When it receives, controller waits for 2 seconds then sends the response just one time
     if (messageReceived && timePassed > period_)
     {
      messageReceived = false;
      checkPoint = millis();
      Serial.println("sending response...");

      //This must be called before sending anything (except acknowledges)
      radio.stopListening(); //Resets TX buffer and switches radio module's mode to transmitter

      char response[32] = "1234567890qwertyuiopasdfghjklzxc";
      radio.write(response, 32);

      unsigned long ack = 0;
      if (radio.isAckPayloadAvailable())
      {
       radio.read(&ack, sizeof(ack));
       Serial.println("ack received: " + String(ack));
      }

      radio.startListening(); //Resets TX buffer and switches radio module's mode to "receiver"
     }
    }


body:
Hello i want to get and compare incomming call number, it works but not as I want.
When im calling from good number it print that I was calling form saved number when the number is stop calling i need to do it on start. And `else` is printing when nobody is calling. How can i do it? Here is my code:

    String d = "";
    void setup()
    {
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial1.println("AT");
      delay(500);
      Serial1.println("AT+CLIP=1");
      delay(1000);
      Serial1.println("AT+CPIN=1439");
    }
    void loop()
    {
     d = Serial1.readString();
     if(d.indexOf("xxxxxxxxx") >=0)
       {
     Serial.println("call is from saved number");
        } else {
           Serial.println("call is not from saved number");
          }
    }

title: I want to get incomming call number and compare it

Answers: 1

body:
The Arduino Serial class member function [`readString()`][1] has a builtin timeout. The function will return on timeout. The default timeout period is 1000 ms. The timeout can be set with [`setTimeout()`][2].

The sketch needs to filter out empty lines (timeout). This can be done by adding a check of the string length. See below for an example of checking:

    void loop()
    {
      String d = Serial1.readString();
      if (d.length() == 0) return;
      Serial.print(d);
      if (d.indexOf("xxxxxxxxx") >= 0) {
        Serial.println(": call is from saved number");
      }
      else {
        Serial.println(": call is not from saved number");
      }
    }

Cheers!

  [1]: https://www.arduino.cc/en/Serial/ReadString
  [2]: https://www.arduino.cc/en/Serial/SetTimeout


body:
I have connected the LCD by the 3 wire method using the LiquidCrystal595 library+74HC595 register shift; sometimes "hello world" is displayed but other times the LCD displays weird characters.
How to solve this problem?

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

[![The circuit][2]][2]

  [1]: https://i.stack.imgur.com/z3jn8.jpg
  [2]: https://i.stack.imgur.com/IPGo8.jpg

title: LCD displays weird characters

Answers: 0


body:
I have the code to pass the data from dht22 to sd but for only one and i want to pass the data from 1 dht22 with one file and the data from other sensor to other file and logging in to sd. Anyone can help me?

```
#include
#include
#include "DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
File data_file;

int CS_pin = 10;
long sec=00;
long mint=00;
long hr=00;

void setup() {
Serial.begin(9600);
pinMode(CS_pin, OUTPUT);
dht.begin(); //This command will start to receive the values from dht22
// SD Card Initialization
if (SD.begin())
{
Serial.println("SD card is initialized and it is ready to use");
} else
{
Serial.println("SD card is not initialized");
return;
}
}

void loop() {
data_file = SD.open("data.txt", FILE_WRITE);
if (data_file) {
getData();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data.txt");
}
delay(1000);
}

void getData(){
for(long sec = 00; sec < 60; sec=sec+2){
float temp = dht.readTemperature(); //Reading the temperature as Celsius and storing in temp
data_file.print(hr);
data_file.print(":");
data_file.print(mint);
data_file.print(":");
data_file.print(sec);
data_file.print(", ");
data_file.println(temp);
Serial.print(hr);
Serial.print(":");
Serial.print(mint);
Serial.print(":");
Serial.print(sec);
Serial.print(", ");
Serial.println(temp);
if(sec>=58){
mint= mint + 1;
}
if (mint>59){
hr = hr + 1;
mint = 0;
}
data_file.flush(); //saving the file
delay(2000);
}
data_file.close(); //closing the file
}
```

Thanks

title: Use 2 DHT22 AND PASS THE DATA TO SD?

Answers: 1

body:
First you need to setup the second DHT sensor and a second file. Please replace the `X` by the number of the pin your second sensor is connected to after `#define DHTPIN2`

    #define DHTPIN 8
    #define DHTPIN2 X
    #define DHTTYPE DHT22
    DHT dht(DHTPIN, DHTTYPE);
    DHT dht2(DHTPIN2, DHTTYPE);
    File data_file, data_file2;

In `setup()` you need to also start the second dht sensor:

    dht.begin(); //This command will start to receive the values from dht22
    dht2.begin(); //This command will start to receive the values from dht22

In `loop()` you have to open the second data file in addition to the first one:

    data_file = SD.open("data.txt", FILE_WRITE);
    if (data_file) {
    getData();
    }
    // if the file didn't open, print an error:
    else {
    Serial.println("error opening data.txt");
    }
    data_file2 = SD.open("data2.txt", FILE_WRITE);
    if (data_file2) {
    getData2();
    }
    // if the file didn't open, print an error:
    else {
    Serial.println("error opening data2.txt");
    }

Although not the most efficient/elegant solution, this requires you to duplicate your `void getData()` function as `void getData2()` to work for the second sensor/file, by replacing `dht` by `dht2` and `data_file` with `data_file2`.
This would do the logging on the two sensors in sequence.
If you want the logging in parallel you need to add the measurement and writing of the second sensor/file into the `void getData()` function.


body:
I have a project that has a photoresistor wired into a voltage divider and connected through a 3.5mm “stereo mini plug”. When nothing is in the mini plug, the analog line is an open circuit, and floats, creating jittery spurious readings.

I’d like to wire a pull-down resistor into the project box to tie it to ground so I get a zero reading when the light sensor is not connected, but want to alter the voltage reading from my photo sensor voltage divider circuit as little as possible.

If I connect a 100KΩ resistor between my analog input and ground, that would give me zero readings on the analog pin when the photo sensor is not plugged in, wouldn’t it? I can’t see how < 20 CM of 26 gauge wire would pick up enough interference to pull my analog pin up from 0 through a 100kΩ resistor.

What is the effective range of an analog pin on an Arduino? (A Mega 2560, if that matters) What’s the lowest voltage that will register above 0?

(The project box is getting crowded, so experimenting is getting tricky. I’d like to make a single change rather than trying different resistor values.)

title: Would a 100KΩ resistor connected to ground pull an open analog line down to 0

Answers: 2

body:
I would expect a 100K pulldown to quiet the A/D, but I'd have to actually try it. I'd think testing it on the bare board, outside of your project box would still give you useful information. But I would sketch up the schematic of the proposed voltage divider with the parallel pulldown and run the numbers to convince yourself of what effect it will have on your measurement. You may be able to ignore it, or you may want to correct for it.

> What is the effective range of an analog pin on an Arduino?

0 - (1023/1024)*Vref, whichever reference, 1.1v, 2.56v, or Vcc applied to the Vref pin, you have selected.

> (A Mega 2560, if that matters) What’s the lowest voltage that will
> register above 0?

Appx (Vref * 2^-11), i.e.,  1/2 an LSB of the 10-bit A/D range.

Update:

Is that a jumper selection?

No, it's programmable; the external Vref is reset default. See ch. 25 of the 2560 datasheet for the low-level details; Arduino.cc's function-reference, for the [`analogReference()`][1] function for the quick & dirty how-to. Remember to take and discard a measurement whenever you change the reference.

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/

body:
With a 100 kΩ resistor to GND, it is not guaranteed that the value will be zero. If a (servo)motor is connected, it might get some noise.

The pull down resistor can be any value, because it is possible to calculate the value of the photoresistor.

There is an alternative solution. I think that all the analog pins of the Arduino Mega 2560 are digital pins as well. You can do a `pinMode(A0,INPUT_PULLUP);` to pull the input high. When a photoresistor is connected, you can turn the internal pullup resistor off with `pinMode(A0,INPUT);`.


body:
I have made a class called subjects and I have then made a subject called math. I am trying to set a classroom for math but it is giving me the error 'math' doesn't name a type.

Code for the class

    class subject {
    public:
      char subjectname[];
      char classroom[];

    };

Code for the classroom and math

    subject math;
    math.classroom = "A1";

How can I set the classroom of math to A1?

title: Error: Does not name a type

Answers: 1

body:
    class subject {
    public:
      char subjectname[];
      char classroom[];

    };

This creates a class `subject` which has two `char` arrays of unspecified size as its members. This will attempt to create an array of size 0 (see [here](https://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c)). This is not what you want. You can e.g. statically allocate the space with a maximum number of characters beforehand and then `strncpy()` your new string inside the buffer.

This would look like

    class subject {
    public:
      char subjectname[32];  //32 bytes buffer
      char classroom[32];
    };

And later

    subject math;
    strncpy(math.classroom, "A1", 31); //copy at max 31 bytes to not overwrite the NUL terminator
    Serial.print("Classroom is: ");
    Serial.println(math.classroom)

Or, just use the Arduino `String` class.  For example

    #include <Arduino.h>
    class subject {
    public:
      String subjectname;
      String classroom;
    };

Then your first usage code can be used unmodified.

Example

    #include <Arduino.h>

    class subject {
    public:
      String subjectname;
      String classroom;
    };

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

        subject math;
        math.classroom = "A1";

        Serial.print("Classroom is: ");
        Serial.println(math.classroom);
    }

    void loop() { }


body:
So I'm trying to read an 8-byte character string from an I2C device and print it to the serial console. This raw 8-char array is *not* terminated when it comes from the device, so I'm pretty sure I need to manually terminate it. Unfortunately, when I go to print the resultant string, the serial monitor just fills up with line breaks. Could someone take a look at this code and tell me where I went wrong?

    uint8_t* HT_Controller::readMultiple(uint8_t reg, uint8_t num)
    {
        Wire.beginTransmission(i2cAddr);
        Wire.write(reg);
        Wire.endTransmission();

        Wire.requestFrom(i2cAddr, num);
        uint8_t* data = new uint8_t[num];

        for(int i = 0; i < num; i++)
        {
            data[i] = Wire.read();
        }

        return data;
    }

    char* HT_Controller::getManufacturer()
    {
        uint8_t* data = readMultiple(REGISTER_MFR, NUM_MFR_BYTES); //Read the bytes from the controller
        char* dataTerminated = new char[NUM_MFR_BYTES + 1]; //Our new array that will have a null char at the end
        memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array
        delete(data); //We're done with the original array, remove it from the heap
        dataTerminated[NUM_MFR_BYTES] = 0; //Add that null char. NB: we don't need to '+1' the index because arrays start at 0, not 1

        return dataTerminated;
    }

And here's how it's used in the main sketch:

    void loop()
    {
        char* data = mc1->getManufacturer();
        Serial.println(data);
        delete(data);
        delay(500);
    }

title: Weird behavior with char/uint8 arrays

Answers: 1

body:
Your memcpy is backwards.

    SYNOPSIS
       #include <string.h>

       void *memcpy(void *dest, const void *src, size_t n);

So the line:

    memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array

should be:

    memcpy(dataTerminated, data, NUM_MFR_BYTES); //Copy the bytes into the new array


body:
I am using this code and I can not save the output of the hash function to an array of `char`. Can you help me how to do that?

    #include "sha256.h"
    #include <Arduino.h>
    #include "./printf.h"

    void printHash(uint8_t* hash) {
      int i;
      for (i=0; i<32; i++) {
        Serial.print("0123456789abcdef"[hash[i]>>4]);
        Serial.print("0123456789abcdef"[hash[i]&0xf]);
      }
      Serial.println();
    }

    void setup()
    { String FinalStr="1234567890";
    Sha256.init();
      Sha256.print(FinalStr);
      printHash(Sha256.result());
    }
    void loop()
    {

    }

title: Storing hash values from SHA256

Answers: 2

body:
Save to a character vector (64 characters + NULL):

    void copyHash(char* buf, uint8_t* hash) {
      int i, j = 0;
      for (i = 0; i < 32; i++) {
        buf[j++] = "0123456789abcdef"[hash[i]>>4];
        buf[j++] = "0123456789abcdef"[hash[i]&0xf];
      }
      buf[j] = 0;
    }

    void setup()
    {
      String FinalStr="1234567890";
      Sha256.init();
      Sha256.print(FinalStr);
      char buf[65];
      copyHash(buf, Sha256.result());
    }

Cheers!

body:
This is the code that worked for me:

    #include "sha256.h"
    void setup(void)
    {char encoded[64];
        Serial.begin(9600);

        // this is actually the RFC4231 4.3 test

        Sha256.init();
        Sha256.print("123");
        uint8_t * result = Sha256.result();

        Serial.println("Expect: 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881");
        Serial.print(  "Got   : ");
        for (int i = 0; i < 32; i++) {
                Serial.print("0123456789abcdef"[result[i] >> 4]);
                Serial.print("0123456789abcdef"[result[i] & 0xf]);

                for(int i = 0; i < 64; i+=2)
                    {
                      encoded[i] = "0123456789abcdef"[result[i / 2] >> 4];
                      encoded[i + 1] = "0123456789abcdef"[result[i / 2] & 0xf];
                    }
        }
        Serial.print("\n");
                for(int z = 0; z < 64; z++)
                Serial.print(encoded[z]);
    }

    void loop(void)
    {}


body: I'm working on an ESP8266 thermostat that should be powered by the 24V AC from the furnace. I'm looking for a converter to 5V DC that would be small enough to fit in a smaller enclosure and not dissipate too much heat. Not fully sure about the current, but I'm planning for up to 500 mA for short periods of time. I found on ebay [this](https://www.ebay.com/itm/AC-DC-Power-Supply-Buck-Converter-Step-Down-Module-3-3V-5V-9V-12V-15V-24V-36V-US/122832954547), but it accepts input from 85V upwards. What would happen if I would feed 24V AC to it? Would it still work. Or alternatively doesn anyone have a link for something similar that would work with 24V?

title: Recommendations for 24V to 5V AC/DC converter

Answers: 2

body:
24VAC rectified with a full diode bridge rectifier (4 diodes) becomes 36VDC when smoothed with a cap, the datasheet indicates this part would be okay with that. You'd probably be okay as you're planning <500mA output most of the time.

https://www.digikey.com/product-detail/en/murata-power-solutions-inc/OKI-78SR-5-1.5-W36-C/811-2196-5-ND/2259781

body:
Transformers for furnaces are typically Class 2 transformers, energy limited. Unloaded, or lightly loaded, they produce a significantly higher output voltage than the rated output voltage, 24 volts in this case. 28 volts is typical, and it may be higher during high line situation. The 24 volt rating is a loaded voltage, with a resistive load.

28rms x 1.4 = 39.2 volts

You should be using a regulator with a voltage rating of at least 40 volts, and that is really marginal.

https://www.aliexpress.com/item/1pcs-2018-new-dc-dc-converter-12V-24V-36V-48V-60V-72V-to-5V-0-5A/32922897633.html

The AC-DC converter you linked to would not work. It has a low voltage cutout. It also would not be able to provide the power if it was able to work at the lower voltage. The input current would be much higher than the normal input current at a normal line voltage.


body:
What are the voltages on a ATmega32u4 (eg Arduino Leonardo) such that a `HIGH` or `LOW` is read?

I want to ensure that I'm reading the [chip reference manual](http://ww1.microchip.com/downloads/en/devicedoc/atmel-7766-8-bit-avr-atmega16u4-32u4_datasheet.pdf) correctly, where Table 29-1 says:

----------

VIL: Input Low Voltage, Except XTAL1 and Reset pin

 * Min: -0.5
 * Max: 0.2VCC-0.1V (LVTTL)

VIH: Input High Voltage, Except XTAL1 and RESET pins

 * Min: 0.2VCC+0.9V (LVTTL)
 * Max: VCC + 0.5V

----
My questions:

1. What is LVTTL?
2. How do I interpret the VIL Max and VIH Min?
3. Is the input undefined between those two values?

title: Digital I/O threshold voltages for ATmega32u4

Answers: 1

body:
 1. LVTTL is Low Voltage Transistor-Transistor Logic. In general, the
    term "TTL" is used for a digital signal.
    The "Low Voltage" part is special,
    the ATmega32U4 switches from low to high (and vice versa)
    at low voltages.
 2. Just as it is written. For example, when the ATmega32U4 runs at 5V,
    then:
    VILmax = 0.2 * 5 - 0.1 = **0.9 V**.
    VIHmin = 0.2 * 5 + 0.9 = **1.9 V**.
 3. Between those values the input signal is seen as low or high,
    but the exact voltage when it switches from low to high may
    vary.
    When the microcontroller is running at 5.0 V and is used
    within the specifications of the datasheet, then a voltage
    below 0.9 V is always seen as low and
    a voltage above 1.9 V is always seen as high (guaranteed).
    Those voltages is what a electronics designer must consider.

In the [datasheet of the ATmega32U4][1] at page 403 is paragraph 30.7 "Pin Threshold and Hysteresis" with figure 30-22 and 30-23.
The figures show that at 25°C and 5V, the input switches from low to high typical at 1.55 V and it switched from high to low at maybe a slightly lower voltage.
The hysteresis is almost none and the voltage depends on VCC and the temperature.

[![pin input threshold voltage][2]][2]

(*Thanks to Edgar Bonet for the correction/addition*)

  [1]: http://ww1.microchip.com/downloads/en/devicedoc/atmel-7766-8-bit-avr-atmega16u4-32u4_datasheet.pdf
  [2]: https://i.stack.imgur.com/1rQ6V.png