body:
Also when I am trying to see the data read on pins in serial monitor, it is not reading as required. The code i am using is as follows:

    const int tuch_Pin0=18;
    const int tuch_Pin1=19;
    const int tuch_Pin2=21;
    const int tuch_Pin3=22;
    const int tuch_Pin4=32;

    int State1=0;
    int State2=0;
    int State3=0;
    int State4=0;
    int State5=0;

    void setup() {
      Serial.begin(38400);
      pinMode( tuch_Pin0,INPUT);
      pinMode( tuch_Pin1,INPUT);
      pinMode( tuch_Pin2,INPUT);
      pinMode( tuch_Pin3,INPUT);
      pinMode( tuch_Pin4,INPUT);
    }

    void loop() {

        State1= digitalRead(tuch_Pin0);
        State2= digitalRead(tuch_Pin1);
        State3= digitalRead(tuch_Pin2);
        State4= digitalRead(tuch_Pin3);
        State5= digitalRead(tuch_Pin4);

        if( State1!=0){

             Serial.println("Touch0 press");
        }
        else if(State2!=0)
        {
          Serial.println("Touch1 press");
        }
         else if(State3!=0)
         {
             Serial.println("Touch2 press");
         }

         else if(State4!=0)
         {
           Serial.println("Touch3 press");
         }
       else if ( State5!=0)
       {
        Serial.println("Touch4 press");
       }
       else
       {
        Serial.println("please press any key");
       }
       delay(100);
    }

.....................the output it shows is... `touch press 0`.. without any touch and shows press any key when I touch any pin. Where I am wrong? Any solution, please?

title: AT42QT1070 sensor output issues in standalone mode

Answers: 0


body:
First of all, thank you for taking the time to read this. I am a newbie, so apologies (done examples on arduino website, basic C++).

I'm trying to get an idea of what the best way to structure a sketch is, which needs to do several things at the same time. For example, reading an IMU sensor and using it to control the mouse, reading a button for on/off and let's say flashing an LED. I have repetitive injury so this is the project I'm trying to complete, but the principle should be scalable for more complex projects.

I've come across some great resources and my understanding is you can use:

 1. [functions (e.g. blink without delay)][1]
 2. [objects (cooperative multitasking)][2]

 3. [interrupts][3]
 4. [something like a RTOS][4]

Where my limits lie is understanding the benefits/limitations of these options and picking which one to focus on for my project. For example, if using functions is sufficient, why do people bother with interrupts and installing a RTOS?

I would appreciate any guidance for what an effective approach should look like.

Thanks again.

  [1]: https://forum.arduino.cc/index.php?topic=223286.0
  [2]: http://paulmurraycbr.github.io/ArduinoTheOOWay.html
  [3]: https://www.allaboutcircuits.com/technical-articles/using-interrupts-on-arduino/
  [4]: https://www.freertos.org/about-RTOS.html

title: Doing several things at the same time with functions, objects or interrupts?

Answers: 1

body:
An RTOS may be a good option for running a complex application on a
quite powerful Arduino. Many Arduinos (the AVR-based ones), however, are
too limited to run complex applications, and the overhead of an RTOS is
quite significant for them. In this case you end up with two options:

* non-blocking programming
* interrupts

Whichever is best depends on the specific tasks you are managing.

### Non-blocking programming

This is best exemplified by the [Blink Without Delay][] Arduino
tutorial. The general principle is to break down you code into small
non-blocking tasks, and perform each one only when it is the right time
to do so. Breaking down the program logic into a set of non-blocking
tasks is not always completely trivial, but you can use a [Finite state
machine][fsm], which is a very powerful and general concept for doing so
in a systematic way.

Once all task are non-blocking, the main program loop then looks like
this pseudo-code:

```c++
void loop() {
    if (task_1_should_be_performed_now()) {
        perform_task_1();
    }
    if (task_2_should_be_performed_now()) {
        perform_task_2();
    }
    // etc...
}
```

Most of the time, all conditions are false, and the program swifts
through the tests completing the loop in a very short time.
Occasionally, it performs one of the tasks, which makes the loop longer
but, since the tasks never block, not very long anyway. Typical loop
time is highly dependent on the specifics of your code, but I would
expect it to be no more than one millisecond most of the time.

This is probably the most common pattern for multitasking on the
Arduino. You can encapsulate this logic in functions, objects,
libraries, etc. This is the approach I would recommend provided none of
your tasks is so urgent that it cannot wait for one loop iteration.

### Interrupts

Occasionally, you may have a task that is so urgent that it cannot wait
for the next loop iteration. It has to be performed right now. Or maybe
the loop takes a very long time because of a blocking call in a library
you have no control over. In those situations, an interrupt may be the
best option.

Interrupts come with some tricky programming issues, which require some
precautions on the part of the programmer:

* they block other interrupts, increasing their latency → interrupt
  service routines should be as short as possible

* they can cause problems with non-reentrant library functions → those
  functions should be avoided in interrupt context

* they can interact badly with the optimizer → variables used in both
  interrupt context and normal context should be qualified as
  `volatile`

* they can cause synchronization issues with the data shared with the
  main code → access to that data in normal context should be protected
  in critical sections.

For all these reasons, it is best to use interrupts only when needed,
i.e. only when a task cannot wait for the next iteration of `loop()`.

[Blink Without Delay]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay
[fsm]: https://majenko.co.uk/blog/finite-state-machine


body:
I want use the `ATmega328P` chip of the `Arduino Uno` board as a **standalone** device.

 - Is that possible?
 - Which pins are which on the Arduino board and the `ATmega328P`?
 - Do I need any external components?

title: Can I use the microchip of Arduino Uno as a standalone microcontroller

Answers: 2

body:
Yes it's possible. To use the ATmega328P to "emulate" an Arduino Uno board (without the USB part) you just need 3 ou 4 additional components: the oscillator, two capacitors and a resistor. Please take a look at: https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoToBreadboard for a schematic/breadboard.
The Atmega328P features itself the memory, cpu and flash so those components are already inside the chip. You can find the relation of the pins in this image: [![Pin matching][1]][1]

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

