body:
I'm trying to write a sketch to use a Wemos D1 mini connected to several shields including a LOLIN TFT & I2C Connector Shield ([v1.1.0][1]). This powers a small ePaper display ([LOLIN 2.13" diagonal ePaper/eInk display][2]) with a [TFT e-Paper Cable][3].

The problem I'm running into is that I can't get the board to either boot properly or get out of deepSleep due to the pin assignment of the TFT display.

I have placed the following code before the `void setup()` as described in the manufacturer's [GitHub example][4] for the board:

    /*D1 Mini*/
    #define EPD_CS D0
    #define EPD_DC D8
    #define EPD_RST -1  // can set to -1 and share with microcontroller Reset!
    #define EPD_BUSY -1 // can set to -1 to not use a pin (will wait a fixed delay)

By doing this, however, it results in the board entering a boot loop when I try to connect D0 --> RST

If I leave the D0 --> RST disconnected, the board will successfully run the sketch and enter into deepSleep but will not be able to Wake Up after a predetermined amount of time (10seconds).
I see the Builtin LED flash after 10seconds and there is some activity on the serial monitor so I suspect that the board is trying to wake up however it is unable to with the D0 disconnected to the reset pin.

If I try to connect the D0 --> RST after the board has gone to deepSleep and before the timer ends, it continues to sleep until the 10 seconds is completed, then starts its boot loop again with the Built-In LED flashing constantly.

Has anyone else had success in this?  I suspect I'm missing something very simple but cannot find much info on this shield anywhere.

  [1]: https://docs.wemos.cc/en/latest/d1_mini_shiled/tft_i2c_connector.html
  [2]: https://docs.wemos.cc/en/latest/d1_mini_shiled/epd_2_13.html
  [3]: https://www.aliexpress.com/item/32848833474.html?spm=a2g0o.detail.1000060.1.2f3c38a6ASner1&gps-id=pcDetailBottomMoreThisSeller&scm=1007.13339.146401.0&scm_id=1007.13339.146401.0&scm-url=1007.13339.146401.0&pvid=b5609db5-c9f3-4250-946e-bfc5b7d37075
  [4]: https://github.com/wemos/LOLIN_EPD_Library/blob/master/examples/graphicstest_2_13_inch_250x122/graphicstest_2_13_inch_250x122.ino

title: D1 Mini + TFT & I2C Connector Shield not going into deepSleep

Answers: 0


body:
I'm working with a digital blood pressure meter using arduino nano. I need to display the pressure reading during inflation and deflation of the cuff instantly. And when an input signal applied to a particular pin during deflation, I need to print the pressure value at that time of input signal, to a display. How to code for this logic. I made the code for showing pressure value during inflation and deflation. But need to pause the value and display constantly the pressure value at the time of input applied to the arduino pin. How this pausing of value can be done?.
Finally I need to print both the systolic and diastolic pressure value constantly as: 120/80 mmHg (systolic/diastolic mmHg)
In this project, the systolic pressure is noted when there is an input at digital pin.

In the case of diastolic pressure, it is noted according to input pulse duration. That is, If the duration of pulse is greater than 50 milli-seconds, print the diastolic pressure as current pressure minus the pressure when pulse duration equal to 50 milli-seconds.

**Below is the code I have written for printing the systolic and diastolic pressure instantly.**

````````````````````````````````````````````````````````````````````
#include <LiquidCrystal.h>//Don't forget to enter this library

LiquidCrystal lcd(12, 11,  10, 9, 8, 7);

int analogInPin = A1;     // Analog input pin that the pressure sensor output is attached to

int pressure = 0;
int sensorValue = 0;        // value read from the pressure sensor via the amplifier stage

