body:
I am trying to communicate with AT30TS75A-MA8M-T with below code, the problem is converting the 16 bit output to float so I can read temp:

Base on [data sheet][1]
[![enter image description here][2]][2]
I suppose to remove first 5 bit in order to read correctly but I am not converting it correctly.

Ex: (0b001001001100000 AND 0 b0111111111100000) = 0b1001001100000
 0b1001001100000 >> 5 = 0b10010011 = 147

        void Atemp::begin()
    {

        Wire.begin();

        // Check if sensor temp sensor is avilable

        // if (mySensor.beginI2C() == false)
        // {
        //     data[9] = 5; // Error Code
        // }
        // Set registor for two decimal
        Wire.beginTransmission(_i2cAddress);
        Wire.write(1);
        Wire.write(0b01100000);
        Wire.endTransmission();
    }

    void Atemp::read()
    {
        Wire.beginTransmission(_i2cAddress);
        Wire.write(0);
        result = Wire.endTransmission();
        // result is 0-4
        if (result != 0)
        {
            data[9] = 5; // Error Code
        }

        result = Wire.requestFrom(_i2cAddress, (uint8_t)2);
        if (result != 2)
        {
            data[9] = 5; // Error Code
        }
        else
        {
            uint8_t part1 = Wire.read();
            uint8_t part2 = Wire.read();

            data[7] = part1;
             data[8] = part2;
            int16_t rawval = (part1 << 8 | part2) ;
            // rawval >>= 6;
            float temp = rawval / 256.0f;
            floatconv(temp);
        }
    }

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-8839-DTS-AT30TS75A-Datasheet.pdf
  [2]: https://i.stack.imgur.com/bGVzS.png

title: Converting 16bit to float

Answers: 2

body:
You need to do two things:

1. Right-shift the data to align it to the right of the variable, and
2. Multiply it by the value of one bit.

When right shifting be sure to do it in a *signed* data type so that C will *sign extend* the value and retain any negativeness to the value.

So taking the 12-bit examples from the datasheet you right shift 4 bits, so

```
SDDDDDDDDDDD0000
```
becomes
```
SSSSSDDDDDDDDDDD
```
(where S is the sign bit and D is a valid data bit, and 0 is padding)

Then simply multiply the value by 0.0625 to get the actual temperature.

In code that might look like:

```c++
int16_t rawval = part1 << 8 | part2;
rawval >>= 4; // Do this in the int16_t to preserve the sign
float temperature = rawval * 0.0625;
```

For different resolutions right shift by different amounts and multiply by the appropriate single-bit value for that resolution (hint: 11 bit is double the value of 12 bit, 10 bit is double the value of 11 bit, etc).

body:
Just a complement to Majenko's answer. The temperature register is set
in such a way that you can interpret it in the same way irrespective of
the selected resolution:

```c++
int16_t rawval = part1 << 8 | part2;
float temperature = rawval * (1/256.0);
```


body:
**Problem description:** Every ~20+ published messages (using terminal), MCU receives that message in a very noticeable delay (mostly ~10 sec, few time it got up to 1 min). Upon receive (printed in Serial monitor), MCU is working as expected.

**Hardware:** ESP32 DEVKIT MCU, `PubSubClient.h` for MQTT and `WiFi.h` for WiFi.

**Important remark:** Code is same for ESP8266 and ESP32.This behavior happens **only** on ESP32.

**Question:** Does ESP32 has a know issue regarding receiving MQTT messages? is there a workaround? or perhaps- bug in code?

What did I do to try isolating the problem:

1) Tried on 3 different ESP32s (2 DEVkit MCU, and 1 with relays on board) - same behavior - it is not an specific MCU hardware problem.

2) Used another PC to publish MQTT messages (via terminal. MAC and Linux, and a 3rd party MQTT App)- no change. It has nothing to do with publishing platform.

3) To rule out it may be a MQTT broker's fault (Local RPI3 connected using LAN cable)- Subscribing to that topic in order to see if the delay repeats . MQTT server receive pubs on time. Broker responds on time (while waiting to see when publish is received in Serial monitor).

4) adding a flashing LED every 200ms in `loop()`, to verify that MCU is not get stuck in a process. `loop()` is looping as expected (see in code below).

5) Spitting heap free memory to Serial monitor, in order to see if there is some memory issue, degradation. Nothing suspicious.

6) Code simplification- used code segments from ESP32 wifi and MQTT pubsub's example, while disabling every functionality of original code(with and without). Delay still happens sporadically.

**OUTPUT1**- sending "0" and "1" almost simultaneously,  almost 15 sec delay

    13:31:21.516 -> Message arrived [myHome/test] 0 <--- right after this, "1" was sent
    13:31:22.510 -> 278616 <---- free heap size (send every 1000 ms. non-blocking)
    13:31:23.570 -> 278616
    13:31:24.630 -> 278616
    13:31:25.657 -> 278616
    13:31:26.718 -> 278616
    13:31:27.778 -> 278616
    13:31:28.805 -> 278616
    13:31:29.866 -> 278616
    13:31:30.926 -> 278616
    13:31:31.954 -> 278616
    13:31:33.014 -> 278616
    13:31:34.075 -> 278616
    13:31:35.102 -> 278616
    13:31:35.964 -> Message arrived [myHome/test] 1 <--- received 15 sec later

**OUTPUT-2:** Code

    #include <WiFi.h>
    #include <PubSubClient.h>

    WiFiClient espClient;
    PubSubClient client(espClient);

    const char *mqtt_server = "192.168.2.100";

    void setup_wifi()
    {

            delay(10);
            // We start by connecting to a WiFi network
            Serial.println();
            Serial.print("Connecting to ");
            // Serial.println(ssid);

            WiFi.mode(WIFI_STA);
            WiFi.begin("iot", "GdS");

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

            Serial.println("");
            Serial.println("WiFi connected");
            Serial.println("IP address: ");
            Serial.println(WiFi.localIP());
    }

    void callback(char *topic, byte *payload, unsigned int length)
    {
            Serial.print("Message arrived [");
            Serial.print(topic);
            Serial.print("] ");
            for (int i = 0; i < length; i++)
            {
                    Serial.print((char)payload[i]);
            }
            Serial.println();

            // Switch on the LED if an 1 was received as first character
    }

    void reconnect()
    {
            // Loop until we're reconnected
            while (!client.connected())
            {
                    Serial.print("Attempting MQTT connection...");
                    // Create a random client ID
                    String clientId = "ESP8266Client-";
                    clientId += String(random(0xffff), HEX);
                    // Attempt to connect
                    if (client.connect(clientId.c_str()),"guy","kupelu9e")
                    {
                            Serial.println("connected");
                            // Once connected, publish an announcement...
                            client.publish("myHome/log", "hello world");
                            // ... and resubscribe
                            client.subscribe("myHome/test");
                    }
                    else
                    {
                            Serial.print("failed, rc=");
                            Serial.print(client.state());
                            Serial.println(" try again in 5 seconds");
                            // Wait 5 seconds before retrying
                            delay(5000);
                    }
            }
    }

    void setup()
    {
            Serial.begin(115200);
            setup_wifi();
            client.setServer(mqtt_server, 1883);
            client.setCallback(callback);
            reconnect();
    }
    void loop()
    {
            loop_buttons();
            if (!client.connected())
            {
                    reconnect();
            }
            client.loop();
            static unsigned long lastentry = 0;
            static unsigned long lastentry2 = 0;
            if (millis() - lastentry > 200)
            {
                    pinMode(2, OUTPUT);
                    digitalWrite(2, !digitalRead(2));
                    lastentry = millis();
            }
            delay(50);
            if (millis() - lastentry2 > 1000)
            {
                    Serial.println(ESP.getFreeHeap());
                    lastentry2 = millis();
            }
    }

title: ESP32- Sporadic slow receive of MQTT messages

Answers: 1

body:
In case somebody finds this when faced with the same issue:
I had a similar problem on a Pico W. Turned out that the Serial.println()s in the MQTT callback clobbered the MQTT+WiFi stack. Something did not multitask nicely. Not accessing the Arduino Serial port in the MQTT callback fixed it.


body:
I checked several answers for same question but none of them help.

I also changed the nano board and GPS module but without luck. I ran it outdoor.

[This post question][1] had same issue except my date **does not display the correct date and time**.

My connection:
```
vcc->5V
rxd->d4
txd->d3
gnd->gnd
```
FullExample program from TinyGPS++, I get following types of entries

```
Sats HDOP  Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum
           (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail
----------------------------------------------------------------------------------------------------------------------------------------
0    100.0  ********** *********** **** 00/00/2000 00:00:00 152  ****** ****** ***** ***   ******** ****** ***   324   0         0
0    100.0  ********** *********** **** 00/00/2000 00:00:00 230  ****** ****** ***** ***   ******** ****** ***   486   0         0
0    100.0  ********** *********** **** 00/00/2000 00:00:00 308  ****** ****** ***** ***   ******** ****** ***   648   0         0
0    100.0  ********** *********** **** 00/00/2000 00:00:00 384  ****** ****** ***** ***   ******** ****** ***   810   0         0
0    100.0  ********** *********** **** 00/00/2000 00:00:00 463  ****** ****** ***** ***   ******** ****** ***   972   0         0
0    100.0  ********** *********** **** 00/00/2000 00:00:00 541  ****** ****** ***** ***   ******** ****** ***   1134  0         0
```

  [1]: https://arduino.stackexchange.com/questions/25901/not-getting-data-from-gps

NMEA read from serial

```
$GPGGA,,,,,,0,00,99.99,,,,,,*48
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPGSV,1,1,01,05,,,20*7F
$GPGLL,,,,,,V,N*64
$GPRMC,,V,,,,,,,,,,N*53
$GPVTG,,,,,,,,,N*30

$GPGGA,,,,,,0,00,99.99,,,,,,*48
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPGSV,1,1,01,14,,,29*76
$GPGLL,,,,,,V,N*64
$GPRMC,,V,,,,,,,,,,N*53
$GPVTG,,,,,,,,,N*30
```

**UPDATE:**

I change the antenna. At some time I got this. From the GPGSV sentence I know that there are about 15 16 satellites in view but the FullExample only show 0.

```
$GPRMC,,V,,,,,,,,,,N*53
$GPVTG,,,,,,,,,N*30
$GPGGA,,,,,,0,00,99.99,,,,,,*48
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPGSV,4,1,15,04,,,31,07,,,33,09,,,34,11,,,30*74
$GPGSV,4,2,15,12,,,33,13,,,30,14,,,33,15,,,27*7D
$GPGSV,4,3,15,16,,,33,19,,,34,20,,,30,21,,,33*70
$GPGSV,4,4,15,22,,,32,23,,,33,33,,,35*7B
$GPGLL,,,,,,V,N*64

$GPRMC,,V,,,,,,,,,,N*53
$GPVTG,,,,,,,,,N*30
$GPGGA,,,,,,0,00,99.99,,,,,,*48
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPGSV,4,1,16,04,,,32,07,,,33,08,,,31,09,,,33*7A
$GPGSV,4,2,16,11,,,29,12,,,33,13,,,30,14,,,34*73
$GPGSV,4,3,16,15,,,32,16,,,33,19,,,33,20,,,31*73
$GPGSV,4,4,16,21,,,33,22,,,33,23,,,34,33,,,35*7D
$GPGLL,,,,,,V,N*64
```
My idea now is to supply external power for the DFRduino Nano