body:
You can check the [UNO's schematic](https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf). You can use this as a starting position. You can leave out the things you don't need. You might for example have no need for a voltage regulator on your board.

You may also have a look at the [schematic of the Pro Mini](https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf), which are a lot more bare-bones.


body:
I am using Raspberry Pi 4 to connect via usb to program ardino Nano, I intend to communicate with the nano via i2c, but this is irrelivant.

With a fresh install of Arduino for ARM 32 bit I get this error when tring to compile a default (fresh) script:

```
Arduino: 1.8.13 (Linux), Board: "Arduino Nano, ATmega328P"

/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/arduino-builder -dump-prefs -logger=machine -hardware /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware -tools /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/tools-builder -tools /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -built-in-libraries /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/libraries -libraries /root/Arduino/libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10813 -build-path /tmp/arduino_build_228832 -warnings=none -build-cache /tmp/arduino_cache_202507 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.arduinoOTA.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -verbose /tmp/untitled1895295462.tmp/sketch_feb16a/sketch_feb16a.ino
/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/arduino-builder -compile -logger=machine -hardware /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware -tools /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/tools-builder -tools /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -built-in-libraries /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/libraries -libraries /root/Arduino/libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10813 -build-path /tmp/arduino_build_228832 -warnings=none -build-cache /tmp/arduino_cache_202507 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.arduinoOTA.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr -verbose /tmp/untitled1895295462.tmp/sketch_feb16a/sketch_feb16a.ino
Using board 'nano' from platform in folder: /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr
Using core 'arduino' from platform in folder: /home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr
Detecting libraries used...
/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/cores/arduino -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/variants/eightanaloginputs /tmp/arduino_build_228832/sketch/sketch_feb16a.ino.cpp -o /dev/null -DARDUINO_LIB_DISCOVERY_PHASE
Generating function prototypes...
/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/cores/arduino -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/variants/eightanaloginputs /tmp/arduino_build_228832/sketch/sketch_feb16a.ino.cpp -o /tmp/arduino_build_228832/preproc/ctags_target_for_gcc_minus_e.cpp -DARDUINO_LIB_DISCOVERY_PHASE
/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /tmp/arduino_build_228832/preproc/ctags_target_for_gcc_minus_e.cpp
Compiling sketch...
/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/cores/arduino -I/home/pi/Desktop/arduino_32_bit/arduino-1.8.13/hardware/arduino/avr/variants/eightanaloginputs /tmp/arduino_build_228832/sketch/sketch_feb16a.ino.cpp -o /tmp/arduino_build_228832/sketch/sketch_feb16a.ino.cpp.o
Assembler messages:
Error: unrecognized option -mmcu=avr5
exit status 1
Error compiling for board Arduino Nano.

```

I am not sure if it's related, but when I try `sudo ./install.sh` I get the result
```
pi@raspberrypi:~/Desktop/arduino_32_bit/arduino-1.8.13 $ sudo ./install.sh
Adding desktop shortcut, menu item and file associations for Arduino IDE...

touch: cannot touch '/root/.config/mimeapps.list': No such file or directory
/usr/bin/xdg-mime: 848: /usr/bin/xdg-mime: cannot create /root/.config/mimeapps.list.new: Directory nonexistent

 done!
```

But arduino studios runs by the script in the folder. I have tried selecting different Programmers with the same result.
I am using arduino arm 32 bit as the 64 bit arm version does install with no error, but it does not start with the script.

Thanks in advance for any ideas on how I can fix this

title: Fresh install getting Assembler Error

Answers: 0


body:
I have following function for my Arduino:

    String readLine() {
      String received = "";
      char ch;
      while (myFile.available()) {
        ch = myFile.read();
        if (ch == '\n' or ch == '\r') {
          if (ch == '\r')
          {
            //get rid of the \n
            myFile.read();
          }
          return String(received);
        } else {
          received += ch;
        }
      }
      myFile.close();
      hasFile = false;
      return received;
    }

This function is used to return a line from a text file on a SD card. Since I do have to do quite some things on the returned string, I would like to have it as cstr instead of string to increase performance. But I am not able to convert this function to one that returns a Cstr. I tried this but it does not work:

    char* readLine() {
      char* received = "";
      char ch;
      while (myFile.available()) {
        ch = myFile.read();
        if (ch == '\n' or ch == '\r') {
          if (ch == '\r')
          {
            //get rid of the \n
            myFile.read();
          }
          return received;
        } else {
          received += ch;
        }
      }
      return received;
    }

Currently I am converting it after the function returns it, by using `c_str()`. It works, but I dont like it and would like to return a Cstr in the first place.

How can this be done?

Thank you!

title: Arduino - Function -> return Cstr instead of string

Answers: 2

body:
You cannot work with c-strings like with `Strings`. You need to use the standard c-string functions (like `sprintf()`, `strcpy()` and siblings) or directly access the `char` array.

This gives the following problems with your code:

- See this line:

        char* received = "";

    Here you create a pointer to a constant empty string. But this will **NOT** create a buffer, where you can put data. If you want to define a buffer to put the data in, you need to define an array:

        char received[30] = "";

    where `30` is the size of the array and thus the buffer has space for 29 characters (30 minus the one character, that is needed for the terminating null character). Now you could use a counter variable to save the current position in the buffer and set the array elements to the received character:

        int position = 0;
        ...
        received[position] = ch;
        position++;

    Then, when you reached the end of the buffer or you received end of line, you would end the data in the buffer with the null character:

        if (ch == '\n' || ch == '\r' || position == 29) {
            if (ch == '\r')
            {
                //get rid of the \n
                myFile.read();
            }
            received[position] = '\0';

- Now you have the second problem: When defining a variable inside the function, it will become invalid, when you exit the function. You try to return a pointer to `char`, which will point to a non-valid memory location. Thus you cannot simply return an array, that was created inside the function (outside of dynamic allocation). Here commonly an external buffer is provided to the function by reference as a pointer. The function will then write into that buffer and does not need to return it.

        //defining the array outside of the function, for example at global scope
        #define BUFFER_SIZE  30
        char received[BUFFER_SIZE] = "";
        ...
        void readLine(char *buffer, int size) {
            ...
            // Here you can use buffer as a simple char array
            buffer[position] = ch;
        }

    Here I also provide the size of the array as parameter, so that the function can make sure not to exceed that (because that will give you bad and difficult to troubleshoot problems). Then, when the function has run, the read data is now in the `received` character array. This way you don't need to use multiple buffers and also don't need to copy data between buffers.

body:
One way is passing external buffer to readLine() to fill:

    size_t readLine(char * buff, size_t maxChars) {
      size_t pos = 0; // current position in buffer
      while (file.myFileAvalable()) {
        buff[pos] = file.read();
        if (buff[pos] == '\n' || buff[pos] == '\r') {
          buff[pos] = '\0';   // terminate string
          break;              // end the loop
        }
        if (++pos == maxChars-1) { // don't forget about nul terminal character
          buff[pos] = '\0';
          break;              // end the loop
        }
      }
      return pos; // return number of read characters (0 nothing was read)
    }

    /// ...

    char ssid[25] = {0}; // create buffer to store at most 24 characters + \0
    char pass[25] = {0}; // it'll also fill buffers by zeroes

    readLine(ssid, sizeof(ssid)-1);  // it'd be better to check how many characters was read
    readLine(pass, sizeof(pass)-1);  // same here

    WiFi.begin(ssid, pass);
    /// ... But it looks much worst than String, however it's much more efficient, as using += for Strings is quite heap unfriendly

**Big NO-NO is doing something like:**

    char* readLine() {
      char buff[50] = {0};
      // ... fill ...
      return buff;           // NO!!!! buffer doesn't exist after the return - you've got dangling pointer
    }
    // ...
    char * ssid = readLine(); // dangling pointer after that...
    char * pass = readLine(); // now the ssid location was overwritten for sure

**Another NO-NO:**

    char* readLine() {
      static char buff[50] = {0}; // one buffer for all calls, it won't get destroyed after the end... but
      // ... fill ...
      return buff;           // ok, buffer exists after the return,...
    }
    // ...
    char * ssid = readLine(); //
    char * pass = readLine(); // but surprise surprise, ssid and pass points to the same buffer and therefore the same data...


body: I have bought a new Arduino UNO and it works on CH340G. I want to code it using iOS phone, don't have a PC is there any way to install CH340G driver for iOS.

title: How to install CH340G in iOS

Answers: 0


body:
I want to control my ESP8266 device from my secure website via 2 different ways:

 1. **if ESP8266 is connected to internet**, commands between website and device will sent over **MQTT** which as working perfectly as I want to be.
 2. **if ESP8266 is disconnected from internet**, commands should be handled through **HTTP request to local webserver**. (*Given I'm connected to the same router*).

So the website coded this way:
if ( there is internet ) {
 Publish MQTT command
} else {
 Send HTTP request
}

When I tested sending HTTP requests: **http://192.168.100.100/?led=on**
I get error message saying `Mixed content is blocked` given my website is secure while local webserver is not.

Then I tried setting up a secure local webserver on my ESP8266:

 - **With Firefox**: It's working perfectly.
 - **With Chrome**:

       GET https://192.168.100.100/?led=off net::ERR_CERT_AUTHORITY_INVALID

 - **With IPhone Safari**: It is not working and I have no mean to debug right now. But I'm suspecting security issues with local webserver.

As I'm targeting IPhone users, and looking for a solution to improve local webserver security or trying another approach.

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>
    #include <DNSServer.h>
    #include <ESP8266mDNS.h>
    #include <ESP8266WebServerSecure.h>

    const char *dname = "esp8266";
    const char* ssid = "SSID";
    const char* password = "PASS";

    BearSSL::ESP8266WebServerSecure server(443);
    ESP8266WebServer serverHTTP(80);

    int ledPin = 2;

    WiFiClient espClient;
    PubSubClient client(espClient);
    WiFiManager wm;

    int value;

    static const char serverCert[] PROGMEM = R"EOF(
    -----BEGIN CERTIFICATE-----
    MIIC6jCCAlOgAwIBAgIUZIw0cBcWDPJZe8ZIDu6bDqdwwvwwDQYJKoZIhvcNAQEL
    BQAwejELMAkGA1UEBhMCUk8xCjAIBgNVBAgMAUIxEjAQBgNVBAcMCUJ1Y2hhcmVz
    dDEbMBkGA1UECgwST25lVHJhbnNpc3RvciBbUk9dMRYwFAYDVQQLDA1PbmVUcmFu
    c2lzdG9yMRYwFAYDVQQDDA1lc3A4MjY2LmxvY2FsMB4XDTE5MDQxMzE1NTMzOFoX
    DTIwMDQxMjE1NTMzOFowejELMAkGA1UEBhMCUk8xCjAIBgNVBAgMAUIxEjAQBgNV
    BAcMCUJ1Y2hhcmVzdDEbMBkGA1UECgwST25lVHJhbnNpc3RvciBbUk9dMRYwFAYD
    VQQLDA1PbmVUcmFuc2lzdG9yMRYwFAYDVQQDDA1lc3A4MjY2LmxvY2FsMIGfMA0G
    CSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiZmrefwe6AwQc5BO+T/18IVyJJ007EASn
    HocT7ODkL2HNgIKuQCnPimiysLh29tL1rRoE4v7qtpV4069BrMo2XqFvZkfbZo/c
    qMcLJi43jSvWVUaWvk8ELlXNR/PX4627MilhC4bLD57VB7Q2AF4jrAVhBLzClqg0
    RyCS1yab+wIDAQABo20wazAdBgNVHQ4EFgQUYvIljCgcnOfeRn1CILrj38c7Ke4w
    HwYDVR0jBBgwFoAUYvIljCgcnOfeRn1CILrj38c7Ke4wDwYDVR0TAQH/BAUwAwEB
    /zAYBgNVHREEETAPgg1lc3A4MjY2LmxvY2FsMA0GCSqGSIb3DQEBCwUAA4GBAI+L
    mejdOgSCmsmhT0SQv5bt4Cw3PFdBj3EMFltoDsMkrJ/ot0PumdPj8Mukf0ShuBlL
    alf/hel7pkwMbXJrQyt3+EN/u4SjjZZJT21Zbxbmo1BB/vy1fkugfY4F3JavVAQ/
    F49UaclGs77AVkDYwKlRh5VWhmnfuXPN6NXkfV+z
    -----END CERTIFICATE-----
    )EOF";

    static const char serverKey[] PROGMEM =  R"EOF(
    -----BEGIN PRIVATE KEY-----
    MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKJmat5/B7oDBBzk
    E75P/XwhXIknTTsQBKcehxPs4OQvYc2Agq5AKc+KaLKwuHb20vWtGgTi/uq2lXjT
    r0GsyjZeoW9mR9tmj9yoxwsmLjeNK9ZVRpa+TwQuVc1H89fjrbsyKWELhssPntUH
    tDYAXiOsBWEEvMKWqDRHIJLXJpv7AgMBAAECgYA5Syqu3mAKdt/vlWOFw9CpB1gP
    JydvC+KoVvPOysY4mqLFjm4MLaTSjIENcZ1SkxewBubkDHVktw+atgvhfqVD4xnC
    ewMpuN6Rku5A6EELhUoDrgMEt6M9D/0/iPaMm3VDtLXJq5SuKTpnM+vyE4/uM2Gu
    4COfL4GQ0A5KWTzGcQJBANfpU/kwdZf8/oaOvpNZPGRsryjIXXuWMzKKM+M1RqSA
    UQV596MGXjo8k8YG/A99rTmVhbeTMC2/7gIyGTePe/kCQQDAjZg2Ujz7wY3gf1Fi
    ZETL7DHsss74sZyWZI490yIX0TQqKpXqEIKlkV+UZTOoSZiAaUyPjokblPmTkKfu
    uMyTAkBIBjfS+o1fxC+L53Y/ZRc2UOMlcaFtpq8xftTMSGtmWL+uWf93zJoGR0rs
    VkwjRsNQYEaY9Gqv+ESHSvsKg7zRAkEAoOLuhpzqVZThHe5jqumKzjS5dkPlScjl
    xIeaji/msa3cf0r73goTj5HLIev5YKi1or3Y+a4oA4LTkifxGTcRvwJBAJB+qUE6
    y8y+4yxStsWu362tn2o4EjyPL2UGc40wtlQng2GzPZ20+xVYcLxsJXE5/Jqg8IeI
    elVVC46RfjDK9G0=
    -----END PRIVATE KEY-----
    )EOF";

    void showWebpage() {
      int ledStatus = digitalRead(ledPin);

      if (server.hasArg("led")) {
        String status = server.arg("led");
        if (status == "off") {
          digitalWrite(ledPin, HIGH);
          ledStatus = 1;
        }
        else if (status == "on") {
          digitalWrite(ledPin, LOW);
          ledStatus = 0;
        }
      }

      String content = "<!DOCTYPE html>";
      content += "<title>ESP8266 Test Server</title>";
      content += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">";
      content += "<link rel=\"shortcut icon\" href=\"data:image/x-icon;base64,AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA/4QAAAAA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARAiIgEQAiAQASAAEAEgAhABAgAQASACARAAIBEQIiAQASACAQACABABIAIAEAAgARACIAABAAIAAAAAAAAAAAAAAAAAAAAAEREAERAAEAAQAAAAAQAQABAAAAABABAAERAAARAAERAQAAAQAAAQARAAABAAABABEREAAREAERCQmQAAZ2YAAGtmAACdEQAAZrsAAGbdAACZ7gAA//8AAP//AAAMdwAAf7cAAH+3AAAecQAAffYAAH32AAAOMQAA\" />";
      content += "";
      content += "";
      content += "
ESP8266 HTTPS Server
<form action=\"/\" method=\"get\">
ledPin LED Status:";

      if (ledStatus) content += " Turned off";
      else content += " Turned on";

      content += "
";

      if (ledStatus) content += "<input type=\"submit\" value=\"on\" name=\"led\">";
      else content += "<input type=\"submit\" value=\"off\" name=\"led\">";

      content += "</form>";

      content += "
";
      time_t now = time(NULL);
      content += ctime(&now);
      content += "
";

      content += "
For more information see OneTransistor.
";

      server.sendHeader("Access-Control-Allow-Origin", "*");
      server.sendHeader("Access-Control-Max-Age", "10000");
      server.sendHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS");
      server.sendHeader("Access-Control-Allow-Headers", "*");
      server.send(200, "text/html", content);
    }

    void secureRedirect() {
      serverHTTP.sendHeader("Location", String("https://esp8266.local"), true);
      serverHTTP.send(301, "text/plain", "");
    }

    void setup() {
      Serial.begin(115200);  pinMode(ledPin, OUTPUT);  digitalWrite(ledPin, LOW);

        // Connect to Wi-Fi
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {    delay(1000);    Serial.println("Connecting to WiFi..");  }
      Serial.print("Connected to WiFi: ");  Serial.println(WiFi.SSID());
      Serial.print("IP: ");  Serial.println(WiFi.localIP());

      Serial.print("Server can be accessed at https://");
      Serial.print(WiFi.localIP());
      if (MDNS.begin(dname)) {
       Serial.print(" or at https://");
       Serial.print(dname);
       Serial.println(".local");
      }

      serverHTTP.on("/", secureRedirect);
      serverHTTP.begin();

      server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey));
      server.on("/", showWebpage);
      server.begin();

    }

    void loop() {
      serverHTTP.handleClient();
      server.handleClient();
      MDNS.update();
      delay(1000);
    }