void setup() {
 Serial.begin(9600);
analogReference(INTERNAL);

void loop() {
lcd.clear();
sensorValue = analogRead(analogInPin);

pressure = sensorValue*(0.9226)-267.7; //Pressure value according to sensor value
  lcd.setCursor(0,1);
  lcd.print("mmHg: ");
  lcd.print(pressure);
  delay(100);

}
``````````````````````````````````````````````````````````````````````````````

I'm using a different method to note systolic as well as diastolic pressure values, like the stethoscope doing the job in conventional measurement method. The dual microphone arrangement will capture the sounds( korotkoff ) of blood flow. This sounds are processed (independent to arduino) by the external analog circuitry which outputs a 5VDC at every noticeable instant of pulse(during blood flow). This signal is then fed to a digital pin of arduino. Here, when the 5V signal reaches at the digial pin first, **we note the systolic pressure** as the pressure at the instant when the 5V signal is generated first. In the case of diastolic pressure, the generated 5V signal from the circuit is compared with an externally given unit step 5V using comparator. This compared signal output is fed to another digital pin of arduino, where the diastolic pressure is noted according to the input 5V pulse signal duration( Eg: If the duration is greater than  50ms ), the **diastolic pressure** is the pressure at which the pulse duration which is equal to 50ms).

I'm totally frustrated with remaining parts of code as mentioned.
**Thank you in Advance..!!**

title: How to pause the analog value according to input signal applied to a particular digital pin?

Answers: 0


body:
I have a concern about the library port handling. I have used direct port direction manipulation successfully in previous projects but there seems to be a problem here.
<!-- language-all: lang-cpp -->

    // This code mostly taken from the example
    #include "LedControl.h"

    LedControl lc=LedControl(11,13,10,1);
    //LedControl lc=LedControl(12,11,10,1); // original
    // pin 12 is connected to the DIN pin (now MOSI 11)
    // pin 11 is connected to the CLK pin (now SCK 13)
    // pin 10 is connected to the CS pin  (now SS 10)
    // 1 as we are only using 1 MAX7219

    // I am actually using all arduino pins except 12 for my project
    #define PD_MSK  B11111100 // Data pins PD2..7 (pins2..7)
    #define PB_MSK  B00000011 // Data pins PB0,1 (pins8,9)
    #define PC_MSK  B00001111 // Data pins PC0..3 (pins 14..17)

    void setup()
    {
    // set pins 2..9 as inputs
      DDRD = DDRD & !PD_MSK; // this works OK
      DDRB = DDRB & !PB_MSK; // configure ports D,B inputs *** doesnt work with this
     // pinMode(8, INPUT); //*** does work with this
      //pinMode(9, INPUT); //*** does work with this

      DDRC = DDRC | PC_MSK; // configure PortC0..3 as outputs
      PORTC |= 0x0F; // set PortC0..3 high (default)

      // the zero refers to the MAX7219 number, it is zero for 1 chip
      lc.shutdown(0,false);// turn off power saving, enables display
      lc.setIntensity(0,8);// sets brightness (0~15 possible values)
      lc.clearDisplay(0);// clear screen

    }
    void loop()
    {
      //numbers 7 to 0
      for (int a=0; a<8; a++)
      {
        lc.setDigit(0,a,a,false);
      }

      delay(1000);

      //display number 8 on all segments
      for (int a=0; a<8; a++)
      {
        lc.setDigit(0,a,8,false);
      }
      delay(1000);

      // numbers 7 to 0 reverse order
      for (int a=8; a>=0; a--)
      {
        lc.setDigit(0,a,a,false);
        //delay(100);
      }
      delay(1000);

    }

The direct port direction setting does not seem to allow the library to work while the pinMode commands doing the same job do. I note that the library uses software SPI but I would like to use hardware if possible. I have certainly used hardware SPI with frequent port direction changes on the remaining pins for other projects.
Any insight as to why this problem occurs?

Thanks.

title: MAX7219 with 8digit 7seg array

Answers: 1

body:
As always I recommend the old RTFM (read the f***ing manual) of the [LedControl.h library](http://wayoda.github.io/LedControl/pages/software).<br>
In the FAQ its clearly stated:

> Why don't you use the hardware SPI-Bus of the Arduino?
>
> When I wrote the first version of the library I didn't knew much about
> the Arduino or AVR processors in general and I knew nothing about
> writing code for the hardware SPI-bus on an ATMega. But I knew how the
> SPI protocol works and how I could make this work using simple
> digitalWrite() commands. I turned out the library code is fast enough
> for common use cases, so there is no need for doing Hi-Speed
> communications.
>
> Other strong points in favour of the (admittedly trivial) code design
> are - Use any three free IO-Pins of your board for the hardware -
> Simple to debug. Much easier than managing 3 differnt SPI devices
> connected to the same hardware bus - Library is easily portable to
> other platforms, since it uses only two very basic functions from the
> Arduino language

So with this library you clearly have never used hardware SPI (although you could use the pins, but only via softwareSPI)


body:
I bought Arduino Mega board (CH341 usb) and I am able to connect to /dev/ttyUSB0 (upload to device) only by using sudo.

OS: Ubuntu 18.04

What I've tried:

1. I have downloaded Arduino IDE and added my user to dialout group. Logged out and logged in. Still nothing.

2. Installed Arduino by using apt

3. Installed Arduino by using snap

For all three cases it worked only by running as root (sudo actually). I saw couple of answers for Ubuntu 14.04 but none of answers didn't help.

I guess some other device access permissions are missing but I still didn't find any solution.

title: Arduino /dev/ttyUSB0 permission denied even when user added to group "dialout' on Ubuntu 18.04

Answers: 1

body:
After some struggle I figured out that I need to add my user to "tty" group as well.

There's another approach that involves udev rules modification for certain vendor:device and update of device's ownership but this seems more sane approach.

To recap:

1. Add your standard user to the group "dialout'

    sudo usermod -a -G dialout your-username

2. Add your standard user to the group "tty"

    sudo usermod -a -G tty your-username

3. Logout/Login

Hope this helps


body:
Some days ago I had the inestimable help of hcheung in this forum to help me find some libraries on github to control a capacitive panel with a HT5xx6 controller. The libraries and code are [here][1].

  [1]: https://github.com/hellange/arduino/tree/master/capacitive_7in_panel

I have copied and created the libraries into a.h and .cpp files and placed where arduino IDE can find them and run the sketch. The startup works fine, meaning the panel is initialized.

However it doesn't give reliable data. Any time you touch the panel in a specific location it does not give a single set of coordinates, it sometimes give 2 or 3 set of coordinates and most of the time 15. This is as if the panel would detect 15 touches!

Even more issues: the coordinates are never the same in one fixed location. So the data is not reliable and I don't know what I am doing wrong.

Has anybody gone through this experience before?

Thanks for your help in advance!

Take care.

Joan.

title: Issues controlling a 10,1 capacitive panel with Arduino

Answers: 0


body:
I have a simple text parser (as a component of a larger project) coded up and seemingly working correctly. It parses a key-value delimited command like the following: `<key1=value1;key2=value2;key3=value3>`.

At present, the functionality is very silly just to test it out: when the Arduino finds a key named "text", it composes a response of a similar form, but just with one key "text_return" and the same value, and sends it back via serial. That is, when the command `<key1=value1;text=123;key3=value3>` is sent, I expect a response from the Arduino of `<text_return=123>`.

I then am connecting the board to my laptop via USB, and testing it out, both with the Serial Monitor in Arduino's IDE, and with a simple program coded in python.

So here's the confusing part:

 1. Serial Monitor with Uno: works
 2. Python with Uno: works
 3. Serial Monitor with Mega: works
 4. Python with Mega: does **NOT** work

Specifically, by "does not work", I mean that the Mega seems to receive the serial input from the program, but does not issue a response.

Here's the terminal output from test #2 as displayed by the python program, showing the command-response I'd expect (I parsed the received command into a dict):
```
SENT: <text=1953>
SENT: <text=1954>
SENT: <text=1954>
SENT: <text=1954>
SENT: <text=1954>
SENT: <text=1954>
SENT: <text=1954>
SENT: <text=1954>
RECD: {'text_return': 1954}
SENT: <text=1954>
RECD: {'text_return': 1954}
SENT: <text=1954>
RECD: {'text_return': 1954}
SENT: <text=1954>
RECD: {'text_return': 1954}
```

And here's the terminal output from the non-working test#4 - i.e.: no response.
```
SENT: <text=2001>
SENT: <text=2002>
SENT: <text=2002>
SENT: <text=2002>
SENT: <text=2002>
SENT: <text=2002>
SENT: <text=2002>
SENT: <text=2002>
SENT: <text=2002>
SENT: <text=2002>
SENT: <text=2002>
SENT: <text=2003>
SENT: <text=2003>
SENT: <text=2003>
SENT: <text=2003>
SENT: <text=2003>
SENT: <text=2003>
SENT: <text=2003>
SENT: <text=2003>
```
In all cases, I'm using 9600 Baud; the only change between the two tests is that I select the Uno vs. Mega / Mega 2560 board in the Arduino IDE.

The Mega board is an Elegoo Mega2560 R3. The code may be extraneous, but to help:

**Opening the port to the arduino from python**
```
def FindArduino(baud=9600, timeout=0):
  initial_time = time.time()
  arduino_found = False
  attempted = False
  while not attempted or time.time() - initial_time < timeout and not arduino_found:
    attempted = True
    ports = serial.tools.list_ports.comports(include_links=False)
    for port in ports:
      manufacturer = port.manufacturer
      if manufacturer and 'arduino' in manufacturer.lower():
        arduino_port = port
        arduino_found = True

  if arduino_found:
    try:
      arduino = serial.Serial(arduino_port.device, baud, timeout=0)
      arduino.reset_input_buffer()
      arduino.reset_output_buffer()
    except serial.SerialException:
      arduino_found = False

  if arduino_found:
    return arduino
  else:
    return None
```
**Sending the serial in python, to Arduino**
```
  cmd = '<text=%d>' % (time.time() - 1586218411)
  print('SENT: %s' %cmd)
  cmd = bytes(cmd, 'ascii')
  arduino.write(cmd)
  time.sleep(.1)
```

**Receiving the serial in python, from Arduino**
```
  cmds = []

  if (arduino.in_waiting>0):
    buffer += arduino.read(arduino.in_waiting).decode('ascii')
    while COMMAND_END_CHAR in buffer:
      end_char_pos = buffer.find(COMMAND_END_CHAR)
      potential_command = buffer[:end_char_pos]
      if COMMAND_START_CHAR in potential_command:
        cmds.append(potential_command[potential_command.find(COMMAND_START_CHAR)+1:])
      buffer = buffer[end_char_pos+1:]

  return (buffer, cmds)
```
**And the full code on the Arduino itself**
```
// command indicators
char START_MARKER = '<';
char END_MARKER = '>';

const int MAX_KEY_VALUE_PAIRS = 3;  // maximum number of key-value pairs in message
const int MAX_ELEMENT_CHARS = 30;  // the maximum number of characters (+1 for terminator) in a key or a value

// message format: <key1=value1;key2=value2;key3=value3>
const int MAX_MESSAGE_CHARS = (MAX_KEY_VALUE_PAIRS * (MAX_ELEMENT_CHARS + 1)) * 2 + (MAX_KEY_VALUE_PAIRS - 1) + 2;  // maximum message size

char received_chars[MAX_MESSAGE_CHARS];
bool new_data = false;
char written_chars[MAX_MESSAGE_CHARS];

char *text =  {'\0'};

void ParseData(char *str) {
  // This picks off the ;-delimited key-value pairs and assigns them to a multi-dim array
  char * pch;
  int pairs_count = 0;
  char config[MAX_KEY_VALUE_PAIRS][2][MAX_ELEMENT_CHARS];

  pch = strtok(str, "=");

  while (pch != NULL)
  {
    strcpy(config[pairs_count][0], pch);
    pch = strtok(NULL, ";");
    if (pch == NULL) break;

    strcpy(config[pairs_count][1], pch);
    pairs_count++;
    pch = strtok(NULL, "=");
    if (pch == NULL) break;
  }

  for(int i=0;i<pairs_count;i++) {
    if (strcmp(config[i][0], "text")==0)
      strcpy(text, config[i][1]);
    WriteSerial();
  }
}

void ReadSerial(){
  // After calling ReceiveText to empty the buffer, if a complete command has been found,
  // parse that command.
  new_data = ReceiveText();
  if (new_data == true) {
    char temp_chars[MAX_MESSAGE_CHARS];  // temporary array for use when parsing
    strcpy(temp_chars, received_chars);
    received_chars[0] = '\0';
    ParseData(temp_chars);
  }
}

void WriteSerial(){
  sprintf(written_chars, "<text_return=%s>\n", text);
  Serial.write(written_chars);
  written_chars[0] = '\0';
}

boolean ReceiveText() {
  // This dumps the characters on the buffer so far received_chars, searching for an END_MARKER
  // along the way; if it finds one, it goes back to find a START_MARKER; if that is also found,
  // the string within is the ;-delimited set of key value pairs
  static boolean recv_in_progress = false;
  static byte ndx = 0;
  char rc;

  boolean new_data = false;
  while (Serial.available() > 0 && new_data == false) {
    rc = Serial.read();

    if (recv_in_progress == true) {
      if (rc != END_MARKER) {
        received_chars[ndx] = rc;
        ndx++;
        if (ndx >= MAX_MESSAGE_CHARS) {
          ndx = MAX_MESSAGE_CHARS - 1;
        }
      } else {
        received_chars[ndx] = '\0'; // terminate the string
        recv_in_progress = false;
        ndx = 0;
        new_data = true;
      }
    } else if (rc == START_MARKER) {
        recv_in_progress = true;
    }
  }
  return new_data;
}

void setup() {
  Serial.begin(9600);
  text = (char*)malloc(25);

  received_chars[0] = '\0';

}

void loop() {
  ReadSerial();
}
```

UPDATE
======
Using the suggested libraries, I updated the code. The comms in both directions for simple test data are working, though I can't seem to convert the packet received by the Arduino into a string correctly.  Here is the output I see from my python terminal; I'd expect to receive back the first character of what was sent (i.e.: the "0", then "1"), rather than just the initialized value of "S".
```
SENT: 0.20
RCVD: S
SENT: 0.41
RCVD: S
SENT: 0.61
RCVD: S
SENT: 0.82
RCVD: S
SENT: 1.02
RCVD: S
SENT: 1.23
RCVD: S
SENT: 1.43
RCVD: S
SENT: 1.64
RCVD: S
```
**Python code**
```
import time
from pySerialTransfer import pySerialTransfer as txfer

if __name__ == '__main__':
  try:
    link = txfer.SerialTransfer('/dev/cu.usbmodem14201')

    link.open()
    time.sleep(2) # allow some time for the Arduino to completely reset
    base = time.time()

    while True:
      time.sleep(0.2)
      s = '%.2f' % (time.time() - base)
      l = len(s)
      for i in range(l):
        link.txBuff[i] = s[i]

      link.send(l)

      while not link.available():
        if link.status < 0:
          print('ERROR: {}'.format(link.status))

      response = ''
      for index in range(link.bytesRead):
        response += chr(link.rxBuff[index])

      print('SENT: %s' % s)
      print('RCVD: %s' % response)

  except KeyboardInterrupt:
    link.close()
```

**Arduino code**

```
#include "SerialTransfer.h"

char str[100];

SerialTransfer myTransfer;
int LED = 13;

void blinkLED(int n)
{
  for (int i = 0; i < n; i++) {
    digitalWrite(LED, HIGH);
    delay(150);
    digitalWrite(LED, LOW);
    delay(150);
  }
}

void setup()
{
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
  str[0] = 'S';
  str[1] = '\n';
  Serial.begin(115200);
  myTransfer.begin(Serial);
}

void loop()
{
  blinkLED(2);
  delay(500);

  // send bytes
  myTransfer.txBuff[0] = str[0];
  myTransfer.sendData(1);
  if(myTransfer.available())
  {
    blinkLED(60);

    // receive bytes
    byte bytes_to_read = myTransfer.bytesRead;
    for(byte i = 0; i < bytes_to_read; i++)
      strncpy(str + i, myTransfer.rxBuff[i], 1);

  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}
```

Thank you!

title: Debugging different serial receive / send behavior between Uno & Mega

Answers: 2

body:
It would be easier if you used Arduino <--> Python compatible libraries to ensure the communication between the two is robust and reliable. An example of such libraries would be [pySerialTransfer][1] and [SerialTransfer.h][2].

pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.

Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs.

**Example Python Script:**

    from time import sleep
    from pySerialTransfer import pySerialTransfer as txfer

    if __name__ == '__main__':
        try:
            link = txfer.SerialTransfer('COM17')

            link.open()
            sleep(2) # allow some time for the Arduino to completely reset

            while True:
                link.txBuff[0] = 'h'
                link.txBuff[1] = 'i'
                link.txBuff[2] = '\n'

                link.send(3)

                while not link.available():
                    if link.status < 0:
                        print('ERROR: {}'.format(link.status))

                print('Response received:')

                response = ''
                for index in range(link.bytesRead):
                    response += chr(link.rxBuff[index])

                print(response)

        except KeyboardInterrupt:
            link.close()

**Example Arduino Sketch:**

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

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

    void loop()
    {
      myTransfer.txBuff[0] = 'h';
      myTransfer.txBuff[1] = 'i';
      myTransfer.txBuff[2] = '\n';

      myTransfer.sendData(3);
      delay(100);

      if(myTransfer.available())
      {
        //do stuff with received packet data
      }
      else if(myTransfer.status < 0)
      {
        Serial.print("ERROR: ");

        if(myTransfer.status == -1)
          Serial.println(F("CRC_ERROR"));
        else if(myTransfer.status == -2)
          Serial.println(F("PAYLOAD_ERROR"));
        else if(myTransfer.status == -3)
          Serial.println(F("STOP_BYTE_ERROR"));
      }
    }

Note that you can send more than just individual chars with these libraries. It is possible to transfer floats, ints, bytes, arrays, and even structs (or any combination of the like) within your program using the libraries! See the examples in [SerialTransfer.h][3] for more info

**For theory behind robust serial communication,** check out the tutorials [Serial Input Basics][4] and [Serial Input Advanced][5].

# EDIT: #

----------

Applying the above example to your case, you can use the following code:

**Python:**

    import time
    import struct
    from pySerialTransfer import pySerialTransfer as txfer

    def stuff_float(txfer_obj, val, start_pos=0):
        '''
        Description:
        ------------
        Insert a 32-bit floating point value into the (pySerialtxfer) TX
        buffer starting at the specified index

        :param txfer_obj: txfer - Transfer class instance to communicate over serial
        :param val:       float - value to be inserted into TX buffer
        :param start_pos: int   - index of TX buffer where the first byte of
                                  the float is to be stored in

        :return start_pos: int - index of the last byte of the float in the TX
                                 buffer + 1
        '''

        val_bytes = struct.pack('f', val)

        txfer_obj.txBuff[start_pos] = val_bytes[0]
        start_pos += 1
        txfer_obj.txBuff[start_pos] = val_bytes[1]
        start_pos += 1
        txfer_obj.txBuff[start_pos] = val_bytes[2]
        start_pos += 1
        txfer_obj.txBuff[start_pos] = val_bytes[3]
        start_pos += 1

        return start_pos

    if __name__ == '__main__':
      try:
        link = txfer.SerialTransfer('COM17')

        link.open()
        time.sleep(2) # allow some time for the Arduino to completely reset
        base = time.time()

        while True:
          time.sleep(0.2)

          sent = time.time() - base
          stuff_float(link, sent)
          link.send(4)

          while not link.available():
            if link.status < 0:
              print('ERROR: {}'.format(link.status))

          response = ''
          for index in range(link.bytesRead):
            response += chr(link.rxBuff[index])

          print('SENT: {}'.format(sent))
          print('RCVD: {}'.format(response))
          print(' ')

      except KeyboardInterrupt:
        link.close()

**Arduino:**

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

    char buff[25];
    char str[] = "I got this: %s%d.d";
    float fromPython = 0;

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

    void loop()
    {
      if(myTransfer.available())
      {
        //////////////////////////////////////////////
        // handle call from Python
        myTransfer.rxObj(fromPython, sizeof(fromPython));

        char sign = (fromPython < 0) ? '-' : ' ';
        uint16_t integer = fromPython;
        float tmpFrac = fromPython - integer;
        uint16_t decimal = trunc(tmpFrac * 10000);
        sprintf(buff, str, sign, integer, decimal);
        //////////////////////////////////////////////

        //////////////////////////////////////////////
        // send response
        myTransfer.txObj(buff, sizeof(buff));
        myTransfer.sendData(sizeof(buff));
        //////////////////////////////////////////////
      }
    }

**Verified Python Output:**

    SENT: 0.20032477378845215
    RCVD: I got this: 0.2003

    SENT: 0.4077117443084717
    RCVD: I got this: 0.4077

    SENT: 0.61326003074646
    RCVD: I got this: 0.6132

# Yet another edit: #

----------

Inspired by the answer submitted by OP, I updated the library (1.2.0) to include the member functions `tx_obj()` and `rx_obj()`. These will allow you to automatically send and receive nearly any standard Python object types (including lists and dictionaries).

**Example Python Code:**

    import time
    from pySerialTransfer import pySerialTransfer as txfer

    if __name__ == '__main__':
        try:
            link = txfer.SerialTransfer('COM17')

            link.open()
            time.sleep(2) # allow some time for the Arduino to completely reset

            while True:
                send_size = 0

                ###################################################################
                # Send a list
                ###################################################################
                list_ = [1, 3]
                list_size = link.tx_obj(list_)
                send_size += list_size

                ###################################################################
                # Send a string
                ###################################################################
                str_ = 'hello'
                str_size = link.tx_obj(str_, send_size) - send_size
                send_size += str_size

                ###################################################################
                # Send a float
                ###################################################################
                float_ = 5.234
                float_size = link.tx_obj(float_, send_size) - send_size
                send_size += float_size

                ###################################################################
                # Transmit all the data to send in a single packet
                ###################################################################
                link.send(send_size)

                ###################################################################
                # Wait for a response and report any errors while receiving packets
                ###################################################################
                while not link.available():
                    if link.status < 0:
                        if link.status == -1:
                            print('ERROR: CRC_ERROR')
                        elif link.status == -2:
                            print('ERROR: PAYLOAD_ERROR')
                        elif link.status == -3:
                            print('ERROR: STOP_BYTE_ERROR')

                ###################################################################
                # Parse response list
                ###################################################################
                rec_list_  = link.rx_obj(obj_type=type(list_),
                                         obj_byte_size=list_size,
                                         list_format='i')

                ###################################################################
                # Parse response string
                ###################################################################
                rec_str_   = link.rx_obj(obj_type=type(str_),
                                         obj_byte_size=str_size,
                                         start_pos=list_size)

                ###################################################################
                # Parse response float
                ###################################################################
                rec_float_ = link.rx_obj(obj_type=type(float_),
                                         obj_byte_size=float_size,
                                         start_pos=(list_size + str_size))

                ###################################################################
                # Display the received data
                ###################################################################
                print('SENT: {} {} {}'.format(list_, str_, float_))
                print('RCVD: {} {} {}'.format(rec_list_, rec_str_, rec_float_))
                print(' ')

        except KeyboardInterrupt:
            link.close()

        except:
            import traceback
            traceback.print_exc()

            link.close()

**Example Arduino Code:**

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

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

    void loop()
    {
      if(myTransfer.available())
      {
        // send all received data back to Python
        for(uint16_t i=0; i < myTransfer.bytesRead; i++)
          myTransfer.txBuff[i] = myTransfer.rxBuff[i];

        myTransfer.sendData(myTransfer.bytesRead);
      }
    }

  [1]: https://github.com/PowerBroker2/pySerialTransfer
  [2]: https://github.com/PowerBroker2/SerialTransfer
  [3]: https://github.com/PowerBroker2/SerialTransfer/tree/master/examples
  [4]: https://forum.arduino.cc/index.php?topic=396450.0
  [5]: https://forum.arduino.cc/index.php?topic=662346.0

body:
Building on P_B's answer to pack additional data types, I extended the python as follows. Of course, the receiving Arduino code needs to receive into the correct data type as well.

```
def StuffInt(txfer_obj, int_to_send, start_pos=0):
  """Insert integer into pySerialtxfer TX buffer starting at the specified index."""
  return StuffObject(txfer_obj, int_to_send, 'i', 4, start_pos=0)

def StuffFloat(txfer_obj, float_to_send, start_pos=0):
  """Insert integer into pySerialtxfer TX buffer starting at the specified index."""
  return StuffObject(txfer_obj, float_to_send, 'f', 4, start_pos=0)

def StuffStr(txfer_obj, string_to_send, max_length=None, start_pos=0):
  """Insert string into pySerialtxfer TX buffer starting at the specified index.

  Args:
    txfer_obj: see StuffObject
    string_to_send: see StuffObject
    max_length: if provided, the string is truncated to the requested size; otherwise
      defaults to the length of the string
    object_byte_size: integer number of bytes of the object to pack
    start_pos: see StuffObject
  Returns:
    start_pos for next object
  """
  if max_length is None:
    max_length = len(string_to_send)
  format_string = '%ds' % max_length
  truncated_string = string_to_send[:max_length]
  truncated_string_b = bytes(truncated_string, 'ascii')
  print (truncated_string_b)
  return StuffObject(txfer_obj, truncated_string_b, format_string, max_length, start_pos=0)

def StuffObject(txfer_obj, val, format_string, object_byte_size, start_pos=0):
  """Insert an object into pySerialtxfer TX buffer starting at the specified index.

  Args:
    txfer_obj: txfer - Transfer class instance to communicate over serial
    val: value to be inserted into TX buffer
    format_string: string used with struct.pack to pack the val
    object_byte_size: integer number of bytes of the object to pack
    start_pos: index of the last byte of the float in the TX buffer + 1

  Returns:
    start_pos for next object
  """
  val_bytes = struct.pack(format_string, val)
  for index in range(object_byte_size):
    txfer_obj.txBuff[index + start_pos] = val_bytes[index]
  return object_byte_size + start_pos
```


body: On the Arduino power connector jack, which is the positive terminal pin and the negative pin?

title: Arduino voltage connection pins

Answers: 1

body: Arduino's power connector jack's tip is positive while the sleeve is negative but the more important thing to know is what will you be using in powering Arduino? Please provide more information about your setup and possibly a schematic. This will help us understand more what you're trying to accomplish.


body:
It is known that address of OLED SSD1306 is 3C. The frame format is as follows:
[![enter image description here][1]][1]

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

The figure implies that the binary pattern should be 01111000 for the first frame (considering write mode and the second last bit is a dont care).
So I was trying to send the first frame using Wire.h library. The following is a code
``` Wire.beginTransmission(0b01111001); ```
But i receive a nack (return value of 2)

However, If I send 00111100, i receive a ack(return value of 0). What is wrong in my interpretation?

title: Finding address of OLED using I2C communication and Arduino

Answers: 2

body:
I2C has a 7-bit address space. The device's actual address is `0b0111100` (=0x3c). The sequences `0b01111001` and `0b01111000` address the same slave while the first one (least significant bit is `1`) starts a read transmission, the second one starts a write transmission.

Those least significant bits are nothing you need to care about when using `Wire.h`: the mode of operation is automatically set when using `Wire.startTransmission(addr)` (returns `0` when slave ACK'ed write command) and `Wire.requestFrom(addr)` (returns `0` when slave ACK'ed read command).

body:
You misinterpret how the `Wire` library is used. Though the first byte in the transmission is called the address byte, the actual address consists only of the 7 higher bits in that byte. The direction bit is not in the address.

So the `Wire.beginTransmission()` method wants the address as parameter, without the direction bit. That bit is set corresponding to the used function (0 for `Wire.beginTransmission()` and 1 for `Wire.requestFrom()`).

`0b0111100` is the real address (when connnecting the address pin to ground)(note, that there are only 7 bits, since the address only has 7 bits). The write operation address byte will then be `0b01111000`, though the library is hiding that way from you. You need to provide the 7 bit address to the function.

> the second last bit is a dont care

As mentioned above, that is not correct. This bit (the least significant bit of the address) is set by the address pin SA0. It seems, that you have it tied to ground, which sets the corresponding bit in the address to zero. If you would tie it to Vcc, it would be 1.


body:
**A NOTE ON THE PROJECT AND PROGRAM STRUCTURE**

I am developing an open source Smart Watch project using Arduino.
The code can be found here: https://github.com/shivangsgangadia/SmartWatch
The code is too large and divided into multiple files, hence I cannot paste it here within the question, hence I request you to look into the github repo.

So far I have interfaced an OLED (128 X 64 SSD1306) and RTC (DS3231 in ZS-042).
I have written libraries for both, which have been included in Github repo.

The program structure allows to add multiple "Modules" which are basically like apps. There is a static State class that holds the program state such as modules to be serviced, and time from RTC.
Each "Module" can be a "App" or "Overlay". Overlays are always visibles, there can be mutiple overlays active, but only 1 app can exist at a time.

**WHAT I AM TRYING TO DO ?**

 1. Read RTC into State class's static variables
 2. Display once
 3. Attach interrupt to set boolean flag when the RTC gives interrupt (alarm
    set to 1 minute) Service interrupt in loop by:

 - Read RTC into State class's static variables
 - Reset alarm for RTC
 - Update display

**WHAT IS THE PROBLEM ?**

The program works fine 2-3 times, i.e. does what's expected after servicing 2-3 interrupts (hence 2-3 minutes), but after that the print on the OLED becomes mangled and the program stops altogether.

**WHAT HAVE I TRIED TO SOLVE IT ?**

With `Serial.println()` in many areas such as before and after `OLED::writeString` is called in respective classes, I concluded that the RTC is not the issue, but the OLED somehow causes the program to stop.

Removing `OLED::writeString` statements does allow the rest of the printing to continue for more than 2-3 times, but the program eventually does stop. I have tried replacing the wires and the breadboard, but nothing seems to have any effect.

title: Arduino program using i2c stops working after printing to OLED a few times

Answers: 2

body:
This is wrong in many ways:

    String input = Serial.readString();
    serialInputBuffer = new char[input.length()];
    input.toCharArray(serialInputBuffer, input.length());

**What's fatal is that you later don't free the memory allocated with `new`.** Don't use String and `new`. Both use heap memory and will fragment it with these small allocations until there is no space for the next allocation. I see you have dynamic allocation in other parts of the sketch and there it looks like you have a `delete`, but they still cause the fragmentation problem.

Use a global buffer like `char serialInputBuffer[64];` and use:

    int l = Serial.readBytes(serialInputBuffer, sizeof(serialInputBuffer));
    serialInputBuffer[l] = 0;

In the scale function, there is a dynamically allocated array. Replace it with a class variable, which acts as a buffer which can hold the maximum number of bytes you expect the use to scale their byte to.

Again, dynamic allocations will cause fragmentation even if the memory is released properly.

body:
Don't use the Wire library.  If you look closely at twi.c, you'll find it has blocking calls with (potentially) infinite loops.  Eventually a condition will occur that causes one of the blocking calls to hang forever.

See [this post][1] and [this post][2] for details

Use something like SBWire

Frank

  [1]: https://www.fpaynter.com/2018/08/integrating-time-memory-and-heading-capability-part-v/
  [2]: https://www.fpaynter.com/2018/08/known-defect-in-arduino-i2c-code-causes-hangup-problems/


body:
I have been trying to find a way to use millis() instead of delay(), in order to press 2 buttons to turn on and off a blue led.

EDITED:

    const int right_button = 8, left_button = 9, yellow_led = 7, blue_led = 6, green_led = 5, red_led = 4;
    int previous_left_button_status = LOW, previous_right_button_status = LOW, blue_status = LOW, green_status = LOW;
    unsigned long time_setup = millis();
    const int delay_task = 250;

    void setup()
    {
      pinMode(right_button, INPUT_PULLUP);
      pinMode(left_button, INPUT_PULLUP);
      pinMode(blue_led, OUTPUT);
      pinMode(green_led, OUTPUT);
      pinMode(red_led, OUTPUT);
      pinMode(yellow_led, OUTPUT);
      Display.clear();
    }

    void loop()
    {
      int right_button_status = digitalRead(right_button);
      int left_button_status = digitalRead(left_button);
      unsigned long time_passes = millis();
      if (time_passes - time_setup >= delay_task)
      {
        time_setup = time_passes;
        if (right_button_status == previous_right_button_status)
        {
          green_status = !green_status;
          digitalWrite(green_led, green_status);
        }
      }
    }

title: Button debounce using millis() in this example

Answers: 1

body:
You've declared the variable for the millis function inside your loop correct and you've declared the delay duration you want to use. Two things you've missed are you've declared 2 variables with the millis function and to use it to control the program flow based on some condition to execute some code, in your case, to press 2 buttons to turn on and off an LED.

The way to to this is to use an if-else statement inside the loop function with one variable declared with the millis function, delay_duration as your reference, and 1 variable declared with a zero value.

    unsigned long storeMillis = 0;
    const int delay_duration = 500;

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

    void loop() {
    unsigned long currentMillis = millis();
    if (currentMillis - storeMillis > 500) {
    storeMillis = currentMillis; //update and store the value of storeMillis for the next iteration
    //code you want to do
    }


body: Im currently working on a project where i build an NFC device and needed some guidance in regards to the library needed for the NFC chip to work on the Arduino IDE. The chip is an M24SR64 chip and i've looked online for the library related to the chip but i couldn't find it. Although i did found a library for the M24SR64-y chip, though i'm not sure if its possible to use it, or whether it will work. If anyone has an idea or any help it would be much appreciated

title: NFC library for M24SR64

Answers: 1

body:
Here you will find a lib for all [M24SR NFC tags](https://github.com/rena2019/ArduinoM24SR)

In this [test sketch](https://github.com/rena2019/ArduinoM24SR/blob/master/examples/NfcTagDisplay/NfcTagDisplay.ino) you find details how to connect and test the tag with Arduino.
 If it helps mark as accepted to help others.


body:
I have a string that looks something like this "43;27;42;27". It is the data from 4 DHT22 temperature sensors, i need to splice this string every ";" and save the number to a variable. In the end, I will have 4 variables, each one for every number. Thanks!
The data comes from another esp wirelessly and I need the data in different strings to a nextion display.
I could also change the delimiters to differ from each other, I am posting this question because I am not sure how i should go about writing all of these 4 values in a string then also "decoding" these strings and assigning each one to a variable.

title: Split string using a delimiter then saving to different variables

Answers: 0


body:
I couldn't find any library for can bus for STM32duino (Maple Mini) on arduino or even on STMcubeIDE
I found one library on github but it doesn't compile it has a lot of error (its a fork of the stm32duino github library)

I hope that someone could provide a working library or a simple example on how to implement can bus peripheral on STM32F103

title: STM32duino Can bus library

Answers: 0


body:
I am trying to do rotational vector calculation using a MPU6050 chip which actually work really well with not too much drift **when I rotate the MPU slowly**. However, when I accelerate too much, e.g. change direction in my slow rotations or just slightly tap the breadboard with my finger, the values completely go nuts.

I am using an ESP8266 chip to control the chip and I have tried multiple libraries for reading the Gyro/Accelerometer values which all have more or less the same behaviour.

My accelerometer readings from the Serial plotter, before and after the light tap to the breadboard:

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

Gyroscope does the same thing. The MPU is new (just arrived in the mail few hours ago), I power it using 3.3V and use 3.3V GPIO logic from the ESP chip.

Does anyone know what could be causing this?

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

title: MPU6050 Accelerometer freezes/glitches after acceleration

Answers: 1

body:
Your problems are (most likely) related to loose connections in the breadboard. Sudden movements can cause power to be interrupted briefly, or data signals to become corrupted.

Breadboards aren't great for prototyping anything that moves, even slightly.


body:
I'm wanting the results from each of the 6 ultrasound modules to print on their respected line after new results have been generated instead of spitting out a continuous flow (see attached image). I've downloaded Realterm and got the results to show on there as I've read that the serial monitor can't do that but I don't know where to put the '\r' syntax within my script as I have multiple serial.prints to display the data I need.

Here is a section for 1 of the ultrasound modules, they are just repeated for the differing modules.

Thanks in advance for any help!

[![serial monitor][1]][1]

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

``` void loop() {

  //Object Ahead Distance.
  long duration1, distance1;
  digitalWrite(trigPin1, HIGH);
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   delay(500);
   if (distance1 >= 40){
    Serial.print("Nothing Ahead, Okay");
    Serial.print(distance1);
    Serial.println("cm");}
   else if (distance1 <= 39 || distance1 >= 29){
    Serial.print("Vehicle Ahead, Slow ");
    Serial.print(distance1);
    Serial.println("cm");}```

title: Serial Moniror, '\r' and Realterm

Answers: 1

body:
`\r` returns the cursor to the start of the current line. You can't use it to go back up to previous lines.

Instead you need to learn ANSI escape sequences to move the cursor around.

For example `Serial.print("\e[2J");` will clear the entire screen. `Serial.print("\e[1;1H");` will move the cursor to the top left corner of the screen (the coordinates are `\e[{Y};{X}H` by the way).

You can also add colour and all sorts of other nice things, none of which the Arduino IDE's "Serial Monitor" can do.

You can find a good reference of ANSI escape codes [here](https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797).


body:
I have the following problem/idea:

I have a electronics workbench and a separate PC desk. Now I have a USB HUB on the workbench, but it doesn't properly work, because the USB-cable to the pc is too long. My setup doesnt really allow me to put the PC somewhere else and the USB-hub is already mounted in the closest usable location.

A few days ago I remembered that I have a arduino nano with a hc-05 bluetooth module attached to its hardware serial port. And as both bluetooth and USB are serial connections I was wondering if I couldn't use the arduino sort of as a middle man and connect the arduino via bluetooth to the pc. Then have a software on the pc that registers the arduino as a USB hub with one port and run some code on the arduino that basically makes the arduino act as a USB host (I know that this is possible with the arduino nano) and have it just move data between the USB connection and the bluetooth module.

Im quite sure that all this should be possible. The atmega should even be capable of doing so at or close to maximum USB 2.0 data rates as that is only 12 Mbit/s and it can run at 16 MHz when powered with 5V. Im not quite sure about the maximum data rate for the bluetooth module though, but I can work with a little lower speeds...

The software for the pc could also be relatively straight forward. Something like a virtual USB-port and the software just shifting data from the com-port that is the bluetooth to this virtual USB-port.

So thats the idea. I have some experience in both programming microcontrollers and software for pc.

So what I need is a bit of help with this, as I am not quite sure how to accomplish this.

The parts that I will need the most help with are going to be the programming of the USB host on the arduino and the virtual USB-port on the pc.

The rest should be relatively easy as its basically just shifting data from one register into another.

title: Wireless Bluetooth USB HUB using Arduino nano

Answers: 2

body:
You can't. As simple as that. The mere act of thinking about it belies a desperate lack of understanding about how USB works.

Yes, it's "serial" in that it sends one bit after another, as opposed to multiple bits all together ("parallel"), but it is completely unrelated in any way to the "serial" that the bluetooth module or the Arduino speak ("UART").

body:
I agree with Majenko. The best way for you is to buy an active USB extension cable, so that you can handle the distance easily (the signal gets refreshed in the cable by active electronics, so that you can use USB over longer distances).

You consider this to be easy, because you haven't dug into the depth of these topics yet. Here are some important information on that:

- Bluetooth and USB are fundamentally different. The term "serial" outside of the Arduino world is just a term for one bit after another. It doesn't describe any protocol or working principle. Interfaces as SPI and I2C are also serial interfaces, but that doesn't mean, that they work similarly, not even in their topology and also not in their protocol behavior. A bridge between these different interfaces is better described as a translator. And translation is always difficult.

- Serial in the Arduino world means the UART interface. No similarity to USB or bluetooth.

- The Bluetooth spec is rather big. There are many types of connection interfaces, that can be build with it. Examples are the UART (Arduino Serial), HID (like a mouse or keyboard on a PC) or audio (like headphones) interfaces. Each connection has it's specific function. The USB spec is even bigger, way bigger to be precise. You would need to understand how bluetooth and USB work at their core for implementing something like that.

- The HC-05 is a chip for getting an UART interface over bluetooth. To change that, you would need to reprogram it with a new firmware. I doubt, that any firmware, that you can find in the web, would be sufficient for your case. Not generic enough. Also the chips hardware is limited, so you can only get limited resources out of it. Most likely you have the HC-05 on an adaptor board, which has a voltage regulator on it (since the HC-05 is a 3.3V device). You would need to ditch that board and solder the chip itself.

- The Nano is a bad choice for everything involving USB. The Atmega328p on it, that you program when programming the Arduino, does not have an USB interface. For that the Nano has a second chip, the Atmega32u4, which acts as USB to UART adaptor. You would need to hack it to do anything different than that. Doing it is possible, but you would need to ask yourself, why you are trying to do something so complex with such an incapable board. Also the Nano cannot be an USB host, nor a hub. There is an USB Host shield for the Uno, but that also is limited.

- Getting anything even remotely near to 12Mbit/s is illusionary. You won't be able to process nearly one bit every clock edge. You already need several clock edges to do very primitive processing (going into an ISR and then moving the data into a different register, as you put it). And the translation between the protocols will not be that easy. You will need much processing power and also quite some RAM and flash (you will certainly need to buffer some data and the program itself will also be very big to implement something like USB). "A little lower speeds" don't cut it there. Even if possible, that would be painstakingly slow in comparison to a real USB hub.

- Most of the software, that you would need for such a project, is non-existent. Doing something that complex with such crappy hardware is an edge case. So you would need to write your own USB stack software. As mentioned, the USB interface is very complex and if you need to ask this question, you are currently not capable of doing this (and neither am I).

I don't say it is absolutely impossible to implement a bit USB functionality with the Nano. But you won't get a satisfying result, that you really can use, even if you were an absolute expert on microcontrollers and the USB and bluetooth stacks (which you really would need to be for it). That is at maximum a project, that an expert would do just for the grind, not for real results.

You have a real life problem, that you want to solve. Choose the easiest way and buy an active USB extension cable.


body:
I have uploaded the BasicOTA sketch in Esp8266-12e.
I am written one program, when i try to upload it first time in Esp using the OTA port it gets uploaded successfully, but when i try to upload any sketch after that it does not work.
The console responds with `No Answer`.

After searching on internet many people have asked to check the sketch size. To check if size matters or not i tried with blinking sketch, and same issue happens there too.

The sketch only gets uploaded in first time.

Can anyone guide me resolving this issue.

title: esp8266 OTA issue

Answers: 1

body:
Things to check:

1. Partition arrangement selected. You have to make sure to keep the same partition arrangement between uploads.
2. Partition arrangement selected. You have to make sure that the partition arrangement you have chose supports OTA uploads.
3. You have to reset the ESP8266 manually after your USB upload. You can only do an OTA update to a sketch that has booted in "run" mode, not "boot" mode.
4. You have the right IP address / hostname selected? (I don't know how that is handled in the Arduino IDE...)
5. You must upload an OTA-enabled sketch for OTA to continue working.


body:
I am trying to implement a toggle switch to turn blinking ON & OFF. However, the code only turns the led ON or OFF and that too unreliably. Can you help me understand why it isn't working?

       const int redLed = 10;
    const int buttonPin = 2;
    unsigned long newTime;
    unsigned long oldTime = 0;
    byte newButtonState;
    byte oldButtonState = 0;
    boolean ledState = false;
    boolean blinkState = false;
    boolean state = LOW;

    void setup() {
      pinMode(redLed, OUTPUT);
      Serial.begin(9600);
      pinMode(buttonPin, INPUT);
    }

    void loop() {

      newButtonState = digitalRead(buttonPin);
      delay(100);

      // check if button state has changed
      if (newButtonState != oldButtonState) {
        // if button was pushed
        if (newButtonState == HIGH) {
          // check led state
          if (ledState == false) {
            ledState = true;
            blinkState = true;
          } else {
            ledState = false;
            blinkState = false;
          }
          if (ledState == true && blinkState == true) {
            newTime = millis();
            if (newTime - oldTime >= 250) {
              state = !state;
              oldTime = newTime;
            }
            digitalWrite(redLed, state);
          }
        }
      }
      oldButtonState = newButtonState;
    }

title: Toggling a blinking led ON & OFF

Answers: 4

body:
You never set the `pinMode` of `buttonPin`.

Normally it defaults to `INPUT` if you don't manually specify anything, and I assume from your results that you don't have an external pullup or pulldown resistor.  Therefore you need to specify `pinMode(buttonPin, INPUT_PULLUP);` and make sure that your switch or button connects the input pin to ground when activated (which means that "active" will be LOW).

Or, if you do have an external pullup or pulldown resistor then it sounds like it may not be wired corrcetly.

body:
Note, this is not an answer, but I want to show some code examples based on the comment:

You can use as said in the comment:

- Remove '== true' in a boolean condition
- Replace '== false' by '!' in a boolean condition

You will get this:

      // check if button state has changed
      if (newButtonState != oldButtonState) {
        // if button was pushed
        if (newButtonState == HIGH) {
          // check led state
          if (!ledState) {
            ledState = true;
            blinkState = true;
          } else {
            ledState = false;
            blinkState = false;
          }
          if (ledState && blinkState) {
            newTime = millis();
            if (newTime - oldTime >= 250) {
              state = !state;
              oldTime = newTime;
            }
            digitalWrite(redLed, state);
          }
        }
      }
      oldButtonState = newButtonState;
    }

About the following fragment:

      if (!ledState) {
        ledState = true;
        blinkState = true;
      } else {
        ledState = false;
        blinkState = false;
      }

Since you write `ledState` and `blinkState` in both clauses, and the condition is simple (so you don't need to put it in a temporary variable, you can replace this fragment by:

    blinkState = !ledState;
    ledState = !ledState;

Note you have to reverse the order as `blinkState` depends on `ledState`.

body:
Your blink code is only active

    if (newButtonState != oldButtonState)

so it won't blink (by itself)

To toggle blinking, just change it e.g. like this

    void loop() {
      bool newButtonState = digitalRead(buttonPin);
      if (newButtonState != oldButtonState) {
        // button state has changed
        delay(5);  // debounce
        oldButtonState = newButtonState; // run only once per button push
        if (newButtonState == HIGH) {
          // toggle blink state
          blinkState = ! blinkState;
        }
      }

      if (blinkState) {
         // BlinkWithoutDelay
         unsigned long newTime = millis();
         if (newTime - oldTime >= 250) {
            state = !state;
            oldTime = newTime;
            digitalWrite(redLed, state);
         }
      } else {
         // no Blinking : just leave redLed as is
      }
    }

Now please clean up the global variables: some are not required globally, some are not required at all.

body:
I don't see why you would set `blinkState` together with `ledState`. I assume, that you want the button to toggle the blinking. 1 press --> LED is blinking, another press --> LED stops blinking, ...

I suggest to restructure your code. First separate input and output, meaning button check code and LED blink code. For blinking you already have a state variable named `blinkState`. So in your `loop()` function you first write

    newTime = millis();
    if(blinkState && newTime - oldTime >= 250){
        ledState = !ledState;
        oldTime = newTime;
    }

That will toggle `ledState`, whenever `blinkState` is set, in intervals. Now we simply `digitalWrite()` that value out directly after that:

    digitalWrite(redLed, ledState);

Now we need to handle the button. Your button if statements seem to be good, so we only need to change, whats inside the statements. There we simply negate the `blinkState` variable:

    if (newButtonState != oldButtonState) {
        // if button was pushed
        if (newButtonState == HIGH) {
            blinkState = !blinkState;
        }
    }
    oldButtonState = newButtonState;
    delay(100);

With this code the LED will stop changing and keep the state, that it had, when you pressed the button. If you want the LED to turn off at that point, you shoud add `ledState = false;` after negating `blinkState`.

Note, that this code doesn't need your `state` variable. 2 variables are enough for this. 1 for the current led state, 1 for the blinking state.

Also note, that using `delay()` is not the best way to debounce a button. It is an easy way, but it might not behave exactly, like you want to. If you want better debouncing, you can use the [Bounce2 library][1] from github. If you don't want to use a library for it, you can still learn about their ways to debounce in the Readme file.

  [1]: https://github.com/thomasfredericks/Bounce2


body:
I understand that `Mouse.move` move the mouse from its current position, example:

`Mouse.move(100, 100);`

Will move the mouse to 100 pixels right and 100 pixels down.

But in reality it will move to somehting like 150 pixels right and/or 150 pixels down..

I already tested without cursor precision/acceleration and it doesn't change a thing.

What unit does the function use ?

I know about the 127 -127 limit, and i respect it, but still... when i ask to move 100,100 it doesn't move 100,100.

title: Mouse.move values

Answers: 1

body:
The mouse coordinates are not pixels. They are a proportion of the physical minimum/maximum parameters of the report descriptor. Since those aren't specified in the report descriptor they are taken to be the same as the logical: -127 to 127.

So moving 100 "units" is moving 100/(127-(-127)) of 100%, which is about 40%.

But 40% of what?

Well, 40% of an inch. Or what your OS believes that an inch is on your current screen.

In the HID specification:

> While Logical Minimum and Logical Maximum (extents) bound the values
returned by a device, Physical Minimum and Physical Maximum give
meaning to those bounds by allowing the report value to be offset and scaled.
For example, a thermometer might have logical extents of 0 and 999 but
physical extents of 32 and 212 degrees.The resolution can be determined
with the following algorithm:
> ```
> if ((Physical Maximum == UNDEFINED) || (Physical Minimum == UNDEFINED) || ((Physical Maximum == 0) && (Physical Minimum == 0))) {
>     Physical Maximum = Logical Maximum;
>     Physical Minimum = Logical Minimum;
> }
>
> If (Unit Exponent == UNDEFINED)
>     Unit Exponent = 0;
>
> Resolution = (Logical Maximum – Logical Minimum) / ((Physical Maximum – Physical Minimum) * (10^Unit Exponent))
```


body:
I'm pretty new to these types of projects I'd like to work on a greenhouse project with an Arduino Uno. The goal is to be able to sense temperature and control a heating lamp, detect humidity and control a humidifier, and connect a soil hydration sensor and connect a small water pump for irrigation.
Could the Uno support all of this power that could theoretically run at the same time? How would controlling the 3 isolated functions look in the Sketch?

title: Can I run 3 devices on Arduino Uno with different power sources?

Answers: 2

body:
Your question is 2 fold:

- **Power requirements:** The actual power requirement depends on the devices, but the Arduino will certainly not be able to provide power for a heating lamp. It just cannot provide that much current (you would fry the Arduino). But the Arduino is also only powered from outside. I guess you have a power source, that can provide enough power for all the devices. Then you can connect these devices in parallel to the power source (meaning + and - of the heating lamp power goes directly to the power supply). That way the current for the devices doesn't flow through the Arduino. The Arduino will only use control signals, which don't have high current. Sensors are normally either analog sensors (which connect to the analog pins with only neglectable currents) or use communication interfaces, which are also ok. The current hungry output devices (humidifier and heat lamp) either have a digital control pin, a communication interface, or they must be controlled via a relay (depends on the actual devices).

- **Controlling all the devices:** The Arduino can only do 1 thing at a time. But that is no problem, since you can do things sequentially very fast. For example write one function for every device, that you want to control. In that function you communicate with/control the device according to some variables (like the measured temperature). The `loop()` function can then look as simple as:

        void loop(){
            measure_temperature();
            measure_humidity();
            measure_soil_hydration();
            control_humidifier();
            control_headlamp();
        }

    If you want to only do this periodically (not all the time), you can either add a `delay()` or - better - use `millis()` like in the `BlinkWithoutDelay` example (there are also many tutorials about `millis()` on the web). Make sure, that the individual functions are not blocking. They should do, what they need to do, and exit quickly. No long staying in loops or waiting for an event there.

body:
Yes, you can run all of those from an UNO, but you'd probably be better off using an ESP32 so that you can add a web portal to your project for relatively the same cost.

You would be able to run the HDT or similar sensor and temperature sensor as well as the hydration sensor directly from an MCU. The other components would require something else, like NPN MOSFET low side power switch (like an FDS3890) that could be controlled by the MCU. You will need to look at the datasheets for each component you buy, find the power ratings, and make sure you have components rated to support the voltage and current of your devices (A good rule of thumb is twice the expected use, so if you have a 12V pump that can sink 3A of current, you should get a MOSFET that can handle 24+ volts and 6+ Amps.

Each sensor will likely have a library you will use and has samples. Googling each one and working on one individual function at a time is a great way to learn and progress your project.

Some MCU only have one core and everything is placed into a loop. Others (like that ESP32) have multiple cores, and can use a RTOS for task scheduling.


body: If I automated an action in a video game through arduino leonardo, can it be detected? Things like autohotkey can be easily detected, however i would expect an arduino would be far more difficult. How easy/difficult would it be detect?

title: Can a video game potentially detect arduino leonardo?

Answers: 2

body: Nigh on impossible. True the game could look to see if there is a specific VID/PID combination visible to the computer, but that is probably not going to happen (and anyway you can change it).  As far as the game is concerned, input from a keyboard is input from a keyboard, whether that keyboard has buttons or a piece of code it really can't tell.

body:
Yes.

First you'll need to define how you plan to inject the new input signal, into the data "packets" as a spoof of controller signals, or just jumping the switches?

In the context of any modern gaming console, it could be detected. Easily. Consoles and controllers use any number of proprietary protocols which sync.commands to improve response and reduce controller lag. If you're just jumping the switches, then no, you could simulate hadouken and probably get away with it just fine.

If you're referencing PC gaming, then that would be hard if not impossible with the variance of input control available.  The best deterrent would be the security of the game software itself and the genre of the gaming. Some games actively encourage Hotkeys.


body:
In using the SerialTransfer.h / pySerialTransfer libraries to send commands between my laptop and an Arduino Mega, I am sending multiple sequential strings between the devices. However, I'm having trouble "clearing" the receiving buffer on the Arduino side - it never shrinks, despite a few different attempts to clear the string (memset; a for loop).

I'm sending a string to the Arduino of the format <rand_len_str=**>, where there are anywhere from 1 to 5 asterisks.  Then the Arduino is simply sending the exact same string back, without any processing (as of yet).  And in the python terminal, I'm printing it all out; this is what I get:
```
SENT (17 bytes): <rand_len_str=**>
RECD (17 bytes): <rand_len_str=**>

SENT (18 bytes): <rand_len_str=***>
RECD (18 bytes): <rand_len_str=***>

SENT (19 bytes): <rand_len_str=****>
RECD (19 bytes): <rand_len_str=****>

SENT (17 bytes): <rand_len_str=**>
RECD (19 bytes): <rand_len_str=**>*>

SENT (18 bytes): <rand_len_str=***>
RECD (19 bytes): <rand_len_str=***>>

SENT (18 bytes): <rand_len_str=***>
RECD (19 bytes): <rand_len_str=***>>
```
As long as the string is growing, all is well - but see the error in the 4th pair, with the extra *> characters, etc.

The following is my Arduino code; I've tried to reset the receiving string using memset, but this seems not to be working.
```
#include "SerialTransfer.h"

SerialTransfer myTransfer;

const int CMD_LEN = 200;
char buff[CMD_LEN];
char received_str[CMD_LEN];

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

void loop()
{
  if(myTransfer.available())
  {
    //////////////////////////////////////////////
    // handle call from Python

    memset(received_str, '\0', CMD_LEN*sizeof(char));
    myTransfer.rxObj(received_str, CMD_LEN);

    sprintf(buff, "%s", received_str);
    //////////////////////////////////////////////

    //////////////////////////////////////////////
    // send response
    myTransfer.txObj(buff, strlen(buff));
    myTransfer.sendData(strlen(buff));
    //////////////////////////////////////////////
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}
```
I didn't see anything in SerialTransfer.h about clearing the rxObj; I can always just use the first terminating > character to parse the command - but I imagine there is a cleaner / better solution in clearing the buffer, or at least, I'd like to understand what's going on! Thanks in advance.

title: Clearing string buffer with memset after a serial read

Answers: 2

body:
Instead of clearing your buffers, make use of the bytesRead property.  Have a look at how they print the received string in the example code from the library using a for loop.  I don't know that it is null terminated or anything.

Example from the library's github page:

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(115200);
      myTransfer.begin(Serial1);
    }

    void loop()
    {
      if(myTransfer.available())
      {
        Serial.println("New Data");
        for(byte i = 0; i < myTransfer.bytesRead; i++)
          Serial.write(myTransfer.rxBuff[i]);
        Serial.println();
      }
      else if(myTransfer.status < 0)
      {
        Serial.print("ERROR: ");

        if(myTransfer.status == -1)
          Serial.println(F("CRC_ERROR"));
        else if(myTransfer.status == -2)
          Serial.println(F("PAYLOAD_ERROR"));
        else if(myTransfer.status == -3)
          Serial.println(F("STOP_BYTE_ERROR"));
      }

body:
Thanks for the pointer - that did the trick.  Applying it to my original code, if I update the few lines around `handle call from Python` to the following, it works as intended.
```
    //////////////////////////////////////////////
    // handle call from Python

    myTransfer.rxObj(received_str, CMD_LEN);
    strncpy(buff, received_str, myTransfer.bytesRead);
    buff[myTransfer.bytesRead] = '\0';

    //////////////////////////////////////////////
```
Thanks again!


body:
I have a setup that controls the rotation of two stepper motor using Arduino UNO, HBS860H stepper drivers, 4X4 keypad and LCD screen. I have replaced the Arduino Uno by a Controllino Mega and it works good. Now I am trying to replace the Keypad and LCD screen by a FATEK HMI PN2043NK.
I have the sketch for the Controllino,
I can use RS485 to communicate both devices.
I use FV Designer to program the HMI, but I don't understand how to run the sketch from the HMI.
I need some help with a simple example Please, any help I could use to start learning to communicate the HMI with the Controllino and run the steppers will be welcome.

title: Controllino Mega and Fatek HMI

Answers: 1

body:
The usual "sketch" is "always" running on your arduino (Controllino) unless it is put into a non-run mode (like when loading a program) or doesn't have power.  What you need in your sketch is to do something IF a command is received on the serial (RS485).  Rather than simply running the command you want, the sketch needs to check the serial and only execute the command if the HMI sent the correct signal.

For motor control, you could use G-code where your HMI sends G-code move commands over RS485 and your Controllino executes them.  A handy RS232 example is grbl.


body:
I am trying to make an IOT project- SMART DOOR where I have used a serve motor and NodeMcu and for adding further functionality I have been thinking of adding a theft detection feature where whenever a large force is applied on the lock an alarm starts beeping and for that I don't have a shock sensor but I do have MEMS accelerometer sensor(MPU6050 Accelerometer and Gyroscope).
So can I use it to add this functionality?
If yes, can I get a little guide on what configuration and sensitivity I should use?

THANK YOU!

title: Can a MEMS accelerometer sensor be used as a shock sensor?

Answers: 1

body:
Sure you can. A "shock" is merely a large amount of acceleration over a short period of time.

You would probably want to set the MPU6050 to its least sensitive setting (±16g), and you might even be able to make use of the "tap" function whereby the MPU6050 itself looks for a sudden short sharp shock to trigger an interrupt (though that may be a little too sensitive for your needs, I don't know).


body:
6 years ago, there has been a question "[How to emulate Arduino on PC][1]".

Since then, probably many more Arduino emulators have been introduces.

With this question, I would like to narrow the search scope down to the following criteria:

- Linux compatible
- headless operation mode without UI/IDE possible to run in a [CI/CD][2] (continuous integration/delivery) system in collaborative environment where many code versions need to be merged and tested.

Do such setups exist already?

  [1]: https://arduino.stackexchange.com/questions/61/can-i-program-for-arduino-without-having-a-real-board
  [2]: https://en.wikipedia.org/wiki/Continuous_integration

title: Can I emulate Arduino in a headless CI/CD setup?

Answers: 1

body:
The problems with this kind of software is:

  - always behind the recent releases of cores/ hw variations.
  - reliable only for simple programs/tasks
  - Imho all the products I tested (mainly on Win) are actually a (somewhat crippled ) teaching and visualization help.
  - if you look into the emulators you mostly see only support for different chips and not the whole micro computer, which is far more complex to create

Due to the low cost of the hardware it is easier to run real HW setups with HW diagnostics (and get also feedback for thermal/electric issues) <br>So this kind of SW is for the low cost avr/esp HW and its hundreds of variants (even between production batches from one manufacturer) hard to develop and mantain. So you'll only find nice "play around" emulators which won't fulfill any professional requirement (even if some claim it)


body:
I'm writing the code in *VS Code* on *IO Platform*. Yesterday i finished my code and uploaded it to the Arduino Uno. It works fine. Next day i launched the VS Code and i changed the code a bit, then i uploaded it and i got the error.

Error:

    Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
    (.text+0x0): multiple definition of `__vector_7'
    NewPing.cpp.o (symbol from plugin):(.text+0x0): first defined here
    collect2.exe: error: ld returned 1 exit status
    *** [.pio\build\uno\firmware.elf] Error 1

I am using the libary `NewPing.h`. The code should does this: If is distance more than 20cm, the the buzz makes the sound and turns on the red led. If distance is less than 20cm, the blue led turns on

The code:

    #include <Arduino.h>  //It has to be there, because the arduino ide in VS Code will not work.

    #include <NewPing.h>

    #define echo_pin 3
    #define trig_pin 4
    #define max_range 450

    #define red_led_pin 7
    #define blue_led_pin 9
    #define buzz_pin 10

    int distance = 0;

    NewPing sonar(trig_pin, echo_pin, max_range);

    void setup(){
      Serial.begin(9600);
      pinMode(red_led_pin, OUTPUT);
      pinMode(blue_led_pin, OUTPUT);

      pinMode(buzz_pin, OUTPUT);
    }

    void loop() {

      distance = sonar.ping_cm();
      delay(50);

      if (distance > 0) {
              distance = 0;

        for (int i=0; i<5; i++) {
          distance += sonar.ping_cm();
          delay(50);
        }
        distance /= 4;

        Serial.print("Distance: ");
        Serial.print(distance);
        Serial.println("cm");

        if (distance > 20) {

          digitalWrite(blue_led_pin, LOW);
          digitalWrite(red_led_pin, HIGH);
          tone(buzz_pin, 1500);
          tone(buzz_pin, 800);
        }

        else {

          digitalWrite(red_led_pin, LOW);
          digitalWrite(blue_led_pin, HIGH);
        }
      }
    }

I don't undersand, what has changed. I tried to import again the libary <https://www.arduino.cc/en/guide/libraries> by importing the *.zip file, also installing in IDE.

title: Uno - error during uploading with library

Answers: 1

body:
You have a conflict of interrupts. Both the internal `tone()` command and the `NewPing.h` use Timer 2 by default, which makes them mutually exclusive.

However you can change `NewPing` to not use a timer by editing the `src/NewPing.h` file and setting `TIMER_ENABLED` to be `false`:

        #define TIMER_ENABLED true      // Set to "false" to disable the timer ISR (if getting "__vector_7" compile errors set this to false). Default=true


body:
While it seems [less valuable][1] to emulate Arduino in a CI/CD setup, are there any experiences/best practices for collaborative teams to automate their acceptance tests where a real Arduino is integrated into a CI/CD toolchain (or, what are comparable practices)?

Minimal example of acceptance testing:

* compilation is successful for a given compiler version.

  [1]: https://arduino.stackexchange.com/questions/74772/can-i-emulate-arduino-in-a-headless-ci-cd-setup?noredirect=1#comment162856_74772

title: Can I integrate Arduino in a CI/CD setup?

Answers: 1

body:
There are different approaches around. I can only point you to some of them:

  - [GitLab CI approach A](https://codeblog.dotsandbrackets.com/gitlab-ci-esp32-arduino/)
  - [GitLab CI approach B](https://dzone.com/articles/hands-on-iot-devops-day-3-gitlab-cicd)
  - Your specific solution: To build [pipelines for Arduino](https://devblogs.microsoft.com/premier-developer/azure-devops-build-pipelines-for-arduino-microcontrollers/) (although its Azure) but you can use this technique on [Linux with Jenkins](https://opensource.com/article/19/9/intro-building-cicd-pipelines-jenkins)

As a valuable commenter mentioned on your previous question - this does not cover the attached hardware testing (sensors/ motors) - this has to be "integrated" via a test lab station, which you have to control manually (or semi-automated via lab equipment) on defined release/version changes


body:
i have NodeMCU with es8266 onboard on it. I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen. So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

one tiny question here: can `Serial.println("asd asd")` cause memory fragmentation?

title: Can stack size be determined by free heap?

Answers: 1

body:
> I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen.

Indeed they do. And such things can be a pain to track down.

> So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

No, you can't.  The "free" amount of heap does not equate to the top address of heap. Heap can (and generally does) have holes in it. The "free" space is the sum of all those holes plus any extra "heap reserved" space above the highest heap entry.

To get the current stack usage you need to know two things:

1. The staring address of the stack, and
2. The current extent of the stack

Item 1 will be a fixed value, though what that value is I have no clue, but some reading will surely give you that value.

Item 2 can be obtained by allocating a local variable in a function and getting the address of that variable.

If all you care about is the change in stack imposed by your code you can record the "starting" stack point and use that in point 1.  For example:

```
char *stack_start;

void setup() {
    char stack;
    stack_start = &stack;
}
```

Then you can use that to get the current stack size compared to the start of your program:

```
uint32_t stack_size() {
    char stack;
    return (uint32_t)stack_start - (uint32_t)&stack;
}
```

> one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

No.  Use of `String` and other dynamic allocation is what causes memory fragmentation.


body:
Following *[approach A][1]* from this Arduino SE answer, I managed to kick off an Arduino CLI compilation in a Docker environment.

However, the project I am trying to compile has a [dependency][2] on a LCD control library.

Error output:

    ...../OpenSourceVentilator/OpenSourceVentilator.ino:494:116:
    fatal error: LiquidCrystal_PCF8574.h:
    No such file or directory
    compilation terminated.

What is the proper way to link dependencies to the compilation environment of an Arduino project?

While the source suggests a direct compiler call, maybe I need a Makefile instead of the following?

    arduino-cli compile --fqbn esp32:esp32:esp32 -o ignored.bin OpenSourceVentilator.ino

  [1]: https://arduino.stackexchange.com/questions/74781/can-i-integrate-arduino-in-a-ci-cd-setup
  [2]: https://github.com/mathertel/LiquidCrystal_PCF8574/tree/master/src

title: How to install a dependency library to an Arduino compilation environment?

Answers: 1

body: If the library is installed the Arduino IDE (or CLI I assume too) just finds it and compiles/links it for you.


body:
I've got 4x 12V 6a peltiers and some [3d printer mosfet controllers][1] to drive them using PWM with my arduino. But I've found the mosfets need ~7V to switch on, so I'm now wanting to control them with some logic level ones I had around. I could just use the logic ones directly to the peltiers, but am finding it difficult to make my stripboard capable of handling 24A ([this page][2] seems to say I need tracks/wire of 2.3+mm diameter which I don't have). Hence I'm trying to make a circuit for the arduino to use the logic mosfets to control the 3d printer mosfets but can't quite get my head around how to do it. I think I'm missing a power source for the first mosfet - do I need to have a whole separate DC power supply for this to the peltiers? Very grateful for a bit of help please!

[![mosfet 3d printer controllers][3]][3]
[![Proposed circuit - sorry the M represents my peltier!][4]][4]

  [1]: https://www.amazon.co.uk/Aibecy-Expansion-Current-Ramps1-4-Printers/dp/B07BS6TQCG
  [2]: https://www.powerstream.com/Wire_Size.htm
  [3]: https://i.stack.imgur.com/cIEPv.png
  [4]: https://i.stack.imgur.com/uYlGw.jpg

title: How to control one Mosfet with another mosfet

Answers: 1

body:
There's one thing you missed with your arrangement, and that is getting the 12V to turn the MOSFET on.  In your current arrangement it's possible to turn it off, but never on.  Adding a pullup resistor can help:

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

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

<!-- End schematic -->

R1 pulls the gate of M1 up above the switching threshold to turn it on. M2, when on, pulls the gate down below the switching threshold, turning it off.

However: you may have noticed that the switching is now backwards: send a HIGH from the Arduino to turn it off. Which of course has the effect that *the output is normally on and you have to actively turn it off*.

Again a pullup resistor can help:

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

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

<!-- End schematic -->

Now R2 keeps the gate of M2 pulled up (switched on) which keeps M1 turned of. That is, until you actively pull the gate down to ground by sending a LOW from the Arduino.

To ensure that the peltier never turns on when you don't want it to you should also take steps to ensure that the 12V power is never provided without the 5V also being provided - so you could maybe power the Arduino through the barrel jack from the 12V supply.  It doesn't matter if the 5V is provided but not the 12V, but the other way around could mean the peltier comes on with no active control over it.


body:
I have this code which works :

    String ErrorMsg;
    .......
    if(!UploadPacketError)
    {
        ErrorMsg="OK";
    }
    else
    {
       ErrorMsg="NOK";
    }

String creates a dynamically allocated array which I want to avoid. I would prefer something like :
```
unsigned char ErrorMsg[5];
......
if(!UploadPacketError)
    {
        strcpy(ErroMsg,"OK",3); // +1 for the Null Termination ?
    }
    else
    {
       strcpy(ErroMsg,"NOK",4); // +1 for the Null Termination ?
    }
```
i.e. is there a way to dynamically assign a value to a fixed size character array ?

Cheers
Thomas

title: Regarding Strings and assignments

Answers: 2

body:
Almost.

First it's `char` not `unsigned char`:

```
char ErrorMsg[5];`
```

Second you don't specify a size with `strcpy`:

```
strcpy(ErrorMsg, "OK");
```

There is a variant of `strcpy` called `strncpy` which copies *at most* `n` characters:

```
strncpy(ErrorMsg, "OK", 5);
```

That is used to prevent buffer overruns. But when working with string literals like that it's pretty pointless.

body:
Also recomending the fixed char approach but for completeness there is a possibility to "get away with String class" IF you **ONLY** use fixed AND predefined Strings to build dynamicly variable messages:

    bool first = true;

    String A = F("My first ");
    String B = F("My second ");
    String C = F("answer");
    if (first) serial.println(A+C);
    else serial.println(B+C);

Read more on the [F-macro here](https://www.baldengineer.com/arduino-f-macro.html).
Conclusion:

  - Large blocks of text to a file system (like SPIFFS, LittleFS, SD)
  - dynamic texts to large enough fixed char arrays and
  - short messages (consisting of fixed parts) can be created with the F-Macro


body:
I have multiple Arduino Nano boards.
I am able to compile or upload code only once. If I try to compile/upload again I get an error: "Error compiling for board Arduino Nano". However there is a workaround: to be able to upload again I change something in tools menu for example board or processor.
I tried all of the nanos and all of the ports.

The error message is below (verbose is enabled).

The problem appeared from nowhere.
Thank you in advance!

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Nauris\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10812 -build-path C:\Users\Nauris\AppData\Local\Temp\arduino_build_956544 -warnings=none -build-cache C:\Users\Nauris\AppData\Local\Temp\arduino_cache_309115 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Nauris\Documents\Arduino\RC\wifi_arduino\wifi_arduino.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Nauris\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10812 -build-path C:\Users\Nauris\AppData\Local\Temp\arduino_build_956544 -warnings=none -build-cache C:\Users\Nauris\AppData\Local\Temp\arduino_cache_309115 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Nauris\Documents\Arduino\RC\wifi_arduino\wifi_arduino.ino
    Using board 'nano' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Detecting libraries used...
    Error compiling for board Arduino Nano.

title: Error compiling for board Arduino Nano

Answers: 2

body: I resolved this issue by installing older arduino ide version.

body:
ive been having this same issue for the last 9 or so month it is driving me insane i have uninstalled and reinstalled arduino in every way i possibly can... using revouninstaller and cccleaner and even tried starting a new user account on my computer and installing it and i still have this issue.. i can only click verify or upload one time and the very next time as soon as i click it i get the exact same error message.. and not just for the nano for every board i have on the list,, it is so irritating!!!! the only work around i have found. well the simplest is to change back and forth from nano old bootloader to atmega328.. or switch back and forth from nano and uno in the boards menu..

so when im trying to put multiple codes together and get it to compile every time i click verify i have to change the board info.. or it instantly says

Using core 'arduino' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Detecting libraries used...
Error compiling for board Arduino Nano.

about to just throw it all in the trash


body:
I have a new atmega328p IC that I wanted to program. To do so I placed it into the socket of an arduino uno. I accidentally placed it the wrong way around (180° rotated), and powered it via USB and tried to upload the blink sketch, which obviously did not succeed. After I noticed it I turned it around and placed it into the socket the right way. I tried again uploading the blink sketch again without success.

1. Have I fried the atmega328p by placing it in the socket the wrong way?
2. Is there something else you need to do to new atmeag328p before you can program them the usual way?

----

**Update:** It seems that just rotating the IC did not damage it in the state where there was no bootloader programmed. And and the bootloader needed to be programmed first before the IC could be used.

title: Possibly fried a new atmega328p?

Answers: 2

body:
Whether your chip is fried or not, we can't say, but they're reasonably tough and will stand a bit of abuse before they fail. Did anything smoke or get hot?

You can buy atmega328p chips pre-programmed with a bootloader from a few vendors, but they don't come from the factory that way so most are not. Preprogrammed chips typically cost a couple of $ US more than blank chips for the time spent by the vendor to buy blank ones, program, and repackage them for sale in small quantities, and are almost always advertised as such. If you don't know whether yours is programmed with a bootloader, it probably isn't. It's worth trying to do it yourself, on a breadboard, using a known-working Uno as a bootloader- programmer. There are lots of how-to articles on the internet.

body: After a reset it should blink pin13 led as all Arduinos do. If not, I'd first try uploading  a bootloader cause I have gotten ones that don't have bootloaders. The 328p if a pretty resistant chip. One time i put 12v into a digital pin and it got so hot the smd desoldered itself but worked fine apart from that pin being blown.


body:
I've seen some interesting explanations on using websocket comms on mkr 1010 but it's always handling the mkr 1010 as the client and the server being always a computer or some other "non-arduino" server . I'm working on a system with several mkr 1010's in a master/slave setup and bidi comms i.e. i want to use one of the mkr's as a server (does the calculations etc.) and the other as clients (get result from calculations ans send back sensor info). I did not found any library or example of websocket server for mkr1010. I found it for ESP systems. Please help as i tried my bidi comms with webclient and webserver using http but not good enough for my applicaton (not realy bidi).
thanks a lot !

title: No Websockets Server for Arduino mkr1010?

Answers: 1

body:
Most websocket libraries work over a Client. Client is base class for all EthernetClient and WiFiClient classes.

But why do you want to use a Websocket for communication of two MCU in the same LAN? Websockets are intended for communication over HTTP infrastructure (firewalls, proxies) to a web server in Internet or from browser to a web server.

Use a basic TCP socket over Arduino Client.

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.

client socket

    if (client.connect(serverIP, PORT)) {
      client.print("request\n");
      String response = client.readStringUntil('\n');
      Serial.println(response);
      client.stop();
    }

server side

    WiFiClient client = server.available();
    if (client && client.connected()) {
      String request = client.readStringUntil('\n');
      Serial.println(request);
      client.print("response\n");
      client.stop();
    }


body:
I want to compile a sketch on Arduino Uno, while Arduino is running and not connected to anything else, and then run the compiled sketch automatically.

Is this feasible?

How?

title: Runtime compilation

Answers: 2

body:
No. It's not feasible.

The Uno cannot compile.  The Uno cannot run code from RAM.  The Uno is *not* a computer.

You *might* be able to find some small scripting language that could run on an Uno, but TBH the Uno is so underpowered you'd be able to do little more than blink an LED...

body:
No, not feasable, not possible.

The Arduino runs machine code and it does not have enough space or computation power for a compiler (also there is simply no version of the avr C++ compiler for the AVR platform, for obvious reasons). Also it is internally hardwired to run code from the flash memory. You cannot execute code from RAM. The Arduino is a microcontroller, not a computer. (Here I mean computer as something like: Has a microprocessor to execute code from RAM; has an OS; has huge amount of resources in relation to the average microcontroller)

Also: "not connected to anything else" --> Then how would you interact with the Arduino, writing the code, triggering compilation?

If this is about the cable connection, you can implement programming over bluetooth through the HC-05 module (google for it, there should be plenty of tutorials out there). Or go away from the Arduino and change to an ESP, so that you can do Over The Air (OTA) updates over wifi.

Or you could change to a minicomputer like the Raspberry Pi Zero, which is just a little bigger than the Arduino Nano and smaller than the Uno. (Though that hardly depends on the goal, what you are trying to achieve. Microcontrollers are sometimes better used for specific tasks in contrast to minicomputers)


body:
When I go to select port there's no port for the connected ESP32 module. I am using Mac OS Mojave, mac mini.
The port I find is [![enter image description here][1]][1]

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

title: Adrduino IDE doesn't show port for connected ESP32 module

Answers: 0