Any idea how I can continue. Should I changed to other type of gps module?

title: No GPS data Neo 6M DFRduino Nano

Answers: 1

body: The ceramic antenna is the issue. I changed to the external 1.5GHz one. It got fix under 5 seconds


body:
I'm looking to network a bunch of devices (boards in a Eurorack case) over I²C, but I don't want to compromise the address space available to each individual device for its own needs. The obvious solution here is to give each device its own I²C bus which it controls, and then connect them together over another.

Two independent I²C connections would be needed on a microcontroller in this setup, and if I understand the datasheet correctly, the MCU on the Arduino Nano Every [can act as host on one bus and client on another][datasheet] using the Dual Mode setup of the Two-Wire Interface (see Chapter 25 of the linked datasheet), but the board only exposes two sets of I²C-capable pins and [they are wired together in the schematic][schematic].

What steps would I need to take to coax another I²C connection out of an Arduino Nano Every?

[datasheet]: https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega4808-09-DataSheet-DS40002173C.pdf
[schematic]: https://docs.arduino.cc/static/1d097e7f46445e1d9a88348af88dcb4f/schematics.pdf

title: Can you coax another I²C connection out of an Arduino Nano Every?

Answers: 1

body:
Welcome!

Theoretically you can connect 127 devices to the I2C bus. I suggest you do a little reading on the I2C bus before you start your design. Hopefully all of these I2C devices are on the same board but since you want to network them I have a feeling you are making a very painful mistake. I2C was never intended to be used for networking.

For a bunch of devices I would seriously look at CAN, two wires to connect them is all that is needed even for well over 250 meters or 800 feet with the baud rate of 250 kbit/s. I usually also run a ground. This will be much faster than the I2C. CAN is a simplex communication mode that turns around very fast. Each node can send and receive under software control. It does its own arbitration no need to worry about it the controllers do it for you.


body: I've been doing projects with the arduino boards for a long time and accordingly also with the libs from adafruit etc. But that was too boring for me and I wanted to get more into the matter, so I used youtube and acquired knowledge about the microcontrollers eeproms etc. itself . But now my question is whether I, if I have the necessary interface adapters, etc., can compile the libs from adafruit, etc. and flash the hex file directly onto an eeprom and then use it with e.g. connect and use a 6502. but I need the corresponding settings in the IDE so that the code can be executed correctly, right? and what is the best way to do this? and general tips would also be nice thanks in advance

title: Can I run Arduino code on a 6502?

Answers: 1

body:
No, you can't.

You would fail at the first hurdle: you would need to find a 6502 C++ compiler, and AFAICT there is no such thing.

Without a C++ compiler for the 6502 you would never be able to compile C++ code for the 6502.

The closest you would come is to program in pure C for the 6502, which means you won't be able to use 99% of the Arduino libraries (not counting the fact that many use architecture-specific register access) since they are written in C++ not in C.


body:
I am using the Nano RP2040 with MicroPython and run the following code:

```
import machine
import time

p0 = machine.Pin(0, machine.Pin.IN)
while True:
    print(p0.value())
    time.sleep(0.3)
```

The Nano has built-in pull-up and pull-down resistors. If I do not specify ```machine.Pin.PULL_xx```, then these built-in resistors are not activated. If they are not activated, then shouldn't the signal received be floating, i.e., shouldn't the environment interfere with the input signal and make the code above print random series of 0s and 1s on the REPL? What actually happens is the REPL prints all 0s.

I read of how input pins are interpreted as high-impedance output and while I suspect this may be the cause, I do not not understand what that means.

title: Input on the Nano RP2040 does not float

Answers: 1

body:
That you'll get noise on a floating input observable in the read value isn't something you can rely on. The AVR like the ATMega328P seems to readily couple house/mains frequency noise onto inputs. However, I went to demonstrate this sort of thing for someone with a NodeMCU(ESP8266) board and found it was much harder to influence.

As I understand it the RP2040 has configurable Schmitt trigger inputs with a minimum hysteresis of 0.1 * IOVDD, 330 mV minimum, I think. And that these are on by default.  So your noise has to be bouncing across this threshold to affect the read value, which it may easily not be doing. If you turn off the Schmitt trigger feature, you *may* see more noise. I don't know how to disable them in MicroPython. The PicoSDK has a function called `gpio_set_input_hysteresis_enabled` that should do it.

You can also try running something like an old vacuum cleaner next to it to throw lots of noise into the environment.

For my own curiosity I may try playing with this on an RPI Pico, though perhaps not in MicroPython (we'll see) and if I do I'll show what I found.


body:
I want to reboot relay (turn off , waiting 4 seconds and turn ON)
it works perfectly if I use delay(4000), but code is blocked while delay (4 seconds) and I cant start relay 2.
How can I use Millis instead of delay to reboot relay 1 and start relay 2 same time?

    #include <SPI.h>
    #include <Ethernet.h>
    #include <Wire.h>
    #include <EthernetUdp.h> //Load the Udp Library

    //Ethernet
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; //Assign mac address
    IPAddress ip(192, 168, 1, 178); //Assign the IP Adress
    unsigned int localPort = 80; // Assign a port to talk over
    char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //dimensian a char array to hold our data packet
    String datReq; //String for our data
    int packetSize; //Size of the packet
    EthernetUDP Udp; // Create a UDP Object                            //server port
    String readString;

    bool relayState = false;
    //define relay pins
    int relay_1 = 22;
    int relay_2 = 24;

    void setup() {
      Serial.begin(9600);
      Ethernet.begin(mac, ip);
      Udp.begin(localPort); //Initialize Udp
      delay(2000);

      //Initial state of the relay
      pinMode(relay_1, OUTPUT); digitalWrite(relay_1, LOW); //relay 1 is On
      pinMode(relay_2, OUTPUT); digitalWrite(relay_2, HIGH);//relay 2 is Off

    }

    void loop() {

      packetSize = Udp.parsePacket(); //Reads the packet size
      if (packetSize > 0) { //if packetSize is >0, that means someone has sent a request
        Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Read the data request
        String datReq(packetBuffer); //Convert char array packetBuffer into a string called datReq
        //Serial.println(datReq);

        if (datReq == "relay1reboot") { //reboot relay
          digitalWrite(relay_1, HIGH);//relay off
          delay(4000);
          digitalWrite(relay_1, LOW);//relay on

          Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send
          Udp.print("relay 1 reboot");
          Udp.endPacket(); //End the packet

        }
        if (datReq == "relay2on") {
          digitalWrite(relay_2, LOW);//relay 2 on
          Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send
          Udp.print("relay 2 on");
          Udp.endPacket(); //End the packet
        }
        if (datReq == "relay1on") {
          digitalWrite(relay_1, LOW);//relay 2 on
          Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send
          Udp.print("relay 1 on");
          Udp.endPacket(); //End the packet
        }
        // Use the snapshot to set track time until next event
        //previousMillis = currentMillis;
      }
    }

    //}
    memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE); //clear out the packetBuffer array

    }

title: Using Millis instead of delay to reboot relay

Answers: 1

body:
A general approach to remove a `delay()` is to replace it by some code
that:

* takes note that some action (whatever follows the `delay()`) will have
  to be performed in the future

* takes note of the current time.

Then, somewhere else in `loop()`, you check whether that “some action”
has to be done right now and, if this is the case, does it.

In this particular case, I would add a global boolean variable named
`relay1isRebooting`. When it is true, that means that the relay has been
turned off and will have to be turned on in the near future.

```c++
bool relay1isRebooting = false;
unsigned long relay1rebootStarted;

void loop() {
  packetSize = Udp.parsePacket();
  if (packetSize > 0) { //we have received a packet
    // ...
    if (datReq == "relay1reboot") {
      digitalWrite(relay_1, HIGH); //relay off
      relay1isRebooting = true;
      relay1rebootStarted = millis();
    }
    // ...
  }

  // Switch back the relay 1 on if needed.
  if (relay1isRebooting && millis() - relay1rebootStarted >= 4000) {
      digitalWrite(relay_1, LOW); //relay on
      relay1isRebooting = false;
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      Udp.print("relay 1 reboot");
      Udp.endPacket();
  }
}
```

Please note that the test for whether the relay 1 should be turned back
on is performed outside the `if (packetSize > 0)` block. Also note that
`relay1rebootStarted` has a valid value only when `relay1isRebooting` is
`true`.


body:
The question is meant as in, can I lock myself out of the Arduino using the bootloader, if I flash a hex file that doesn't contain the bootloader?

Or does the bootloader automatically add the flashed file after itself, so that it's never overwritten?

The device in question is an Arduino Pro Micro (ATMega32u4). Asking, because I don't have an ISP available right now, and I have to flash pre-compiled hex files.

title: Is it possible to remove the bootloader while flashing using the bootloader?

Answers: 1

body:
If you don't play around ISP programming and have not already been playing around with ISP programming, your bootloader is fine and will remain fine no matter what you try to upload. The bootloader has its own protected section, so it's not necessary to tack it onto your sketch code on every upload. The Pro Micro bootloader can't be updated via itself anyway.

Worst case what you try to upload your precompiled binaries and they simply don't work.

You *can* upload code that fails to respond to the 1200 baud touch request that is used to reset the board into the bootloader, which may make you think you've screwed up the board, but you haven't. The Pro Micro version of Caterina bootloader supports a double-tap reset for an 8-second upload window no matter what you've put (or tried putting) on the chip.

Practically speaking, the existing bootloader is immutable and will always work for you until ISP becomes involved at some point.


body: Where can I find the list of supported boards in Arduino IDE 2.0 without installing the IDE? Googling it was not fruitful. Specifically, I'm looking for ESP32-S3 support.

title: List of supported boards in Arduino IDE 2.0

Answers: 2