title: Controlling Offline ESP8266 from secure website

Answers: 0


body:
I'm a researcher and I'm looking to build a very tiny embedded system. I must to send data from the desert and above the ocean, to do that I think that my single option is to use satellite transmission (and not GSM).

Thus, I found Iridium Satellite (RockBLOCK) but my main issue is that their Arduino module is too big for my project (4cm of length and too heavy).

Do you know if there is other module to send data via satellite with Arduino ?
If not, do you know other microcontroller which can do that ? (Using Arduino is not mandatory for me)

Thank you a lot,
Sincerely.

title: Arduino : send data via satellite (or other solutions ? without GSM)

Answers: 1

body:
My two cents: A possibility might be LoRaWAN on the 2.4GHz spectrum, for which there are also satellites in orbit.

The LoRaWAN ("Long Range Wide-Area-Network") protocol is based on a chirp-spread-spectrum (CSS) modulation and has a very high range.

I've used LoRaWAN before but not on 2.4GHz or with a satelitte, so I can't comment on the practical feasibility. However, there are some materials from The Things Conference (by The Things Network, a leading developer of LoRa network servers).

 * https://www.youtube.com/watch?v=iwocSYupdIQ
 * https://www.youtube.com/watch?v=jlNyBDxpKUw
 * https://enterpriseiotinsights.com/20190618/channels/news/lora-shoots-for-75pc-of-iot-market
* https://enterpriseiotinsights.com/20200130/channels/news/lorawan-enters-2-4gh-plus-satellite-boost-network-sharing-embedded-security
* https://www.semtech.com/company/press/semtech-and-swarm-deliver-satellite-communications-with-lora

Also maybe other modules that can talk to the Iridium satellites suite you better. Sparkfun has a few
* https://www.sparkfun.com/products/13745
* https://www.sparkfun.com/products/16394


body:
My serial monitor window opens frozen, without any output or possibility to input, or even activate the window.
Sketch is very simple, but behavior is same even with empty sketch, so I assume problem is not in sketch. I also checked if sketch is uploaded correctly by uploading simple sketch with blinking diode, which worked.

Same behavior with Arduino Nano and Uno.

I tried to reinstall IDE, uninstalled, removed and reinstalled serial driver (ch340) with no success.

I can see Serial monitor window only on windows taskbar, it won't activate after click.

Until now I haven't had any significant problems with IDE or serial monitor for years.

[![window state][1]][1]

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

title: Serial monitor window opens frozen

Answers: 2

body:
Try updating the java. Also check whether the device manager shows the USB serial port without any yellow warning sign on it.
If there is a current short in the usb port that specific port will be off for safety, restarting the computer should resolve that problem.

body: Unfortunaltely, nothing worked, and after hours of trying and googling I reinstalled windows, and now Serial Monitor works correctly.


body:
We have built a HAB (high-altitude balloon) tracker based on an Arduino and a U-blox GPS module, but we have a sporadic issue where the altitude data gets stuck at odd (usually low) values. The altitude data of two flights are shown below, showing the issue. All other data (lat, long, time etc) is correct, it's just altitude we have the issue with. We would expect a linear increase in altitude, then a quick drop once it bursts. The squares on the graph mark the data points, so it's not just a case of us missing the data. Sometimes it gets stuck at the current value, and sometimes it just gets stuck at a nonsense value.

For example, in both cases the value is initially stuck at about 270m, which is correct for our launch site. However, it then gets stuck at other nonsense values for a long time (less than 500m) before it starts correctly reporting the altitude. In the 2018 chart you can see that the value drops to 0 for a while.

We have searched online and asked on some forums where people often use the U-blox GPS module, but it doesn't seem to be an issue others have come across. Also, the flights shown here were done on 2 different sets of hardware (Arduino and GPS module), with the 2019 flight using brand new components, so we don't think it's a hardware issue. It's not a transmission issue, as one data set is what was recorded by receivers and uploaded to HABHub, and the other is what was stored on the SD card and recovered after the flight. The same code was used for both, so that is our current suspect. The code had been used in previous years without problem, with only minor modifications between years.

The whole code is pasted below, I have highlighted the main loop with ####### as this is where the reading of the GPS occurs. Some notes on the code:

 1. This is the code I've inherited, so I can't necessarily say why things have been done in a certain way.
 2. The TinyGPS library looks like it hasn't been updated since this was written (2014ish I think).
 3. I am considering re-writing the code from scratch, but I want to make sure I understand the cause of this issue if possible so I can avoid it in the future.

The current hardware is an Elegoo Mega2560 R3 and a u-blox NEO-6M GPS module.

Are we doing something wrong with reading/storing/processing the altitude data?

**Edit to add more information and observations:**

The code takes time, lat, long, altitude from the GPS module, along with the packet counter, callsign and checksum and assembles them into a string, which is transmitted via radio and stored on the SD card. The string has the following format:
``$$Callsign,PacketNumber,HHMMSS,lat,long,alt*Checksum``

Here's an example packet:

``$$XXXXXXXX,1377,121226,51.545547,-1.296546,23*DE62``

These packets are generated every 11-12s and stored and transmitted.
During the periods of incorrect data, the packets appear fine: counter and time increasing, lat and long giving sensible values, just with a nonsense altitude (in this example, 23m). In the 2018 flight, the altitude is stuck at 267m (the altitude of the launch site) for about 40minutes, even though we have seen it ascend into the clouds. The value then drops to 23m and stays there for over an hour, before briefly jumping to 117m for a couple of minutes before jumping to 15,669m, and from then on reports sensible data (until the drop to 0 during the descent).

What I have just noticed while inspecting the logs is that every time the altitude value jumps to a new nonsense value (either from a sensible value or a nonsense one), the packet that reports the new altitude value is corrupted in some manner! This is true even in the data logged on the SD card, so it is not something that has been introduced by transmitting it, but an issue with generating the string.

Below are 3 adjacent packets received, showing a jump between 2 (nonsense) altitude values:

``$$XXXXXXXX,1377,121226,51.545547,-1.296546,23*DE62``

``$$XXXXXXXX,1379,121226,5.216667,-0.583333,117*CDB2``

``$$XXXXXXXX,1381,121248,51.547260,-1.293762,117*80C5``

Note that the packet counter has increased correctly (by 2, but it's "supposed" to do that, it's not an error), but the timestamp is identical in the first and second packets, and the timestamp of the 3rd is 22s later (they should be every 11s). Also, the second packet (the one with the new altitude), reports a nonsense lat and/or long value. Packets then continue to be sensible (except for the altitude), until at some point it starts reporting correct altitude. Looking though both logs, I can see that this happens every time we get a new nonsense altitude.

Any suggestion as to what is messing up acquiring the altitude data and/or assembling the string? I notice that altitude is handled differently in the code compared to lat/long/time, but I am not aware of the reason for this.