body:
The 2.X IDE [makes use][1] of [arduino-cli](https://github.com/arduino/arduino-cli):

> The backend operations such as compilation and uploading are offloaded
> to an arduino-cli instance running in daemon mode.

which has roughly the same internals as [arduino-builder](https://github.com/arduino/arduino-builder)

> The arduino-builder is now just a wrapper of arduino-cli

which is what the 1.X IDE uses to launch the build process. Roughly speaking, they support the same boards.

About the only difference I've noticed is that the 2.X IDE does not *yet* support `disableRTS` and `disableRTS` board properties, so some ESP32 board that require these settings will not (yet) work in with the 2.X IDE's serial monitor. The ESP32-CAM-MB together with ESP32CAM is one combination where the Serial Monitor won't work. You can still upload with it though.

So, the IDE should compile and upload for your ESP32-S3 just fine. If you want to know whether or not the Serial Monitor will work, it's down to looking at the specific board schematic to see whether or not the EN/RESET and GPIO0 signals are connected to the serial transceiver using only diodes. The official boards don't do this. So if you have one of the Expressif devkits (or a clone) the 2.0 IDE Serial Monitor will work fine with it.

  [1]: https://github.com/arduino/arduino-ide

body:
> Where can I find the list of supported boards in Arduino IDE 2.0
> Specifically, I'm looking for ESP32-S3 support.

Without knowing what you want to do, the short answer is: check this JSON's `"boards"` properties: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json.

The Arduino IDE is just a user interface on top of the `arduino-cli`. It provides a way to change the [`board_manager#additional_urls`](https://arduino.github.io/arduino-cli/latest/configuration/) property of the CLI configuration. Once a new 3rd party platform URL is specified in the IDE, the CLI will see the available boards of the [platform](https://arduino.github.io/arduino-cli/latest/platform-specification/). You'll need to install the platform to verify and upload your sketches. After installing the platform, the [`"boards.txt"`](https://arduino.github.io/arduino-cli/latest/platform-specification/#boardstxt) will be available on your filesystem for the CLI. For this example, this is https://github.com/espressif/arduino-esp32/blob/master/boards.txt.


body:
I’ve worked with esp8266/esp32 boards in the past and they were great. But now I have a very simple project where both of these are way too powerful.

I want to read one analog input over USB per COM. That’s it. No wifi, no Bluetooth, no 32 bit or any of these _fancy things_.
It should be programmable without any hardware other than a computer though. It doesn’t need to be Arduino. All it has to do is to read the input and respond to serial communication.

But I’m absolutely overwhelmed by all these microcontrollers. Most of them are feature packed.

So I’m asking for a way to find a proper controller/board on my own. Feel free to recommend one though.

title: Looking for a very simple board

Answers: 2

body:
Since you seem to have some experience, seemingly these are valid options:

1. Obtain the smallest Arduino you can get. For example, a DigiSpark  original or clone, or a DFRobot Beetle. Use the Arduino IDE to program it.

1. Obtain the smallest AVR board you can get. For example, with an ATmega32u4. Download ASF, the Atmel Software Framework, learn how to use it. It provides a lot of sources for ADC and USB.

body:
Since you require USB, nano/micro are your way forward.
being mass produced anything smaller would actually turnout to be more expensive.

If you for those reading this message latter: If you do not need USB then you have a pro-miny (needs USB->ttl for programing)

If you are going really minimalist you can go with MSP430 chips (arduino programming available via PlatformIO).
Atmega32u4 can although run on its own without crystal, but I find Crystal free (using builtin crystal) run of MSP430 much better with timing.
Problem with MSP430 is that TI software development dedepartment is stuck in middle ages. (I am not sure if they even employ a full-time programmer) and if you are programming on arm, you might Have a problem compiling it from arm platform.


body:
I would like to know how can I change LED pin for [avr_boot][1] bootloader.

I can see there is option in variants folder but in the manual it mention "if using USE_LED adapt LED-pins in asmfunc.S" which is not clear. I am using pin PC3 how do I write it.

  [1]: https://github.com/zevero/avr_boot

title: avr_boot change LED pin

Answers: 1

body:
Near the top of asmfunc.S, you have [these lines][code]:

```lisp
; LED Pins
#define DDR_SS _SFR_IO_ADDR(DDRD), 5 // SS pin (PIN, PORT)
#define PORT_SS _SFR_IO_ADDR(PORTD), 5

#define DDR_PW _SFR_IO_ADDR(DDRD), 6 // Power pin (PIN, PORT)
#define PORT_PW _SFR_IO_ADDR(PORTD), 6
```

These define the “write” or “slave select” LED pin as PD5 (registers
DDRD and PORTD, bit 5), and the “power” LED as PD6 (registers DDRD
and PORTD, bit  6).

These are the lines you have to change if using different pins. For
example, pin PC3 is: registers DDRC and PORTC, bit 3.

[code]: https://github.com/zevero/avr_boot/blob/v1.3.0/asmfunc.S#L9-L14


body:
I made a simple test sketch to make my ATTiny85 emulate a Keyboard and send a sequence of keystrokes.

    #include "DigiKeyboard.h"
    void setup() {
      // don't need to set anything up to use DigiKeyboard
    }

    void loop() {
      DigiKeyboard.delay(1000);
      DigiKeyboard.sendKeyStroke(0);
      DigiKeyboard.sendKeyStroke(106); // F15
      DigiKeyboard.delay(59 * 1000);
    }

It worked fine, but now every time I plug it to the USB port on my computer, Windows detects it as a Keyboard and starts typing what I programmed it to type.

Arduino IDE can't reprogram it. When it says "Plug in device now", I do it, but it immediately acts like a Keyboard, not like a programmable ATTiny85.

[![Arduino IDE][1]][1]

*Note: Image shows the console output. Code is just a simple blinker.*

Is there any way to save this board? I just want to upload another sketch to it. Maybe some way to rewrite the bootloader or to erase the flash memory entirely.

Also, please give me some advice so I can avoid being locked out again in the future. I really want to use this board as a Keyboard emulator, but I want to be able to reprogram it if necessary.

[![ATTiny85][2]][2]

  [1]: https://i.stack.imgur.com/3VvD1.png
  [2]: https://i.stack.imgur.com/aSlE2.png

title: Unlocking Digispark ATTiny85 after flashing it to HID

Answers: 1

body: If you can't access the bootloader using USB your remaining option is ISP/ICSP (In-Circuit Serial Programming). I have that digispark board and I have never been able to program it using Arduino's IDE/USB. However, since then I always use both an USBasp programmer and the AVRDUDESS programming tool. With them you can eassily program the controller (they have never failed me). Connect the SPI, +5V, GND and RESET connectors from the ATTINY85 to the programmer, compile the code, program the binaries with AVRDUDESS and voila.


body:
Hello I would like to optimise a few values for transmission via radio (LoRa) beforehand. I have a sensor number (1-255), temperature (00.00-99.99) and humidity. (00.00-99.99) I would like to transmit this data compressed as a byte array. I have already calculated that I need 5 bytes via BCD for this.

How do I get my numbers mapped into the respective byte?

```
float temperature = 24.12;
float humidity = 60.12;
byte message[5];

void setup() {
  Serial.begin(9600);
  message[0] = 12; //sensor id 12
}

void loop() {
  float temperature1 = floor(temperature);
  float temperature2 = (temperature - temperature1) * 100;
  Serial.println(temperature1, 0);
  Serial.println(temperature2, 0);
  message[1] //?? temperature1
  message[2] //?? temperature2

  float humidity1 = floor(humidity);
  float humidity2 = (humidity - humidity1) * 100;
  message[3] //?? humidity1
  message[4] //?? humidity2
}
```

title: compress data with 8-4-2-1-BCD-Code

Answers: 2

body:
Why don't you use the following mapping:

1 byte: sensor number (0-255)

2 bytes: temperature (0-65535) by mapping the temperature to

    (int) (65536.0 * (temperature / 100.0))

2 bytes: humidity (0-65535) by mapping the humidity to

    (int) (65536.0 * (humidity / 100.0))

You will lose a little bit of accuracy for the temperature and humidity. If you know ranges in which the temperature/humidity will be, you can get a better accuracy.

    message[0] = 12; // Sensor id 12
    message[1] = highByte(temperature);
    message[2] = lowByte(temperature);
    message[3] = highByte(humidity);
    message[4] = lowByte(humidity);

Note if you have multiple sensors and have to transmit them all, you don't need to send the sensor number, send in bytes 0..3 the temperature/humidity for sensor 0, in bytes 4..7 the temperature/humidity for sensor 1 etc.

body:
This is my final solution with BCD-Code

```
int temperature1 = int(floor(temperature));
int temperature2 = int(round((temperature - temperature1) * 100));
uint8_t bcdTemperature1 = uint8_t((temperature1/10) <<4) | (temperature1 );
uint8_t bcdTemperature2 = uint8_t((temperature2/10) <<4) | (temperature2 );

message[0] = moduleUniqueidentifier;
message[1] = bcdTemperature1;
message[2] = bcdTemperature2;
message[3] = uint8_t(ceil(humidity));
```


body:
My arduino cannot connect to any port of my computer. So far i tried the following, without any luck:
 1. Using another arduino to check the usb, and it worked. So no problem with usb cable.
 2. Resetting the arduino (double tap the reset-button)
 3. Inserting deleting and updating the drivers from the device manager
 4. Deleting the drivers, and then inserting the arduino while pressing the reset button.
 5. Connecting the arduino to a different pc and it still doesn't work.
 6. I followed everything listed [here](https://support.arduino.cc/hc/en-us/articles/4404168794514-Nano-RP2040-Connect-not-being-detected-on-USB-port). (Resetting, uploading a uf2 blink file). I even compiled my blink uf2 file, with the newest version of mbed os for rp2040. And i even tried with older versions of the mbed os.
7. I tried uploading a flash_nuke.uf2 file

Is there something else i can do? Or is it permenantly damaged?

When i connect to to the computer, this comes up:
[![enter image description here][1]][1]

In my device manager, i see the following:

[![Another][2]][2]

Also, in the IDE, i cannot select any port.

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

**Extra info :** I was trying to use Serial2 from another arduino to this, so i was changing some jumper wires while they were powered. So it is possible it is damaged.  I also tried uploading some sketches to use a second serial with some modifications to the core of the OS. The changes were on the spirit of [this](https://arduino.stackexchange.com/questions/90583/adding-serial2-ends-up-blocking-nano-rp2040) post, but not necessairily the same.

  [1]: https://i.stack.imgur.com/xquoE.png
  [2]: https://i.stack.imgur.com/GWyoe.png
  [3]: https://i.stack.imgur.com/poW8Z.png

title: Arduino cannot connect to port (arduino nano rp2040)

Answers: 2

body:
The RP2040 doesn't have a USB serial port *unless you program it to have one*.

Unlike "traditional" Arduinos the RP2040 uses the UF2 bootloader system. This involes the RP2040 pretending to be a USB flash drive, and then uploading code is as simple as copying the .UF2 file to that drive.

If you are seeing that drive then the chip is ready and waiting for you to upload code. You don't need to select a port in the IDE to upload the code since the port is not used for uploading (only for resetting the board to enter the bootloader mode, which you don't need since you are already in bootloader mode).

If the IDE is struggling to find the virtual flash drive then just find the .UF2 file that the IDE created and manually drag and drop it to that drive and it will program the code onto the drive for you.

body:
I had the same issue, even after following all the possible RESET/HARD RESET/BOOTLOADER procedures. I have found a solution for this board to regularly work under Windows, and this involves reintalling it as a DIFFERENT board.

What I became aware of, is that my Win OS (8.1) was not properly installing the Arduino Nano RP2024 driver, for reasons unknown. So, I was first trying to manually reinstall the driver after searching for the proper .inf driver file, which is located in "C:\Users\<USERNAME>\AppData\Local\Arduino15\packages\arduino\hardware\mbed_nano\3.2.0\drivers". Unfortunately this come up with the same issue.

So I went for a "fake" manual install of the device, by selecting "Manually choose from a list of device drivers in your PC".  I then selected "Ports (COM and LPT)", because this is how you would like your board to behave under your OS. THIS STEP IS ESSENTIAL. As far I could see, if you simply chose the Nano RP2024 .inf file located in the above folder, the boards will continue in not showing up in the COM ports list.

After this step, I went through a list of vendors, finding several Arduino-like entries. Among these, I selected "Arduino SA", which ws containing "Arduino Nano 33 BLE" as a device, which I found to be a working option. The board is now regulary showing up into the IDE, even after several connect/disconnect cycles, and also the serial monitor works.

NOTE: in case you select a different working mode of the board (e.g. HID peripheral such as mouse, keyboard or similar) you may have to reinstall it following the procedure above.

Hope this helps!
Cheers
Attila


body:
I want to "translate" existing code, that utilizes one of these modules, for the other module.

Specifically, i have code that utilizes an "RS485 to TTL converter". As you can see in this picture,
[![enter image description here][1]][1]

The side that connects to the Arduino has four pins, VCC, GND, TX, RX.
But out of those pins, only two are data pins.

However, if we look at the MAX485 module,
[![enter image description here][2]][2]

The Arduino side has four pins as well, DI, DE, RE, RO.
However, all four of these pins are data pins.

Since the protocol is the same, how come the pins are different?
In the "RS485 to TTL converter" code, `SoftWareSerial` is being used, and it gets the two pins that will eventually connect to the TX, RX on the module - as arguments.

How can i translate this code for the MAX485? How should the pinout be?

  [1]: https://i.stack.imgur.com/38prk.png
  [2]: https://i.stack.imgur.com/h9GvK.png

title: Differences between two common RS485 to TTL modules

Answers: 2

body:
So far as I'm able to tell, your first module must have a feature that automatically enabled RS485 driver when you are sending and disabled it as soon as you aren't. This is not an uncommon feature.

The latter doesn't support it apparently. It looks like a common MAX485 type design which doesn't. Instead it exposes driver enable and receiver enable pins. These are normally active at opposite levels, which allows you to tie them together and run them to a single pin on the Arduino for controlling both at the same time. Any code that you had using the prior module would need to be changed to manually enable the driver when sending and then disable it afterwards.

You would need an extra digital pin (`PIN_DE_RE`) connected from the Arduino to the module, to both of its RE and DE pins. It would need to be set to output in `setup()` with `pinMode(PIN_DE_RE, OUTPUT);` And set to low `digitalWrite(PIN_DE_RE, LOW);` for a chip following the MAX485 design such that the receiver is enabled and driver disabled initially.

Your write transactions would then need to look like this:
```c++
delayMicroseconds(10);
digitalWrite(PIN_DE_RE, HIGH);
delayMicroseconds(10);
your_serial.write(whatever); // or .print etc
your_serial.flush();
delayMicroseconds(10);
digitalWrite(PIN_DE_RE, LOW);
delayMicroseconds(10);
```

You *may* not need explicit delays around the `digitalWrite` since `digitalWrite` is often slow enough anyway, but the point of them is to give support the minimum time needed between changing the RE/DE pins and a transaction. I picked 10uS somewhat arbitrarily.  More than anything it's just there to raise the point that the timing between the signal change and sending/receiving is important.

For `SoftwareSerial` `.flush()` does nothing usually, at least it doesn't on the AVR. But I include it just to make the point that whatever you use to send serial you must make sure the transaction has left the actual device and not merely been queued for send before disabling the RS485 driver. If you were doing this with `Serial1` on a Leonardo/Micro/Mega etc it would be important. I'd leave `.flush()` as is for `SoftwareSerial` in part because it won't cost you anything to do so and it will make things work if you switch to a buffered-output type serial connection.

body:
RS485 is a standard for a communication bus with potentially multiple senders, of course not at the same time. As such, a device needs to disable its transmitting circuit to let others communicate. The application layer protocol is not defined by RS485.

For this reason, a good driver module provides two control inputs beside the data lines:

- DE is "driver enable". It needs to be active, if the device wants to drive the bus and send its message.
- RE is "receiver enable". It needs to be active, if the device wants to listen to the bus and receive some message.

The data lines are commonly denoted like this:

- DI is "driver input". If you use the ubiquitous serial communication, this is the same as TXD.
- RO is "receiver output". If you use the ubiquitous serial communication, this is the same as RXD.

---

How does this work in the module that only has TXD and RXD?

Well, the hardware assumes some specific baud rate, which should be documented.

As soon as the start bit is detected on TXD, the module internally activates the driver (DE). It might additionally disable the receiver (RE) to avoid reception of the message as an echo.

This activation is controlled by a timer that lasts at least as long as the transmission at the specific baud rate needs to be sent.

---

Now, what to do with the MAX485 module's control lines?

You can connect TXD to DI and RXD to RO, respectively.

If your module simply uses the driver chip manufactured by Maxim, the control input RE has actually inverted logic. This means, the receiver is active, if the line is low. In contrast, the driver is active, if the line DE is high.

Put appropriate calls of `digitalWrite()` at the places where you want to send something to the sensor. Please be aware that the transmission needs some time. You need to make sure that all bits are sent before you disable the driver.

If you only want to receive from the sensor, just disable the driver and enable the receiver all the time.


body:
Given I have two Arduinos that are supposed to primitively communicate with each other using digital pins. On Arduino Ar1, pin D13 is to be used as an input, connected to Ar2's D2 pin.

Will I need to use the internal pullup resistor of Ar1 on pin 13, or is an outputted signal of LOW/HIGH already dragged to 0V/5V?

title: Will I need the internal pullup resistor if no button is used?

Answers: 1

body:
If you set a pin to output mode in Arduino, it is "push-pull". This means, that any value, 0 or 1, is actively driven.

Therefore, you do not need a pull-up or pull-down resistor on the receiving input.

---

You need such a resistor, only if the driver does not drive the voltage actively. For example, this is the case with buttons or switches, which simply open and close a contact.

Some output modes exist like "open-drain" that only drive to GND at a value of 0, but do not drive the output pin at a value of 1. Such modes are not used if you call `pinMode()`.


body:
**Background Info**
I want to have two serials in my arduino nano rp2040 connect, in order to be able to communicate using the following scheme. (μC is a microcontroller).

μC1 <--> μC2 <--> μC3<-->....<-->μCn

So i tried changing the core and upload a sketch to test if it is possible. However, i ended up blocking the arduino, and
1. it disappears from the COM port,
2. the arduino red light is constantly blinking,
3. the serial port of my computer freezes,
4. the whole arduino application is not responding.
5. The arduino disappears from the device manager and it ends up as a USB device.

**I want to understand what causes it, in order to avoid doing it in the future.**

I usually reset the board, and then i upload a Blink.ino.elf.uf2 i have previously compiled. The application gets unstuck, the arduino runs the blink programm, and it appears at COM4.

**Changes i made to the core**:

**1st change**

In

    C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\hardware\mbed_nano\3.2.0\variants\NANO_RP2040_CONNECT

i changed the defines.txt and i changed the line:

    -DDEVICE_SERIAL=1

to

    -DDEVICE_SERIAL=2

**2nd change**

In the same folder, i changed pins_arduino.h in the following way:

    // Serial
    #define PIN_SERIAL_RX (0ul)
    #define PIN_SERIAL_TX (1ul)

    #define PIN_SERIAL2_RX (3ul)
    #define PIN_SERIAL2_TX (4ul)

and

    #define SERIAL_HOWMANY  2
    #define SERIAL1_TX   (digitalPinToPinName(PIN_SERIAL_TX))
    #define SERIAL1_RX   (digitalPinToPinName(PIN_SERIAL_RX))
    #define SERIAL2_TX          (digitalPinToPinName(PIN_SERIAL2_TX))
    #define SERIAL2_RX          (digitalPinToPinName(PIN_SERIAL2_RX))

**My programm:**

    #define led LED_BUILTIN
    char c;

    void setup() {
      pinMode(led, OUTPUT);
      // put your setup code here, to run once:
      Serial.begin(9600);
      while(!Serial);
      digitalWrite(led,HIGH);
      delay(1000);
      digitalWrite(led,LOW);

      Serial2.begin(9600);
      while(!Serial2);
      digitalWrite(led,HIGH);
      delay(1000);
      digitalWrite(led,LOW);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      if (Serial.available() ){
        c = Serial.read();
        if (c != '\n'){
          Serial.print("Master wrote : ");
          Serial.println(c);
          Serial2.print(c);
        }
      }

      if (Serial2.available() ){
        c = Serial2.read();
        if (c != '\n'){
          Serial.print("Slave wrote : ");
          Serial.println(c);
        }
      }
    delay(1000);
    }

**Edit** I uploaded the same sketch with earlephilhower's core (you can find it [here]( https://github.com/earlephilhower/arduino-pico ) ) and the IDE showed this message:

    Resetting COM4
    Converting to uf2, output size: 136192, start address: 0x2000
    Flashing D: (RPI-RP2)
    Wrote 136192 bytes to D:/NEW.UF2
    Board at COM4 is not available
    Board at COM4 is not available

The last 2 messages were from me trying to open serial monitor. So i think the sketch has the problem, and not the modiffications i made to the mbed os core.

title: Adding Serial2 ends up blocking nano rp2040

Answers: 0


body:
I'm trying to read data being transferred via Infrared from my Smartmeter on my ESP8266 using the following sketch:
```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPUpdateServer.h>
#include <Ticker.h>
#include <AsyncMqttClient.h>

#ifndef STASSID
#define STASSID "mySSID"
#define STAPSK  "myPassword"
#endif

#ifndef MQTT_HOST
#define MQTT_HOST IPAddress(192, 168, 0, 100)
#define MQTT_PORT 1883
#endif

#ifndef IR
#define SerialDebug Serial1
#define IR Serial
#endif

AsyncMqttClient mqttClient;
Ticker mqttReconnectTimer;

WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
Ticker wifiReconnectTimer;

const char* host = "esp8266-webupdate";

const byte firstByte = 0x7E;
const byte lastByte = 0x7E;

uint8_t i;

ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;

void connectToWifi() {
  SerialDebug.println("Connecting to WiFi ...");
  WiFi.begin(STASSID, STAPSK);
}

void connectToMqtt() {
  SerialDebug.println("Connecting to MQTT ...");
  mqttClient.connect();
}

void onWifiConnect(const WiFiEventStationModeGotIP& event) {
  SerialDebug.println("Connected to Wi-Fi.");
  connectToMqtt();
}

void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
  SerialDebug.println("Disconnected from Wi-Fi.");
  mqttReconnectTimer.detach();
  wifiReconnectTimer.once(2, connectToWifi);
}

void onMqttConnect(bool sessionPresent) {
  SerialDebug.println("Connected to MQTT.");
  SerialDebug.print("Session present: ");
  SerialDebug.println(sessionPresent);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  SerialDebug.println("Disconnected from MQTT.");

  if (WiFi.isConnected()) {
    mqttReconnectTimer.once(2, connectToMqtt);
  }
}

void array_to_string(byte array[], unsigned int len, char buffer[]) {
  for (unsigned int i = 0; i < len; i++) {
    byte nib1 = (array[i] >> 4) & 0x0F;
    byte nib2 = (array[i] >> 0) & 0x0F;
    buffer[i*2+0] = nib1  < 0xA ? '0' + nib1  : 'A' + nib1  - 0xA;
    buffer[i*2+1] = nib2  < 0xA ? '0' + nib2  : 'A' + nib2  - 0xA;
  }
  buffer[len*2] = '\0';
}

void setup() {

  SerialDebug.begin(115200);
  IR.begin(9600);
  SerialDebug.println();
  SerialDebug.println("Booting Sketch...");

  wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
  wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);

  connectToWifi();

  httpUpdater.setup(&httpServer);
  httpServer.begin();

  mqttClient.setWill("smartmeter/online", 0, true, "no");
}

void loop() {
  httpServer.handleClient();

  uint32_t timeout = 2000;

  int readCnt = 0;
  uint32_t start_time = millis();
  byte tempChar = 0;
  byte *readMessage;
  uint32_t messageLen = 0;

  while ((tempChar != 0x7E) && (millis() - start_time < timeout)) {
    if (IR.available()) {
      tempChar = IR.read();
    }
  }

  start_time = millis();
  timeout = 1000;
  bool done = false;

  if (tempChar == firstByte) { // if first byte == 0x7E
    while ((millis() - start_time) < timeout && !done) {
      if (IR.available()) {
        tempChar = IR.read(); // second byte must be 0xA0
        if(tempChar == 0xA0) {
          while ((millis() - start_time) < timeout && !done) {
            if (IR.available()) {
              tempChar = IR.read(); // 3rd byte tells the legth of the message

              readMessage = new byte[tempChar+2];
              memset(readMessage, 0, tempChar+2);
              readMessage[0] = firstByte;
              readMessage[1] = 0xA0;
              readMessage[2] = tempChar;
              messageLen = ((uint32_t)(tempChar))+2;
              readCnt = 3;

              while ( readCnt < messageLen && ((millis() - start_time) < timeout)) { // minimum len 120 chars for 0x7E format
                if (IR.available()) {
                  readMessage[readCnt] = IR.read();
                  readCnt++;

                  if(readCnt == tempChar+2 && readMessage[readCnt-1] != lastByte) { // correct len but last byte not 0x7E
                    done = true;
                    SerialDebug.printf("Wrong end byte found - %d\n", readMessage[readCnt-1]);
                  } else if(readCnt == tempChar+2) { // correct len and correct last byte
                    done = true;
                    char str[251] = "";
                    array_to_string(readMessage, readCnt, str);
                    mqttClient.publish("smartmeter/raw", 0, false, str);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  mqttClient.publish("smartmeter/online", 0, true, "yes");
  char heap[6] = "";
  itoa(ESP.getFreeHeap(), heap, 10);
  mqttClient.publish("smartmeter/freeHeap", 0, false, heap);
}
```
I'm getting the encoded HEX-data published on my MQTT Topic as desired, the outputs length is 250 characters long (= 125 Bytes) which is correct:

> 7ea07bcf000200231362b1e6e700db08534d536770075f626120000e32e62addedaede38e64c8c3173035a0a853851a28efc57f7fd76a9df59dbb152f796939328ff0f28df7f257d20b5cb2a458c4eb9188e2c1c251701c891244d859ed9c159714bb4451c090d9b1ed3bbb1fc89785ebafbf59ec4f9d540eb4c90d47e

As I found out, the ESP's heap is decreasing by 100-300 by each iteration of the loop (data is being transmitted every second via Infrared from the power-grid Smartmeter) until the ESP will eventually be rebooted by the watchdog after like 5-8 minutes.

I explicitly did not use String variables in the sketch but I legit cannot find the reason for the memory leak. Tried turning off wifi, webserver and mqtt one after each other which didn't actually made a difference.

The heap-size stays at a constant level though when there is no data being received via the Infrared serial port, so I imagine something is fishy when storing the data in the byte array "readMessage".

Anything obvious that immediately pops into someones eye that I missed?

title: memory leak w/ no Strings involved

Answers: 1

body:
You do a `new` inside the loop

     readMessage = new byte[tempChar+2];

which causes the heap to be filled with `tempChar+2` bytes, but you never delete this.

Try reusing this memory (making it a local, or make it 'dirty' global).

Probably (not tested) the above line can be rewritten as:

    byte readMessage[tempChar+2];


body:
I'm using an arduino uno R3 for lighting a few LEDs in response to coputer control. I've written two programs, the first to try an Object Oriented style, and the second to split up the code into more manageable chunks. They both implement the same function, turning one led on, then off and repeat for the other led. I'd also put 100uF capacitors between the anode and ground of each led for a fade effect. When running with the first sketch this works fine, but I noticed with the second sketch, the fade no longer works and the leds are much brighter. There was no change in hardware between sketches, and reverting to either doesn't change anything. On inspection with a multimeter there appears to be a large difference in output voltage (1.6v -> 5.2v) between programs. I've tried changing pins and this seems to have no effect. Is it the code or have I missed something obvious with the hardware?

Program 1
```
#include "Arduino.h"
// create signal class
class two_aspect_signal {
  //store pin numbers
  const int danger_aspect;
  const int clear_aspect;

  public:
    two_aspect_signal(int danger_pin, int clear_pin):
      danger_aspect(danger_pin),
      clear_aspect(clear_pin)
    {}
    void setup(){
      //set to output
      pinMode(danger_aspect,OUTPUT);
      pinMode(clear_aspect,OUTPUT);
    }

    void danger(){
      //turn red light on, green light off
      digitalWrite(danger_aspect,HIGH);
      digitalWrite(clear_aspect,LOW);
    }

    void cleaR(){
      //turn red light off, green light on
      digitalWrite(danger_aspect,LOW);
      digitalWrite(clear_aspect,HIGH);
    }
};
//create signal object
two_aspect_signal sig(7,8);
void setup() {
}
void loop() {
  //turn red light on, green off
  sig.danger();
  delay(2000);
  //turn green light on, red light off
  sig.cleaR();
  delay(2000);
}
```

Program 2
```
#include "sig2.h"
//create signal object
two_aspect sig(7,8);
void setup(){}
void loop() {
  // set red light on, green off
  sig.danger();
  delay(2000);
  // set green on, red off
  sig.cleaR();
  delay(2000);
}
```
Program 2 (sig2.cpp)
```
#include "Arduino.h"
#include "sig2.h"

two_aspect::two_aspect(int clear_pin, int danger_pin)
{
  //set pins to output and store
  pinMode(danger_pin,OUTPUT);
  pinMode(clear_pin,OUTPUT);
  _danger_pin = danger_pin;
  _clear_pin = clear_pin;
}

void two_aspect::danger()
{
  //set red light on, green off
  digitalWrite(_danger_pin,HIGH);
  digitalWrite(_clear_pin,LOW);
}
void two_aspect::cleaR()
{
  //set green led on, red led off
  digitalWrite(_danger_pin,LOW);
  digitalWrite(_clear_pin,HIGH);
}

```
Program 2 (sig2.h)
```
#ifndef sig2_h
#define sig2_h

#include "Arduino.h"

class two_aspect
{
  public:
    two_aspect(int clear_pin, int danger_pin);
    void danger();
    void cleaR();
  private:
    int _clear_pin;
    int _danger_pin;
};

#endif
```

Please let me know if this should've been in the electronics forum, thanks for reading.

title: digitalWrite giving different output voltages between programs

Answers: 1

body:
The difference is, that in your first sketch you never call `two_aspect_signal.setup()`, thus the pins are never set as output. By default pins are configured as inputs. Doing `digitalWrite()` while the pin is configured as input will enable or disable the internal pullup resistor of that pin.

So in your first sketch you are powering the LEDs through the internal pullup resistor (if I correctly remember about 10kOhm). Thus they are rather dim. Also it takes some time for the capacitor to be charged through the big pullup resistor.

In your second sketch you configure the pins as output. So the LEDs will now  be actively driven through the pins output driver. It can provide way more current than the pullup resistor, thus the LEDs light up brigther. And the bigger current can also charge the capacitor in way less time (a time so small, that you don't even see it). Thus you don't see any fading (the fading is there, but just too fast for your eyes).

**What to do know?** You can of course just use the pullup resistor (and not configuring the pins as output). Or you can configure the pins as outputs and add a current limiting resistor between the pin and the LED/capacitor bundle. With your second sketch and the current circuit you are risking to damage the output drivers of that pin (through the LED current and through the high inrush current until the capacitor is charged). The sizing of that resistor depends on your needs. Make sure, that the current never exceeds 20mA (sustainable pin max current) (for 5V this would be R=U/I=5V/20mA=250Ohm as minimum resistance). The higher the resistance, the dimmer the LED will be and the longer the capacitor needs to charge. After that you can also change the capacitance. The higher the capacitance, the longer it will take to charge it (so longer fade effect).


body:
I got a strange issue with my Arduino Leonardo (clone). It seems to be laggy or buggy, I don't know what the issue is.

I get issues when I use "long" delays.

Below sketch is working fine.

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

    void loop() {
      delay(1000);
      Serial.println("Hello World 1000"); // added delay to line for debugging
    }

When I use `delay(2000)` it still is fine. But when I try `delay(3000)` the serial monitor doesn't output anything (or just 1 line). When I lower the delay to like 2500, it gets better. But not without issues. Sometime it will just skip one iteration, see log below.

    11:33:06.328 -> Hello World 2500
    11:33:11.331 -> Hello World 2500
    11:33:13.909 -> Hello World 2500
    11:33:18.815 -> Hello World 2500
    11:33:21.395 -> Hello World 2500
    11:33:23.815 -> Hello World 2500
    11:33:26.392 -> Hello World 2500

What might the issue be?

EDIT:

- when I do 3x `delay(1000)` I get same (weird) results. With 2 times, it does work ok.
- The logs are from the serial monitor from the Arduino IDE
- I added below line in the setup, it does print the line just once.

    `while (!Serial) {}`
    `Serial.println("setup()");`

**Important note**: I think it might have to do more with the serial communication than with the Arduino itself. I tested the same things on another computer (Windows 10), and then I just get the expected results. I am using Manajaro Linux as the main machine.

When the output to the serial port is "lagging" so the printing of the line is missed/skipped, I see the RX and TX led on the Arduino light up for a while. Then when they go out, the serial monitor sometimes outputs 2 lines at once.

title: Arduino lagging or buggy with delays and serial print?

Answers: 0


body:
I want to get an ATMega328 off of the Digi-Key, and use it like an Arduino (without requiring the whole Arduino board).

When it comes to programming, do I need to do anything special like burn the bootloader onto it or something like that?

I want to use the Arduino IDE to program it.

title: Standalone ATMega328 - do I need to burn the bootloader?

Answers: 2

body:
No, you do NOT need to burn the bootloader. But depending on your equipment and programing habits you may want to.
The bootloader used by Arduino (which is known by the name 'optiboot') is used to allow to program the microcontroller via serial interface. If you want to program your microcontroler this way, then you need the bootloader. Otherwise you will need a programmer for In-System-Programing that uses the SPI interface like Atmel AVRISP MKII, any cheap clone like USBtinyISP or any regular Arduino with ArduinoISP flashed on it.

body:
At the risk of having my answer closed as "link only" I want to tell you that I have [a page describing how to make an Atmega328P into an Arduino-compatible board](http://www.gammon.com.au/forum/?id=11637).

There is far too much detail to post here, but once you have installed your processor with a resistor and a couple of decoupling capacitors you can use another Arduino to burn the bootloader.

[![Burning the bootloader][1]][1]

Once you have done that you can use an FTDI cable to program your new Arduino-compatible from the Arduino IDE. The cable would be hooked up like this:

[![Programming with FTDI cable][2]][2]

Now you can program the chip just using the IDE as if it was a "real" Arduino.

  [1]: https://i.stack.imgur.com/3zhtf.jpg
  [2]: https://i.stack.imgur.com/6GiDl.jpg


body:
After updating ESP32 to core version 2.0.4 (file in Arduino IDE preferences was replaced  to`https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json` to upgrade), I get the following error:

    /Users/guydvir/Dropbox/Arduino/libraries/LittleFS_esp32/src/LITTLEFS.cpp: In member function 'virtual bool LITTLEFSImpl::exists(const char*)':
    /Users/guydvir/Dropbox/Arduino/libraries/LittleFS_esp32/src/LITTLEFS.cpp:44:28: error: no matching function for call to 'LITTLEFSImpl::open(const char*&, const char [2])'
         File f = open(path, "r");
                                ^
    In file included from /Users/guydvir/Dropbox/Arduino/libraries/LittleFS_esp32/src/LITTLEFS.cpp:17:
    /Users/guydvir/Library/Arduino15/packages/esp32/hardware/esp32/2.0.4/libraries/FS/src/vfs_api.h:38:17: note: candidate: 'virtual fs::FileImplPtr VFSImpl::open(const char*, const char*, bool)'
         FileImplPtr open(const char* path, const char* mode, const bool create) override;
                     ^~~~

I minimized code to headers only ( and empty `setup` and `loop`:

#include "FS.h"
//#include "LITTLEFS.h" // <----- commenting out stops the error message
#include <time.h>
#include <WiFi.h>

What may be the error and how to fix it ?

title: ESP32 - error when using `LITTLEFS.h` after core updated to 2.0.4

Answers: 2

body: As Juraj commented - no need for `LittleFS_esp32` library, after upgrade to esp32 Arduino 2.0.4

body:
As you experienced, the Lorol's LittleFS_esp32 library was merged into ESP32 core from v1.0.6 and creates compile error to some old codes.

The difference is you have to use `#include <LittleFS.h>` instead of `#include <LITTLEFS.h>` for new cores (v1.0.6, v2.0.0+)

Check and modify the following snippet (used widely in my [ESP_WiFiManager library](https://github.com/khoih-prog/ESP_WiFiManager) ) for your purpose

```
// Check cores/esp32/esp_arduino_version.h and cores/esp32/core_version.h
//#if ( ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(2, 0, 0) )  //(ESP_ARDUINO_VERSION_MAJOR >= 2)
#if ( defined(ESP_ARDUINO_VERSION_MAJOR) && (ESP_ARDUINO_VERSION_MAJOR >= 2) )
  #if (_WIFIMGR_LOGLEVEL_ > 3)
    #warning Using ESP32 Core 1.0.6 or 2.0.0+
  #endif

  // The library has been merged into esp32 core from release 1.0.6
  #include <LittleFS.h>       // https://github.com/espressif/arduino-esp32/tree/master/libraries/LittleFS

  FS* filesystem =      &LittleFS;
  #define FileFS        LittleFS
  #define FS_Name       "LittleFS"
#else
  #if (_WIFIMGR_LOGLEVEL_ > 3)
    #warning Using ESP32 Core 1.0.5-. You must install LITTLEFS library
  #endif

  // The library has been merged into esp32 core from release 1.0.6
  #include <LITTLEFS.h>       // https://github.com/lorol/LITTLEFS

  FS* filesystem =      &LITTLEFS;
  #define FileFS        LITTLEFS
  #define FS_Name       "LittleFS"
#endif
```


body:
I did a search on the meaning of RX and TX and it seems TX means sending data and RX means receiving data.
So when my transmitter is turned off, my receiver looks like this and it works with a battery:

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

and when I turn on the transmitter my receiver looks like this:

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

So Tx is blinking and I'm confused, because Rx is not blinking and I think I receive nothing.

receiver code:

    #include <RF24.h>
    #include <SPI.h>

    int speedpin1=5;
    int dir11=3;
    int dir12=7;

    int speedpin2=A4;
    int dir21=8;
    int dir22=A3;

    int speedpin3=A2;
    int dir31=A1;
    int dir32=A0;

    int speedpin4=2;
    int dir41=4;
    int dir42=6;

    int mspeed;

    const byte CE = 9;
    const byte CS = 10;

    int data[1];

    RF24 Radio(CE,CS);
    const byte address[6]="00001";

    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(speedpin1,OUTPUT);
    pinMode(dir11,OUTPUT);
    pinMode(dir12,OUTPUT);

    pinMode(speedpin2,OUTPUT);
    pinMode(dir21,OUTPUT);
    pinMode(dir22,OUTPUT);

    pinMode(speedpin3,OUTPUT);
    pinMode(dir31,OUTPUT);
    pinMode(dir32,OUTPUT);

    pinMode(speedpin4,OUTPUT);
    pinMode(dir41,OUTPUT);
    pinMode(dir42,OUTPUT);

    Radio.begin();
    Radio.openReadingPipe(1,address);
    Radio.startListening();
    }

    void loop() {
      // put your main code here, to run repeatedly:
    if(Radio.available()){
      Radio.read(data,sizeof(data));
      if (data[0]>131){

        digitalWrite(dir41,LOW);
        digitalWrite(dir42,HIGH);

        analogWrite(dir31,0);
        analogWrite(dir32,255);

        digitalWrite(dir21,HIGH);
        analogWrite(dir22,0);

        digitalWrite(dir11,HIGH);
        digitalWrite(dir12,LOW);

        mspeed=255;

        analogWrite(speedpin1,mspeed);
        analogWrite(speedpin2,mspeed);
        analogWrite(speedpin3,mspeed);
        analogWrite(speedpin4,mspeed);
        Serial.println(mspeed);

      }
      if (data[0]<131){

        digitalWrite(dir41,HIGH);
        digitalWrite(dir42,LOW);

        analogWrite(dir31,255);
        analogWrite(dir32,0);

        digitalWrite(dir21,LOW);
        analogWrite(dir22,255);

        digitalWrite(dir11,LOW);
        digitalWrite(dir12,HIGH);

        mspeed=255;

        analogWrite(speedpin1,mspeed);
        analogWrite(speedpin2,mspeed);
        analogWrite(speedpin3,mspeed);
        analogWrite(speedpin4,mspeed);
        Serial.println(mspeed);

      }
      if (data[0]==131){

        mspeed=0;
        analogWrite(speedpin1,mspeed);
        analogWrite(speedpin2,mspeed);
        analogWrite(speedpin3,mspeed);
        analogWrite(speedpin4,mspeed);
        Serial.println(mspeed);

      }

    }

transmitter code:

    #include <RF24.h>
    #include <SPI.h>
    const byte CE = 9;
    const byte CS = 10;
    int jpin=A0;
    int datax;
    int data[1];

    RF24 Radio(CE,CS);
    const byte address[6]="00001";
    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    Radio.begin();
    Radio.setRetries(5,10);
    Radio.openWritingPipe(address);
    }

    void loop() {
      // put your main code here, to run repeatedly:
    datax=analogRead(jpin);
    datax=map(datax, 0, 1023, 0, 255);
    data[0]=datax;
    Serial.print("data x: ");
    Serial.println(data[0]);
    Radio.write(data,sizeof(data));

    }

I'm using nRF2401 and in my transmitter and my receiver the Rx is not blinking and Tx is blinking; why does Rx not blinking?

I also don't know that why does Tx in my receiver not blinking when I move the joystick in my transmitter.

I can control my motors only a few times with a Joystick and after that the Tx in my receiver does not blink and then my motors are keep working or they stop and I can't control them.

----------
## Edit ##

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

  [1]: https://i.stack.imgur.com/eeZTJ.jpg
  [2]: https://i.stack.imgur.com/2SMBM.jpg
  [3]: https://i.stack.imgur.com/S2deH.png

title: I'm using nRF2401 and in my transmitter and receiver the Rx is not blinking and Tx is blinking; why does Rx not blink?

Answers: 1

body:
We've got multiple questions here, so:

## Why is TX/RX blinking weirdly? ##

The RX and TX LEDs on the Arduino Nano are connected to the RX0 and TX1 pins: they show activity on the Serial-over-USB port that connects your Arduino to the PC.

So, every time you receive data, you do a `Serial.print()`, transmitting text to the PC (where you can see that text in the Serial monitor). And _that_ is what's showing up in the RX/TX LEDs: the text you send over the serial line to the PC. If you want to get RX blinking in this setup, just enter some text in the Serial monitor's input box and send it. The TX LED should blink shortly, then (maybe too short to be noticeable).

Reusing those LEDs to show activity on the wireless transceiver by writing to the RX0/TX1 pins would mean that you'll lose the Serial monitor, i.e. `Serial.print()` would no longer be possible. Not recommended.

Your best option would be to introduce your own LEDs as an activity monitor. Just add an LED in series with an 1K resistor to pins D11 and D12 each (which are [the MOSI and MISO lines of the SPI interface][1], i.e. the equivalent of RX and TX of a serial interface).

In other words, add these components:
```
  D11 --> -LED+ --> 1K resistor --> 5V
  D12 --> -LED+ --> 1K resistor --> 5V
```

## Why does my transmission stop? ##

That's harder to see, but: I think you're using the RF24 library interface wrong.

According to [the code example "Transmitter Lv2" on this page][2], `Radio.read()` and `Radio.write()` expect a _reference_ to the data array, so you'd need to use `Radio.read(&data, sizeof(data))` and `Radio.write(&data, sizeof(data))` (note the ampersands).

It also may be that your transmitter is transmitting faster than your receiver can accept data, so you could try and add a `delay(5)` in the `loop()` of your transmitter.

  [1]: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface#Interface
  [2]: https://create.arduino.cc/projecthub/Arnov_Sharma_makes/arduino-based-nrf24-transmitter-receiver-setup-d73279#code


body:
I'm trying to transfer a monochrome ~4kb image file over WebBT to an ESP32 via BLE.

The EPD display looks for an unsigned char array to represent a bitmap. So..it should be in the format of something like

    `const unsigned char epd_bitmap_123_1 [] PROGMEM = {
     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};`

I've been successfully able to chunk, serialize, and reassemble an ArrayBuffer of the image from JS to the mcu in C++ (as a String).
I can verify that printing the Hex String on the board is the same as what's given from JS.

However, the image does not display properly on my EPD.

        class MyCallbacks: public BLECharacteristicCallbacks {
        void onWrite(BLECharacteristic *pCharacteristic) {
         //String value of raw data from JS ArrayBuffer..I can only get data as String with BLECharacteristic...
         std::string value = pCharacteristic->getValue();

         //Converting of String above into a Hex String
         string s2;
         stringstream ss;
         for (const auto &item : total) {
           ss << hex << int(item);
         }
         s2 = ss.str();

         //Converting Hex String into Char Array for EPD
         char * const cstr2 = new char [s2.length()+1];
         std::strcpy (cstr2, s2.c_str());

         //Displaying final Char array on EPD
         display.clearBuffer();
         display.drawBitmap(0,0,(unsigned char *)cstr2,296,128,EPD_BLACK);
         display.display();
    };

Any idea what's going wrong here? I'm thinking it's something with encoding.

title: String of raw data to Char Hex Array for Bitmap

Answers: 0


body:
I have a issue with my Arduino Uno r3.

I am sorry for my English and explanation of my problem I am not great with explaining.

I'm not sure why is that happening but I have 5V 18A power supply to power my LEDs. I connected 5v from arduino to 5v from external power supply and I plugged this combined cabble to my LEDs. I did the same with GND. On data pin 6 I used 220 Ohm resistor. Also I am using 12V power supply to power my arduino.

In the same time the usb was plugged.

In and between usb and power some chip is getting HOT I got quickly scared and un plugged whole arduino I am not sure how I should plug this in.  It worked fine until I plugged in external power supply and I was using few LEDs at the time.

This is how it looked like in more understandable way.

[![this  is how it looked like in more understandable way][1]][1]

Just point to me what I did wrong. I will be gratefull for any kind of help.

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

title: Arduino Uno usb 5v and external power supply 12v overheating

Answers: 1

body:
I suggest you do not use the 12V external power when you are already supplying it with an externally regulated 5V source.

The sole purpose of the 12V input is to provide a 5V regulated supply voltage for the microcontroller. The PCB outputs this on the 5V header. The problem is that you are feeding your external 5V into that pin.

You can either continue powering the Arduino from the 12V supply and disconnect the external 5V from the Arduino (keep the GND from the external 5V conected). Or you can just remove the 12V power source.

It could end up that you have damaged the chip that overheated. If the Arduino still works after doing one of the solutions above, then you may be lucky and not damaged anything.

As a precaution, please measure your external 5V source with a multimeter to make sure it is within specs that Arduino allows.


body:
I was browsing a library for steppers motors when I ran across this line of foreign-looking code:

    digitalWrite(enable_pin, (enable_active_state == HIGH) ? LOW : HIGH);

Is this some kind of shortcut to tossing an if statement into a function call? I've never seen this before. What exactly does it do, and what is this particular arrangement of code called?

Thanks!

title: IF statement inside of a function call? Code help

Answers: 1

body:
You could look at this as an "if expression", the correct term is "conditional operator" (C++ standard chapter 8.16). Many know it as "ternary operator" because it has three operands. You might already know the "unary operator" with one operand like the negation sign `-x`, or the "binary operator" with two operands like the addition `a + b`.

This expression consists of:
- the first operand
- the operator `?`
- the second operand
- the operator `:`
- the third operand

The first operator is evaluated and converted (if necessary) into a boolean.

If the result is `true`, the second operand is evaluated and gives the value of the expression.

If the result is `false`, the third operand is evaluated and gives the value of the expression.

Only one of the second and third operands is evaluated. This is important, if you use operands with side effects, like function calls can have.

This operator is often frowned upon. If used excessively, the source becomes easily unreadable. Many professional code style guide prohibit its use for this reason.

In your case it could have been written more clearly as
```c++
if (enable_active_state == HIGH) {
    digitalWrite(enable_pin, LOW);
} else {
    digitalWrite(enable_pin, HIGH);
}
```

It outputs the inverted value of the variable `enable_active_state` at the pin `enable_pin`.

Experienced Arduino users know that `HIGH` and `LOW` are represented in a way that are compatible with boolean values. Boolean inversions can be simpler expressed with the logical negation operator:
```c++
digitalWrite(enable_pin, !enable_active_state);
```

Anyway, the current compilers are commonly smart enough to generate the same machine code for each of the variants. Therefore, please write your source in the best way to express your intention. Anything else is "premature optimization", which is a bad thing. But this is a completely other topic.


body:
Anyone can help me decode the temperature of [the M117 chip from mysentech.com][1]?

I tried things, but I get a constant raw value of 0xFFFF, which becomes 1 once 2's complemented is applied.

The chip shows up at the expected address (TEMP_SENSOR_ADDRESS is 0x45) during a scan operation of the I2C bus.

```cpp

 // Start I2C Transmission
 Wire.beginTransmission(TEMP_SENSOR_ADDRESS);
 // Select data register
 Wire.write(0x00);
 // Stop I2C Transmission
 Wire.endTransmission();
 delay(300);

 // == Request for the raw temp 2 bytes
 Wire.requestFrom(TEMP_SENSOR_ADDRESS, 2);
 const size_t count = Wire.available();
 log("%d bytes available", count);

 if (count!=2) {
  *ready = false;
  warn("I2c temp is not available");
 }
 else {
  *ready = true;
     // Get the raw data as the 16-bit big endian (MSB-LSB)
  byte data0 = Wire.read();
  byte data1 = Wire.read();
  const uint16_t raw = data0<<8 | data1;
  const int sign = raw>>15 == 1 ? -1 : 1;

  // Get the raw temperature as a 2's complement of the 16-bit (MSB-LSB) value
  const int16_t c2Raw = ~raw + 1;

  // Apply scale and offset
  temperature = sign * float(c2Raw)/256.0 + 40;
  log("raw: x (%d) | Raw 2's complement  x (%d) | temperature: %f°C",
   raw, raw,
   c2Raw, c2Raw,
   temperature
  );
    }
```

**[UPDATE | SEPT. 2nd 2022]**
 Following the discussion I had with @jsoleta, my current code is as follows. But still getting FFFF AC. AC being the correct CRC for FFFF.
Coud it be the result of a wiring issue of the component on our custom PCB?

The logs:

```
b5725|—|  Thermometer: Command: Writing to register command 0xCC44
b5725|—|  Thermometer: Command byte 0: cc
b5725|—|  Thermometer: Command byte 1: 44
b5725|—|  Thermometer: Command: register transmitted 2 bytes
b5725|—|  Thermometer: 3 bytes available
b5725|—|  Thermometer: Actually read 3 bytes: ff ff ac
b5725|—|  Thermometer:  CRC matched: computed: ac == read: ac
b5725|—|  Thermometer: raw: ffff (65535) | Raw 2's complement  0001 (1) | temperature: 39.996094°C
b5725|—|  Thermometer: raw: ffff (65535) | temperature: 39.996094°C
b5725|—|  Thermometer: Transmitting board temperature 40.0°C over the RS-485 bus (raw is 799 - 0x031f)
```

The updated code:
```cpp
loat I2cThermometer :: readTemperature(bool *ready) {
 float temperature = 0;

 log("Command: Writing to register command 0xCC44");
    // Start I2C Transmission
 Wire.beginTransmission(TEMP_SENSOR_ADDRESS);

 // Select data register 0x00, config 0x01

 const uint16_t command =
  0xcc44 // Wait for temperature measurement
  //0xf32d  // Read status
  //0x611d // Measurement result set alarm
 ;
 byte * data = (byte*)&command;
 Wire.write(data[1]); log("Command byte 0: x", data[1]);
 Wire.write(data[0]); log("Command byte 1: x", data[0]);

 // Stop I2C Transmission
 const auto readCount = Wire.endTransmission();
 log("Command: register transmitted %d bytes", readCount);
 delay(15);
 // == Request for the raw temp 2 bytes + CRC
 Wire.requestFrom(TEMP_SENSOR_ADDRESS, 3); // 2-byte data + 1-byte CRC
 const size_t count = Wire.available();
 log("%d bytes available", count);

 if (count!=3) {
  *ready = false;
  warn("No temp data is not available");
 }
 else {
  *ready = true;

   // Get the raw data as the 16-bit big endian (MSB-LSB)
   byte data[3];
   const size_t r = Wire.readBytes(data, sizeof data);
   log("Actually read %d bytes: x x x", r, data[0], data[1], data[2]);
   const byte crc = MY_CRC8(data, 2);
   if (crc != data[2]) {
    warn("CRC mismatch: computed: x != read: x", crc, data[2]);
   }
   else {
    success("CRC matched: computed: x == read: x", crc, data[2]);
   }
   const uint16_t raw = *(uint16_t*)data;

   const int sign = raw>>15 == 1 ? -1 : 1;

   // Get the raw temperature as a 2's complement of the 16-bit big engdian (MSB-LSB)
   const int16_t c2Raw = ~raw + 1;

   // Apply scale and offset
   temperature = sign * float(c2Raw)/256.0 + 40;
   #if LOG_LEVEL >= LOG_LEVEL_DEBUG
   log("raw: x (%d) | Raw 2's complement  x (%d) | temperature: %f°C",
    raw, raw,
    c2Raw, c2Raw,
    temperature
   );
   #endif

  #if LOG_LEVEL >= LOG_LEVEL_DEBUG
  log("raw: x (%d) | temperature: %f°C",
   raw, raw,
   temperature
  );
  #endif

  writeBoardTemperatureMessage(temperature);
 }

 if (!(*ready)) {
  #if LOG_LEVEL >= LOG_LEVEL_INFO
  log("Temperature is not ready %d°C", temperature);
  #endif
  return temperature;
 }

 #if LOG_LEVEL >= LOG_LEVEL_INFO
 log("Temperature is %d°C", temperature);
 #endif

 return temperature;
}

```

  [1]: https://www-mysentech-com.translate.goog/productinfo/535226.html?_x_tr_sch=http&_x_tr_sl=zh-CN&_x_tr_tl=en&_x_tr_hl=en&_x_tr_pto=sc

title: How to use the M117 temperature sensor from mysentech?

Answers: 2

body:
> WARNING: I have no way to test/verify the parts of this that directly apply to your chip.

## Issue conversion command

This device does not appear to follow the common write-register-address followed by read-register-value scheme. **Instead, it seems in order for the device to  sample and convert temperature at all you must first issue  a command to perform the conversion. You're not doing that, so that seems to be the principal problem.** You're reading whatever the value is prior to every having asked for a conversion an the datasheet says indicates this is indeterminate. So 0xFFFF is plausible and unremarkable for a value you'd get not having already requested conversion.

Issuing the conversion command (again, I'm not able to test this):

```c++
void request_temperature_conversion() {
  Wire.beginTransmission(TEMP_SENSOR_ADDRESS);
  Wire.write(0xCC);
  Wire.write(0x44);
  const auto check_me = Wire.endTransmission();
  delay(15); // Ensure a completed conversion.
}
```

## Read result

To read the result of value of the most recent conversion:

```c++
uint16_t read_u16_temperature() {
  const auto read_count = Wire.requestFrom(
    TEMP_SENSOR_ADDRESS,
    3 // the actual transaction includes an 8-bit as well as 16-bit sample
  );
  uint8_t temp_payload[2];  // 2 because i'm going to ignore the CRC.
  Wire.read(temp_payload, sizeof temp_payload);

  return uint16_t(temp_payload[0]) << 8 | temp_payload[1];
}

int16_t read_s16_temperature() {
  int16_t r;
  const uint16_t u = read_u16_temperature();
  memcpy(&r, &u, sizeof r);
  return r;
}
```

## Together

Again, I can't really test this.

```c++
request_temperature_conversion();
temperature =
  sign
  * float(read_s16_temperature()) / 256
  + 40;
```

You probably can and should avoid the use of the floating point type.  If you're logging this data and transmitting this data to somewhere else to be logged, you may be better off transmitting/storing the raw values which can be (re)interpreted later rather than having different versions of your sketch potentially affecting how a calculation is done on the values.

## Manufacturer's documentation

The website you have linked to has a datasheet in Chinese. You may get some use out of you machine translate it to English (or whatever). Google Drive is capable of this. Probably more useful are the archives of sample code intended for STM32.  That's where all the information came from, including crucially the use of `0xCC44` command to prompt conversion. The 15ms delay is also lifted from what I read in the STM32 sample code in the rar archive from the site; I didn't put much thought into its significance or how the part behaves if you don't wait long enough. You should read through it, because there's more about configuring the chip, the CRC, etc.

[![Chip Maker's download center showing filenames M117 M117B Digital Temperature Chip Product Manual-Minyuan 202206.pdf, M117B_IIC_Samplecode_stm32-MY202203.rar, M117_MTS01_IIC_Samplecode_stm32-MY202202.rar][1]][1]

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

body:
Ok, I found something weird. My code do work if I request the sensor every 4 seconds at max. But if the frequency is below that, it won't work.

Will replace the sensor, rolling back to TMP112, as before.


body:
I have an IMU sensor and a Bluerobotics temperature sensor, both have different I2C addresses.

I want to integrate both with an Arduino UNO, I know I can do this with an I2C multiplexer but I don't have access to one right now.

Is it possible to integrate them with arduino without a multiplexer, i.e., by just connecting them parallelly on the A4 and A5 pins of Arduino? (This didn't work though when I tried, the temperature sensor was giving values but the values of IMU sensor were only zeros on the Arduino Serial Monitor)

I've found some videos on it on YT, some have connected pull up resistors to the sensors, but this method doesn't seem to work.

So before delving deeper into it, I'd like to know if this is even possible to do without a multiplexer, because my time is precious since I have a project deadline.

title: Is it possible to use multiple I2C sensors with Arduino without an I2C multiplexer?

Answers: 2

body:
first of all , you said they have different I2C addresses , so you don't need **I2C
 multiplexer** , I2C multiplexer is only used when having more than one device having same I2C address , and refer to [Adafruit I2C multiplexer][1] as they say :

> Finally, a way to get up to 8 same-address I2C devices hooked up to one microcontroller

which means it can handle 8 devices having the same address , but in your case , the addresses already are different , so why you need I2C multiplexer.

your problem needs to dig deep into debugging , you can get your self a cheap logic analyzer like [this cheap 10$ saleae clone analyzer][2] to see what data is actually put into the bus , the analyzer will make your debugging way more easy than you think , like the below picture obtained from [saleae official website][3] and also this cheap saleae clone works perfect with *logic* software offered from saleae:
  [![enter image description here][4]][4]

but for your problem , I am guessing that it's due to pull resistors and the parasitic capacitance between the 2 buses , reading from [I2C specification file][5], at section 7.1 , there is equation from minimum and maximum allowed pull up resistors according to nodes connected to the bus :

> Rp(min) = (Vdd - Vol(max)) / Iol
>
>
> Rp(max) = tr / (0.8473 * Cb)
>

where `Vdd` is 5V when using arduino , `tr` is the rise time maximum and it depends on MCU, `Cb` is  estimated bus capacitance and you can get that from datasheet of every component in your bus line as for arduino its capacitance is specified in [datasheet][6] at page 264 saying

> Capacitance for each I/O pin Ci – 10 pF

other symbols , you can get from the I2C specifications mentioned above , but your problem is due to pull up resistors I guess and you can't really know without debugging. I recommend you using logic analyzers.

  [1]: https://www.adafruit.com/product/2717
  [2]: https://www.amazon.com/HiLetgo-Analyzer-Ferrite-Channel-Arduino/dp/B077LSG5P2/ref=sr_1_3?keywords=logic analyzer&qid=1661924579&sprefix=logic a,aps,413&sr=8-3
  [3]: https://www.saleae.com/
  [4]: https://i.stack.imgur.com/26n6R.jpg
  [5]: https://www.nxp.com/docs/en/user-guide/UM10204.pdf
  [6]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf

body:
Since you did not give links I went on line and checked them. Be sure the I2C modules do not have pull up resistors. If so note the value.  Adjust your external so the pull up to 3V3 is about 3.1K. You will need a level translator for both the IMU module and the Bluerobotics temperature sensor they are both 3V3 boars. Good news one set of level translators will work for both. Remember you will need pull ups on both sides of the translators, check as not all do.

Since you are just getting started you can pick one of the fine 3V3 micros in the Arduino or ESP series of boards. Simple starting point rule for pull up on I2C: 3.1K for 3V3 and 4.7K for 5V. Let us know how you do.

Bad News it is possible you damaged one or both of the I2C boards with 5V.


body:
I have a circuit which consists of a pushbutton and 2 relays.

The power supply is driven either over USB, where the circuit seems to work fine, or powered by a linear regulator board I've knocked together consisting of an LM78XX (see the next paragraph for detail), where the circuit exhibits the behaviour.

Detail of power supply:

The LM7808 was used to drive the main voltage into the Nano, via the VIN pin. It is supported by a 330n and 100n capacitor, as per the standard circuit diagrams for LM78XX chips. The LM7805 was also used to drive the nano via the 5v pin, as well as the Pico via its 5v pin. Using LM7805, I drove the 5v relay boards directly from the power supply, not utilising the onboard 5v regulator. Using the LM7808, I used the onboard 5v regulator to power the relay boards since they required 5v, not 8v. I have tried each of these configurations with no success.

I have 2 relay boards, each has 5v, GND, and IN. These take their 5v and GND directly from the same power supply driving the Arduino where possible, or from the regulator on the board where necessary (when powered by 8v).

On power up, the relays go to opposing states (one switches on, the other stays off).

I also have essentially a pushbutton, which currently consists of a choc block that I short out with a piece of wire by hand. I have had it pulled up by the Arduino, and shorting it to ground with the pushbutton. I have also had it pulled up manually, with a 10k resistor as per the circuit diagram below. In all configurations, note that it was a choc block and a piece of wire.

[![pushbutton circuit diagram][1]][1]

Now, for the unexpected behaviour. When I power this circuit over USB, the pushbutton works almost entirely. I may have seen it fail once or twice, I can't be sure. It seems to behave as expected 99% of the time. When I power it from a 12v power supply (into the LM78XX regulator) however, I only need to wave my hand near the choc block of the "pushbutton" and it will fire. Sometimes it will fire for seemingly no reason at all, other times I will need to connect a small length of wire *only to the GPIO side of the choc block* and it will fire the switch.

My current code is as below:

```
const int signal_1 = 10;
const int relay_1 = 11;
const int relay_2 = 12;
bool state = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(relay_1, OUTPUT);
  pinMode(relay_2, OUTPUT);
  pinMode(signal_1, INPUT_PULLUP);

  digitalWrite(relay_1, LOW);
  digitalWrite(relay_2, HIGH);
}

void toggleRelays() {
  digitalWrite(relay_1, !state);
  delay(5000);
  digitalWrite(relay_2, state);
  state = !state;
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensor_1_val = digitalRead(signal_1);

  if (sensor_1_val == LOW) {
    toggleRelays();
  }
}
```

I have simplified this as much as possible, and tried it in as many variations as I can think of. I still suffer from this interference issue.

Can anyone explain what might be happening here? Is it possible that I'm suffering from a brownout, and need to add an additional capacitor on the power supply? Is there something I'm obviously missing about the switch circuit?

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

title: Pushbutton firing somewhat randomly

Answers: 0


body:
I have built a custom circuit board using the **ESP32-C3-MINI-1-H4** module([datasheet][1]).

Here is a schematic:
[![enter image description here][2]][2]

I have the GND, Tx, and Rx lines hooked up to an arduino uno without the atmega. The 3V3 comes from an external power supply.

I have successfully put the chip into download mode(as shown from the serial output below).

>ESP-ROM:esp32c3-api1-20210207
>
>Build:Feb  7 2021
>
>rst:0x1 (POWERON),boot:0x5 (DOWNLOAD(USB/UART0/1))
>
>waiting for download

I attempted to upload an example sketch using the following settings(Arduino IDE).

[![Arduino Settings][3]][3]

I held down the reset button(S4) until the Rx light on the uno started flashing.

It works about 5% of the time, but 95% of the time it ends in this:

> A fatal error occurred: Failed to connect to ESP32-C3: No serial data received.

I'm not sure how that is possible, as the serial data appears on the oscilloscope, and it is clearly in download mode as shown by the serial output.

I have tried removing the voltage divider form the RX line, but that didn't help. Is there any way to make uploading more consistent?

  [1]: https://www.espressif.com/sites/default/files/documentation/esp32-c3-mini-1_datasheet_en.pdf
  [2]: https://i.stack.imgur.com/KELzh.png
  [3]: https://i.stack.imgur.com/l38V5.png

title: Upload to ESP32-C3 Fails

Answers: 1

body:
You must be in flash mode DIO and watch the "USB CDC on boot" which must be on if you use native C3 usb and off if you use an external usb-serial converter.

You can upload OK in QIO mode but program wont start, that is EXACTLY what OP is asking.


body:
when I try to upload any code to Arduino it isn't getting uploaded the "RX LED" keeps blinking about 10 times but the "TX LED" doesn't light up. I have done a loopback test but it failed the cable is working there is no problem with my cable "Pin 13 LED" and "ON LED" are working, also my Arduino is not getting recognized in the device manager, my Arduino was working before. My Arduino model is: "UNO R3".
the error I get when I upload the code:
```
An error occurred while uploading the sketch
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
```

title: code not getting uploaded to Arduino

Answers: 0