![](https://i.stack.imgur.com/xQcO5.png)
![](https://i.stack.imgur.com/qC4co.png)

```
//434.25MHz USB RTTY 50 Baud 500Hz shift ASCII-7 no parity 2 stop bits

#include <TinyGPS.h>
#include <SD.h>
#include <string.h>
#include <util/crc16.h>
#include <Arduino.h>

#define TempAPin A8
#define TempBPin A12
#define PresAPin A10
#define PresBPin A13
#define BatteryVoltagePin A7
#define GreenLED 11
#define RedLED 13
#define RADIOPIN 10
#define RADIOEN 9
int RADIOHIGH = 110;
int RADIOLOW = 100;

int sentance_id = 0;

char UKHAS[80];
char logString[100];
char datastring[80];
char slat[10];
char slon[10];
File myFile; //SD card setup

unsigned int TempA = 0;
unsigned int TempB = 0;
unsigned int PresA = 0;
unsigned int PresB = 0;
unsigned int BatteryVoltage = 0;

long lat, lon, alt;
unsigned long date, oldtime, time, fix_age, vel, bearing;
unsigned char dop, sats;
int year;
byte month, day, hour, minute, second, hundredths;

byte gps_set_sucess = 0 ;

TinyGPS gps;

void setup()
{
  delay(1000);
  Serial.begin(9600);
  //Serial2.begin(9600); //Bluetooth
  analogReference(DEFAULT);

  pinMode(RedLED, OUTPUT);
  pinMode(GreenLED, OUTPUT);
  digitalWrite(RedLED, HIGH);// Switch both on until GPS module is configured
  digitalWrite(GreenLED, HIGH);
  Serial.println("PROGRAM START");
  SetupGPS();
  digitalWrite(GreenLED, LOW);
  delay(1000);

  //SD setup
  //pinMode(10, OUTPUT); //Required for SPI CS to work
  //if (!SD.begin(10)) {
    pinMode(53, OUTPUT); //Required for SPI CS to work
  if (!SD.begin(53)) {
    Serial.println("Card failed, or not present");
    return;
  }
  Serial.println("SD card initialization done.");
  delay(1000);
  //radio setup
   pinMode(RADIOPIN,OUTPUT);
   pinMode(RADIOEN,OUTPUT);
   setPwmFrequency(RADIOPIN, 1);
   digitalWrite(RADIOEN,HIGH);
   Serial.println("FREE RAM:");
   Serial.println(freeRam() );
}

void SetupGPS(void)
{
   // START OUR SERIAL DEBUG PORT
  Serial.println("Initialising GPS....");
  //
  // THE FOLLOWING COMMAND SWITCHES MODULE TO 4800 BAUD
  // THEN SWITCHES THE SOFTWARE SERIAL TO 4,800 BAUD
  //
  Serial3.begin(9600);
  Serial3.print("$PUBX,41,1,0007,0003,4800,0*13\r\n");
  delay(2000);
  Serial3.begin(4800);
  //Serial3.flush();

  //  THIS COMMAND SETS FLIGHT MODE AND CONFIRMS IT
  Serial.println("Setting uBlox nav mode: ");
  uint8_t setNav[] = {
    0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0xFF, 0xFF, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x05, 0x00, 0xFA, 0x00, 0xFA, 0x00, 0x64, 0x00, 0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0xDC                        };
  while(!gps_set_sucess)
  {
    sendUBX(setNav, sizeof(setNav)/sizeof(uint8_t));
    gps_set_sucess=getUBX_ACK(setNav);
  }
  gps_set_sucess=0;
}

unsigned int charsToInt(unsigned char loByte, unsigned char hiByte)
{
  unsigned int temp = 0;
  temp = loByte + (hiByte<<8);
  return temp;
}

unsigned char lo(unsigned int input)
{
  unsigned char temp = 0;
  temp = (unsigned char)(input & 0xFF);
  return temp;
}

unsigned char hi(unsigned int input)
{
  unsigned char temp = 0;
  temp = (unsigned char)((input>>8) & 0xFF);
  return temp;
}

###################################################################################
void loop()
{
  unsigned char b = 0;
  long int counter = 10000;
  int x = 0;
  int mem;
  while(1)
  {
    counter--;
    x = counter % 10000;
    if (x == 1)
    {
      Serial.println(counter);
    }

    if (counter==0)
    {

      counter = 100000;
      digitalWrite(GreenLED, LOW);
      digitalWrite(RedLED, HIGH);
      readSensors();
      sprintf(logString, "NOGPS,%i,%lu,0,0,0,%i,%i,%i,%i", sentance_id++, time, TempA, TempB, PresA, PresB);
      Serial.println(logString);
      writeSD();

     sprintf(UKHAS,  "&&XXXXXXXX,%i,NOGPS", sentance_id);

      Serial.println(UKHAS);

      writeRADIO();

    }
    if(Serial3.available() & 0)
    {

       b=Serial3.read();

       if (gps.encode(b))
       {
        Serial.println("TEST");
         counter = 1000000;
         digitalWrite(GreenLED, HIGH);
         digitalWrite(RedLED, LOW);
         //Serial.println("Got valid GPS data");
         // read values from the gps.
         gps.get_position(&lat, &lon, &fix_age);
         gps.get_datetime(&date, &time, &fix_age);
         alt = gps.altitude();
         Serial.print("alt=");
           Serial.println(alt);
         vel = gps.speed();
         bearing = gps.course();
         gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &fix_age);
         readSensors();
         //if (time > (oldtime + 1000))
         //{
           // print the details to BT and SD every 10 seconds
           oldtime = time;
           // comaptible comms protocol: http://ukhas.org.uk/communication:protocol
    sentance_id++; //count number of packets
           char timeS[10] = {time/100};
           char hour[10];

           alt = alt / 100; //convert from cm to m
           //if (alt > 50000){ //if nonsense altitude
          //   alt = -1;
          // }
           double dlat = double(lat);
          //char slat[10];
           dtostrf(dlat/1000000, 8, 6, slat);
           if (lon > 0){ //if west of meridian
             lon = lon * -1;
           }
           double dlon = double(lon);
           //char slon[10];
           dtostrf(dlon/1000000, 8, 6, slon);
           sprintf(UKHAS, "$$XXXXXXXX,%i,lu,%s,%s,%lu", sentance_id, time/100, slat, slon, alt);
           //sprintf(UKHAS, "$$XXXXXXXX,%i,%lu:%lu:%lu,%s,%s,%lu", sentance_id, hour, minute, second, slat, slon, alt);
           //change time format
          sprintf(logString, "LOG,%i,%lu,%s,%s,%lu,%i,%i,%i,%i", sentance_id++, time, slat, slon, alt, TempA, TempB, PresA, PresB);
           Serial.println(logString); //debug
           //Serial2.println(logString); //Bluetooth
           Serial.println(UKHAS); //debug
           //50 buad 500Hz
           writeSD();
           writeRADIO();
         //}
       }
    }//if GPS available
  }//while(1)
}//loop
###########################################################################
void writeRADIO()
{
 //digitalWrite(RADIOEN,HIGH);
 //delay(10);
 //Serial.println(UKHAS);

 snprintf(datastring,80,UKHAS); // Puts the text in the datastring

 unsigned int CHECKSUM = gps_CRC16_checksum(datastring); // Calculates the checksum for this datastring

 char checksum_str[8];

 sprintf(checksum_str, "*X\n", CHECKSUM);

 strcat(datastring,checksum_str);
Serial.println(datastring);
 rtty_txstring (datastring);

Serial.println("MS");
 //digitalWrite(RADIOEN,LOW);
}

void writeSD() //write sensor log to file on SD card
{
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
  myFile = SD.open("log.txt", FILE_WRITE);
  // if the file opened okay, write to it:

  if (myFile) {
    Serial.print("Writing to SD card");
    //write full telemetry packet
     myFile.println(logString);

    //close the file:
    myFile.close();
    Serial.println("done.");
  }
   else {
     //if the file didn't open, print an error:
    Serial.println("error opening SD card file");
  }
}

void readSensors()
{
  TempA = analogRead(TempAPin);
  TempB = analogRead(TempBPin);
  PresA = analogRead(PresAPin);
  PresB = analogRead(PresBPin);
  BatteryVoltage = analogRead(BatteryVoltagePin);
}

void rtty_txstring (char * string)
{

/* Simple function to sent a char at a time to
 ** rtty_txbyte function.
 ** NB Each char is one byte (8 Bits)
 */

char c;

c = *string++;

while ( c != '\0')
 {
 rtty_txbyte (c);
 c = *string++;
 }
}
void rtty_txbyte (char c)
{
 /* Simple function to sent each bit of a char to
 ** rtty_txbit function.
 ** NB The bits are sent Least Significant Bit first
 **
 ** All chars should be preceded with a 0 and
 ** proceed with a 1. 0 = Start bit; 1 = Stop bit
 **
 */

int i;

rtty_txbit (0); // Start bit

// Send bits for for char LSB first

for (i=0;i<7;i++) // Change this here 7 or 8 for ASCII-7 / ASCII-8
 {
 if (c & 1) rtty_txbit(1);

else rtty_txbit(0);

c = c >> 1;

}
rtty_txbit (1); // Stop bit
rtty_txbit (1); // Stop bit
}

void rtty_txbit (int bit)
{
 if (bit)
 {
 // high
 analogWrite(RADIOPIN,115);
 }
 else
 {
 // low
 analogWrite(RADIOPIN,100);
 }

// delayMicroseconds(3370); // 300 baud
 delayMicroseconds(10000); // For 50 Baud uncomment this and the line below.
 delayMicroseconds(10150); // You can't do 20150 it just doesn't work as the
 // largest value that will produce an accurate delay is 16383
 // See : http://arduino.cc/en/Reference/DelayMicroseconds

}

uint16_t gps_CRC16_checksum (char *string)
{
 size_t i;
 uint16_t crc;
 uint8_t c;

crc = 0xFFFF;

// Calculate checksum ignoring the first two $s
 for (i = 2; i < strlen(string); i++)
 {
 c = string[i];
 crc = _crc_xmodem_update (crc, c);
 }

return crc;
}

void setPwmFrequency(int pin, int divisor) {
 byte mode;
 if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
 switch(divisor) {
 case 1:
 mode = 0x01;
 break;
 case 8:
 mode = 0x02;
 break;
 case 64:
 mode = 0x03;
 break;
 case 256:
 mode = 0x04;
 break;
 case 1024:
 mode = 0x05;
 break;
 default:
 return;
 }
 if(pin == 5) {
 TCCR3B = TCCR3B & 0b11111000 | mode;
 }
 else {
 TCCR2B = TCCR2B & 0b11111000 | mode;
 }
 }
 else if(pin == 3 || pin == 11) {
 switch(divisor) {
 case 1:
 mode = 0x01;
 break;
 case 8:
 mode = 0x02;
 break;
 case 32:
 mode = 0x03;
 break;
 case 64:
 mode = 0x04;
 break;
 case 128:
 mode = 0x05;
 break;
 case 256:
 mode = 0x06;
 break;
 case 1024:
 mode = 0x7;
 break;
 default:
 return;
 }
  TCCR3B = TCCR3B & 0b11111000 | mode;
 }
}

// Send a byte array of UBX protocol to the GPS
void sendUBX(uint8_t *MSG, uint8_t len) {
  for(int i=0; i<len; i++) {
    Serial3.write(MSG[i]);
    Serial.print(MSG[i], HEX);
  }
  Serial3.println();
}

// Calculate expected UBX ACK packet and parse UBX response from GPS
boolean getUBX_ACK(uint8_t *MSG) {
  uint8_t b;
  uint8_t ackByteID = 0;
  uint8_t ackPacket[10];
  unsigned long startTime = millis();
  Serial.print(" * Reading ACK response: ");

  // Construct the expected ACK packet
  ackPacket[0] = 0xB5; // header
  ackPacket[1] = 0x62; // header
  ackPacket[2] = 0x05; // class
  ackPacket[3] = 0x01; // id
  ackPacket[4] = 0x02; // length
  ackPacket[5] = 0x00;
  ackPacket[6] = MSG[2]; // ACK class
  ackPacket[7] = MSG[3]; // ACK id
  ackPacket[8] = 0;  // CK_A
  ackPacket[9] = 0;  // CK_B

  // Calculate the checksums
  for (uint8_t i=2; i<8; i++) {
    ackPacket[8] = ackPacket[8] + ackPacket[i];
    ackPacket[9] = ackPacket[9] + ackPacket[8];
  }

  while (1) {

    // Test for success
    if (ackByteID > 9) {
      // All packets in order!
      Serial.println(" (SUCCESS!)");
      return true;
    }

    // Timeout if no valid response in 3 seconds
    if (millis() - startTime > 3000) {
      Serial.println(" (FAILED!)");
      return false;
    }

    // Make sure data is available to read
    if (Serial3.available()) {
      b = Serial3.read();

      // Check that bytes arrive in sequence as per expected ACK packet
      if (b == ackPacket[ackByteID]) {
        ackByteID++;
        Serial.print(b, HEX);
      }
      else {
        ackByteID = 0; // Reset and look again, invalid order
      }

    }
  }
}

int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
```

title: U-blox GPS module (and TinyGPS library): altitude data getting stuck at strange values

Answers: 0


body:
I am doing a project for object detection. But my problem is I'm using a 12V photoelectric OMRON sensor to connect with 5V Digital PWM port 3 on Arduino using normal coding. Do I need an extra circuit to step down the voltage to 5V? Can it work because the only connection between the sensor and Arduino is the output signal, the VCC and Ground are from external power. [Link to the datasheet][1] Please help me

  [1]: https://www.ia.omron.com/product/item/721/

title: Can a 12V sensor connected to a 5V output signal of an Arduino Uno

Answers: 2

body:
For one, you need to connect the two grounds together.

Secondly, the 12V signal will indeed fry your Arduino. Lower the voltage to just below 5V, using a voltage divider circuit. You could for example use a combinations of a 2.2kOhm and a 1.5kOhm resistor, to get around 4.9V.

body:
My favorite solution for such an application is to use an optoisolation module. In this case, the signal can have a voltage of 12 V and the output of the optoisolation module can be connected to the input of the Arduino, where the input is configured as INPUT_PULLUP.
Example of the optoisolation module:

[![PC817][1]][1]

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

In this way it is possible to connect other types of sensors and switches and the solution is universal also for other development kits, e.g. with 3V3 logic.


body:
Im attempting a device that measures lean angle. I have an ESP8266 + MPU6050 + SSD1306 setup, and I've managed to build a shaky but somewhat functioning device.

What Id like to do is use the Adafruit_SSD1306 library to call the ``` display.drawLine(x, y, x1, y1, color) ``` function and have the line drawn to the measured angle output of the MPU6050.

The screen I'm using is 128 X 64

The MPU6050 is initially laying flat at 180 degrees, but is set and displayed as 0 degrees of tilt. The line is drawn vertically on the screen and pivots around x1 and y1 at 64, 64 respectively in the middle at the bottom of the screen.

If the MPU6050 pivots left like in the picture, the angle measurement itself is roughly correct, but the line indicator is showing more like 30 degrees than 45, and gets worse the larger the angle value.
[![line indicator][1]][1]

**My code:**
```
#include <Adafruit_MPU6050.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>

const int MPU_addr=0x68;
int16_t axis_X,axis_Y,axis_Z;

Adafruit_MPU6050 mpu;
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);

int minVal=265;
int maxVal=402;

double x;
double y;
double z;
int tiltAngle;
double y2;

void setup(){
  Serial.begin(9600);
  Serial.println("MPU6050 OLED demo");

  if (!mpu.begin()) {
    Serial.println("Sensor init failed");
    while (1)
      yield();
  }
  Serial.println("Found a MPU-6050 sensor");

    // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ; // Don't proceed, loop forever
  }

  display.display();
  delay(500); // Pause for 2 seconds
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setRotation(0);
}
void loop(){
  display.clearDisplay();
  display.setCursor(0, 0);

  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);
  axis_X=Wire.read()<<8|Wire.read();
  axis_Y=Wire.read()<<8|Wire.read();
  axis_Z=Wire.read()<<8|Wire.read();
    int xAng = map(axis_X,minVal,maxVal,-90,90);
    int yAng = map(axis_Y,minVal,maxVal,-90,90);
    int zAng = map(axis_Z,minVal,maxVal,-90,90);

     x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
     y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
     z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

     tiltAngle = (int) x - 180; // we want the tilt angle to be 0 degrees
     display.println(" ");
     display.println(" ");
     display.println(" ");

     // display only positive angle values for either direction of tilt
     if(tiltAngle > 0){ display.print(tiltAngle);}
     else if (tiltAngle < 0) { display.print(tiltAngle * -1);}
     else {display.print(tiltAngle);}

     display.drawLine(-tiltAngle + 64, 0,64,64,WHITE);
     display.display();
     delay(100);
}
```

Im aware that for my first y co-ordinate I will need to use some kind of formula to get the line to move down from 0 (the top of the screen) as the lean angle gets greater. I'm hoping someone could point me in the right direction for drawing the line at the angle given by the MPU6050.

I did consider using case statements for each angle value and drawing the line with fixed co-ordinates based on each angle value. But that seems too compute intensive and could take up too much of the DRAM. Is anyone aware of a simple formula I could use? Thanks for reading.

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

title: Drawing a line at a given angle

Answers: 1

body:
Use trigonometry (`sin()` and `cos()`) functions to get the right x and y coordinates.

I would consider replacing your `drawLine()` command with something like this (untested) assuming the `tiltAngle` is in degrees from -90 to +90 (with 0 degrees is straight up) and you want to draw a line at this angle from the origin (63, 63) with a radius of 64.

    float tiltAngleRad = tiltAngle * DEG_TO_RAD; // convert angle to radians
    int xEnd = 63 + 64 * sin (tiltAngleRad); // Ending x-coordinate offset & radius
    int yEnd = 63 - 64 * cos (tiltAngleRad); // Ending y-coordinate offset & radius
    display.drawLine (63, 63, xEnd, yEnd);

You might have to experiment with the offset and radius but I believe this will get you close yo what you want.


body: I am building a VU meter with two 5v neopixel rings, two potentiometers, a headphone jack and an Arduino nano. Will 5 volts 1 amp cut it, or do I need more power? FYI I'll be powering it via a DC jack once I get it working.

title: Building a VU meter

Answers: 1

body:
Normally the maximum amount of current a typical LED can withstand is 20 mA. This means per color and per LED.

So if you have 60 LEDs, than you get 60 (leds) * 3 (R/G/B colors) * 20 mA = 3,600 mA.
To give some headroom I would use a 4A or 5A adapter.

However, note that probably 5 mA or 10 mA per LED would be enough to be very good visible, unless you want it to be as bright as possible.


body:
I am trying to control esp8266 esp 01 with Alexa

This is my code:
```
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "fauxmoESP.h"

#define ssid "admin"
#define pass "admin0000"

#define device1 "arduino"

fauxmoESP fauxmo;

void wifi()
{
  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid,pass);
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print("not connected\n");
    delay(100);
  }
    Serial.print("1");

}

void setup()
{
  Serial.begin(115200);
  wifi();
  fauxmo.createServer(true);
  fauxmo.addDevice(device1);
  Serial.print("device added\n");
    fauxmo.setPort(80);
   fauxmo.enable(true);

  fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state, unsigned char value) {
  Serial.printf("[MAIN](%s) state: %s\n",device_name, state ? "ON" : "OFF");
    if (strcmp(device_name, device1) == 0)
    {
      if (state)
        Serial.print("3");
      else
        Serial.print("2");
    }

  });
}

void loop()
{
  fauxmo.handle();
}
```

And I am getting an error after 10 - 20 sec
```
ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset
```
Anyone please help me to solve this issue

title: ESP8366: ets Jan 8 2013,rst cause:4, boot mode:(1,7)

Answers: 0


body:
I've been learning how to encapsulate my code within functions, and one of the examples I worked on is a simple INPUT_PULLUP button. When I upload the sketch from the [arduino website][1] everything works, so I know it's not a hardware issue. However, with the code below the button will just not go LOW.

I just don't see what the issue is, and I'm feeling really hopeless that I can't even get the simple thing done. I would be grateful for any advice.

  [1]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/InputPullupSerial

    int button_pin = 2;
    int button_state = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(button_pin, INPUT_PULLUP);
    }

    void loop() {
      Button();
    }

    void Button() {
      // Read button(s)
      button_state = digitalRead(button_pin);
      if (button_state = LOW) {
        Serial.println(button_state);
      };
    };

title: Unable to make a really basic sketch work

Answers: 1

body:
    #define button_pin 2  //defining button pin as pin 2
    bool button_state = 0; //button state is either 0/1 so using bool
    void Button();
    void setup()
    {
        Serial.begin(9600);
        pinMode(button_pin, INPUT_PULLUP); //Setting input as input pullup
    }

    void loop()
    {
        Button();
    }

    void Button()
    {

        button_state = digitalRead(button_pin); //Read button state
        if (button_state == LOW)
        {
            Serial.println(button_state); //print button state when it is low
        }
    }

In your code, you have used `=` operator in place of `==` in the if loop. Just if you change it, it will start working also you can use my above code it is same as yours just I have made some minor changes such as using `bool` in place of int and use of `#define` in place of pin declaration where you used `int`


body:
I am using ESPAsyncWebServer Library in a ESP32 DevKit. I want to make a form in the browser in order to upload files in SPIFFS.

I have to notice that the whole device works perfectly. I connect to Wi-Fi, it uploads files via IDE etc.

Through searching in the net, I found this part of code that does not work.

    server.on("/upload-file", HTTP_GET, [](AsyncWebServerRequest* request) {
        String html = "
<form method='post' action='/upload-file'><input type='file'><button>Send</button></form>
";
        request->send(200, "text/html", html);
        });

    server.on("/upload-file", HTTP_POST, [](AsyncWebServerRequest* request) {
        AsyncWebServerResponse* response = request->beginResponse(200, "text/html", "hello world");
        response->addHeader("Connection", "close");
        request->send(response);
        }, handleUpload);
 server.onFileUpload(handleUpload);

The handleUpload function:

    void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
    if (!index) {
        request->_tempFile = SPIFFS.open("/" + filename, "w");
    }
    if (len) {
        request->_tempFile.write(data, len);
    }
    if (final) {
        request->_tempFile.close();
        request->redirect("/files");
    }
    }

It shows the form but the file doesn't upload.
Is there any idea on how can I make it work?

title: ESP-32 Upload Files to SPIFFS via browser

Answers: 1

body:
I had the same problem and thanks to you, I did solve the problem!

Here is the full code,
My html code for the upload page, the form is in the <iframe> tag:
```html

<!DOCTYPE html>
<html>
<head>
  <title>File Upload Example</title>
</head>
<body>
  <h1>File Upload Example</h1>
<form method="POST" action="/upload" enctype="multipart/form-data" target="iframe"><input type="file" name="upload"><input type="submit" value="Upload"></form>
<iframe style="visibility: hidden;" src="http://" )+local_IPstr+"/Usm" name="iframe"></iframe>
</body>
</html>
```
code for ESP:
```c++

void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
if (!index) {
    request->_tempFile = SPIFFS.open("/" + filename, "w");
    Serial.println("1");
}
if (len) {
    request->_tempFile.write(data, len);
     Serial.println("2");
}
if (final) {
   Serial.println("3");
    request->_tempFile.close();
    request->redirect("/");
}
}

 controlserver.on("/upload", HTTP_POST, [](AsyncWebServerRequest *request) {
        request->send(200); }, handleUpload);

  controlserver.on("/UPL", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/html", upl);
  });

  readFile(SPIFFS, "/11.txt"); // show the content of the uploaded file, obviously you should know the name of the uploaded file!
```

you can write a function like this to make sure the file was delivered:
```c++
  readFile(fs::FS &fs, const char * path){
  Serial.printf("Reading file: %s\r\n", path);
  File file = fs.open(path, "r");
  if(!file || file.isDirectory()){
    Serial.println("- empty file or failed to open file");
    return String();
  }
  Serial.println("- read from file:");
  String fileContent;
  while(file.available()){
    fileContent+=String((char)file.read());
  }
  file.close();
  Serial.println(fileContent);

}
```


body:
i just bought a hobby telescope, it works well for being nothing much than a toy, the very problem is that the gesrs that should keep it stable are all plastic and very hard to tighten while keeping it steady.

So I thought to let the gears wide open and move it with arduino: you point the object manually then with 4 buttons move it by small steps.

I've tried to use a couple of servos i had at home, mg90s 2kg 180°; while 180° is enough for the purpose, first i don't think 2kg is enough for the X axis motor, second one is not very precise (using the default library).
I know I can achieve better results calibrating the pulse manually, but maybe is better if I use better motors.

What motors (and why) would you reccomand?
Servo or stepper?

Being for a hobby the budget is low, so very max 50$?

title: What motor to move a small telescope?

Answers: 1

body:
I wouldn't use a servo for this. You don't have very fine control over the angle with a servo. Also with a typical telescope the focus is more on rather slow and precise movements, instead of fast ones.

Instead I would use a stepper motor. Depending on your exact requirements, these can be rather cheap to rather expensive.

Here also the mechanics come into play. The motor should not be attached directly to the axis, but instead through some gears (the axis of the telescope having the larger gear). That will allow for smaller, more precise movements and also lower the needed torque for the motor. Of course this depends on your actual telescope hardware, meaning if you can put a gear right to the axis. If not, you could limit the motor driven movement a bit and install a level, which then could be pushed or pulled by a nut on a threaded rod, which gets driven by the servo motor. This would be rather easy to implement, though you may need to correct for the different rotation behavior, when you get to the outer sides of the movement (for the actuator being linear, while the resulting movement is circular), by some mathematics in your code.

Since you want to keep your costs very low, you might wanna use the 28BYJ-48 stepper motor (including the fitting driver). In terms of stepper motors they are rather bad, but they are really really cheap and - depending on the gear ratio/level length/thread pitch - it might not matter that much for you. You could always update to a better stepper motor in the future.


body:
I have an [SPI flash based mp3 module][1] and was wondering whether its possible to write to the flash chip using a microcontroller(arduino). the IC supports FAT16/FAT32 file systems. I have researched arduino and the fat file system but they are all in relation to SD cards which operate differently as far as i understand. Is it possible to write data to a fat file system on SPI flash using an arduino?

  [1]: http://www.icstation.com/player-module-audio-voice-board-8bit-uart-contorl-4mbytes-flash-voice-playback-module-p-13454.html

Answers: 1

body:
The first and most important problem is not the filesystem. Currently on the board the USB port is connected to the internal MCU, which in turn is connected via SPI to the flash chip. The internal MCU is the master on the SPI bus. But the SPI bus does not support multiple masters on one bus. So just connecting the external MCU to the SPI lines as master would not work.

I see 2 possible ways to go here:

- You can unsolder the flash chip from the board and add a fitting multiplexer chip, which can switch the SPI lines between the two masters. That effectively gives you only one master on the SPI bus at any time. This way would be rather hacky and difficult for a beginner. It might also be important to keep an eye on the capacitance of the bus, since it might run with rather high speed. A too high capacitance (for example through using a breadboard) might result in erroneous communication.

    Then you could use one of the FAT libraries. I don't know them in detail, but I think you could also use them for a simple SPI flash chip. You just would need to implement the lower level access functions, that the FAT library needs.

- Or you could try to use a USB host board with your external MCU and try to write data through the USB port. I don't have much experience with USB host boards, so I cannot really tell you, if and how exactly this is possible with the available hardware (the board will most likely implement an USB interface like a simple flash USB stick).

All in all I think, this would be rather hacky. Your board is not really made for changing the data through another microcontroller. Depending on what exactly you want to achieve, you might want to go to a different hardware setup.


body:
I have a simple sketch which sends IR codes, plays a sound and toggles an LED when you press a button and toggles another LED when it receives that code. The idea is that I have two Arduinos with this same sketch and when you press the button on one, the LED is toggled and so is another LED on the other Arduino. This program works as intended when the sound is not included.

Here is the sketch:
~~~

#include <IRremote.h> // For the IR transmition and receiving
#include <PCM.h> // For the audio output

IRsend irsend; // Setup the IR transmitter
const int receiver = 8; // Initialize pin 13 as recevier pin.
IRrecv irrecv(receiver); // Create a new instance of receiver
decode_results results;

// Declare arrays to hold sound notes to play
const unsigned char gunShot[] PROGMEM = {}; // There is a huge list of numbers in this array, but I removed them to make the code easier to read

const unsigned char gunClick[] PROGMEM = {}; // There is a huge list of numbers in this array, but I removed them to make the code easier to read

// declare consants
const int button = 13;
const int greenLight = 7;
const int yellowLight = 2;
const int timeBetweenTransmittion = 800; // At least 800 milliseconds between two transmissions
// The speaker is fixed on pin 11

// declare variables
bool toggleGreen = true; // Bool variables to toggle the lights
bool toggleYellow = true;
long int previousTransmittion = 0; // Long int to store the timestamp in millis of the previous transmission

// put your setup code in here, to run once:
void setup()
{
  pinMode(button, INPUT_PULLUP); // Setup the button with an internal pullup resistor
  Serial.begin(9600);
  irrecv.enableIRIn(); // Enable the receiver
  Serial.println("start");
}

// put your main code in here, to run repeatedly:
void loop() {
  if (not digitalRead(button) && millis() > previousTransmittion + timeBetweenTransmittion) // If the button is pressed and it's been enought time since the last transmittion
  {
    Serial.println("send!");

    // Different orders of these lines of code were tried:

    //startPlayback(gunShot, sizeof(gunShot)); // Play shot before sending the code and enabling the receiver (play command 1 for reference)
    //delay(250);

    irsend.sendNEC(1367857, 32); // Send the code

    //startPlayback(gunShot, sizeof(gunShot)); // Play shot between sending the code and enabling the receiver (play command 2 for reference)
    //delay(250);

    irrecv.enableIRIn(); // Sending ir stops the receiver so start the receiver again

    startPlayback(gunShot, sizeof(gunShot)); // Play shot after sending the code and enabling the receiver (play command 3 for reference)
    delay(250);

    // Toggle the yellow light
    digitalWrite(yellowLight, toggleYellow);
    toggleYellow = not toggleYellow;

    previousTransmittion = millis(); // Set the record for latest transmittion to the currnt time
  }

  if (irrecv.decode(&results)) // If we have received an IR signal
  {
    Serial.println (String(results.value, HEX)); // Display HEX results
    if (String(results.value, DEC) == "1367857") // If the code is the right one
    {
      Serial.println("correct code");

      // toggle the green light
      digitalWrite(greenLight, toggleGreen);
      toggleGreen = not toggleGreen;
    }
    irrecv.resume(); // Prepare the receiver for the next code
 }
}

~~~
// End of sketch

As you can see, I tried putting the play sound line before, between and after the IR transmission lines of code. The delays are there so I can see if the audio starts to play and stops or if it just never plays. Here is what I found from all the combinations:

- In all the combinations (play command 1, 2 and 3), The IR receiver worked as intended if used BEFORE ever pressing the button.

- None of the combinations stop the loop as if I put <Serial.println("loop");> at the start of the loop() routine, it continues to print "loop", regardless of what I do.

- In play command 1 and 2, the sound plays when I press the button, but stops after the 250ms delay. Once the button has been pressed once, it doesn't do anything when I press it again (doesn't print "send!" or toggle the light). The receiver receives one more code after pressing the button, but always prints the code "2a", regardless of what button on my tv remote I press (the tv remote usually prints a 6 character hex code). After it prints "2a", it doesn't receive any more codes.

- Play command 3 plays the full sound and sends the right code, and allows me to do it as many times as I want (the button still works after pressing it more than once). However the receiver still no longer works after the first time I press the button. It doesn't receive "2a" the first time after pressing the button unlike the first 2.

I am using the libraries IRremote by shirriff, z3t0 and ArminJo (VERSION 2.6.1) and PCM by David Mellis, Michael Smith (VERSION 1.0.0) (http://highlowtech.org/?p=1963). I don't know if there is a simple way around this problem or if these libraries just cannot be used together.

I have the speaker on pin 11.

If you need anything clarifying please ask. Any help would be appreciated, thanks in advance.

title: IRremote and PCM sound libraries interfering

Answers: 2

body: The PCM library uses timer 1, and timer 2. The IRremote library uses timer 1. So they both need timer 1. So there's a conflict. So you can't use both libraries at the same time, unfortunately.

body:
It works for me if i put a delay after `startPlayback` followed by a `irrecv.enableIRIn();`

    startPlayback(sample, sizeof(sample));
    delay(1000); // delay needed as long audio is playing
    irrecv.enableIRIn(); // enable input from IR receiver after using PCM library startPlayback


body:
I have tried almost everything but the servo is not moving at all
here is my schematics
https://create.arduino.cc/projecthub/arcaegecengiz/how-to-use-servo-motors-with-arduino-b02bed

Here is my code

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

    void loop() {
      for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
    }

title: SG 90 not working

Answers: 0


body:
I am fairly new to working with sensors and Arduino. I am working on a project using Max MPS to control the volume of three audio files. There will be three framed photos, each having its own IR sensor and audio file. So when someone gets closer to the sensor, the volume of the corresponding file gets louder. Is this doable? The samples I have seen with the board I have and an IR sensor only use one. I'm assuming I'll be able to use the breadboard I have to add more sensors like I've done in the past with photocell sensors but I have yet to test it since it's in the mail. Just hoping to get ahead of any issues I may face and see if I should order any other equipment.

I ordered 3 of these [IR sensors][1] and this is the [Arduino kit][2] I am working with.

Sorry if I may not be describing it in enough detail, but thanks in advance!

[![Arduino Board example][3]][3]

  [1]: https://www.amazon.com/gp/product/B07WQWHNDW/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1
  [2]: https://www.adafruit.com/product/193
  [3]: https://i.stack.imgur.com/g0HXH.jpg

title: Multiple IR Sensors with Arduino

Answers: 1

body:
technically yes, there is no reason you can't do that project but the issues will come in how complex you wish to make system. For example, it shouldn't be too hard to hook up the three sensors to three analogue Pins on the Arduino and then have the Arduino constantly loop to check the voltage of the sensors, from which, you would tell it to 'do something' when one of the IR sensors voltage is above or below a certain value. What you then choose to do is up to you, if it's just to turn on a light then it can be done fairly quickly once you have all the components. For controlling the Audio in the file, I personally have no experience with this.

What might be better is first checking to see if you can Adjust the audio in one of your files using an Arduino (you may need to use bluetooth or have something on your PC communicate with your Arduino via UART through the USB).

Generally, with new projects, it's a good idea to figure out a solid plan for exactly what you want to do, so I would write down in detail what you want the system to do and then go through each part to see if it's possible


body:
Having trouble with arduino
Ultrasonic Sensor  Module
HC-SR04
I'm sure when you read this you're going to say how stupid can he be and you're probably right but I'm 82 years old and I'm trying very hard. They say you're never too old to learn I hope they're right
This sensor model is driving me crazy I have tried and written two or three sketches and I cannot get it to work I know how simple it is for wires big deal but when I tried to read it through my serial monitor I get this a bunch of backward ? A C S A ? But the question are backwards . I have used two different boards new ones and tried three Ultrasonic Sensor hope you can help me thank you Dennis

title: Ultrasonic HC-SR04

Answers: 0


body:
So I [understand][1] [that generally][2] [speaking, dynamic allocation should be avoided][3]. My question isn't how or why, but *what* happens when you call a function that allocates memory?

On Windows or Linux, when a program allocates memory, a whole bunch of stuff happens, things like virtualisation and security related features that have no relevance to arduino, and the bit that I'm interested in, memory management:

There will be some code, that will look at the alignment and size requirements of the allocation request, look at the pool of memory it has access to, find a space big enough, make a note of the allocation (which also uses some amount of memory) and then return a pointer to the allocated space back to the calling function.

Is there a custom malloc implementation for each device, or does it come with the arduino toolchain (and does that mean Arduino has a different implementation from Teensy, or avr from sam?), or is there some magical default implementation supplied by the compiler? What kind of memory overhead is incurred with every allocation? How easy is it to override this functionality and implement your own (out of morbid curiosity or tendency towards masochistic endeavours)?

  [1]: https://arduino.stackexchange.com/questions/682/is-using-malloc-and-free-a-really-bad-idea-on-arduino
  [2]: https://arduino.stackexchange.com/questions/12821/malloc-with-objects-in-arduino-libraries
  [3]: https://arduino.stackexchange.com/questions/77061/why-is-it-considered-bad-practice-to-use-the-new-keyword-in-arduino

title: What happens when you call malloc()/free()/new/delete?

Answers: 1

body:
There are some hardware-specific abstractions (they mostly define the maximum memory available), but otherwise these are functions are implemented by the C/C++ runtime (on arduinos an implementation called "NewLib") and usually "just work". You might want to take a look at [this question][1], where quite a bit of background is given on the SAM implementation of the hardware abstractions (because it's broken).

And yes, of course using malloc/free has some considerable overhead, which is one reason why it's not the recommended way of allocating memory on microcontrollers. But the logic behind it is mostly the same whether there's 2k of memory or 2G. And the _memory model_ of modern microcontrollers (at least the 32 bit ones) is very similar to the one seen in 32 bit Windows or Linux apps.

  [1]: https://arduino.stackexchange.com/questions/80535/memory-allocation-on-arduino-due-never-returns-null